text
stringlengths
54
60.6k
<commit_before>#include "../../IRCBot/include/command-interface.hpp" #include "../../IRCBot/include/bot.hpp" #include "./random-line-stream.hpp" /* for use in BabblerCommand */ #include "./iplookup.hpp" #include "./googler.hpp" #include "./stocks.hpp" #include "./quotes.hpp" #include "./http.hpp" #include "./hash.hpp" #include "./urban.hpp" #include <algorithm> #include <string> #include <vector> #include <random> #include <cctype> #include <unistd.h> /* getpid() */ namespace Plugins { class GoogleCommand : protected IRC::CommandInterface { unsigned long long times_executed; public: GoogleCommand() /* pointer to owning bot not needed. */ : CommandInterface("@google ", "Performs google search and returns shortened links.", nullptr, true), times_executed(0) {} void run(const IRC::Packet& p) { std::vector<std::string> res_vec; Googler::do_google_search(p.content.substr(this->trigger().length()), 2, res_vec); for (auto& res : res_vec) { p.reply(res); } this->times_executed++; } std::string get_stats(void) { return "GoogleCommand -> Times Executed: " + std::to_string(this->times_executed); } }; class LMGTFYCommand : protected IRC::CommandInterface { public: LMGTFYCommand() : CommandInterface("@lmgtfy ", "mean way to tell ppl to google things.") {} void run(const IRC::Packet& p) { p.reply("http://lmgtfy.com/?q=" + MyHTTP::uri_encode( p.content.substr(this->trigger().length()) ) ); } }; class UrbanCommand : protected IRC::CommandInterface { public: UrbanCommand() : CommandInterface("@urban ", "checks urban dictionary for a definition.") {} void run(const IRC::Packet& p) { std::string def = ""; Urban::get_first_result(p.content.substr(this->trigger_string.length()) , def); if (!def.empty()) { p.reply(def); } } }; class IPLookupCommand : protected IRC::CommandInterface { public: IPLookupCommand() : IRC::CommandInterface("@iplookup ", "looks up IP address.", nullptr, true) {} void run(const IRC::Packet& p) { p.reply(IPLookup::do_lookup(p.content.substr(this->trigger().length()))); } }; class SayHiCommand : protected IRC::CommandInterface { public: SayHiCommand() : IRC::CommandInterface("@sayhi", "says hi.") {} void run(const IRC::Packet& p) { p.reply("Hello!"); } }; class SlapCommand : protected IRC::CommandInterface { public: SlapCommand() : IRC::CommandInterface("@slap ", "slaps arguments.") {} void run(const IRC::Packet& p) { p.reply("\001ACTION slapped the hell outta " + p.content.substr(this->trigger().length()) + "\001"); } }; class SpeakCommand : protected IRC::CommandInterface { public: SpeakCommand() : IRC::CommandInterface("@speak ", "says a message to channel: @speak <chan> <msg...>", nullptr, true) {} void run(const IRC::Packet& p) { std::string arguments = p.content.substr(this->trigger().length()); // everything after "@speak " size_t first_space_idx = arguments.find(" "); if (first_space_idx == std::string::npos) return; std::string chan = arguments.substr(0, first_space_idx); std::string msg = arguments.substr(first_space_idx + 1); p.owner->privmsg( chan , msg ); } }; class BabblerCommand : protected IRC::CommandInterface { RandomLineStream rls; public: BabblerCommand(const std::string& babbles_filepath) : CommandInterface("@babble", "does a babble."), rls(babbles_filepath) {} void run(const IRC::Packet& p) { p.reply(rls.sample()); } }; class StocksCommand : protected IRC::CommandInterface { unsigned long long queries_done; public: StocksCommand() : CommandInterface("@stock ", "checks a stock ticker price."), queries_done(0) {} void run(const IRC::Packet& p) { p.reply(Stocks::get_stock_summary( p.content.substr(this->trigger().length()) )); this->queries_done++; } std::string get_stats(void) { return "Stock Queries Done: " + std::to_string(queries_done); } }; class QuoteCommand : protected IRC::CommandInterface { public: QuoteCommand() : CommandInterface("@quote", "delivers the quote of the day.") {} void run(const IRC::Packet& p) { p.reply(Quotes::get_random_quote()); } }; class EliteCommand : protected IRC::CommandInterface { const std::string reglr = "abeiolgsqtz"; const std::string elite = "48310195972"; public: EliteCommand() : CommandInterface("@1337 ", "translates to and from 13375p34k.") {} void run(const IRC::Packet& p) { std::string sub = p.content.substr(this->trigger_string.length()); std::string msg = ""; try { msg = sub.substr(sub.find(" ")); } catch (std::exception& e) { std::cerr << "EliteCommand::run() error: " << e.what() << '\n'; p.reply("Error. Usage: @1337 [to1337 | from1337] [message...]"); } sub = sub.substr(0, sub.find(" ")); if (sub == "from1337") { for (auto& e : msg) { for (size_t i = 0; i < elite.length(); ++i) { if (std::tolower(e) == elite[i]) e = reglr[i]; } } } else { for (auto& e : msg) { for (size_t i = 0; i < reglr.length(); ++i) { if (std::tolower(e) == reglr[i]) e = elite[i]; } } } p.reply(msg); } }; class ChooseCommand : protected IRC::CommandInterface { std::minstd_rand random_gen; public: ChooseCommand() : CommandInterface("@choose ", "chooses a thing of comma-separated list.") { random_gen.seed(getpid()); } bool triggered(const IRC::Packet& p) { std::string s = p.content.substr(0, this->trigger_string.length()-1); return p.type == IRC::Packet::PacketType::PRIVMSG && !std::isalpha(s[0]) && !std::isdigit(s[0]) && s.substr(1) == this->trigger_string.substr(1, s.length()-1); } void run(const IRC::Packet& p) { std::string choices_str = p.content.substr(this->trigger_string.length()); std::vector<std::string> choices_vec; size_t last = 0, next = 0; while (last < choices_str.length() && (next = choices_str.find(",", last)) != std::string::npos) { choices_vec.push_back(choices_str.substr( last, next - last ) ); last = next+1; while (last < choices_str.length() && choices_str[last] == ',') ++last; } choices_vec.push_back(choices_str.substr(last)); std::cout << "choices_vec.size() = " << choices_vec.size() << '\n'; if ( !choices_vec.empty() ) p.reply(choices_vec.at( random_gen() % choices_vec.size() ) ); } }; class UtilityCommands : protected IRC::CommandInterface { public: UtilityCommands(IRC::Bot *b = nullptr) : IRC::CommandInterface("@kick,@join,@part,@quit,@nick,@adda", "does utility actions", b, true) { if (b == nullptr) { throw std::logic_error("In UtilityCommands, Bot *b cannot be nullptr!"); } } bool triggered(const IRC::Packet& p) { std::string cmd = p.content.substr(0,5); return p.type == IRC::Packet::PacketType::PRIVMSG && ( cmd == "@kick" || cmd == "@join" || cmd == "@part" || cmd == "@quit" || cmd == "@nick" || cmd == "@adda"); } void run(const IRC::Packet& p) { std::string cmd = p.content.substr(0,5); if (p.content.length() > 5) { if ( cmd == "@kick" ) { p.owner->kick(p.channel, p.content.substr(6)); } else if ( cmd == "@join" ) { p.owner->join_channel( p.content.substr(6 , p.content.find(" ", 6) - 6) ); } else if ( cmd == "@part" ) { p.owner->part_channel( p.content.substr(6) ); } else if ( cmd == "@nick" ) { p.owner->set_nick( p.content.substr(6) ); } else if ( cmd == "@adda" ) { std::vector<std::string> args; p.get_args(args); if (args.size() < 3) { p.owner->privmsg(p.sender, "Error. Usage: @adda TYPE name"); return; } try { std::transform(args[1].begin(), args[1].end(), args[1].begin(), ::tolower); } catch (...) { std::cerr << "failed in UtilityCommands @adda to transform to lowercase : " << args[1] << '\n'; return; } IRC::Bot::RELATIONSHIP r = IRC::Bot::RELATIONSHIP::IGNORED; if (args[1] == "admin") { r = IRC::Bot::RELATIONSHIP::ADMIN; } else if (args[1] != "ignore") { // all else except "admin" and "ignore" (case insensitive) p.owner->privmsg(p.sender, "Error. Invalid argument: " + args[1]); return; } bot_ptr->add_a(r , args[2]); p.reply("Added " + args[2] + " to " + args[1] + " list."); } } if (cmd == "@quit") { // quit p.owner->disconnect( p.content.length() > 6 ? p.content.substr(6) : "Quitting..." ); } } }; class RecoveryCommand : public IRC::CommandInterface { public: RecoveryCommand(IRC::Bot *b = nullptr) : CommandInterface("@recover ", "recover the bot with a password.", b) {} void run(const IRC::Packet& p) { std::string password = p.content.substr(this->trigger().length()); if ( bot_ptr->reauthenticate(p.sender, Hash::sha256(password)) ) { p.owner->privmsg(p.sender, "Password accepted! You now have admin rights."); } else { p.owner->privmsg(p.sender, "Denied. Password invalid."); } } }; }; <commit_msg>fix critical error in one of the commands<commit_after>#include "../../IRCBot/include/command-interface.hpp" #include "../../IRCBot/include/bot.hpp" #include "./random-line-stream.hpp" /* for use in BabblerCommand */ #include "./iplookup.hpp" #include "./googler.hpp" #include "./stocks.hpp" #include "./quotes.hpp" #include "./http.hpp" #include "./hash.hpp" #include "./urban.hpp" #include <algorithm> #include <string> #include <vector> #include <random> #include <cctype> #include <unistd.h> /* getpid() */ namespace Plugins { class GoogleCommand : protected IRC::CommandInterface { unsigned long long times_executed; public: GoogleCommand() /* pointer to owning bot not needed. */ : CommandInterface("@google ", "Performs google search and returns shortened links.", nullptr, true), times_executed(0) {} void run(const IRC::Packet& p) { std::vector<std::string> res_vec; Googler::do_google_search(p.content.substr(this->trigger().length()), 2, res_vec); for (auto& res : res_vec) { p.reply(res); } this->times_executed++; } std::string get_stats(void) { return "GoogleCommand -> Times Executed: " + std::to_string(this->times_executed); } }; class LMGTFYCommand : protected IRC::CommandInterface { public: LMGTFYCommand() : CommandInterface("@lmgtfy ", "mean way to tell ppl to google things.") {} void run(const IRC::Packet& p) { p.reply("http://lmgtfy.com/?q=" + MyHTTP::uri_encode( p.content.substr(this->trigger().length()) ) ); } }; class UrbanCommand : protected IRC::CommandInterface { public: UrbanCommand() : CommandInterface("@urban ", "checks urban dictionary for a definition.") {} void run(const IRC::Packet& p) { std::string def = ""; Urban::get_first_result(p.content.substr(this->trigger_string.length()) , def); if (!def.empty()) { p.reply(def); } } }; class IPLookupCommand : protected IRC::CommandInterface { public: IPLookupCommand() : IRC::CommandInterface("@iplookup ", "looks up IP address.", nullptr, true) {} void run(const IRC::Packet& p) { p.reply(IPLookup::do_lookup(p.content.substr(this->trigger().length()))); } }; class SayHiCommand : protected IRC::CommandInterface { public: SayHiCommand() : IRC::CommandInterface("@sayhi", "says hi.") {} void run(const IRC::Packet& p) { p.reply("Hello!"); } }; class SlapCommand : protected IRC::CommandInterface { public: SlapCommand() : IRC::CommandInterface("@slap ", "slaps arguments.") {} void run(const IRC::Packet& p) { p.reply("\001ACTION slapped the hell outta " + p.content.substr(this->trigger().length()) + "\001"); } }; class SpeakCommand : protected IRC::CommandInterface { public: SpeakCommand() : IRC::CommandInterface("@speak ", "says a message to channel: @speak <chan> <msg...>", nullptr, true) {} void run(const IRC::Packet& p) { std::string arguments = p.content.substr(this->trigger().length()); // everything after "@speak " size_t first_space_idx = arguments.find(" "); if (first_space_idx == std::string::npos) return; std::string chan = arguments.substr(0, first_space_idx); std::string msg = arguments.substr(first_space_idx + 1); p.owner->privmsg( chan , msg ); } }; class BabblerCommand : protected IRC::CommandInterface { RandomLineStream rls; public: BabblerCommand(const std::string& babbles_filepath) : CommandInterface("@babble", "does a babble."), rls(babbles_filepath) {} void run(const IRC::Packet& p) { p.reply(rls.sample()); } }; class StocksCommand : protected IRC::CommandInterface { unsigned long long queries_done; public: StocksCommand() : CommandInterface("@stock ", "checks a stock ticker price."), queries_done(0) {} void run(const IRC::Packet& p) { p.reply(Stocks::get_stock_summary( p.content.substr(this->trigger().length()) )); this->queries_done++; } std::string get_stats(void) { return "Stock Queries Done: " + std::to_string(queries_done); } }; class QuoteCommand : protected IRC::CommandInterface { public: QuoteCommand() : CommandInterface("@quote", "delivers the quote of the day.") {} void run(const IRC::Packet& p) { p.reply(Quotes::get_random_quote()); } }; class EliteCommand : protected IRC::CommandInterface { const std::string reglr = "abeiolgsqtz"; const std::string elite = "48310195972"; public: EliteCommand() : CommandInterface("@1337 ", "translates to and from 13375p34k.") {} void run(const IRC::Packet& p) { std::string sub = p.content.substr(this->trigger_string.length()); std::string msg = ""; try { msg = sub.substr(sub.find(" ")); } catch (std::exception& e) { std::cerr << "EliteCommand::run() error: " << e.what() << '\n'; p.reply("Error. Usage: @1337 [to1337 | from1337] [message...]"); } sub = sub.substr(0, sub.find(" ")); if (sub == "from1337") { for (auto& e : msg) { for (size_t i = 0; i < elite.length(); ++i) { if (std::tolower(e) == elite[i]) e = reglr[i]; } } } else { for (auto& e : msg) { for (size_t i = 0; i < reglr.length(); ++i) { if (std::tolower(e) == reglr[i]) e = elite[i]; } } } p.reply(msg); } }; class ChooseCommand : protected IRC::CommandInterface { std::minstd_rand random_gen; public: ChooseCommand() : CommandInterface("@choose ", "chooses a thing of comma-separated list.") { random_gen.seed(getpid()); } bool triggered(const IRC::Packet& p) { if (p.content.length() < this->trigger_string.length()) return false; std::string s = p.content.substr(0, this->trigger_string.length()-1); return p.type == IRC::Packet::PacketType::PRIVMSG && !std::isalpha(s[0]) && !std::isdigit(s[0]) && s.substr(1) == this->trigger_string.substr(1, s.length()-1); } void run(const IRC::Packet& p) { std::string choices_str = p.content.substr(this->trigger_string.length()); std::vector<std::string> choices_vec; size_t last = 0, next = 0; while (last < choices_str.length() && (next = choices_str.find(",", last)) != std::string::npos) { choices_vec.push_back(choices_str.substr( last, next - last ) ); last = next+1; while (last < choices_str.length() && choices_str[last] == ',') ++last; } choices_vec.push_back(choices_str.substr(last)); std::cout << "choices_vec.size() = " << choices_vec.size() << '\n'; if ( !choices_vec.empty() ) p.reply(choices_vec.at( random_gen() % choices_vec.size() ) ); } }; class UtilityCommands : protected IRC::CommandInterface { public: UtilityCommands(IRC::Bot *b = nullptr) : IRC::CommandInterface("@kick,@join,@part,@quit,@nick,@adda", "does utility actions", b, true) { if (b == nullptr) { throw std::logic_error("In UtilityCommands, Bot *b cannot be nullptr!"); } } bool triggered(const IRC::Packet& p) { std::string cmd = p.content.substr(0,5); return p.type == IRC::Packet::PacketType::PRIVMSG && ( cmd == "@kick" || cmd == "@join" || cmd == "@part" || cmd == "@quit" || cmd == "@nick" || cmd == "@adda"); } void run(const IRC::Packet& p) { std::string cmd = p.content.substr(0,5); if (p.content.length() > 5) { if ( cmd == "@kick" ) { p.owner->kick(p.channel, p.content.substr(6)); } else if ( cmd == "@join" ) { p.owner->join_channel( p.content.substr(6 , p.content.find(" ", 6) - 6) ); } else if ( cmd == "@part" ) { p.owner->part_channel( p.content.substr(6) ); } else if ( cmd == "@nick" ) { p.owner->set_nick( p.content.substr(6) ); } else if ( cmd == "@adda" ) { std::vector<std::string> args; p.get_args(args); if (args.size() < 3) { p.owner->privmsg(p.sender, "Error. Usage: @adda TYPE name"); return; } try { std::transform(args[1].begin(), args[1].end(), args[1].begin(), ::tolower); } catch (...) { std::cerr << "failed in UtilityCommands @adda to transform to lowercase : " << args[1] << '\n'; return; } IRC::Bot::RELATIONSHIP r = IRC::Bot::RELATIONSHIP::IGNORED; if (args[1] == "admin") { r = IRC::Bot::RELATIONSHIP::ADMIN; } else if (args[1] != "ignore") { // all else except "admin" and "ignore" (case insensitive) p.owner->privmsg(p.sender, "Error. Invalid argument: " + args[1]); return; } bot_ptr->add_a(r , args[2]); p.reply("Added " + args[2] + " to " + args[1] + " list."); } } if (cmd == "@quit") { // quit p.owner->disconnect( p.content.length() > 6 ? p.content.substr(6) : "Quitting..." ); } } }; class RecoveryCommand : public IRC::CommandInterface { public: RecoveryCommand(IRC::Bot *b = nullptr) : CommandInterface("@recover ", "recover the bot with a password.", b) {} void run(const IRC::Packet& p) { std::string password = p.content.substr(this->trigger().length()); if ( bot_ptr->reauthenticate(p.sender, Hash::sha256(password)) ) { p.owner->privmsg(p.sender, "Password accepted! You now have admin rights."); } else { p.owner->privmsg(p.sender, "Denied. Password invalid."); } } }; }; <|endoftext|>
<commit_before>#include "../../IRCBot/include/command-interface.hpp" #include "../../IRCBot/include/bot.hpp" #include "./random-line-stream.hpp" /* for use in BabblerCommand */ #include "./iplookup.hpp" #include "./googler.hpp" #include "./stocks.hpp" #include "./quotes.hpp" #include "./http.hpp" #include "./hash.hpp" #include "./urban.hpp" #include <algorithm> #include <string> #include <vector> namespace Plugins { class GoogleCommand : protected IRC::CommandInterface { unsigned long long times_executed; public: GoogleCommand() /* pointer to owning bot not needed. */ : CommandInterface("@google ", "Performs google search and returns shortened links.", nullptr, true), times_executed(0) {} void run(const IRC::Packet& p) { std::vector<std::string> res_vec; Googler::do_google_search(p.content.substr(this->trigger().length()), 2, res_vec); for (auto& res : res_vec) { p.reply(res); } this->times_executed++; } std::string get_stats(void) { return "GoogleCommand -> Times Executed: " + std::to_string(this->times_executed); } }; class LMGTFYCommand : protected IRC::CommandInterface { public: LMGTFYCommand() : CommandInterface("@lmgtfy ", "mean way to tell ppl to google things.") {} void run(const IRC::Packet& p) { p.reply("http://lmgtfy.com/?q=" + MyHTTP::uri_encode( p.content.substr(this->trigger().length()) ) ); } }; class UrbanCommand : protected IRC::CommandInterface { public: UrbanCommand() : CommandInterface("@urban ", "checks urban dictionary for a definition.") {} void run(const IRC::Packet& p) { std::string def = ""; Urban::get_first_result(p.content.substr(this->trigger_string.length()) , def); if (!def.empty()) { p.reply(def); } } }; class IPLookupCommand : protected IRC::CommandInterface { public: IPLookupCommand() : IRC::CommandInterface("@iplookup ", "looks up IP address.", nullptr, true) {} void run(const IRC::Packet& p) { p.reply(IPLookup::do_lookup(p.content.substr(this->trigger().length()))); } }; class SayHiCommand : protected IRC::CommandInterface { public: SayHiCommand() : IRC::CommandInterface("@sayhi", "says hi.") {} void run(const IRC::Packet& p) { p.reply("Hello!"); } }; class SlapCommand : protected IRC::CommandInterface { public: SlapCommand() : IRC::CommandInterface("@slap ", "slaps arguments.") {} void run(const IRC::Packet& p) { p.reply("\001ACTION slapped the hell outta " + p.content.substr(this->trigger().length()) + "\001"); } }; class SpeakCommand : protected IRC::CommandInterface { public: SpeakCommand() : IRC::CommandInterface("@speak ", "says a message to channel: @speak <chan> <msg...>", nullptr, true) {} void run(const IRC::Packet& p) { std::string arguments = p.content.substr(this->trigger().length()); // everything after "@speak " size_t first_space_idx = arguments.find(" "); if (first_space_idx == std::string::npos) return; std::string chan = arguments.substr(0, first_space_idx); std::string msg = arguments.substr(first_space_idx + 1); p.owner->privmsg( chan , msg ); } }; class BabblerCommand : protected IRC::CommandInterface { RandomLineStream rls; public: BabblerCommand(const std::string& babbles_filepath) : CommandInterface("@babble", "does a babble."), rls(babbles_filepath) {} void run(const IRC::Packet& p) { p.reply(rls.sample()); } }; class StocksCommand : protected IRC::CommandInterface { unsigned long long queries_done; public: StocksCommand() : CommandInterface("@stock ", "checks a stock ticker price."), queries_done(0) {} void run(const IRC::Packet& p) { p.reply(Stocks::get_stock_summary( p.content.substr(this->trigger().length()) )); this->queries_done++; } std::string get_stats(void) { return "Stock Queries Done: " + std::to_string(queries_done); } }; class QuoteCommand : protected IRC::CommandInterface { public: QuoteCommand() : CommandInterface("@quote", "delivers the quote of the day.") {} void run(const IRC::Packet& p) { p.reply(Quotes::get_random_quote()); } }; class EliteCommand : protected IRC::CommandInterface { const std::string reglr = "aeiolgsqtz"; const std::string elite = "4310195972"; public: EliteCommand() : CommandInterface("@1337 ", "translates to and from 13375p34k.") {} void run(const IRC::Packet& p) { std::string sub = p.content.substr(this->trigger_string.length()); std::string msg = sub.substr(sub.find(" ")); sub = sub.substr(0, sub.find(" ")); if (sub == "from1337") { for (auto& e : msg) { for (size_t i = 0; i < elite.length(); ++i) { if (std::tolower(e) == elite[i]) e = reglr[i]; } } } else { for (auto& e : msg) { for (size_t i = 0; i < reglr.length(); ++i) { if (std::tolower(e) == reglr[i]) e = elite[i]; } } } p.reply(msg); } }; class UtilityCommands : protected IRC::CommandInterface { public: UtilityCommands(IRC::Bot *b = nullptr) : IRC::CommandInterface("@kick,@join,@part,@quit,@nick,@adda", "does utility actions", b, true) { if (b == nullptr) { throw std::logic_error("In UtilityCommands, Bot *b cannot be nullptr!"); } } bool triggered(const IRC::Packet& p) { std::string cmd = p.content.substr(0,5); return p.type == IRC::Packet::PacketType::PRIVMSG && ( cmd == "@kick" || cmd == "@join" || cmd == "@part" || cmd == "@quit" || cmd == "@nick" || cmd == "@adda"); } void run(const IRC::Packet& p) { std::string cmd = p.content.substr(0,5); if (p.content.length() > 5) { if ( cmd == "@kick" ) { p.owner->kick(p.channel, p.content.substr(6)); } else if ( cmd == "@join" ) { p.owner->join_channel( p.content.substr(6 , p.content.find(" ", 6) - 6) ); } else if ( cmd == "@part" ) { p.owner->part_channel( p.content.substr(6) ); } else if ( cmd == "@nick" ) { p.owner->set_nick( p.content.substr(6) ); } else if ( cmd == "@adda" ) { std::vector<std::string> args; p.get_args(args); if (args.size() < 3) { p.owner->privmsg(p.sender, "Error. Usage: @adda TYPE name"); return; } try { std::transform(args[1].begin(), args[1].end(), args[1].begin(), ::tolower); } catch (...) { std::cerr << "failed in UtilityCommands @adda to transform to lowercase : " << args[1] << '\n'; return; } IRC::Bot::RELATIONSHIP r = IRC::Bot::RELATIONSHIP::IGNORED; if (args[1] == "admin") { r = IRC::Bot::RELATIONSHIP::ADMIN; } else if (args[1] != "ignore") { // all else except "admin" and "ignore" (case insensitive) p.owner->privmsg(p.sender, "Error. Invalid argument: " + args[1]); return; } bot_ptr->add_a(r , args[2]); p.reply("Added " + args[2] + " to " + args[1] + " list."); } } if (cmd == "@quit") { // quit p.owner->disconnect( p.content.length() > 6 ? p.content.substr(6) : "Quitting..." ); } } }; class RecoveryCommand : public IRC::CommandInterface { public: RecoveryCommand(IRC::Bot *b = nullptr) : CommandInterface("@recover ", "recover the bot with a password.", b) {} void run(const IRC::Packet& p) { std::string password = p.content.substr(this->trigger().length()); if ( bot_ptr->reauthenticate(p.sender, Hash::sha256(password)) ) { p.owner->privmsg(p.sender, "Password accepted! You now have admin rights."); } else { p.owner->privmsg(p.sender, "Denied. Password invalid."); } } }; }; <commit_msg>fix a bug<commit_after>#include "../../IRCBot/include/command-interface.hpp" #include "../../IRCBot/include/bot.hpp" #include "./random-line-stream.hpp" /* for use in BabblerCommand */ #include "./iplookup.hpp" #include "./googler.hpp" #include "./stocks.hpp" #include "./quotes.hpp" #include "./http.hpp" #include "./hash.hpp" #include "./urban.hpp" #include <algorithm> #include <string> #include <vector> namespace Plugins { class GoogleCommand : protected IRC::CommandInterface { unsigned long long times_executed; public: GoogleCommand() /* pointer to owning bot not needed. */ : CommandInterface("@google ", "Performs google search and returns shortened links.", nullptr, true), times_executed(0) {} void run(const IRC::Packet& p) { std::vector<std::string> res_vec; Googler::do_google_search(p.content.substr(this->trigger().length()), 2, res_vec); for (auto& res : res_vec) { p.reply(res); } this->times_executed++; } std::string get_stats(void) { return "GoogleCommand -> Times Executed: " + std::to_string(this->times_executed); } }; class LMGTFYCommand : protected IRC::CommandInterface { public: LMGTFYCommand() : CommandInterface("@lmgtfy ", "mean way to tell ppl to google things.") {} void run(const IRC::Packet& p) { p.reply("http://lmgtfy.com/?q=" + MyHTTP::uri_encode( p.content.substr(this->trigger().length()) ) ); } }; class UrbanCommand : protected IRC::CommandInterface { public: UrbanCommand() : CommandInterface("@urban ", "checks urban dictionary for a definition.") {} void run(const IRC::Packet& p) { std::string def = ""; Urban::get_first_result(p.content.substr(this->trigger_string.length()) , def); if (!def.empty()) { p.reply(def); } } }; class IPLookupCommand : protected IRC::CommandInterface { public: IPLookupCommand() : IRC::CommandInterface("@iplookup ", "looks up IP address.", nullptr, true) {} void run(const IRC::Packet& p) { p.reply(IPLookup::do_lookup(p.content.substr(this->trigger().length()))); } }; class SayHiCommand : protected IRC::CommandInterface { public: SayHiCommand() : IRC::CommandInterface("@sayhi", "says hi.") {} void run(const IRC::Packet& p) { p.reply("Hello!"); } }; class SlapCommand : protected IRC::CommandInterface { public: SlapCommand() : IRC::CommandInterface("@slap ", "slaps arguments.") {} void run(const IRC::Packet& p) { p.reply("\001ACTION slapped the hell outta " + p.content.substr(this->trigger().length()) + "\001"); } }; class SpeakCommand : protected IRC::CommandInterface { public: SpeakCommand() : IRC::CommandInterface("@speak ", "says a message to channel: @speak <chan> <msg...>", nullptr, true) {} void run(const IRC::Packet& p) { std::string arguments = p.content.substr(this->trigger().length()); // everything after "@speak " size_t first_space_idx = arguments.find(" "); if (first_space_idx == std::string::npos) return; std::string chan = arguments.substr(0, first_space_idx); std::string msg = arguments.substr(first_space_idx + 1); p.owner->privmsg( chan , msg ); } }; class BabblerCommand : protected IRC::CommandInterface { RandomLineStream rls; public: BabblerCommand(const std::string& babbles_filepath) : CommandInterface("@babble", "does a babble."), rls(babbles_filepath) {} void run(const IRC::Packet& p) { p.reply(rls.sample()); } }; class StocksCommand : protected IRC::CommandInterface { unsigned long long queries_done; public: StocksCommand() : CommandInterface("@stock ", "checks a stock ticker price."), queries_done(0) {} void run(const IRC::Packet& p) { p.reply(Stocks::get_stock_summary( p.content.substr(this->trigger().length()) )); this->queries_done++; } std::string get_stats(void) { return "Stock Queries Done: " + std::to_string(queries_done); } }; class QuoteCommand : protected IRC::CommandInterface { public: QuoteCommand() : CommandInterface("@quote", "delivers the quote of the day.") {} void run(const IRC::Packet& p) { p.reply(Quotes::get_random_quote()); } }; class EliteCommand : protected IRC::CommandInterface { const std::string reglr = "aeiolgsqtz"; const std::string elite = "4310195972"; public: EliteCommand() : CommandInterface("@1337 ", "translates to and from 13375p34k.") {} void run(const IRC::Packet& p) { std::string sub = p.content.substr(this->trigger_string.length()); std::string msg = ""; try { msg = sub.substr(sub.find(" ")); } catch (std::exception& e) { std::cerr << "EliteCommand::run() error: " << e.what() << '\n'; p.reply("Error. Usage: @1337 [to1337 | from1337] [message...]"); } sub = sub.substr(0, sub.find(" ")); if (sub == "from1337") { for (auto& e : msg) { for (size_t i = 0; i < elite.length(); ++i) { if (std::tolower(e) == elite[i]) e = reglr[i]; } } } else { for (auto& e : msg) { for (size_t i = 0; i < reglr.length(); ++i) { if (std::tolower(e) == reglr[i]) e = elite[i]; } } } p.reply(msg); } }; class UtilityCommands : protected IRC::CommandInterface { public: UtilityCommands(IRC::Bot *b = nullptr) : IRC::CommandInterface("@kick,@join,@part,@quit,@nick,@adda", "does utility actions", b, true) { if (b == nullptr) { throw std::logic_error("In UtilityCommands, Bot *b cannot be nullptr!"); } } bool triggered(const IRC::Packet& p) { std::string cmd = p.content.substr(0,5); return p.type == IRC::Packet::PacketType::PRIVMSG && ( cmd == "@kick" || cmd == "@join" || cmd == "@part" || cmd == "@quit" || cmd == "@nick" || cmd == "@adda"); } void run(const IRC::Packet& p) { std::string cmd = p.content.substr(0,5); if (p.content.length() > 5) { if ( cmd == "@kick" ) { p.owner->kick(p.channel, p.content.substr(6)); } else if ( cmd == "@join" ) { p.owner->join_channel( p.content.substr(6 , p.content.find(" ", 6) - 6) ); } else if ( cmd == "@part" ) { p.owner->part_channel( p.content.substr(6) ); } else if ( cmd == "@nick" ) { p.owner->set_nick( p.content.substr(6) ); } else if ( cmd == "@adda" ) { std::vector<std::string> args; p.get_args(args); if (args.size() < 3) { p.owner->privmsg(p.sender, "Error. Usage: @adda TYPE name"); return; } try { std::transform(args[1].begin(), args[1].end(), args[1].begin(), ::tolower); } catch (...) { std::cerr << "failed in UtilityCommands @adda to transform to lowercase : " << args[1] << '\n'; return; } IRC::Bot::RELATIONSHIP r = IRC::Bot::RELATIONSHIP::IGNORED; if (args[1] == "admin") { r = IRC::Bot::RELATIONSHIP::ADMIN; } else if (args[1] != "ignore") { // all else except "admin" and "ignore" (case insensitive) p.owner->privmsg(p.sender, "Error. Invalid argument: " + args[1]); return; } bot_ptr->add_a(r , args[2]); p.reply("Added " + args[2] + " to " + args[1] + " list."); } } if (cmd == "@quit") { // quit p.owner->disconnect( p.content.length() > 6 ? p.content.substr(6) : "Quitting..." ); } } }; class RecoveryCommand : public IRC::CommandInterface { public: RecoveryCommand(IRC::Bot *b = nullptr) : CommandInterface("@recover ", "recover the bot with a password.", b) {} void run(const IRC::Packet& p) { std::string password = p.content.substr(this->trigger().length()); if ( bot_ptr->reauthenticate(p.sender, Hash::sha256(password)) ) { p.owner->privmsg(p.sender, "Password accepted! You now have admin rights."); } else { p.owner->privmsg(p.sender, "Denied. Password invalid."); } } }; }; <|endoftext|>
<commit_before><commit_msg>WaE: ordered comparison of pointer with integer zero<commit_after><|endoftext|>
<commit_before>#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> using namespace std; template <typename T> class stack { public: stack(); stack(stack const &); ~stack(); size_t count() const; auto push(T const &) -> void; auto copy_(T * item, size_t size, size_t count) -> T*; T pop(); auto operator=(stack const & right)->stack &; private: T * array_; size_t array_size_; size_t count_; }; int main() { stack<int> a; a.push(1); a.push(2); a.push(3); stack<int> b; b.push(2); a = b; system("pause"); } template <typename T> size_t stack<T>::count() const { return count_; } template <typename T> stack<T>::stack() { array_size_ = 0; array_ = new T[array_size_]; count_ = 0; } template<typename T> stack<T>::stack(stack const & item) { array_size_ = item.array_size_; count_ = item.count_; delete[] array_; array_ = copy_(array_, array_size_, array_size_);; } template <typename T> stack<T>::~stack() { delete[] array_; } template<typename T> auto stack<T>::push(T const & item) -> void { if (count_ == array_size_) { size_t size = array_size_ * 2 + (array_size_ == 0) ; delete[] array_; array_ = copy_(array_, size, array_size_); array_size_ = size; } ++count_; array_[count_ - 1] = item; } template<typename T> auto stack<T>::copy_(T * item, size_t size, size_t count) -> T* { T * buff = new T[size]; copy(item, item + count, buff); return buff; } template<typename T> T stack<T>::pop() { if (count_ == 0) { throw std::logic_error("Stack is empty!"); } return array_[--count_]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { delete[] array_; count_ = right.count_; array_size_ = right.array_size_; copy_(right.array_, array_size_, count_); } return *this; } #endif <commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> using namespace std; template <typename T> class stack { public: stack(); stack(stack const &); ~stack(); size_t count() const; auto push(T const &) -> void; auto copy_(T * item, size_t size, size_t count) -> T*; T pop(); auto operator=(stack const & right)->stack &; private: T * array_; size_t array_size_; size_t count_; }; template <typename T> size_t stack<T>::count() const { return count_; } template <typename T> stack<T>::stack() { array_size_ = 0; array_ = new T[array_size_]; count_ = 0; } template<typename T> stack<T>::stack(stack const & item) { array_size_ = item.array_size_; count_ = item.count_; delete[] array_; array_ = copy_(array_, array_size_, array_size_);; } template <typename T> stack<T>::~stack() { delete[] array_; } template<typename T> auto stack<T>::push(T const & item) -> void { if (count_ == array_size_) { size_t size = array_size_ * 2 + (array_size_ == 0) ; delete[] array_; array_ = copy_(array_, size, array_size_); array_size_ = size; } ++count_; array_[count_ - 1] = item; } template<typename T> auto stack<T>::copy_(T * item, size_t size, size_t count) -> T* { T * buff = new T[size]; copy(item, item + count, buff); return buff; } template<typename T> T stack<T>::pop() { if (count_ == 0) { throw std::logic_error("Stack is empty!"); } return array_[--count_]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { delete[] array_; count_ = right.count_; array_size_ = right.array_size_; copy_(right.array_, array_size_, count_); } return *this; } #endif <|endoftext|>
<commit_before>#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> template <typename T1, typename T2> void construct(T1 * ptr, T2 const & value) { new(ptr) T1 (value); } template <typename T> void destroy(T * ptr) noexcept { ptr->~T(); } template <typename FwdIter> void destroy(FwdIter first, FwdIter last) noexcept { for (; first != last; ++first) { destroy(&*first); } } template <typename T> class allocator { protected: allocator(size_t size = 0); ~allocator(); auto swap(allocator & other) -> void; allocator(allocator const &) = delete; auto operator =(allocator const &) -> allocator & = delete; T * ptr_; size_t size_; size_t count_; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), count_(0){}; template<typename T> allocator<T>::~allocator(){ operator delete(ptr_); } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(count_, other.count_); std::swap(size_, other.size_); } template <typename T> class stack : private allocator<T> { public: stack(size_t size = 0 ); //noexcept stack(stack const &); //strong ~stack(); //noexcept size_t count() const; //noexcept auto push(T const &) -> void; //strong void pop(); //strong const T& top(); //strong auto operator=(stack const & right)->stack &; //strong auto empty() const -> bool; //noexcept }; template <typename T> size_t stack<T>::count() const { return allocator<T>::count_; } template <typename T> stack<T>::stack(size_t size):allocator<T>(size){} template <typename T> stack<T>::stack(const stack& item) : allocator<T>(item.size_){ for (size_t i = 0; i < item.count_; i++) construct(allocator<T>::ptr_ + i, item.ptr_[i]); allocator<T>::count_ = item.count_; }; template <typename T> stack<T>::~stack() { destroy(allocator<T>::ptr_, allocator<T>::ptr_ + allocator<T>::count_); } template <typename T> void stack<T>::push(T const &item){ if (allocator<T>::count_ == allocator<T>::size_) { size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]); this->swap(temp); } construct(allocator<T>::ptr_ + allocator<T>::count_, item); ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator<T>::count_> 0) { --allocator<T>::count_; } else throw ("Stack is empty"); } template<typename T> const T& stack<T>::top() { if (allocator<T>::count_ == 0) { throw ("Stack is empty!"); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { stack<T> temp (right.size_); while (temp.count_ < right.count_){ construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]); ++temp.count_; } this -> swap(temp); } return *this; } template<typename T> auto stack<T>::empty() const -> bool{ if (allocator<T>::count_ == 0){ return true; } else{ return false; } } #endif <commit_msg>Update stack.hpp<commit_after>#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> template <typename T1, typename T2> void construct(T1 * ptr, T2 const & value) { new(ptr) T1 (value); } template <typename T> void destroy(T * ptr) noexcept { ptr->~T(); } template <typename FwdIter> void destroy(FwdIter first, FwdIter last) noexcept { for (; first != last; ++first) { destroy(&*first); } } class bitset { public: explicit bitset( size_t size ) /*strong*/; bitset( bitset const & other ) = delete; auto operator =( bitset const & other ) -> bitset & = delete; bitset( bitset && other ) = delete; auto operator =( bitset && other ) -> bitset & = delete; auto set( size_t index ) /*strong*/ -> void; auto reset( size_t index ) /*strong*/ -> void; auto test( size_t index ) /*strong*/ -> bool; auto size() /*noexcept*/ -> size_t; auto counter() /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; template <typename T> class allocator { public: explicit allocator( std::size_t size = 0 ) /*strong*/; allocator( allocator const & other ) /*strong*/; auto operator =( allocator const & other ) -> allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value ) /*strong*/ -> void; auto destroy( T * ptr ) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; private: auto destroy( T * first, T * last ) /*noexcept*/ -> void; auto swap( allocator & other ) /*noexcept*/ -> void; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template <typename T> class stack { public: explicit stack( size_t size = 0 ); auto operator =( stack const & other ) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push( T const & value ) /*strong*/ -> void; auto pop() /*strong*/ -> void; auto top() /*strong*/ -> T &; auto top() const /*strong*/ -> T const &; private: allocator<T> allocator_; auto throw_is_empty() const -> void; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), count_(0){}; template<typename T> allocator<T>::~allocator(){ operator delete(ptr_); } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(count_, other.count_); std::swap(size_, other.size_); } template <typename T> size_t stack<T>::count() const { return allocator<T>::count_; } template <typename T> stack<T>::stack(size_t size):allocator<T>(size){} template <typename T> stack<T>::stack(const stack& item) : allocator<T>(item.size_){ for (size_t i = 0; i < item.count_; i++) construct(allocator<T>::ptr_ + i, item.ptr_[i]); allocator<T>::count_ = item.count_; }; template <typename T> stack<T>::~stack() { destroy(allocator<T>::ptr_, allocator<T>::ptr_ + allocator<T>::count_); } template <typename T> void stack<T>::push(T const &item){ if (allocator<T>::count_ == allocator<T>::size_) { size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]); this->swap(temp); } construct(allocator<T>::ptr_ + allocator<T>::count_, item); ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator<T>::count_> 0) { --allocator<T>::count_; } else throw ("Stack is empty"); } template<typename T> const T& stack<T>::top() { if (allocator<T>::count_ == 0) { throw ("Stack is empty!"); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { stack<T> temp (right.size_); while (temp.count_ < right.count_){ construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]); ++temp.count_; } this -> swap(temp); } return *this; } template<typename T> auto stack<T>::empty() const -> bool{ if (allocator<T>::count_ == 0){ return true; } else{ return false; } } #endif <|endoftext|>
<commit_before>/*************************************************************************/ /* ip_unix.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 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 "ip_unix.h" #if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED) #include <string.h> #ifdef WINDOWS_ENABLED #include <stdio.h> #include <winsock2.h> // Needs to be included after winsocks2.h #include <windows.h> #include <ws2tcpip.h> #ifndef UWP_ENABLED #if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4) // MinGW-w64 on Ubuntu 12.04 (our Travis build env) has bugs in this code where // some includes are missing in dependencies of iphlpapi.h for WINVER >= 0x0600 (Vista). // We don't use this Vista code for now, so working it around by disabling it. // MinGW-w64 >= 4.0 seems to be better judging by its headers. #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // Windows XP, disable Vista API #include <iphlpapi.h> #undef _WIN32_WINNT #define _WIN32_WINNT 0x0600 // Reenable Vista API #else #include <iphlpapi.h> #endif // MINGW hack #endif #else #include <netdb.h> #ifdef ANDROID_ENABLED #include "platform/android/ifaddrs_android.h" #else #ifdef __FreeBSD__ #include <sys/types.h> #endif #include <ifaddrs.h> #endif #include <arpa/inet.h> #include <sys/socket.h> #ifdef __FreeBSD__ #include <netinet/in.h> #endif #endif static IP_Address _sockaddr2ip(struct sockaddr *p_addr) { IP_Address ip; if (p_addr->sa_family == AF_INET) { struct sockaddr_in *addr = (struct sockaddr_in *)p_addr; ip.set_ipv4((uint8_t *)&(addr->sin_addr)); } else if (p_addr->sa_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr; ip.set_ipv6(addr6->sin6_addr.s6_addr); }; return ip; }; IP_Address IP_Unix::_resolve_hostname(const String &p_hostname, Type p_type) { struct addrinfo hints; struct addrinfo *result; memset(&hints, 0, sizeof(struct addrinfo)); if (p_type == TYPE_IPV4) { hints.ai_family = AF_INET; } else if (p_type == TYPE_IPV6) { hints.ai_family = AF_INET6; hints.ai_flags = 0; } else { hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_ADDRCONFIG; }; int s = getaddrinfo(p_hostname.utf8().get_data(), NULL, &hints, &result); if (s != 0) { ERR_PRINT("getaddrinfo failed!"); return IP_Address(); }; if (result == NULL || result->ai_addr == NULL) { ERR_PRINT("Invalid response from getaddrinfo"); return IP_Address(); }; IP_Address ip = _sockaddr2ip(result->ai_addr); freeaddrinfo(result); return ip; } #if defined(WINDOWS_ENABLED) #if defined(UWP_ENABLED) void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const { using namespace Windows::Networking; using namespace Windows::Networking::Connectivity; auto hostnames = NetworkInformation::GetHostNames(); for (int i = 0; i < hostnames->Size; i++) { if (hostnames->GetAt(i)->Type == HostNameType::Ipv4 || hostnames->GetAt(i)->Type == HostNameType::Ipv6 && hostnames->GetAt(i)->IPInformation != nullptr) { r_addresses->push_back(IP_Address(String(hostnames->GetAt(i)->CanonicalName->Data()))); } } }; #else void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const { ULONG buf_size = 1024; IP_ADAPTER_ADDRESSES *addrs; while (true) { addrs = (IP_ADAPTER_ADDRESSES *)memalloc(buf_size); int err = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, addrs, &buf_size); if (err == NO_ERROR) { break; }; memfree(addrs); if (err == ERROR_BUFFER_OVERFLOW) { continue; // will go back and alloc the right size }; ERR_EXPLAIN("Call to GetAdaptersAddresses failed with error " + itos(err)); ERR_FAIL(); return; }; IP_ADAPTER_ADDRESSES *adapter = addrs; while (adapter != NULL) { IP_ADAPTER_UNICAST_ADDRESS *address = adapter->FirstUnicastAddress; while (address != NULL) { IP_Address ip; if (address->Address.lpSockaddr->sa_family == AF_INET) { SOCKADDR_IN *ipv4 = reinterpret_cast<SOCKADDR_IN *>(address->Address.lpSockaddr); ip.set_ipv4((uint8_t *)&(ipv4->sin_addr)); r_addresses->push_back(ip); } else if (address->Address.lpSockaddr->sa_family == AF_INET6) { // ipv6 SOCKADDR_IN6 *ipv6 = reinterpret_cast<SOCKADDR_IN6 *>(address->Address.lpSockaddr); ip.set_ipv6(ipv6->sin6_addr.s6_addr); r_addresses->push_back(ip); }; address = address->Next; }; adapter = adapter->Next; }; memfree(addrs); }; #endif #else void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const { struct ifaddrs *ifAddrStruct = NULL; struct ifaddrs *ifa = NULL; int family; getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) continue; family = ifa->ifa_addr->sa_family; if (family != AF_INET && family != AF_INET6) continue; IP_Address ip = _sockaddr2ip(ifa->ifa_addr); r_addresses->push_back(ip); } if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct); } #endif void IP_Unix::make_default() { _create = _create_unix; } IP *IP_Unix::_create_unix() { return memnew(IP_Unix); } IP_Unix::IP_Unix() { } #endif <commit_msg>Explicitily unsed AI_NUMERICHOST flag to fix HTML5<commit_after>/*************************************************************************/ /* ip_unix.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 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 "ip_unix.h" #if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED) #include <string.h> #ifdef WINDOWS_ENABLED #include <stdio.h> #include <winsock2.h> // Needs to be included after winsocks2.h #include <windows.h> #include <ws2tcpip.h> #ifndef UWP_ENABLED #if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4) // MinGW-w64 on Ubuntu 12.04 (our Travis build env) has bugs in this code where // some includes are missing in dependencies of iphlpapi.h for WINVER >= 0x0600 (Vista). // We don't use this Vista code for now, so working it around by disabling it. // MinGW-w64 >= 4.0 seems to be better judging by its headers. #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // Windows XP, disable Vista API #include <iphlpapi.h> #undef _WIN32_WINNT #define _WIN32_WINNT 0x0600 // Reenable Vista API #else #include <iphlpapi.h> #endif // MINGW hack #endif #else #include <netdb.h> #ifdef ANDROID_ENABLED #include "platform/android/ifaddrs_android.h" #else #ifdef __FreeBSD__ #include <sys/types.h> #endif #include <ifaddrs.h> #endif #include <arpa/inet.h> #include <sys/socket.h> #ifdef __FreeBSD__ #include <netinet/in.h> #endif #endif static IP_Address _sockaddr2ip(struct sockaddr *p_addr) { IP_Address ip; if (p_addr->sa_family == AF_INET) { struct sockaddr_in *addr = (struct sockaddr_in *)p_addr; ip.set_ipv4((uint8_t *)&(addr->sin_addr)); } else if (p_addr->sa_family == AF_INET6) { struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr; ip.set_ipv6(addr6->sin6_addr.s6_addr); }; return ip; }; IP_Address IP_Unix::_resolve_hostname(const String &p_hostname, Type p_type) { struct addrinfo hints; struct addrinfo *result; memset(&hints, 0, sizeof(struct addrinfo)); if (p_type == TYPE_IPV4) { hints.ai_family = AF_INET; } else if (p_type == TYPE_IPV6) { hints.ai_family = AF_INET6; hints.ai_flags = 0; } else { hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_ADDRCONFIG; }; hints.ai_flags &= !AI_NUMERICHOST; int s = getaddrinfo(p_hostname.utf8().get_data(), NULL, &hints, &result); if (s != 0) { ERR_PRINT("getaddrinfo failed!"); return IP_Address(); }; if (result == NULL || result->ai_addr == NULL) { ERR_PRINT("Invalid response from getaddrinfo"); return IP_Address(); }; IP_Address ip = _sockaddr2ip(result->ai_addr); freeaddrinfo(result); return ip; } #if defined(WINDOWS_ENABLED) #if defined(UWP_ENABLED) void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const { using namespace Windows::Networking; using namespace Windows::Networking::Connectivity; auto hostnames = NetworkInformation::GetHostNames(); for (int i = 0; i < hostnames->Size; i++) { if (hostnames->GetAt(i)->Type == HostNameType::Ipv4 || hostnames->GetAt(i)->Type == HostNameType::Ipv6 && hostnames->GetAt(i)->IPInformation != nullptr) { r_addresses->push_back(IP_Address(String(hostnames->GetAt(i)->CanonicalName->Data()))); } } }; #else void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const { ULONG buf_size = 1024; IP_ADAPTER_ADDRESSES *addrs; while (true) { addrs = (IP_ADAPTER_ADDRESSES *)memalloc(buf_size); int err = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, addrs, &buf_size); if (err == NO_ERROR) { break; }; memfree(addrs); if (err == ERROR_BUFFER_OVERFLOW) { continue; // will go back and alloc the right size }; ERR_EXPLAIN("Call to GetAdaptersAddresses failed with error " + itos(err)); ERR_FAIL(); return; }; IP_ADAPTER_ADDRESSES *adapter = addrs; while (adapter != NULL) { IP_ADAPTER_UNICAST_ADDRESS *address = adapter->FirstUnicastAddress; while (address != NULL) { IP_Address ip; if (address->Address.lpSockaddr->sa_family == AF_INET) { SOCKADDR_IN *ipv4 = reinterpret_cast<SOCKADDR_IN *>(address->Address.lpSockaddr); ip.set_ipv4((uint8_t *)&(ipv4->sin_addr)); r_addresses->push_back(ip); } else if (address->Address.lpSockaddr->sa_family == AF_INET6) { // ipv6 SOCKADDR_IN6 *ipv6 = reinterpret_cast<SOCKADDR_IN6 *>(address->Address.lpSockaddr); ip.set_ipv6(ipv6->sin6_addr.s6_addr); r_addresses->push_back(ip); }; address = address->Next; }; adapter = adapter->Next; }; memfree(addrs); }; #endif #else void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const { struct ifaddrs *ifAddrStruct = NULL; struct ifaddrs *ifa = NULL; int family; getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) continue; family = ifa->ifa_addr->sa_family; if (family != AF_INET && family != AF_INET6) continue; IP_Address ip = _sockaddr2ip(ifa->ifa_addr); r_addresses->push_back(ip); } if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct); } #endif void IP_Unix::make_default() { _create = _create_unix; } IP *IP_Unix::_create_unix() { return memnew(IP_Unix); } IP_Unix::IP_Unix() { } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: vlMath.hh Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ // // Class for performing common math operations (e.g., dot, cross products) // #ifndef __vlMath_hh #define __vlMath_hh #include <math.h> class vlMath { public: vlMath() {}; float Pi() {return 3.14159265358979;}; float DegreesToRadians() {return 0.018977369;}; float Dot(float x[3], float y[3]) {return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];}; void Cross(float x[3], float y[3], float z[3]) {z[0] = x[1]*y[2] - x[2]*y[1]; z[1] = x[2]*y[0] - x[0]*y[2]; z[2] = x[0]*y[1] - x[1]*y[0];}; float Norm(float x[3]) {return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);}; float Determinate3x3(float *c1, float *c2, float *c3) {return c1[0]*c2[1]*c3[2] + c2[0]*c3[1]*c1[2] + c3[0]*c1[1]*c2[2] - c1[0]*c3[1]*c2[2] - c2[0]*c1[1]*c3[2] - c3[0]*c2[1]*c1[2];}; float Determinate2x2(float *c1, float *c2) {return c1[0]*c2[1] - c2[0]*c1[1];}; float Distance2BetweenPoints(float *x, float *y) {return (x[0]-y[0])*(x[0]-y[0]) + (x[1]-y[1])*(x[1]-y[1]) + (x[2]-y[2])*(x[2]-y[2]);}; void RandomSeed(long s); float Random(); float Random(float min, float max) {return min+Random()*(max-min);}; protected: static long Seed; }; #endif <commit_msg>*** empty log message ***<commit_after>/*========================================================================= Program: Visualization Library Module: vlMath.hh Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ // // Class for performing common math operations (e.g., dot, cross products) // #ifndef __vlMath_hh #define __vlMath_hh #include <math.h> class vlMath { public: vlMath() {}; float Pi() {return 3.14159265358979;}; float DegreesToRadians() {return 0.018977369;}; float Dot(float x[3], float y[3]) {return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];}; void Cross(float x[3], float y[3], float z[3]) {z[0] = x[1]*y[2] - x[2]*y[1]; z[1] = x[2]*y[0] - x[0]*y[2]; z[2] = x[0]*y[1] - x[1]*y[0];}; float Norm(float x[3]) {return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);}; void Normalize(float x[3]) {float den; int i; if ( (den = this->Norm(x)) != 0.0 ) for (i=0; i < 3; i++) x[i] /= den; } float Determinate3x3(float *c1, float *c2, float *c3) {return c1[0]*c2[1]*c3[2] + c2[0]*c3[1]*c1[2] + c3[0]*c1[1]*c2[2] - c1[0]*c3[1]*c2[2] - c2[0]*c1[1]*c3[2] - c3[0]*c2[1]*c1[2];}; float Determinate2x2(float *c1, float *c2) {return c1[0]*c2[1] - c2[0]*c1[1];}; float Distance2BetweenPoints(float *x, float *y) {return (x[0]-y[0])*(x[0]-y[0]) + (x[1]-y[1])*(x[1]-y[1]) + (x[2]-y[2])*(x[2]-y[2]);}; void RandomSeed(long s); float Random(); float Random(float min, float max) {return min+Random()*(max-min);}; protected: static long Seed; }; #endif <|endoftext|>
<commit_before>#include "objparser.hpp" #include "../src/meshoptimizer.hpp" #include <algorithm> #define NOMINMAX #include <windows.h> #include <GL/gl.h> #pragma comment(lib, "opengl32.lib") struct Options { bool wireframe; enum { Mode_Default, Mode_Texture, Mode_Normals } mode; }; struct Vertex { float px, py, pz; float nx, ny, nz; float tx, ty; }; struct Mesh { std::vector<Vertex> vertices; std::vector<unsigned int> indices; }; static Mesh parseObj(const char* path) { ObjFile file; if (!objParseFile(file, path) || !objValidate(file)) { printf("Error loading %s\n", path); return Mesh(); } objTriangulate(file); size_t total_indices = file.f.size() / 3; std::vector<Vertex> vertices; vertices.reserve(total_indices); for (size_t i = 0; i < file.f.size(); i += 3) { int vi = file.f[i + 0]; int vti = file.f[i + 1]; int vni = file.f[i + 2]; Vertex v = { file.v[vi * 3 + 0], file.v[vi * 3 + 1], file.v[vi * 3 + 2], vni >= 0 ? file.vn[vni * 3 + 0] : 0, vni >= 0 ? file.vn[vni * 3 + 1] : 0, vni >= 0 ? file.vn[vni * 3 + 2] : 0, vti >= 0 ? file.vt[vti * 3 + 0] : 0, vti >= 0 ? file.vt[vti * 3 + 1] : 0, }; vertices.push_back(v); } Mesh result; result.indices.resize(total_indices); size_t total_vertices = generateIndexBuffer(&result.indices[0], &vertices[0], total_indices, sizeof(Vertex)); result.vertices.resize(total_vertices); generateVertexBuffer(&result.vertices[0], &result.indices[0], &vertices[0], total_indices, sizeof(Vertex)); return result; } Mesh optimize(const Mesh& mesh, int lod) { return mesh; } void display(int width, int height, const Mesh& mesh, const Options& options) { glViewport(0, 0, width, height); glClearDepth(1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); glPolygonMode(GL_FRONT_AND_BACK, options.wireframe ? GL_LINE : GL_FILL); float centerx = 0; float centery = 0; float centerz = 0; for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; centerx += v.px; centery += v.py; centerz += v.pz; } centerx /= float(mesh.vertices.size()); centery /= float(mesh.vertices.size()); centerz /= float(mesh.vertices.size()); float extent = 0; for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; extent = std::max(extent, fabsf(v.px - centerx)); extent = std::max(extent, fabsf(v.py - centery)); extent = std::max(extent, fabsf(v.pz - centerz)); } extent *= 1.1f; float scalex = width > height ? float(height) / float(width) : 1; float scaley = height > width ? float(width) / float(height) : 1; glBegin(GL_TRIANGLES); for (size_t i = 0; i < mesh.indices.size(); ++i) { const Vertex& v = mesh.vertices[mesh.indices[i]]; switch (options.mode) { case Options::Mode_Texture: glColor3f(v.tx - floorf(v.tx), v.ty - floorf(v.ty), 0.5f); break; case Options::Mode_Normals: glColor3f(v.nx * 0.5f + 0.5f, v.ny * 0.5f + 0.5f, v.nz * 0.5f + 0.5f); break; default: float intensity = -(v.pz - centerz) / extent * 0.5f + 0.5f; glColor3f(intensity, intensity, intensity); } glVertex3f((v.px - centerx) / extent * scalex, (v.py - centery) / extent * scaley, (v.pz - centerz) / extent); } glEnd(); } void stats(HWND hWnd, const char* path, const Mesh& mesh) { char title[256]; sprintf(title, "%s: %d triangles", path, int(mesh.indices.size() / 3)); SetWindowTextA(hWnd, title); } int main(int argc, char** argv) { if (argc <= 1) { printf("Usage: %s [.obj file]\n", argv[0]); return 0; } HWND hWnd = CreateWindow(L"ListBox", L"Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL); HDC hDC = GetDC(hWnd); PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, 0, 32 }; pfd.cDepthBits = 24; SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd); wglMakeCurrent(hDC, wglCreateContext(hDC)); ShowWindow(hWnd, SW_SHOWNORMAL); const char* path = argv[1]; Mesh basemesh = parseObj(path); Options options = {}; stats(hWnd, path, basemesh); Mesh mesh = basemesh; MSG msg; while (GetMessage(&msg, hWnd, 0, 0) && msg.message) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_KEYDOWN) { if (msg.wParam == 'W') { options.wireframe = !options.wireframe; } else if (msg.wParam == 'T') { options.mode = options.mode == Options::Mode_Texture ? Options::Mode_Default : Options::Mode_Texture; } else if (msg.wParam == 'N') { options.mode = options.mode == Options::Mode_Normals ? Options::Mode_Default : Options::Mode_Normals; } else if (msg.wParam == '0') { mesh = basemesh; stats(hWnd, path, mesh); } else if (msg.wParam >= '1' && msg.wParam <= '9') { mesh = optimize(basemesh, msg.wParam - '0'); stats(hWnd, path, mesh); } } RECT rect; GetClientRect(hWnd, &rect); display(rect.right - rect.left, rect.bottom - rect.top, mesh, options); SwapBuffers(hDC); } } <commit_msg>demo: Show LOD in the title<commit_after>#include "objparser.hpp" #include "../src/meshoptimizer.hpp" #include <algorithm> #define NOMINMAX #include <windows.h> #include <GL/gl.h> #pragma comment(lib, "opengl32.lib") struct Options { bool wireframe; enum { Mode_Default, Mode_Texture, Mode_Normals } mode; }; struct Vertex { float px, py, pz; float nx, ny, nz; float tx, ty; }; struct Mesh { std::vector<Vertex> vertices; std::vector<unsigned int> indices; }; static Mesh parseObj(const char* path) { ObjFile file; if (!objParseFile(file, path) || !objValidate(file)) { printf("Error loading %s\n", path); return Mesh(); } objTriangulate(file); size_t total_indices = file.f.size() / 3; std::vector<Vertex> vertices; vertices.reserve(total_indices); for (size_t i = 0; i < file.f.size(); i += 3) { int vi = file.f[i + 0]; int vti = file.f[i + 1]; int vni = file.f[i + 2]; Vertex v = { file.v[vi * 3 + 0], file.v[vi * 3 + 1], file.v[vi * 3 + 2], vni >= 0 ? file.vn[vni * 3 + 0] : 0, vni >= 0 ? file.vn[vni * 3 + 1] : 0, vni >= 0 ? file.vn[vni * 3 + 2] : 0, vti >= 0 ? file.vt[vti * 3 + 0] : 0, vti >= 0 ? file.vt[vti * 3 + 1] : 0, }; vertices.push_back(v); } Mesh result; result.indices.resize(total_indices); size_t total_vertices = generateIndexBuffer(&result.indices[0], &vertices[0], total_indices, sizeof(Vertex)); result.vertices.resize(total_vertices); generateVertexBuffer(&result.vertices[0], &result.indices[0], &vertices[0], total_indices, sizeof(Vertex)); return result; } Mesh optimize(const Mesh& mesh, int lod) { return mesh; } void display(int width, int height, const Mesh& mesh, const Options& options) { glViewport(0, 0, width, height); glClearDepth(1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); glPolygonMode(GL_FRONT_AND_BACK, options.wireframe ? GL_LINE : GL_FILL); float centerx = 0; float centery = 0; float centerz = 0; for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; centerx += v.px; centery += v.py; centerz += v.pz; } centerx /= float(mesh.vertices.size()); centery /= float(mesh.vertices.size()); centerz /= float(mesh.vertices.size()); float extent = 0; for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; extent = std::max(extent, fabsf(v.px - centerx)); extent = std::max(extent, fabsf(v.py - centery)); extent = std::max(extent, fabsf(v.pz - centerz)); } extent *= 1.1f; float scalex = width > height ? float(height) / float(width) : 1; float scaley = height > width ? float(width) / float(height) : 1; glBegin(GL_TRIANGLES); for (size_t i = 0; i < mesh.indices.size(); ++i) { const Vertex& v = mesh.vertices[mesh.indices[i]]; switch (options.mode) { case Options::Mode_Texture: glColor3f(v.tx - floorf(v.tx), v.ty - floorf(v.ty), 0.5f); break; case Options::Mode_Normals: glColor3f(v.nx * 0.5f + 0.5f, v.ny * 0.5f + 0.5f, v.nz * 0.5f + 0.5f); break; default: float intensity = -(v.pz - centerz) / extent * 0.5f + 0.5f; glColor3f(intensity, intensity, intensity); } glVertex3f((v.px - centerx) / extent * scalex, (v.py - centery) / extent * scaley, (v.pz - centerz) / extent); } glEnd(); } void stats(HWND hWnd, const char* path, const Mesh& mesh, int lod) { char title[256]; snprintf(title, sizeof(title), "%s: LOD %d - %d triangles", path, lod, int(mesh.indices.size() / 3)); SetWindowTextA(hWnd, title); } int main(int argc, char** argv) { if (argc <= 1) { printf("Usage: %s [.obj file]\n", argv[0]); return 0; } HWND hWnd = CreateWindow(L"ListBox", L"Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL); HDC hDC = GetDC(hWnd); PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, 0, 32 }; pfd.cDepthBits = 24; SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd); wglMakeCurrent(hDC, wglCreateContext(hDC)); ShowWindow(hWnd, SW_SHOWNORMAL); const char* path = argv[1]; Mesh basemesh = parseObj(path); Options options = {}; stats(hWnd, path, basemesh, 0); Mesh mesh = basemesh; MSG msg; while (GetMessage(&msg, hWnd, 0, 0) && msg.message) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_KEYDOWN) { if (msg.wParam == 'W') { options.wireframe = !options.wireframe; } else if (msg.wParam == 'T') { options.mode = options.mode == Options::Mode_Texture ? Options::Mode_Default : Options::Mode_Texture; } else if (msg.wParam == 'N') { options.mode = options.mode == Options::Mode_Normals ? Options::Mode_Default : Options::Mode_Normals; } else if (msg.wParam == '0') { mesh = basemesh; stats(hWnd, path, mesh, 0); } else if (msg.wParam >= '1' && msg.wParam <= '9') { int lod = int(msg.wParam - '0'); mesh = optimize(basemesh, lod); stats(hWnd, path, mesh, lod); } } RECT rect; GetClientRect(hWnd, &rect); display(rect.right - rect.left, rect.bottom - rect.top, mesh, options); SwapBuffers(hDC); } } <|endoftext|>
<commit_before>/* * Author: Jeff Thompson * * BSD license, See the LICENSE file for more information. */ #include <sstream> #include "Name.hpp" using namespace std; namespace ndn { /** * Write the value to result, escaping characters according to the NDN URI Scheme. * This also adds "..." to a value with zero or more ".". * @param value the buffer with the value to escape * @param result the string stream to write to. */ static void toEscapedString(const vector<unsigned char> &value, ostringstream &result) { bool gotNonDot = false; for (unsigned i = 0; i < value.size(); ++i) { if (value[i] != 0x2e) { gotNonDot = true; break; } } if (!gotNonDot) { // Special case for component of zero or more periods. Add 3 periods. result << "..."; for (unsigned int i = 0; i < value.size(); ++i) result << "."; } else { // In case we need to escape, set to upper case hex and save the previous flags. ios::fmtflags saveFlags = result.flags(ios::hex | ios::uppercase); for (unsigned int i = 0; i < value.size(); ++i) { unsigned char x = value[i]; // Check for 0-9, A-Z, a-z, (+), (-), (.), (_) if (x >= 0x30 && x <= 0x39 || x >= 0x41 && x <= 0x5a || x >= 0x61 && x <= 0x7a || x == 0x2b || x == 0x2d || x == 0x2e || x == 0x5f) result << x; else { result << "%"; if (x < 16) result << "0"; result << (unsigned int)x; } } // Restore. result.flags(saveFlags); } } void Name::get(struct ndn_Name &nameStruct) { if (nameStruct.maxComponents < components_.size()) throw runtime_error("nameStruct.maxComponents must be >= this name getNComponents()"); nameStruct.nComponents = components_.size(); for (unsigned int i = 0; i < nameStruct.nComponents; ++i) components_[i].get(nameStruct.components[i]); } void Name::set(struct ndn_Name &nameStruct) { clear(); for (unsigned int i = 0; i < nameStruct.nComponents; ++i) addComponent(nameStruct.components[i].value, nameStruct.components[i].valueLength); } std::string Name::to_uri() { if (components_.size() == 0) return "/"; ostringstream result; for (unsigned int i = 0; i < components_.size(); ++i) { result << "/"; toEscapedString(components_[i].getValue(), result); } return result.str(); } } <commit_msg>Added trim and unescape.<commit_after>/* * Author: Jeff Thompson * * BSD license, See the LICENSE file for more information. */ #include <sstream> #include "Name.hpp" using namespace std; namespace ndn { /** * Write the value to result, escaping characters according to the NDN URI Scheme. * This also adds "..." to a value with zero or more ".". * @param value the buffer with the value to escape * @param result the string stream to write to. */ static void toEscapedString(const vector<unsigned char> &value, ostringstream &result) { bool gotNonDot = false; for (unsigned i = 0; i < value.size(); ++i) { if (value[i] != 0x2e) { gotNonDot = true; break; } } if (!gotNonDot) { // Special case for component of zero or more periods. Add 3 periods. result << "..."; for (unsigned int i = 0; i < value.size(); ++i) result << "."; } else { // In case we need to escape, set to upper case hex and save the previous flags. ios::fmtflags saveFlags = result.flags(ios::hex | ios::uppercase); for (unsigned int i = 0; i < value.size(); ++i) { unsigned char x = value[i]; // Check for 0-9, A-Z, a-z, (+), (-), (.), (_) if (x >= 0x30 && x <= 0x39 || x >= 0x41 && x <= 0x5a || x >= 0x61 && x <= 0x7a || x == 0x2b || x == 0x2d || x == 0x2e || x == 0x5f) result << x; else { result << "%"; if (x < 16) result << "0"; result << (unsigned int)x; } } // Restore. result.flags(saveFlags); } } static const char *WHITESPACE_CHARS = " \n\r\t"; /** * Modify str in place to erase whitespace on the left. * @param str */ static inline void trimLeft(string &str) { size_t found = str.find_first_not_of(WHITESPACE_CHARS); if (found != string::npos) { if (found > 0) str.erase(0, found); } else // All whitespace str.clear(); } /** * Modify str in place to erase whitespace on the right. * @param str */ static inline void trimRight(string &str) { size_t found = str.find_last_not_of(WHITESPACE_CHARS); if (found != string::npos) { if (found + 1 < str.size()) str.erase(found + 1); } else // All whitespace str.clear(); } /** * Modify str in place to erase whitespace on the left and right. * @param str */ static void trim(string &str) { trimLeft(str); trimRight(str); } /** * Convert the hex character to an integer from 0 to 15, or -1 if not a hex character. * @param c * @return */ static int fromHexChar(unsigned char c) { if (c >= '0' && c <= '9') return (int)c - (int)'0'; else if (c >= 'A' && c <= 'F') return (int)c - (int)'A' + 10; else if (c >= 'a' && c <= 'f') return (int)c - (int)'a' + 10; else return -1; } /** * Return a copy of str, converting each escaped "%XX" to the char value. * @param str */ static string unescape(const string &str) { ostringstream result; for (unsigned int i = 0; i < str.size(); ++i) { if (str[i] == '%' && i + 2 < str.size()) { int hi = fromHexChar(str[i + 1]); int lo = fromHexChar(str[i + 2]); if (hi < 0 || lo < 0) // Invalid hex characters, so just keep the escaped string. result << str[i] << str[i + 1] << str[i + 2]; else result << (unsigned char)(16 * hi + lo); // Skip ahead past the escaped value. i += 2; } else // Just copy through. result << str[i]; } return result.str(); } void Name::get(struct ndn_Name &nameStruct) { if (nameStruct.maxComponents < components_.size()) throw runtime_error("nameStruct.maxComponents must be >= this name getNComponents()"); nameStruct.nComponents = components_.size(); for (unsigned int i = 0; i < nameStruct.nComponents; ++i) components_[i].get(nameStruct.components[i]); } void Name::set(struct ndn_Name &nameStruct) { clear(); for (unsigned int i = 0; i < nameStruct.nComponents; ++i) addComponent(nameStruct.components[i].value, nameStruct.components[i].valueLength); } std::string Name::to_uri() { if (components_.size() == 0) return "/"; ostringstream result; for (unsigned int i = 0; i < components_.size(); ++i) { result << "/"; toEscapedString(components_[i].getValue(), result); } return result.str(); } } <|endoftext|>
<commit_before>// Copyright 2018 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VK_PHYSICAL_DEVICE_HPP_ #define VK_PHYSICAL_DEVICE_HPP_ #include "VkObject.hpp" #ifdef VK_USE_PLATFORM_ANDROID_KHR #include <vulkan/vk_android_native_buffer.h> #endif namespace vk { class PhysicalDevice { public: static constexpr VkSystemAllocationScope GetAllocationScope() { return VK_SYSTEM_ALLOCATION_SCOPE_DEVICE; } PhysicalDevice(const void*, void* mem); void destroy(const VkAllocationCallbacks* pAllocator) {} static size_t ComputeRequiredAllocationSize(const void*) { return 0; } const VkPhysicalDeviceFeatures& getFeatures() const; void getFeatures(VkPhysicalDeviceSamplerYcbcrConversionFeatures* features) const; void getFeatures(VkPhysicalDevice16BitStorageFeatures* features) const; void getFeatures(VkPhysicalDeviceVariablePointerFeatures* features) const; void getFeatures(VkPhysicalDevice8BitStorageFeaturesKHR* features) const; void getFeatures(VkPhysicalDeviceMultiviewFeatures* features) const; void getFeatures(VkPhysicalDeviceProtectedMemoryFeatures* features) const; void getFeatures(VkPhysicalDeviceShaderDrawParameterFeatures* features) const; bool hasFeatures(const VkPhysicalDeviceFeatures& requestedFeatures) const; const VkPhysicalDeviceProperties& getProperties() const; void getProperties(VkPhysicalDeviceIDProperties* properties) const; void getProperties(VkPhysicalDeviceMaintenance3Properties* properties) const; void getProperties(VkPhysicalDeviceMultiviewProperties* properties) const; void getProperties(VkPhysicalDevicePointClippingProperties* properties) const; void getProperties(VkPhysicalDeviceProtectedMemoryProperties* properties) const; void getProperties(VkPhysicalDeviceSubgroupProperties* properties) const; void getProperties(const VkExternalMemoryHandleTypeFlagBits* handleType, VkExternalImageFormatProperties* properties) const; void getProperties(VkSamplerYcbcrConversionImageFormatProperties* properties) const; #ifdef __ANDROID__ void getProperties(VkPhysicalDevicePresentationPropertiesANDROID* properties) const; #endif void getProperties(const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo, VkExternalBufferProperties* pExternalBufferProperties) const; void getProperties(const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo, VkExternalFenceProperties* pExternalFenceProperties) const; void getProperties(const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo, VkExternalSemaphoreProperties* pExternalSemaphoreProperties) const; void getFormatProperties(VkFormat format, VkFormatProperties* pFormatProperties) const; void getImageFormatProperties(VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties* pImageFormatProperties) const; uint32_t getQueueFamilyPropertyCount() const; void getQueueFamilyProperties(uint32_t pQueueFamilyPropertyCount, VkQueueFamilyProperties* pQueueFamilyProperties) const; const VkPhysicalDeviceMemoryProperties& getMemoryProperties() const; private: const VkPhysicalDeviceLimits& getLimits() const; VkSampleCountFlags getSampleCounts() const; }; using DispatchablePhysicalDevice = DispatchableObject<PhysicalDevice, VkPhysicalDevice>; static inline PhysicalDevice* Cast(VkPhysicalDevice object) { return DispatchablePhysicalDevice::Cast(object); } } // namespace vk #endif // VK_PHYSICAL_DEVICE_HPP_ <commit_msg>VkPhysicalDevice should use Instance allocation scope<commit_after>// Copyright 2018 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VK_PHYSICAL_DEVICE_HPP_ #define VK_PHYSICAL_DEVICE_HPP_ #include "VkObject.hpp" #ifdef VK_USE_PLATFORM_ANDROID_KHR #include <vulkan/vk_android_native_buffer.h> #endif namespace vk { class PhysicalDevice { public: static constexpr VkSystemAllocationScope GetAllocationScope() { return VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE; } PhysicalDevice(const void*, void* mem); void destroy(const VkAllocationCallbacks* pAllocator) {} static size_t ComputeRequiredAllocationSize(const void*) { return 0; } const VkPhysicalDeviceFeatures& getFeatures() const; void getFeatures(VkPhysicalDeviceSamplerYcbcrConversionFeatures* features) const; void getFeatures(VkPhysicalDevice16BitStorageFeatures* features) const; void getFeatures(VkPhysicalDeviceVariablePointerFeatures* features) const; void getFeatures(VkPhysicalDevice8BitStorageFeaturesKHR* features) const; void getFeatures(VkPhysicalDeviceMultiviewFeatures* features) const; void getFeatures(VkPhysicalDeviceProtectedMemoryFeatures* features) const; void getFeatures(VkPhysicalDeviceShaderDrawParameterFeatures* features) const; bool hasFeatures(const VkPhysicalDeviceFeatures& requestedFeatures) const; const VkPhysicalDeviceProperties& getProperties() const; void getProperties(VkPhysicalDeviceIDProperties* properties) const; void getProperties(VkPhysicalDeviceMaintenance3Properties* properties) const; void getProperties(VkPhysicalDeviceMultiviewProperties* properties) const; void getProperties(VkPhysicalDevicePointClippingProperties* properties) const; void getProperties(VkPhysicalDeviceProtectedMemoryProperties* properties) const; void getProperties(VkPhysicalDeviceSubgroupProperties* properties) const; void getProperties(const VkExternalMemoryHandleTypeFlagBits* handleType, VkExternalImageFormatProperties* properties) const; void getProperties(VkSamplerYcbcrConversionImageFormatProperties* properties) const; #ifdef __ANDROID__ void getProperties(VkPhysicalDevicePresentationPropertiesANDROID* properties) const; #endif void getProperties(const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo, VkExternalBufferProperties* pExternalBufferProperties) const; void getProperties(const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo, VkExternalFenceProperties* pExternalFenceProperties) const; void getProperties(const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo, VkExternalSemaphoreProperties* pExternalSemaphoreProperties) const; void getFormatProperties(VkFormat format, VkFormatProperties* pFormatProperties) const; void getImageFormatProperties(VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties* pImageFormatProperties) const; uint32_t getQueueFamilyPropertyCount() const; void getQueueFamilyProperties(uint32_t pQueueFamilyPropertyCount, VkQueueFamilyProperties* pQueueFamilyProperties) const; const VkPhysicalDeviceMemoryProperties& getMemoryProperties() const; private: const VkPhysicalDeviceLimits& getLimits() const; VkSampleCountFlags getSampleCounts() const; }; using DispatchablePhysicalDevice = DispatchableObject<PhysicalDevice, VkPhysicalDevice>; static inline PhysicalDevice* Cast(VkPhysicalDevice object) { return DispatchablePhysicalDevice::Cast(object); } } // namespace vk #endif // VK_PHYSICAL_DEVICE_HPP_ <|endoftext|>
<commit_before>/* * simple.cpp - simple demo for FTGL, the OpenGL font library * * Copyright (c) 2008 Sam Hocevar <sam@zoy.org> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "config.h" #include <math.h> #if defined HAVE_GL_GLUT_H # include <GL/glut.h> #elif defined HAVE_GLUT_GLUT_H # include <GLUT/glut.h> #else # error GLUT headers not present #endif #include <FTGL/ftgl.h> static FTFont *font; static void RenderScene(void) { float n = (float)glutGet(GLUT_ELAPSED_TIME) / 10.; float t1 = sin(n / 80); float t2 = sin(n / 50 + 1); float t3 = sin(n / 30 + 2); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glPushMatrix(); glTranslatef(-0.9, -0.2, -10.0); float ambient[4] = { (t1 + 2.0) / 3, (t2 + 2.0) / 3, (t3 + 2.0) / 3, 1.0 }; float diffuse[4] = { 1.0, 0.9, 0.9, 1.0 }; float specular[4] = { 1.0, 0.7, 0.7, 1.0 }; float position[4] = { 200.0, 200.0, 0.0, 1.0 }; glLightfv(GL_LIGHT1, GL_AMBIENT, ambient); glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, specular); glLightfv(GL_LIGHT1, GL_POSITION, position); glEnable(GL_LIGHT1); glColorMaterial(GL_FRONT, GL_DIFFUSE); glPopMatrix(); glPushMatrix(); glTranslatef(0.0, 0.0, 20.0); glRotatef(n / 1.11, 0.0, 1.0, 0.0); glRotatef(n / 2.23, 1.0, 0.0, 0.0); glRotatef(n / 3.17, 0.0, 0.0, 1.0); glTranslatef(-260.0, -0.2, 0.0); glColor3f(0.0, 0.0, 0.0); font->Render("Hello FTGL!"); glPopMatrix(); glutSwapBuffers(); } void ProcessKeys(unsigned char key, int x, int y) { if(key == 27) { delete font; exit(0); } } int main(int argc, char **argv) { if(argc < 2) { fprintf(stderr, "Usage: %s <font_name.ttf>\n", argv[0]); return EXIT_FAILURE; } // Initialise GLUT stuff glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(640, 480); glutCreateWindow("FTGL simple demo"); glutDisplayFunc(RenderScene); glutIdleFunc(RenderScene); glutKeyboardFunc(ProcessKeys); // Initialise FTGL stuff font = new FTExtrudeFont(argv[1]); if(font->Error()) { fprintf(stderr, "%s: could not load font `%s'\n", argv[0], argv[1]); return EXIT_FAILURE; } font->FaceSize(80); font->Depth(10); font->Outset(0, 3); font->CharMap(ft_encoding_unicode); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective(90, 640.0f / 480.0f, 1, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0, 0.0, 640.0f / 2.0f, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); // Run GLUT loop glutMainLoop(); return EXIT_SUCCESS; } <commit_msg> * Show how to subclass FTFont classes in the simple demo.<commit_after>/* * simple.cpp - simple demo for FTGL, the OpenGL font library * * Copyright (c) 2008 Sam Hocevar <sam@zoy.org> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "config.h" #include <math.h> #if defined HAVE_GL_GLUT_H # include <GL/glut.h> #elif defined HAVE_GLUT_GLUT_H # include <GLUT/glut.h> #else # error GLUT headers not present #endif #include <FTGL/ftgl.h> static FTFont *font[3]; static int fontindex = 0; // // FTHaloGlyph is a derivation of FTOutlineGlyph that displays several // outlines at varying offsets and with varying outset values. // class FTHaloGlyph : public FTOutlineGlyph { public: FTHaloGlyph(FT_GlyphSlot glyph) : FTOutlineGlyph(glyph, 0, true) { for(int i = 0; i < 5; i++) { subglyph[i] = new FTOutlineGlyph(glyph, i, true); } } private: const FTPoint& Render(const FTPoint& pen, int renderMode) { glPushMatrix(); for(int i = 0; i < 5; i++) { glTranslatef(0.0, 0.0, -2.0); subglyph[i]->Render(pen, renderMode); } glPopMatrix(); return FTOutlineGlyph::Render(pen, renderMode); } FTOutlineGlyph *subglyph[5]; }; // // FTHaloFont is a simple FTOutlineFont derivation that builds FTHaloGlyph // objects. // class FTHaloFont : public FTOutlineFont { public: FTHaloFont(char const *fontFilePath) : FTOutlineFont(fontFilePath) {} private: virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot) { return new FTHaloGlyph(slot); } }; // // Main OpenGL loop: set up lights, apply a few rotation effects, and // render text using the current FTGL object. // static void RenderScene(void) { float n = (float)glutGet(GLUT_ELAPSED_TIME) / 20.; float t1 = sin(n / 80); float t2 = sin(n / 50 + 1); float t3 = sin(n / 30 + 2); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glPushMatrix(); glTranslatef(-0.9, -0.2, -10.0); float ambient[4] = { (t1 + 2.0) / 3, (t2 + 2.0) / 3, (t3 + 2.0) / 3, 0.3 }; float diffuse[4] = { 1.0, 0.9, 0.9, 1.0 }; float specular[4] = { 1.0, 0.7, 0.7, 1.0 }; float position[4] = { 100.0, 100.0, 0.0, 1.0 }; glLightfv(GL_LIGHT1, GL_AMBIENT, ambient); glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, specular); glLightfv(GL_LIGHT1, GL_POSITION, position); glEnable(GL_LIGHT1); glPopMatrix(); glPushMatrix(); float front_ambient[4] = { 0.7, 0.7, 0.7, 0.0 }; glMaterialfv(GL_FRONT, GL_AMBIENT, front_ambient); glColorMaterial(GL_FRONT, GL_DIFFUSE); glTranslatef(0.0, 0.0, 20.0); glRotatef(n / 1.11, 0.0, 1.0, 0.0); glRotatef(n / 2.23, 1.0, 0.0, 0.0); glRotatef(n / 3.17, 0.0, 0.0, 1.0); glTranslatef(-260.0, -0.2, 0.0); glColor3f(0.0, 0.0, 0.0); font[fontindex]->Render("Hello FTGL!"); glPopMatrix(); glutSwapBuffers(); } // // GLUT key processing function: <esc> quits, <tab> cycles across fonts. // void ProcessKeys(unsigned char key, int x, int y) { switch(key) { case 27: delete font[0]; delete font[1]; delete font[2]; exit(0); break; case '\t': fontindex = (fontindex + 1) % 3; break; } } // // Main program entry point: set up GLUT window, load fonts, run GLUT loop. // int main(int argc, char **argv) { if(argc < 2) { fprintf(stderr, "Usage: %s <font_name.ttf>\n", argv[0]); return EXIT_FAILURE; } // Initialise GLUT stuff glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(640, 480); glutCreateWindow("FTGL simple demo"); glutDisplayFunc(RenderScene); glutIdleFunc(RenderScene); glutKeyboardFunc(ProcessKeys); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90, 640.0f / 480.0f, 1, 1000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0, 0.0, 640.0f / 2.0f, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); // Initialise FTGL stuff font[0] = new FTExtrudeFont(argv[1]); font[1] = new FTPolygonFont(argv[1]); font[2] = new FTHaloFont(argv[1]); if(font[0]->Error() || font[1]->Error() || font[2]->Error()) { fprintf(stderr, "%s: could not load font `%s'\n", argv[0], argv[1]); return EXIT_FAILURE; } font[0]->FaceSize(80); font[0]->Depth(10); font[0]->Outset(0, 3); font[0]->CharMap(ft_encoding_unicode); font[1]->FaceSize(80); font[1]->CharMap(ft_encoding_unicode); font[2]->FaceSize(80); font[2]->CharMap(ft_encoding_unicode); // Run GLUT loop glutMainLoop(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(FUNCTIONLOCALNAME_HEADER_GUARD_1357924680) #define FUNCTIONLOCALNAME_HEADER_GUARD_1357924680 // Base header file. Must be first. #include <XPath/XPathDefinitions.hpp> #include <vector> #include <PlatformSupport/DOMStringHelper.hpp> // Base class header file... #include <XPath/Function.hpp> #include <XPath/NodeRefListBase.hpp> #include <XPath/XObject.hpp> #include <XPath/XObjectFactory.hpp> #include <XPath/XPathExecutionContext.hpp> /** * XPath implementation of "local-name" function. */ // // These are all inline, even though // there are virtual functions, because we expect that they will only be // needed by the XPath class. class XALAN_XPATH_EXPORT FunctionLocalName : public Function { public: // These methods are inherited from Function ... virtual XObject* execute( XPathExecutionContext& executionContext, XalanNode* context, int /* opPos */, const XObjectArgVectorType& args) { const XObjectArgVectorType::size_type theSize = args.size(); if(theSize > 1) { executionContext.error("The local-name() function takes zero or one arguments!", context); } XalanDOMString theData; if (theSize == 0) { assert(context != 0); theData = executionContext.getLocalNameOfNode(*context); } else { assert(args[0] != 0); const NodeRefListBase& theNodeList = args[0]->nodeset(); if (theNodeList.getLength() > 0) { theData = executionContext.getLocalNameOfNode(*theNodeList.item(0)); } } return executionContext.getXObjectFactory().createString(theData); } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionLocalName* #endif clone() const { return new FunctionLocalName(*this); } private: // Not implemented... FunctionLocalName& operator=(const FunctionLocalName&); bool operator==(const FunctionLocalName&) const; }; #endif // FUNCTIONLOCALNAME_HEADER_GUARD_1357924680 <commit_msg>More error checking.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(FUNCTIONLOCALNAME_HEADER_GUARD_1357924680) #define FUNCTIONLOCALNAME_HEADER_GUARD_1357924680 // Base header file. Must be first. #include <XPath/XPathDefinitions.hpp> #include <vector> #include <PlatformSupport/DOMStringHelper.hpp> // Base class header file... #include <XPath/Function.hpp> #include <XPath/NodeRefListBase.hpp> #include <XPath/XObject.hpp> #include <XPath/XObjectFactory.hpp> #include <XPath/XPathExecutionContext.hpp> /** * XPath implementation of "local-name" function. */ // // These are all inline, even though // there are virtual functions, because we expect that they will only be // needed by the XPath class. class XALAN_XPATH_EXPORT FunctionLocalName : public Function { public: // These methods are inherited from Function ... virtual XObject* execute( XPathExecutionContext& executionContext, XalanNode* context, int /* opPos */, const XObjectArgVectorType& args) { const XObjectArgVectorType::size_type theSize = args.size(); if(theSize > 1) { executionContext.error("The local-name() function takes zero or one arguments!", context); } XalanDOMString theData; if (theSize == 0) { if (context == 0) { executionContext.error("The local-name() function requires a non-null context node!"); } theData = executionContext.getLocalNameOfNode(*context); } else { assert(args[0] != 0); const NodeRefListBase& theNodeList = args[0]->nodeset(); if (theNodeList.getLength() > 0) { theData = executionContext.getLocalNameOfNode(*theNodeList.item(0)); } } return executionContext.getXObjectFactory().createString(theData); } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) virtual Function* #else virtual FunctionLocalName* #endif clone() const { return new FunctionLocalName(*this); } private: // Not implemented... FunctionLocalName& operator=(const FunctionLocalName&); bool operator==(const FunctionLocalName&) const; }; #endif // FUNCTIONLOCALNAME_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "FunctionGenerateID.hpp" #include <XalanDOM/XalanDocument.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <XPath/NodeRefListBase.hpp> #include <XPath/XObjectFactory.hpp> const XalanDOMString FunctionGenerateID::s_emptyString; FunctionGenerateID::FunctionGenerateID() : Function(), m_prefix(XALAN_STATIC_UCODE_STRING("N")), m_prefixLength(length(m_prefix)) { } FunctionGenerateID::~FunctionGenerateID() { } // Append the suffix to the provided string. void getSuffix( const XalanNode* theNode, XalanDOMString& theResult) { assert(theNode != 0); assert(theNode->getOwnerDocument() != 0); const unsigned long theIndex = theNode->getIndex(); const unsigned long theNumber = theNode->getOwnerDocument()->getNumber(); if (theNumber != 0) { UnsignedLongToHexDOMString(theNumber, theResult); append(theResult, XalanDOMChar(XalanUnicode::charFullStop)); } if (theIndex == 0) { // We're assuming here that each nodes has an implementation with a // unique address that we can convert into a string PointerToDOMString(theNode, theResult); } else { UnsignedLongToHexDOMString(theIndex, theResult); } } XObjectPtr FunctionGenerateID::execute( XPathExecutionContext& executionContext, XalanNode* context, const Locator* locator) const { if (context == 0) { executionContext.error( "The generate-id() function requires a non-null context node!", context, locator); return XObjectPtr(); } else { XPathExecutionContext::GetAndReleaseCachedString theID(executionContext); theID.get() = m_prefix; getSuffix(context, theID.get()); return executionContext.getXObjectFactory().createString(theID); } } XObjectPtr FunctionGenerateID::execute( XPathExecutionContext& executionContext, XalanNode* /* context */, const XObjectPtr arg1, const Locator* locator) const { assert(arg1.null() == false); const NodeRefListBase& theNodeList = arg1->nodeset(); if (theNodeList.getLength() == 0) { return executionContext.getXObjectFactory().createString(s_emptyString); } else { return execute(executionContext, theNodeList.item(0), locator); } } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) Function* #else FunctionGenerateID* #endif FunctionGenerateID::clone() const { return new FunctionGenerateID(*this); } const XalanDOMString FunctionGenerateID::getError() const { return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The generate-id function takes zero or one arguments!")); } <commit_msg>Consistently use document number in ID.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "FunctionGenerateID.hpp" #include <XalanDOM/XalanDocument.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <XPath/NodeRefListBase.hpp> #include <XPath/XObjectFactory.hpp> const XalanDOMString FunctionGenerateID::s_emptyString; FunctionGenerateID::FunctionGenerateID() : Function(), m_prefix(XALAN_STATIC_UCODE_STRING("N")), m_prefixLength(length(m_prefix)) { } FunctionGenerateID::~FunctionGenerateID() { } // Append the suffix to the provided string. void getSuffix( const XalanNode* theNode, XalanDOMString& theResult) { assert(theNode != 0); assert(theNode->getOwnerDocument() != 0); const unsigned long theNumber = theNode->getOwnerDocument()->getNumber(); UnsignedLongToHexDOMString(theNumber, theResult); append(theResult, XalanDOMChar(XalanUnicode::charFullStop)); const unsigned long theIndex = theNode->getIndex(); if (theIndex == 0) { // We're assuming here that each node has an implementation with a // unique address that we can convert into a string... PointerToDOMString(theNode, theResult); } else { UnsignedLongToHexDOMString(theIndex, theResult); } } XObjectPtr FunctionGenerateID::execute( XPathExecutionContext& executionContext, XalanNode* context, const Locator* locator) const { if (context == 0) { executionContext.error( "The generate-id() function requires a non-null context node!", context, locator); return XObjectPtr(); } else { XPathExecutionContext::GetAndReleaseCachedString theID(executionContext); theID.get() = m_prefix; getSuffix(context, theID.get()); return executionContext.getXObjectFactory().createString(theID); } } XObjectPtr FunctionGenerateID::execute( XPathExecutionContext& executionContext, XalanNode* /* context */, const XObjectPtr arg1, const Locator* locator) const { assert(arg1.null() == false); const NodeRefListBase& theNodeList = arg1->nodeset(); if (theNodeList.getLength() == 0) { return executionContext.getXObjectFactory().createString(s_emptyString); } else { return execute(executionContext, theNodeList.item(0), locator); } } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) Function* #else FunctionGenerateID* #endif FunctionGenerateID::clone() const { return new FunctionGenerateID(*this); } const XalanDOMString FunctionGenerateID::getError() const { return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The generate-id function takes zero or one arguments!")); } <|endoftext|>
<commit_before>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include "SoundSample.hpp" #include "MainMenu.hpp" using namespace std; using namespace ouzel; SoundSample::SoundSample(): test8BitButton("button.png", "button_selected.png", "button_down.png", "", "8-bit", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), test24BitButton("button.png", "button_selected.png", "button_down.png", "", "24-bit", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), jumpButton("button.png", "button_selected.png", "button_down.png", "", "Jump", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), ambientButton("button.png", "button_selected.png", "button_down.png", "", "Ambient", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), musicButton("button.png", "button_selected.png", "button_down.png", "", "Music", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), backButton("button.png", "button_selected.png", "button_down.png", "", "Back", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK) { eventHandler.gamepadHandler = bind(&SoundSample::handleGamepad, this, placeholders::_1, placeholders::_2); eventHandler.uiHandler = bind(&SoundSample::handleUI, this, placeholders::_1, placeholders::_2); eventHandler.keyboardHandler = bind(&SoundSample::handleKeyboard, this, placeholders::_1, placeholders::_2); sharedEngine->getEventDispatcher()->addEventHandler(&eventHandler); test8BitSound.reset(new audio::Sound()); test8BitSound->init(sharedEngine->getCache()->getSoundData("8-bit.wav")); test24BitSound.reset(new audio::Sound()); test24BitSound->init(sharedEngine->getCache()->getSoundData("24-bit.wav")); jumpSound.reset(new audio::Sound()); jumpSound->init(sharedEngine->getCache()->getSoundData("jump.wav")); ambientSound.reset(new audio::Sound()); ambientSound->init(sharedEngine->getCache()->getSoundData("ambient.wav")); music.reset(new audio::Sound()); music->init(sharedEngine->getCache()->getSoundData("music.ogg")); guiCamera.setScaleMode(scene::Camera::ScaleMode::SHOW_ALL); guiCamera.setTargetContentSize(Size2(800.0f, 600.0f)); guiLayer.addChild(&guiCamera); addLayer(&guiLayer); guiLayer.addChild(&menu); test8BitButton.setPosition(Vector2(0.0f, 80.0f)); menu.addWidget(&test8BitButton); test24BitButton.setPosition(Vector2(0.0f, 40.0f)); menu.addWidget(&test24BitButton); jumpButton.setPosition(Vector2(0.0f, 0.0f)); menu.addWidget(&jumpButton); ambientButton.setPosition(Vector2(0.0f, -40.0f)); menu.addWidget(&ambientButton); musicButton.setPosition(Vector2(0.0f, -80.0f)); menu.addWidget(&musicButton); backButton.setPosition(Vector2(-200.0f, -200.0f)); menu.addWidget(&backButton); } bool SoundSample::handleGamepad(Event::Type type, const GamepadEvent& event) { if (type == Event::Type::GAMEPAD_BUTTON_CHANGE) { if (event.pressed && event.button == input::GamepadButton::FACE_RIGHT) { sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu())); } } return true; } bool SoundSample::handleUI(Event::Type type, const UIEvent& event) const { if (type == Event::Type::CLICK_NODE) { if (event.node == &backButton) { sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu())); } else if (event.node == &test8BitButton) { test8BitSound->play(); } else if (event.node == &test24BitButton) { test24BitSound->play(); } else if (event.node == &jumpButton) { jumpSound->play(); } else if (event.node == &ambientButton) { ambientSound->play(); } else if (event.node == &musicButton) { music->play(); } } return true; } bool SoundSample::handleKeyboard(Event::Type type, const KeyboardEvent& event) const { if (type == Event::Type::KEY_PRESS) { switch (event.key) { case input::KeyboardKey::ESCAPE: case input::KeyboardKey::MENU: sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu())); break; default: break; } } return true; } <commit_msg>Fix the attribute init order<commit_after>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include "SoundSample.hpp" #include "MainMenu.hpp" using namespace std; using namespace ouzel; SoundSample::SoundSample(): backButton("button.png", "button_selected.png", "button_down.png", "", "Back", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), test8BitButton("button.png", "button_selected.png", "button_down.png", "", "8-bit", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), test24BitButton("button.png", "button_selected.png", "button_down.png", "", "24-bit", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), jumpButton("button.png", "button_selected.png", "button_down.png", "", "Jump", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), ambientButton("button.png", "button_selected.png", "button_down.png", "", "Ambient", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK), musicButton("button.png", "button_selected.png", "button_down.png", "", "Music", "arial.fnt", 0, Color::BLACK, Color::BLACK, Color::BLACK) { eventHandler.gamepadHandler = bind(&SoundSample::handleGamepad, this, placeholders::_1, placeholders::_2); eventHandler.uiHandler = bind(&SoundSample::handleUI, this, placeholders::_1, placeholders::_2); eventHandler.keyboardHandler = bind(&SoundSample::handleKeyboard, this, placeholders::_1, placeholders::_2); sharedEngine->getEventDispatcher()->addEventHandler(&eventHandler); test8BitSound.reset(new audio::Sound()); test8BitSound->init(sharedEngine->getCache()->getSoundData("8-bit.wav")); test24BitSound.reset(new audio::Sound()); test24BitSound->init(sharedEngine->getCache()->getSoundData("24-bit.wav")); jumpSound.reset(new audio::Sound()); jumpSound->init(sharedEngine->getCache()->getSoundData("jump.wav")); ambientSound.reset(new audio::Sound()); ambientSound->init(sharedEngine->getCache()->getSoundData("ambient.wav")); music.reset(new audio::Sound()); music->init(sharedEngine->getCache()->getSoundData("music.ogg")); guiCamera.setScaleMode(scene::Camera::ScaleMode::SHOW_ALL); guiCamera.setTargetContentSize(Size2(800.0f, 600.0f)); guiLayer.addChild(&guiCamera); addLayer(&guiLayer); guiLayer.addChild(&menu); test8BitButton.setPosition(Vector2(0.0f, 80.0f)); menu.addWidget(&test8BitButton); test24BitButton.setPosition(Vector2(0.0f, 40.0f)); menu.addWidget(&test24BitButton); jumpButton.setPosition(Vector2(0.0f, 0.0f)); menu.addWidget(&jumpButton); ambientButton.setPosition(Vector2(0.0f, -40.0f)); menu.addWidget(&ambientButton); musicButton.setPosition(Vector2(0.0f, -80.0f)); menu.addWidget(&musicButton); backButton.setPosition(Vector2(-200.0f, -200.0f)); menu.addWidget(&backButton); } bool SoundSample::handleGamepad(Event::Type type, const GamepadEvent& event) { if (type == Event::Type::GAMEPAD_BUTTON_CHANGE) { if (event.pressed && event.button == input::GamepadButton::FACE_RIGHT) { sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu())); } } return true; } bool SoundSample::handleUI(Event::Type type, const UIEvent& event) const { if (type == Event::Type::CLICK_NODE) { if (event.node == &backButton) { sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu())); } else if (event.node == &test8BitButton) { test8BitSound->play(); } else if (event.node == &test24BitButton) { test24BitSound->play(); } else if (event.node == &jumpButton) { jumpSound->play(); } else if (event.node == &ambientButton) { ambientSound->play(); } else if (event.node == &musicButton) { music->play(); } } return true; } bool SoundSample::handleKeyboard(Event::Type type, const KeyboardEvent& event) const { if (type == Event::Type::KEY_PRESS) { switch (event.key) { case input::KeyboardKey::ESCAPE: case input::KeyboardKey::MENU: sharedEngine->getSceneManager()->setScene(std::unique_ptr<scene::Scene>(new MainMenu())); break; default: break; } } return true; } <|endoftext|>
<commit_before>/************************************************************************ filename: FalThumb.cpp created: Sun Jul 3 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "FalThumb.h" #include "falagard/CEGUIFalWidgetLookManager.h" #include "falagard/CEGUIFalWidgetLookFeel.h" // Start of CEGUI namespace section namespace CEGUI { const utf8 FalagardThumb::WidgetTypeName[] = "Falagard/Thumb"; FalagardThumb::FalagardThumb(const String& type, const String& name) : Thumb(type, name) { } FalagardThumb::~FalagardThumb() { } void FalagardThumb::populateRenderCache() { // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName); bool norm = false; String state; if (isDisabled()) { state = "Disabled"; } else if (d_pushed) { state = "Pushed"; } else if (d_hovering) { state = "Hover"; } else { state = "Normal"; norm = true; } if (!norm && !wlf.isStateImageryPresent(state)) { state = "Normal"; } wlf.getStateImagery(state).render(*this); } ////////////////////////////////////////////////////////////////////////// /************************************************************************* Factory Methods *************************************************************************/ ////////////////////////////////////////////////////////////////////////// Window* FalagardThumbFactory::createWindow(const String& name) { return new FalagardThumb(d_type, name); } void FalagardThumbFactory::destroyWindow(Window* window) { delete window; } } // End of CEGUI namespace section <commit_msg>Added "PushedOff" rendering state for Falagard Thumb base class.<commit_after>/************************************************************************ filename: FalThumb.cpp created: Sun Jul 3 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "FalThumb.h" #include "falagard/CEGUIFalWidgetLookManager.h" #include "falagard/CEGUIFalWidgetLookFeel.h" // Start of CEGUI namespace section namespace CEGUI { const utf8 FalagardThumb::WidgetTypeName[] = "Falagard/Thumb"; FalagardThumb::FalagardThumb(const String& type, const String& name) : Thumb(type, name) { } FalagardThumb::~FalagardThumb() { } void FalagardThumb::populateRenderCache() { // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName); bool norm = false; String state; if (isDisabled()) { state = "Disabled"; } else if (d_pushed) { state = d_hovering ? "Pushed" : "PushedOff"; } else if (d_hovering) { state = "Hover"; } else { state = "Normal"; norm = true; } if (!norm && !wlf.isStateImageryPresent(state)) { state = "Normal"; } wlf.getStateImagery(state).render(*this); } ////////////////////////////////////////////////////////////////////////// /************************************************************************* Factory Methods *************************************************************************/ ////////////////////////////////////////////////////////////////////////// Window* FalagardThumbFactory::createWindow(const String& name) { return new FalagardThumb(d_type, name); } void FalagardThumbFactory::destroyWindow(Window* window) { delete window; } } // End of CEGUI namespace section <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TreeComposite.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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 "vtkConeSource.h" #include "vtkSphereSource.h" #include "vtkPieceScalars.h" #include "vtkMultiProcessController.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkMath.h" #include "vtkTreeComposite.h" #include <unistd.h> void process(vtkMultiProcessController *controller, void *arg ) { vtkSphereSource *sphere; vtkConeSource *cone; vtkPieceScalars *color; vtkPolyDataMapper *mapper; vtkActor *actor; vtkCamera *cam; int myid, numProcs; float val; myid = controller->GetLocalProcessId(); numProcs = controller->GetNumberOfProcesses(); // Compute a different color for each process. sphere = vtkSphereSource::New(); sphere->SetPhiResolution(40); sphere->SetThetaResolution(60); cone = vtkConeSource::New(); cone->SetResolution(40); color = vtkPieceScalars::New(); color->SetInput(sphere->GetOutput()); color->SetInput(cone->GetOutput()); mapper = vtkPolyDataMapper::New(); mapper->SetPiece(myid); mapper->SetNumberOfPieces(numProcs); mapper->SetInput(color->GetOutput()); actor = vtkActor::New(); actor->SetMapper(mapper); vtkRenderer *ren = vtkRenderer::New(); vtkRenderWindow *renWindow = vtkRenderWindow::New(); renWindow->AddRenderer(ren); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWindow); vtkTreeComposite* treeComp = vtkTreeComposite::New(); treeComp->SetRenderWindow(renWindow); ren->SetBackground(0.9, 0.9, 0.9); renWindow->SetSize( 400, 400); // assign our actor to the renderer ren->AddActor(actor); cam = vtkCamera::New(); cam->SetFocalPoint(0, 0, 0); cam->SetPosition(0, 0, 10); cam->SetViewUp(0, 1, 0); cam->SetViewAngle(30); // this was causing an update. //ren->ResetCameraClippingRange(); //{ //double *range = ren->GetActiveCamera()->GetClippingRange(); //cerr << range[0] << ", " << range[1] << endl; //} cam->SetClippingRange(5.0, 15.0); ren->SetActiveCamera(cam); ren->CreateLight(); // Begin mouse interaction (for proc 0, others start rmi loop). iren->Start(); } void main( int argc, char *argv[] ) { vtkMultiProcessController *controller; char save_filename[100]="\0"; controller = vtkMultiProcessController::New(); controller->Initialize(argc, argv); // Needed for threaded controller. // controller->SetNumberOfProcesses(2); controller->SetSingleMethod(process, save_filename); if (controller->IsA("vtkThreadedController")) { controller->SetNumberOfProcesses(8); } controller->SingleMethodExecute(); controller->Delete(); } <commit_msg>Working now.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TreeComposite.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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 "vtkConeSource.h" #include "vtkSphereSource.h" #include "vtkPieceScalars.h" #include "vtkMultiProcessController.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkMath.h" #include "vtkTreeComposite.h" #include <unistd.h> void process(vtkMultiProcessController *controller, void *arg ) { vtkSphereSource *sphere; vtkConeSource *cone; vtkPieceScalars *color; vtkPolyDataMapper *mapper; vtkActor *actor; vtkCamera *cam; int myid, numProcs; float val; myid = controller->GetLocalProcessId(); numProcs = controller->GetNumberOfProcesses(); // Compute a different color for each process. sphere = vtkSphereSource::New(); sphere->SetPhiResolution(40); sphere->SetThetaResolution(60); cone = vtkConeSource::New(); cone->SetResolution(40); color = vtkPieceScalars::New(); color->SetInput(sphere->GetOutput()); //color->SetInput(cone->GetOutput()); mapper = vtkPolyDataMapper::New(); mapper->SetInput(color->GetOutput()); mapper->SetScalarRange(0, 3); actor = vtkActor::New(); actor->SetMapper(mapper); vtkRenderer *ren = vtkRenderer::New(); vtkRenderWindow *renWindow = vtkRenderWindow::New(); renWindow->AddRenderer(ren); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWindow); ren->SetBackground(0.9, 0.9, 0.9); renWindow->SetSize( 400, 400); // assign our actor to the renderer ren->AddActor(actor); // The only thing we have to do to get parallel execution. vtkTreeComposite* treeComp = vtkTreeComposite::New(); treeComp->SetRenderWindow(renWindow); // Tell the mappers to only update a piece (based on process) of their inputs. treeComp->InitializePieces(); treeComp->InitializeOffScreen(); // Begin mouse interaction (for proc 0, others start rmi loop). iren->Start(); } void main( int argc, char *argv[] ) { vtkMultiProcessController *controller; char save_filename[100]="\0"; controller = vtkMultiProcessController::New(); controller->Initialize(argc, argv); // Needed for threaded controller. // controller->SetNumberOfProcesses(2); controller->SetSingleMethod(process, save_filename); if (controller->IsA("vtkThreadedController")) { controller->SetNumberOfProcesses(8); } controller->SingleMethodExecute(); controller->Delete(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2010 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ # include "config.h" # include <iostream> # include <cassert> # include <typeinfo> # include "compiler.h" # include "netlist.h" # include "netmisc.h" NexusSet* NetExpr::nex_input(bool) { cerr << get_fileline() << ": internal error: nex_input not implemented: " << *this << endl; return 0; } NexusSet* NetProc::nex_input(bool) { cerr << get_fileline() << ": internal error: NetProc::nex_input not implemented" << endl; return 0; } NexusSet* NetEBinary::nex_input(bool rem_out) { NexusSet*result = left_->nex_input(rem_out); NexusSet*tmp = right_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetEConcat::nex_input(bool rem_out) { if (parms_[0] == NULL) return NULL; NexusSet*result = parms_[0]->nex_input(rem_out); for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) { if (parms_[idx] == NULL) { delete result; return NULL; } NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetEAccess::nex_input(bool) { return new NexusSet; } /* * A constant has not inputs, so always return an empty set. */ NexusSet* NetEConst::nex_input(bool) { return new NexusSet; } NexusSet* NetECReal::nex_input(bool) { return new NexusSet; } /* * A parameter by definition has no inputs. It represents a constant * value, even if that value is a constant expression. */ NexusSet* NetEParam::nex_input(bool) { return new NexusSet; } NexusSet* NetEEvent::nex_input(bool) { return new NexusSet; } NexusSet* NetEScope::nex_input(bool) { return new NexusSet; } NexusSet* NetESelect::nex_input(bool rem_out) { NexusSet*result = base_? base_->nex_input(rem_out) : new NexusSet(); NexusSet*tmp = expr_->nex_input(rem_out); if (tmp == NULL) { delete result; return NULL; } result->add(*tmp); delete tmp; /* See the comment for NetESignal below. */ if (base_ && warn_sens_entire_vec) { cerr << get_fileline() << ": warning: @* is sensitive to all " "bits in '" << *expr_ << "'." << endl; } return result; } NexusSet* NetESFunc::nex_input(bool rem_out) { if (nparms_ == 0) return new NexusSet; NexusSet*result = parms_[0]->nex_input(rem_out); for (unsigned idx = 1 ; idx < nparms_ ; idx += 1) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetESignal::nex_input(bool rem_out) { /* * This is not what I would expect for the various selects (bit, * part, index, array). This code adds all the bits/array words * instead of building the appropriate select and then using it * as the trigger. Other simulators also add everything. */ NexusSet*result = new NexusSet; /* If we have an array index add it to the sensitivity list. */ if (word_) { NexusSet*tmp; tmp = word_->nex_input(rem_out); result->add(*tmp); delete tmp; if (warn_sens_entire_arr) { cerr << get_fileline() << ": warning: @* is sensitive to all " << net_->array_count() << " words in array '" << name() << "'." << endl; } } for (unsigned idx = 0 ; idx < net_->pin_count() ; idx += 1) result->add(net_->pin(idx).nexus()); return result; } NexusSet* NetETernary::nex_input(bool rem_out) { NexusSet*tmp; NexusSet*result = cond_->nex_input(rem_out); tmp = true_val_->nex_input(rem_out); result->add(*tmp); delete tmp; tmp = false_val_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetEUFunc::nex_input(bool rem_out) { NexusSet*result = new NexusSet; for (unsigned idx = 0 ; idx < parms_.count() ; idx += 1) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetEUnary::nex_input(bool rem_out) { return expr_->nex_input(rem_out); } NexusSet* NetAssign_::nex_input(bool rem_out) { NexusSet*result = new NexusSet; if (word_) { NexusSet*tmp = word_->nex_input(rem_out); result->add(*tmp); delete tmp; } if (base_) { NexusSet*tmp = base_->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetAssignBase::nex_input(bool rem_out) { NexusSet*result = rval_->nex_input(rem_out); /* It is possible that the lval_ can have nex_input values. In particular, index expressions are statement inputs as well, so should be addressed here. */ for (NetAssign_*cur = lval_ ; cur ; cur = cur->more) { NexusSet*tmp = cur->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } /* * The nex_input of a begin/end block is the NexusSet of bits that the * block reads from outside the block. That means it is the union of * the nex_input for all the substatements. * * The input set for a sequential set is not exactly the union of the * input sets because there is the possibility of intermediate values, * that don't deserve to be in the input set. To wit: * * begin * t = a + b; * c = ~t; * end * * In this example, "t" should not be in the input set because it is * used by the sequence as a temporary value. */ NexusSet* NetBlock::nex_input(bool rem_out) { if (last_ == 0) return new NexusSet; if (type_ == PARA) { cerr << get_fileline() << ": internal error: Sorry, " << "I don't know how to synthesize fork/join blocks." << endl; return 0; } NetProc*cur = last_->next_; /* This is the accumulated input set. */ NexusSet*result = new NexusSet; /* This is an accumulated output set. */ NexusSet*prev = new NexusSet; do { /* Get the inputs for the current statement. */ NexusSet*tmp = cur->nex_input(rem_out); /* Add the current input set to the accumulated input set. */ if (tmp != 0) result->add(*tmp); delete tmp; /* Add the current outputs to the accumulated output set, so they can be removed from the input set below. */ cur->nex_output(*prev); cur = cur->next_; } while (cur != last_->next_); /* Remove from the input set those bits that are outputs from other statements. They aren't really inputs to the block, just internal intermediate values. */ if (rem_out) result->rem(*prev); return result; } /* * The inputs to a case statement are the inputs to the expression, * the inputs to all the guards, and the inputs to all the guarded * statements. */ NexusSet* NetCase::nex_input(bool rem_out) { NexusSet*result = expr_->nex_input(rem_out); if (result == 0) return 0; for (unsigned idx = 0 ; idx < nitems_ ; idx += 1) { /* Skip cases that have empty statements. */ if (items_[idx].statement == 0) continue; NexusSet*tmp = items_[idx].statement->nex_input(rem_out); assert(tmp); result->add(*tmp); delete tmp; /* Usually, this is the guard expression. The default case is special and is identified by a null guard. The default guard obviously has no input. */ if (items_[idx].guard) { tmp = items_[idx].guard->nex_input(rem_out); assert(tmp); result->add(*tmp); delete tmp; } } return result; } NexusSet* NetCAssign::nex_input(bool) { cerr << get_fileline() << ": internal warning: NetCAssign::nex_input()" << " not implemented." << endl; return new NexusSet; } NexusSet* NetCondit::nex_input(bool rem_out) { NexusSet*result = expr_->nex_input(rem_out); if (if_ != 0) { NexusSet*tmp = if_->nex_input(rem_out); result->add(*tmp); delete tmp; } if (else_ != 0) { NexusSet*tmp = else_->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetForce::nex_input(bool) { cerr << get_fileline() << ": internal warning: NetForce::nex_input()" << " not implemented." << endl; return new NexusSet; } NexusSet* NetForever::nex_input(bool rem_out) { NexusSet*result = statement_->nex_input(rem_out); return result; } /* * The NetPDelay statement is a statement of the form * * #<expr> <statement> * * The nex_input set is the input set of the <statement>. Do *not* * include the input set of the <expr> because it does not affect the * result. The statement can be omitted. */ NexusSet* NetPDelay::nex_input(bool rem_out) { if (statement_ == 0) return 0; NexusSet*result = statement_->nex_input(rem_out); return result; } NexusSet* NetRepeat::nex_input(bool rem_out) { NexusSet*result = statement_->nex_input(rem_out); NexusSet*tmp = expr_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetSTask::nex_input(bool rem_out) { if (parms_.count() == 0) return new NexusSet; NexusSet*result = parms_[0]->nex_input(rem_out); for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } /* * The NetUTask represents a call to a user defined task. There are no * parameters to consider, because the compiler already removed them * and converted them to blocking assignments. */ NexusSet* NetUTask::nex_input(bool) { return new NexusSet; } NexusSet* NetWhile::nex_input(bool rem_out) { NexusSet*result = proc_->nex_input(rem_out); NexusSet*tmp = cond_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } <commit_msg>Ignore system tasks/functions NULL arguments in @* calculation.<commit_after>/* * Copyright (c) 2002-2010 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ # include "config.h" # include <iostream> # include <cassert> # include <typeinfo> # include "compiler.h" # include "netlist.h" # include "netmisc.h" NexusSet* NetExpr::nex_input(bool) { cerr << get_fileline() << ": internal error: nex_input not implemented: " << *this << endl; return 0; } NexusSet* NetProc::nex_input(bool) { cerr << get_fileline() << ": internal error: NetProc::nex_input not implemented" << endl; return 0; } NexusSet* NetEBinary::nex_input(bool rem_out) { NexusSet*result = left_->nex_input(rem_out); NexusSet*tmp = right_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetEConcat::nex_input(bool rem_out) { if (parms_[0] == NULL) return NULL; NexusSet*result = parms_[0]->nex_input(rem_out); for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) { if (parms_[idx] == NULL) { delete result; return NULL; } NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetEAccess::nex_input(bool) { return new NexusSet; } /* * A constant has not inputs, so always return an empty set. */ NexusSet* NetEConst::nex_input(bool) { return new NexusSet; } NexusSet* NetECReal::nex_input(bool) { return new NexusSet; } /* * A parameter by definition has no inputs. It represents a constant * value, even if that value is a constant expression. */ NexusSet* NetEParam::nex_input(bool) { return new NexusSet; } NexusSet* NetEEvent::nex_input(bool) { return new NexusSet; } NexusSet* NetEScope::nex_input(bool) { return new NexusSet; } NexusSet* NetESelect::nex_input(bool rem_out) { NexusSet*result = base_? base_->nex_input(rem_out) : new NexusSet(); NexusSet*tmp = expr_->nex_input(rem_out); if (tmp == NULL) { delete result; return NULL; } result->add(*tmp); delete tmp; /* See the comment for NetESignal below. */ if (base_ && warn_sens_entire_vec) { cerr << get_fileline() << ": warning: @* is sensitive to all " "bits in '" << *expr_ << "'." << endl; } return result; } /* * The $fread, etc. system functions can have NULL arguments. */ NexusSet* NetESFunc::nex_input(bool rem_out) { if (nparms_ == 0) return new NexusSet; NexusSet*result; if (parms_[0]) result = parms_[0]->nex_input(rem_out); else result = new NexusSet; for (unsigned idx = 1 ; idx < nparms_ ; idx += 1) { if (parms_[idx]) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } } return result; } NexusSet* NetESignal::nex_input(bool rem_out) { /* * This is not what I would expect for the various selects (bit, * part, index, array). This code adds all the bits/array words * instead of building the appropriate select and then using it * as the trigger. Other simulators also add everything. */ NexusSet*result = new NexusSet; /* If we have an array index add it to the sensitivity list. */ if (word_) { NexusSet*tmp; tmp = word_->nex_input(rem_out); result->add(*tmp); delete tmp; if (warn_sens_entire_arr) { cerr << get_fileline() << ": warning: @* is sensitive to all " << net_->array_count() << " words in array '" << name() << "'." << endl; } } for (unsigned idx = 0 ; idx < net_->pin_count() ; idx += 1) result->add(net_->pin(idx).nexus()); return result; } NexusSet* NetETernary::nex_input(bool rem_out) { NexusSet*tmp; NexusSet*result = cond_->nex_input(rem_out); tmp = true_val_->nex_input(rem_out); result->add(*tmp); delete tmp; tmp = false_val_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } NexusSet* NetEUFunc::nex_input(bool rem_out) { NexusSet*result = new NexusSet; for (unsigned idx = 0 ; idx < parms_.count() ; idx += 1) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetEUnary::nex_input(bool rem_out) { return expr_->nex_input(rem_out); } NexusSet* NetAssign_::nex_input(bool rem_out) { NexusSet*result = new NexusSet; if (word_) { NexusSet*tmp = word_->nex_input(rem_out); result->add(*tmp); delete tmp; } if (base_) { NexusSet*tmp = base_->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetAssignBase::nex_input(bool rem_out) { NexusSet*result = rval_->nex_input(rem_out); /* It is possible that the lval_ can have nex_input values. In particular, index expressions are statement inputs as well, so should be addressed here. */ for (NetAssign_*cur = lval_ ; cur ; cur = cur->more) { NexusSet*tmp = cur->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } /* * The nex_input of a begin/end block is the NexusSet of bits that the * block reads from outside the block. That means it is the union of * the nex_input for all the substatements. * * The input set for a sequential set is not exactly the union of the * input sets because there is the possibility of intermediate values, * that don't deserve to be in the input set. To wit: * * begin * t = a + b; * c = ~t; * end * * In this example, "t" should not be in the input set because it is * used by the sequence as a temporary value. */ NexusSet* NetBlock::nex_input(bool rem_out) { if (last_ == 0) return new NexusSet; if (type_ == PARA) { cerr << get_fileline() << ": internal error: Sorry, " << "I don't know how to synthesize fork/join blocks." << endl; return 0; } NetProc*cur = last_->next_; /* This is the accumulated input set. */ NexusSet*result = new NexusSet; /* This is an accumulated output set. */ NexusSet*prev = new NexusSet; do { /* Get the inputs for the current statement. */ NexusSet*tmp = cur->nex_input(rem_out); /* Add the current input set to the accumulated input set. */ if (tmp != 0) result->add(*tmp); delete tmp; /* Add the current outputs to the accumulated output set, so they can be removed from the input set below. */ cur->nex_output(*prev); cur = cur->next_; } while (cur != last_->next_); /* Remove from the input set those bits that are outputs from other statements. They aren't really inputs to the block, just internal intermediate values. */ if (rem_out) result->rem(*prev); return result; } /* * The inputs to a case statement are the inputs to the expression, * the inputs to all the guards, and the inputs to all the guarded * statements. */ NexusSet* NetCase::nex_input(bool rem_out) { NexusSet*result = expr_->nex_input(rem_out); if (result == 0) return 0; for (unsigned idx = 0 ; idx < nitems_ ; idx += 1) { /* Skip cases that have empty statements. */ if (items_[idx].statement == 0) continue; NexusSet*tmp = items_[idx].statement->nex_input(rem_out); assert(tmp); result->add(*tmp); delete tmp; /* Usually, this is the guard expression. The default case is special and is identified by a null guard. The default guard obviously has no input. */ if (items_[idx].guard) { tmp = items_[idx].guard->nex_input(rem_out); assert(tmp); result->add(*tmp); delete tmp; } } return result; } NexusSet* NetCAssign::nex_input(bool) { cerr << get_fileline() << ": internal warning: NetCAssign::nex_input()" << " not implemented." << endl; return new NexusSet; } NexusSet* NetCondit::nex_input(bool rem_out) { NexusSet*result = expr_->nex_input(rem_out); if (if_ != 0) { NexusSet*tmp = if_->nex_input(rem_out); result->add(*tmp); delete tmp; } if (else_ != 0) { NexusSet*tmp = else_->nex_input(rem_out); result->add(*tmp); delete tmp; } return result; } NexusSet* NetForce::nex_input(bool) { cerr << get_fileline() << ": internal warning: NetForce::nex_input()" << " not implemented." << endl; return new NexusSet; } NexusSet* NetForever::nex_input(bool rem_out) { NexusSet*result = statement_->nex_input(rem_out); return result; } /* * The NetPDelay statement is a statement of the form * * #<expr> <statement> * * The nex_input set is the input set of the <statement>. Do *not* * include the input set of the <expr> because it does not affect the * result. The statement can be omitted. */ NexusSet* NetPDelay::nex_input(bool rem_out) { if (statement_ == 0) return 0; NexusSet*result = statement_->nex_input(rem_out); return result; } NexusSet* NetRepeat::nex_input(bool rem_out) { NexusSet*result = statement_->nex_input(rem_out); NexusSet*tmp = expr_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } /* * The $display, etc. system tasks can have NULL arguments. */ NexusSet* NetSTask::nex_input(bool rem_out) { if (parms_.count() == 0) return new NexusSet; NexusSet*result; if (parms_[0]) result = parms_[0]->nex_input(rem_out); else result = new NexusSet; for (unsigned idx = 1 ; idx < parms_.count() ; idx += 1) { if (parms_[idx]) { NexusSet*tmp = parms_[idx]->nex_input(rem_out); result->add(*tmp); delete tmp; } } return result; } /* * The NetUTask represents a call to a user defined task. There are no * parameters to consider, because the compiler already removed them * and converted them to blocking assignments. */ NexusSet* NetUTask::nex_input(bool) { return new NexusSet; } NexusSet* NetWhile::nex_input(bool rem_out) { NexusSet*result = proc_->nex_input(rem_out); NexusSet*tmp = cond_->nex_input(rem_out); result->add(*tmp); delete tmp; return result; } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkBlurMaskFilter.h" namespace skiagm { class BlursGM : public GM { public: BlursGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual uint32_t onGetFlags() const SK_OVERRIDE { return this->INHERITED::onGetFlags() | GM::kSkipPipe_Flag; } virtual SkString onShortName() { return SkString("blurs"); } virtual SkISize onISize() { return make_isize(700, 500); } virtual void onDraw(SkCanvas* canvas) { SkBlurMaskFilter::BlurStyle NONE = SkBlurMaskFilter::BlurStyle(-999); static const struct { SkBlurMaskFilter::BlurStyle fStyle; int fCx, fCy; } gRecs[] = { { NONE, 0, 0 }, { SkBlurMaskFilter::kInner_BlurStyle, -1, 0 }, { SkBlurMaskFilter::kNormal_BlurStyle, 0, 1 }, { SkBlurMaskFilter::kSolid_BlurStyle, 0, -1 }, { SkBlurMaskFilter::kOuter_BlurStyle, 1, 0 }, }; SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(25)); canvas->translate(SkIntToScalar(-40), SkIntToScalar(0)); SkBlurMaskFilter::BlurFlags flags = SkBlurMaskFilter::kNone_BlurFlag; for (int j = 0; j < 2; j++) { canvas->save(); paint.setColor(SK_ColorBLUE); for (size_t i = 0; i < SK_ARRAY_COUNT(gRecs); i++) { if (gRecs[i].fStyle != NONE) { SkMaskFilter* mf = SkBlurMaskFilter::Create( SkIntToScalar(20), gRecs[i].fStyle, flags ); paint.setMaskFilter(mf)->unref(); } else { paint.setMaskFilter(NULL); } canvas->drawCircle(SkIntToScalar(200 + gRecs[i].fCx*100) , SkIntToScalar(200 + gRecs[i].fCy*100) , SkIntToScalar(50) , paint); } // draw text { SkMaskFilter* mf = SkBlurMaskFilter::Create( SkIntToScalar(4) , SkBlurMaskFilter::kNormal_BlurStyle , flags ); paint.setMaskFilter(mf)->unref(); SkScalar x = SkIntToScalar(70); SkScalar y = SkIntToScalar(400); paint.setColor(SK_ColorBLACK); canvas->drawText("Hamburgefons Style", 18, x, y, paint); canvas->drawText("Hamburgefons Style", 18 , x, y + SkIntToScalar(50), paint); paint.setMaskFilter(NULL); paint.setColor(SK_ColorWHITE); x -= SkIntToScalar(2); y -= SkIntToScalar(2); canvas->drawText("Hamburgefons Style", 18, x, y, paint); } canvas->restore(); flags = SkBlurMaskFilter::kHighQuality_BlurFlag; canvas->translate(SkIntToScalar(350), SkIntToScalar(0)); } } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BlursGM; } static GMRegistry reg(MyFactory); } <commit_msg>Only skip pipe playback for blurs GM in FIXED mode.<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkBlurMaskFilter.h" namespace skiagm { class BlursGM : public GM { public: BlursGM() { this->setBGColor(0xFFDDDDDD); } protected: #ifdef SK_SCALAR_IS_FIXED virtual uint32_t onGetFlags() const SK_OVERRIDE { // SkCanvas::drawCircle, used by this test, performs a quick reject. // The large size given to the device used by SkGPipeCanvas means that // the device clip will not be set properly and circles will be // rejected when in FIXED. return this->INHERITED::onGetFlags() | GM::kSkipPipe_Flag; } #endif virtual SkString onShortName() { return SkString("blurs"); } virtual SkISize onISize() { return make_isize(700, 500); } virtual void onDraw(SkCanvas* canvas) { SkBlurMaskFilter::BlurStyle NONE = SkBlurMaskFilter::BlurStyle(-999); static const struct { SkBlurMaskFilter::BlurStyle fStyle; int fCx, fCy; } gRecs[] = { { NONE, 0, 0 }, { SkBlurMaskFilter::kInner_BlurStyle, -1, 0 }, { SkBlurMaskFilter::kNormal_BlurStyle, 0, 1 }, { SkBlurMaskFilter::kSolid_BlurStyle, 0, -1 }, { SkBlurMaskFilter::kOuter_BlurStyle, 1, 0 }, }; SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(25)); canvas->translate(SkIntToScalar(-40), SkIntToScalar(0)); SkBlurMaskFilter::BlurFlags flags = SkBlurMaskFilter::kNone_BlurFlag; for (int j = 0; j < 2; j++) { canvas->save(); paint.setColor(SK_ColorBLUE); for (size_t i = 0; i < SK_ARRAY_COUNT(gRecs); i++) { if (gRecs[i].fStyle != NONE) { SkMaskFilter* mf = SkBlurMaskFilter::Create( SkIntToScalar(20), gRecs[i].fStyle, flags ); paint.setMaskFilter(mf)->unref(); } else { paint.setMaskFilter(NULL); } canvas->drawCircle(SkIntToScalar(200 + gRecs[i].fCx*100) , SkIntToScalar(200 + gRecs[i].fCy*100) , SkIntToScalar(50) , paint); } // draw text { SkMaskFilter* mf = SkBlurMaskFilter::Create( SkIntToScalar(4) , SkBlurMaskFilter::kNormal_BlurStyle , flags ); paint.setMaskFilter(mf)->unref(); SkScalar x = SkIntToScalar(70); SkScalar y = SkIntToScalar(400); paint.setColor(SK_ColorBLACK); canvas->drawText("Hamburgefons Style", 18, x, y, paint); canvas->drawText("Hamburgefons Style", 18 , x, y + SkIntToScalar(50), paint); paint.setMaskFilter(NULL); paint.setColor(SK_ColorWHITE); x -= SkIntToScalar(2); y -= SkIntToScalar(2); canvas->drawText("Hamburgefons Style", 18, x, y, paint); } canvas->restore(); flags = SkBlurMaskFilter::kHighQuality_BlurFlag; canvas->translate(SkIntToScalar(350), SkIntToScalar(0)); } } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BlursGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkGradientShader.h" #include "SkPM4fPriv.h" DEF_SIMPLE_GM(gamma, canvas, 560, 200) { SkPaint p; const SkScalar sz = 50.0f; const int szInt = SkScalarTruncToInt(sz); const SkScalar tx = sz + 5.0f; const SkRect r = SkRect::MakeXYWH(0, 0, sz, sz); SkShader::TileMode rpt = SkShader::kRepeat_TileMode; auto srgbColorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named); SkBitmap ditherBmp; ditherBmp.allocN32Pixels(2, 2); SkPMColor* pixels = reinterpret_cast<SkPMColor*>(ditherBmp.getPixels()); pixels[0] = pixels[3] = SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF); pixels[1] = pixels[2] = SkPackARGB32(0xFF, 0, 0, 0); SkBitmap linearGreyBmp; SkImageInfo linearGreyInfo = SkImageInfo::MakeN32(szInt, szInt, kOpaque_SkAlphaType, nullptr); linearGreyBmp.allocPixels(linearGreyInfo); linearGreyBmp.eraseARGB(0xFF, 0x7F, 0x7F, 0x7F); SkBitmap srgbGreyBmp; SkImageInfo srgbGreyInfo = SkImageInfo::MakeN32(szInt, szInt, kOpaque_SkAlphaType, srgbColorSpace); srgbGreyBmp.allocPixels(srgbGreyInfo); // 0xBC = 255 * linear_to_srgb(0.5f) srgbGreyBmp.eraseARGB(0xFF, 0xBC, 0xBC, 0xBC); SkBitmap mipmapBmp; SkImageInfo mipmapInfo = SkImageInfo::Make(2, 2, kN32_SkColorType, kOpaque_SkAlphaType, srgbColorSpace); mipmapBmp.allocPixels(mipmapInfo); SkPMColor* mipmapPixels = reinterpret_cast<SkPMColor*>(mipmapBmp.getPixels()); unsigned s25 = 0x89; // 255 * linear_to_srgb(0.25f) unsigned s75 = 0xE1; // 255 * linear_to_srgb(0.75f) mipmapPixels[0] = mipmapPixels[3] = SkPackARGB32(0xFF, s25, s25, s25); mipmapPixels[1] = mipmapPixels[2] = SkPackARGB32(0xFF, s75, s75, s75); SkPaint textPaint; textPaint.setColor(SK_ColorWHITE); // Helpers: auto advance = [&]() { canvas->translate(tx, 0); p.reset(); }; auto nextRect = [&](const char* label, const char* label2) { canvas->drawRect(r, p); canvas->drawText(label, strlen(label), 0, sz + textPaint.getFontSpacing(), textPaint); if (label2) { canvas->drawText(label2, strlen(label2), 0, sz + 2 * textPaint.getFontSpacing(), textPaint); } advance(); }; auto nextBitmap = [&](const SkBitmap& bmp, const char* label) { canvas->drawBitmap(bmp, 0, 0); canvas->drawText(label, strlen(label), 0, sz + textPaint.getFontSpacing(), textPaint); advance(); }; auto nextXferRect = [&](SkColor srcColor, SkXfermode::Mode mode, SkColor dstColor) { p.setColor(dstColor); canvas->drawRect(r, p); p.setColor(srcColor); p.setXfermodeMode(mode); canvas->drawRect(r, p); SkString srcText = SkStringPrintf("%08X", srcColor); SkString dstText = SkStringPrintf("%08X", dstColor); canvas->drawText(srcText.c_str(), srcText.size(), 0, sz + textPaint.getFontSpacing(), textPaint); const char* modeName = SkXfermode::ModeName(mode); canvas->drawText(modeName, strlen(modeName), 0, sz + 2 * textPaint.getFontSpacing(), textPaint); canvas->drawText(dstText.c_str(), dstText.size(), 0, sz + 3 * textPaint.getFontSpacing(), textPaint); advance(); }; // Necessary for certain Xfermode tests to work (ie some of them output white @ 50% alpha): canvas->clear(SK_ColorBLACK); // *Everything* should be perceptually 50% grey. Only the first rectangle // is guaranteed to draw that way, though. canvas->save(); // Black/white dither, pixel perfect. This is ground truth. p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kNone_SkFilterQuality); nextRect("Dither", "Reference"); // Black/white dither, sampled at half-texel offset. Tests bilerp. // NOTE: We need to apply a non-identity scale and/or rotation to trick // the raster pipeline into *not* snapping to nearest. SkMatrix offsetMatrix = SkMatrix::Concat( SkMatrix::MakeScale(-1.0f), SkMatrix::MakeTrans(0.5f, 0.0f)); p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt, &offsetMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Dither", "Bilerp"); // Black/white dither, scaled down by 2x. Tests minification. SkMatrix scaleMatrix = SkMatrix::MakeScale(0.5f); p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt, &scaleMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Dither", "Scale"); // 25%/75% dither, scaled down by 2x. Tests ALL aspects of minification. Specifically, are // sRGB sources decoded to linear before computing mipmaps? p.setShader(SkShader::MakeBitmapShader(mipmapBmp, rpt, rpt, &scaleMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("MipMaps", 0); // 50% grey via paint color. p.setColor(0xff7f7f7f); nextRect("Color", 0); // Black -> White gradient, scaled to sample just the middle. // Tests gradient interpolation. SkPoint points[2] = { SkPoint::Make(0 - (sz * 10), 0), SkPoint::Make(sz + (sz * 10), 0) }; SkColor colors[2] = { SK_ColorBLACK, SK_ColorWHITE }; p.setShader(SkGradientShader::MakeLinear(points, colors, nullptr, 2, SkShader::kClamp_TileMode)); nextRect("Gradient", 0); // 50% grey from linear bitmap, with drawBitmap nextBitmap(linearGreyBmp, "Lnr BMP"); // 50% grey from sRGB bitmap, with drawBitmap nextBitmap(srgbGreyBmp, "sRGB BMP"); // Bitmap wrapped in a shader (linear): p.setShader(SkShader::MakeBitmapShader(linearGreyBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Lnr BMP", "Shader"); // Bitmap wrapped in a shader (sRGB): p.setShader(SkShader::MakeBitmapShader(srgbGreyBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("sRGB BMP", "Shader"); // Carriage return. canvas->restore(); canvas->translate(0, 2 * sz); const U8CPU sqrtHalf = 0xB4; const SkColor sqrtHalfAlpha = SkColorSetARGB(sqrtHalf, 0, 0, 0); const SkColor sqrtHalfWhite = SkColorSetARGB(0xFF, sqrtHalf, sqrtHalf, sqrtHalf); // Xfermode tests, all done off-screen so certain modes work... canvas->saveLayer(nullptr, nullptr); nextXferRect(0x7fffffff, SkXfermode::kSrcOver_Mode, SK_ColorBLACK); nextXferRect(0x7f000000, SkXfermode::kSrcOver_Mode, SK_ColorWHITE); nextXferRect(SK_ColorBLACK, SkXfermode::kDstOver_Mode, 0x7fffffff); nextXferRect(SK_ColorWHITE, SkXfermode::kSrcIn_Mode, 0x7fff00ff); nextXferRect(0x7fff00ff, SkXfermode::kDstIn_Mode, SK_ColorWHITE); nextXferRect(sqrtHalfWhite, SkXfermode::kSrcIn_Mode, sqrtHalfAlpha); nextXferRect(sqrtHalfAlpha, SkXfermode::kDstIn_Mode, sqrtHalfWhite); nextXferRect(0xff3f3f3f, SkXfermode::kPlus_Mode, 0xff3f3f3f); nextXferRect(sqrtHalfWhite, SkXfermode::kModulate_Mode, sqrtHalfWhite); canvas->restore(); } <commit_msg>Improve the gamma GM significantly<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkGradientShader.h" #include "SkPM4fPriv.h" DEF_SIMPLE_GM(gamma, canvas, 650, 200) { SkPaint p; const SkScalar sz = 50.0f; const int szInt = SkScalarTruncToInt(sz); const SkScalar tx = sz + 15.0f; const SkRect r = SkRect::MakeXYWH(0, 0, sz, sz); SkShader::TileMode rpt = SkShader::kRepeat_TileMode; auto srgbColorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named); SkBitmap ditherBmp; ditherBmp.allocN32Pixels(2, 2); SkPMColor* pixels = reinterpret_cast<SkPMColor*>(ditherBmp.getPixels()); pixels[0] = pixels[3] = SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF); pixels[1] = pixels[2] = SkPackARGB32(0xFF, 0, 0, 0); SkBitmap linearGreyBmp; SkImageInfo linearGreyInfo = SkImageInfo::MakeN32(szInt, szInt, kOpaque_SkAlphaType, nullptr); linearGreyBmp.allocPixels(linearGreyInfo); linearGreyBmp.eraseARGB(0xFF, 0x7F, 0x7F, 0x7F); SkBitmap srgbGreyBmp; SkImageInfo srgbGreyInfo = SkImageInfo::MakeN32(szInt, szInt, kOpaque_SkAlphaType, srgbColorSpace); srgbGreyBmp.allocPixels(srgbGreyInfo); // 0xBC = 255 * linear_to_srgb(0.5f) srgbGreyBmp.eraseARGB(0xFF, 0xBC, 0xBC, 0xBC); SkBitmap mipmapBmp; SkImageInfo mipmapInfo = SkImageInfo::Make(2, 2, kN32_SkColorType, kOpaque_SkAlphaType, srgbColorSpace); mipmapBmp.allocPixels(mipmapInfo); SkPMColor* mipmapPixels = reinterpret_cast<SkPMColor*>(mipmapBmp.getPixels()); unsigned s25 = 0x89; // 255 * linear_to_srgb(0.25f) unsigned s75 = 0xE1; // 255 * linear_to_srgb(0.75f) mipmapPixels[0] = mipmapPixels[3] = SkPackARGB32(0xFF, s25, s25, s25); mipmapPixels[1] = mipmapPixels[2] = SkPackARGB32(0xFF, s75, s75, s75); SkPaint textPaint; textPaint.setAntiAlias(true); textPaint.setColor(SK_ColorWHITE); sk_tool_utils::set_portable_typeface(&textPaint); // Helpers: auto advance = [&]() { canvas->translate(tx, 0); p.reset(); }; auto nextRect = [&](const char* label, const char* label2) { canvas->drawRect(r, p); canvas->drawText(label, strlen(label), 0, sz + textPaint.getFontSpacing(), textPaint); if (label2) { canvas->drawText(label2, strlen(label2), 0, sz + 2 * textPaint.getFontSpacing(), textPaint); } advance(); }; auto nextBitmap = [&](const SkBitmap& bmp, const char* label) { canvas->drawBitmap(bmp, 0, 0); canvas->drawText(label, strlen(label), 0, sz + textPaint.getFontSpacing(), textPaint); advance(); }; auto nextXferRect = [&](SkColor srcColor, SkXfermode::Mode mode, SkColor dstColor) { p.setColor(dstColor); canvas->drawRect(r, p); p.setColor(srcColor); p.setXfermodeMode(mode); canvas->drawRect(r, p); SkString srcText = SkStringPrintf("%08X", srcColor); SkString dstText = SkStringPrintf("%08X", dstColor); canvas->drawText(srcText.c_str(), srcText.size(), 0, sz + textPaint.getFontSpacing(), textPaint); const char* modeName = SkXfermode::ModeName(mode); canvas->drawText(modeName, strlen(modeName), 0, sz + 2 * textPaint.getFontSpacing(), textPaint); canvas->drawText(dstText.c_str(), dstText.size(), 0, sz + 3 * textPaint.getFontSpacing(), textPaint); advance(); }; // Necessary for certain Xfermode tests to work (ie some of them output white @ 50% alpha): canvas->clear(SK_ColorBLACK); // *Everything* should be perceptually 50% grey. Only the first rectangle // is guaranteed to draw that way, though. canvas->save(); // Black/white dither, pixel perfect. This is ground truth. p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kNone_SkFilterQuality); nextRect("Dither", "Reference"); // Black/white dither, sampled at half-texel offset. Tests bilerp. // NOTE: We need to apply a non-identity scale and/or rotation to trick // the raster pipeline into *not* snapping to nearest. SkMatrix offsetMatrix = SkMatrix::Concat( SkMatrix::MakeScale(-1.0f), SkMatrix::MakeTrans(0.5f, 0.0f)); p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt, &offsetMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Dither", "Bilerp"); // Black/white dither, scaled down by 2x. Tests minification. SkMatrix scaleMatrix = SkMatrix::MakeScale(0.5f); p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt, &scaleMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Dither", "Scale"); // 25%/75% dither, scaled down by 2x. Tests ALL aspects of minification. Specifically, are // sRGB sources decoded to linear before computing mipmaps? p.setShader(SkShader::MakeBitmapShader(mipmapBmp, rpt, rpt, &scaleMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("MipMaps", 0); // 50% grey via paint color. Paint color (SkColor) is specified to be sRGB! p.setColor(0xffbcbcbc); nextRect("Color", 0); // Black -> White gradient, scaled to sample just the middle. // Tests gradient interpolation. SkPoint points[2] = { SkPoint::Make(0 - (sz * 10), 0), SkPoint::Make(sz + (sz * 10), 0) }; SkColor colors[2] = { SK_ColorBLACK, SK_ColorWHITE }; p.setShader(SkGradientShader::MakeLinear(points, colors, nullptr, 2, SkShader::kClamp_TileMode)); nextRect("Gradient", 0); // 50% grey from linear bitmap, with drawBitmap nextBitmap(linearGreyBmp, "Lnr BMP"); // 50% grey from sRGB bitmap, with drawBitmap nextBitmap(srgbGreyBmp, "sRGB BMP"); // Bitmap wrapped in a shader (linear): p.setShader(SkShader::MakeBitmapShader(linearGreyBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Lnr BMP", "Shader"); // Bitmap wrapped in a shader (sRGB): p.setShader(SkShader::MakeBitmapShader(srgbGreyBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("sRGB BMP", "Shader"); // Carriage return. canvas->restore(); canvas->translate(0, 2 * sz); // Xfermode tests, all done off-screen so certain modes work... canvas->saveLayer(nullptr, nullptr); nextXferRect(0x7fffffff, SkXfermode::kSrcOver_Mode, SK_ColorBLACK); nextXferRect(0x7f000000, SkXfermode::kSrcOver_Mode, SK_ColorWHITE); nextXferRect(SK_ColorBLACK, SkXfermode::kDstOver_Mode, 0x7fffffff); nextXferRect(SK_ColorWHITE, SkXfermode::kSrcIn_Mode, 0x7fff00ff); nextXferRect(0x7fff00ff, SkXfermode::kDstIn_Mode, SK_ColorWHITE); // 0x89 = 255 * linear_to_srgb(0.25) nextXferRect(0xff898989, SkXfermode::kPlus_Mode, 0xff898989); // 0xDB = 255 * linear_to_srgb(sqrt(0.5)) nextXferRect(0xffdbdbdb, SkXfermode::kModulate_Mode, 0xffdbdbdb); canvas->restore(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: svgfilter.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ka $ $Date: 2003-12-15 13:57:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SVGFILTER_HXX #define SVGFILTER_HXX #ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGETARGET_HPP_ #include <com/sun/star/drawing/XMasterPageTarget.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XMasterPagesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONSUPPLIER_HPP_ #include <com/sun/star/presentation/XPresentationSupplier.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_ #include <com/sun/star/document/XFilter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_ #include <com/sun/star/document/XImporter.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_ #include <com/sun/star/document/XExporter.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE5_HXX_ #include <cppuhelper/implbase5.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_ #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_ #include <com/sun/star/presentation/AnimationEffect.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_ #include <com/sun/star/presentation/AnimationSpeed.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_ #include <com/sun/star/presentation/ClickAction.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_ #include <com/sun/star/presentation/FadeEffect.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #include <com/sun/star/java/XJavaVM.hpp> #include <com/sun/star/java/XJavaThreadRegister_11.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <hash_map> #include <osl/diagnose.h> #include <rtl/process.h> #include <tools/debug.hxx> #include <comphelper/processfactory.hxx> #include <unotools/tempfile.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/ucbstreamhelper.hxx> #include <unotools/streamwrap.hxx> #include <vcl/cvtgrf.hxx> #include <vcl/svapp.hxx> #include <vcl/outdev.hxx> #include <vcl/metaact.hxx> #include <goodies/grfmgr.hxx> #include <svx/unomodel.hxx> #include <svx/unoapi.hxx> #include <svx/svdxcgv.hxx> #include <svx/svdobj.hxx> #include <xmloff/xmlexp.hxx> #include <sj2/jnihelp.hxx> #include "svgfilter.hxx" #include "svgscript.hxx" using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::java; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::presentation; using namespace ::com::sun::star::document; using namespace ::com::sun::star::text; using namespace ::com::sun::star::io; using namespace ::com::sun::star::xml::sax; using namespace ::std; // ----------- // - Defines - // ----------- #define SVG_EXPORT_ALLPAGES ((sal_Int32)-1) // ------------- // - SVGExport - // ------------- class SVGExport : public SvXMLExport { private: SVGExport(); protected: virtual void _ExportMeta() {} virtual void _ExportStyles( BOOL bUsed ) {} virtual void _ExportAutoStyles() {} virtual void _ExportContent() {} virtual void _ExportMasterStyles() {} virtual ULONG exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ) { return 0; } public: SVGExport( const Reference< XDocumentHandler >& rxHandler ); virtual ~SVGExport(); }; // ------------------------ // - ObjectRepresentation - // ------------------------ class ObjectRepresentation { private: Reference< XInterface > mxObject; GDIMetaFile* mpMtf; public: ObjectRepresentation(); ObjectRepresentation( const Reference< XInterface >& rxIf, const GDIMetaFile& rMtf ); ObjectRepresentation( const ObjectRepresentation& rPresentation ); ~ObjectRepresentation(); ObjectRepresentation& operator=( const ObjectRepresentation& rPresentation ); bool operator==( const ObjectRepresentation& rPresentation ) const; const Reference< XInterface >& GetObject() const { return mxObject; } sal_Bool HasRepresentation() const { return mpMtf != NULL; } const GDIMetaFile& GetRepresentation() const { return *mpMtf; } }; // --------------------------- // - HashReferenceXInterface - // --------------------------- struct HashReferenceXInterface { size_t operator()( const Reference< XInterface >& rxIf ) const { return reinterpret_cast< size_t >( rxIf.get() ); } }; // ------------- // - SVGFilter - // ------------- class SVGFontExport; class SVGActionWriter; class SVGFilter : public cppu::WeakImplHelper5 < XFilter, XImporter, XExporter, XInitialization, XServiceInfo > { typedef ::std::hash_map< Reference< XInterface >, ObjectRepresentation, HashReferenceXInterface > ObjectMap; private: ObjectMap* mpObjects; Reference< XMultiServiceFactory > mxMSF; Reference< XComponent > mxSrcDoc; Reference< XComponent > mxDstDoc; SvXMLElementExport* mpSVGDoc; SVGExport* mpSVGExport; SVGFontExport* mpSVGFontExport; SVGActionWriter* mpSVGWriter; sal_Bool mbPresentation; sal_Bool implImport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException); sal_Bool implExport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException); Reference< XDocumentHandler > implCreateExportDocumentHandler( const Reference< XOutputStream >& rxOStm ); sal_Bool implGenerateMetaData( const Reference< XDrawPages >& rxMasterPages, const Reference< XDrawPages >& rxDrawPages ); sal_Bool implGenerateScript( const Reference< XDrawPages >& rxMasterPages, const Reference< XDrawPages >& rxDrawPages ); sal_Bool implExportDocument( const Reference< XDrawPages >& rxMasterPages, const Reference< XDrawPages >& rxDrawPages, sal_Int32 nPageToExport ); sal_Bool implExportPages( const Reference< XDrawPages >& rxPages, sal_Int32 nFirstPage, sal_Int32 nLastPage, sal_Int32 nVisiblePage, sal_Bool bMaster ); sal_Bool implExportShapes( const Reference< XShapes >& rxShapes ); sal_Bool implExportShape( const Reference< XShape >& rxShape ); sal_Bool implCreateObjects( const Reference< XDrawPages >& rxMasterPages, const Reference< XDrawPages >& rxDrawPages, sal_Int32 nPageToExport ); sal_Bool implCreateObjectsFromShapes( const Reference< XShapes >& rxShapes ); sal_Bool implCreateObjectsFromShape( const Reference< XShape >& rxShape ); sal_Bool implCreateObjectsFromBackground( const Reference< XDrawPage >& rxMasterPage ); OUString implGetDescriptionFromShape( const Reference< XShape >& rxShape ); OUString implGetValidIDFromInterface( const Reference< XInterface >& rxIf ); protected: // XFilter virtual sal_Bool SAL_CALL filter( const Sequence< PropertyValue >& rDescriptor ) throw(RuntimeException); virtual void SAL_CALL cancel( ) throw (RuntimeException); // XImporter virtual void SAL_CALL setTargetDocument( const Reference< XComponent >& xDoc ) throw(IllegalArgumentException, RuntimeException); // XExporter virtual void SAL_CALL setSourceDocument( const Reference< XComponent >& xDoc ) throw(IllegalArgumentException, RuntimeException); // XInitialization virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw(RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(RuntimeException); virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() throw(RuntimeException); public: SVGFilter( const Reference< XMultiServiceFactory > &rxMSF ); virtual ~SVGFilter(); }; // ----------------------------------------------------------------------------- ::rtl::OUString SVGFilter_getImplementationName () throw ( ::com::sun::star::uno::RuntimeException ); // ----------------------------------------------------------------------------- sal_Bool SAL_CALL SVGFilter_supportsService( const ::rtl::OUString& ServiceName ) throw ( ::com::sun::star::uno::RuntimeException ); // ----------------------------------------------------------------------------- ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL SVGFilter_getSupportedServiceNames( ) throw ( ::com::sun::star::uno::RuntimeException ); // ----------------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL SVGFilter_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw ( ::com::sun::star::uno::Exception ); #endif // SVGFILTER_HXX <commit_msg>INTEGRATION: CWS geordi2q11 (1.4.144); FILE MERGED 2003/12/16 12:04:15 hr 1.4.144.1: #111934#: join CWS ooo111fix1<commit_after>/************************************************************************* * * $RCSfile: svgfilter.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-12-17 15:25:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SVGFILTER_HXX #define SVGFILTER_HXX #ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGETARGET_HPP_ #include <com/sun/star/drawing/XMasterPageTarget.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XMASTERPAGESSUPPLIER_HPP_ #include <com/sun/star/drawing/XMasterPagesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_XPRESENTATIONSUPPLIER_HPP_ #include <com/sun/star/presentation/XPresentationSupplier.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_ #include <com/sun/star/document/XFilter.hpp> #endif #ifdef SOLAR_JAVA #ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_ #include <com/sun/star/document/XImporter.hpp> #endif #endif // SOLAR_JAVA #ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_ #include <com/sun/star/document/XExporter.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifdef SOLAR_JAVA #ifndef _CPPUHELPER_IMPLBASE5_HXX_ #include <cppuhelper/implbase5.hxx> #endif #else // !SOLAR_JAVA #ifndef _CPPUHELPER_IMPLBASE4_HXX_ #include <cppuhelper/implbase4.hxx> #endif #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_ #include <com/sun/star/io/XActiveDataSource.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONEFFECT_HPP_ #include <com/sun/star/presentation/AnimationEffect.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_ANIMATIONSPEED_HPP_ #include <com/sun/star/presentation/AnimationSpeed.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_ #include <com/sun/star/presentation/ClickAction.hpp> #endif #ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_ #include <com/sun/star/presentation/FadeEffect.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #include <com/sun/star/java/XJavaVM.hpp> #include <com/sun/star/java/XJavaThreadRegister_11.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <hash_map> #include <osl/diagnose.h> #include <rtl/process.h> #include <tools/debug.hxx> #include <comphelper/processfactory.hxx> #include <unotools/tempfile.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/ucbstreamhelper.hxx> #include <unotools/streamwrap.hxx> #include <vcl/cvtgrf.hxx> #include <vcl/svapp.hxx> #include <vcl/outdev.hxx> #include <vcl/metaact.hxx> #include <goodies/grfmgr.hxx> #include <svx/unomodel.hxx> #include <svx/unoapi.hxx> #include <svx/svdxcgv.hxx> #include <svx/svdobj.hxx> #include <xmloff/xmlexp.hxx> #ifdef SOLAR_JAVA #include <sj2/jnihelp.hxx> #endif #include "svgfilter.hxx" #include "svgscript.hxx" using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::java; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::presentation; using namespace ::com::sun::star::document; using namespace ::com::sun::star::text; using namespace ::com::sun::star::io; using namespace ::com::sun::star::xml::sax; using namespace ::std; // ----------- // - Defines - // ----------- #define SVG_EXPORT_ALLPAGES ((sal_Int32)-1) // ------------- // - SVGExport - // ------------- class SVGExport : public SvXMLExport { private: SVGExport(); protected: virtual void _ExportMeta() {} virtual void _ExportStyles( BOOL bUsed ) {} virtual void _ExportAutoStyles() {} virtual void _ExportContent() {} virtual void _ExportMasterStyles() {} virtual ULONG exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ) { return 0; } public: SVGExport( const Reference< XDocumentHandler >& rxHandler ); virtual ~SVGExport(); }; // ------------------------ // - ObjectRepresentation - // ------------------------ class ObjectRepresentation { private: Reference< XInterface > mxObject; GDIMetaFile* mpMtf; public: ObjectRepresentation(); ObjectRepresentation( const Reference< XInterface >& rxIf, const GDIMetaFile& rMtf ); ObjectRepresentation( const ObjectRepresentation& rPresentation ); ~ObjectRepresentation(); ObjectRepresentation& operator=( const ObjectRepresentation& rPresentation ); bool operator==( const ObjectRepresentation& rPresentation ) const; const Reference< XInterface >& GetObject() const { return mxObject; } sal_Bool HasRepresentation() const { return mpMtf != NULL; } const GDIMetaFile& GetRepresentation() const { return *mpMtf; } }; // --------------------------- // - HashReferenceXInterface - // --------------------------- struct HashReferenceXInterface { size_t operator()( const Reference< XInterface >& rxIf ) const { return reinterpret_cast< size_t >( rxIf.get() ); } }; // ------------- // - SVGFilter - // ------------- class SVGFontExport; class SVGActionWriter; #ifdef SOLAR_JAVA class SVGFilter : public cppu::WeakImplHelper5 < XFilter, XImporter, XExporter, XInitialization, XServiceInfo > #else // !SOLAR_JAVA class SVGFilter : public cppu::WeakImplHelper4 < XFilter, XExporter, XInitialization, XServiceInfo > #endif { typedef ::std::hash_map< Reference< XInterface >, ObjectRepresentation, HashReferenceXInterface > ObjectMap; private: ObjectMap* mpObjects; Reference< XMultiServiceFactory > mxMSF; Reference< XComponent > mxSrcDoc; #ifdef SOLAR_JAVA Reference< XComponent > mxDstDoc; #endif SvXMLElementExport* mpSVGDoc; SVGExport* mpSVGExport; SVGFontExport* mpSVGFontExport; SVGActionWriter* mpSVGWriter; sal_Bool mbPresentation; #ifdef SOLAR_JAVA sal_Bool implImport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException); #endif sal_Bool implExport( const Sequence< PropertyValue >& rDescriptor ) throw (RuntimeException); Reference< XDocumentHandler > implCreateExportDocumentHandler( const Reference< XOutputStream >& rxOStm ); sal_Bool implGenerateMetaData( const Reference< XDrawPages >& rxMasterPages, const Reference< XDrawPages >& rxDrawPages ); sal_Bool implGenerateScript( const Reference< XDrawPages >& rxMasterPages, const Reference< XDrawPages >& rxDrawPages ); sal_Bool implExportDocument( const Reference< XDrawPages >& rxMasterPages, const Reference< XDrawPages >& rxDrawPages, sal_Int32 nPageToExport ); sal_Bool implExportPages( const Reference< XDrawPages >& rxPages, sal_Int32 nFirstPage, sal_Int32 nLastPage, sal_Int32 nVisiblePage, sal_Bool bMaster ); sal_Bool implExportShapes( const Reference< XShapes >& rxShapes ); sal_Bool implExportShape( const Reference< XShape >& rxShape ); sal_Bool implCreateObjects( const Reference< XDrawPages >& rxMasterPages, const Reference< XDrawPages >& rxDrawPages, sal_Int32 nPageToExport ); sal_Bool implCreateObjectsFromShapes( const Reference< XShapes >& rxShapes ); sal_Bool implCreateObjectsFromShape( const Reference< XShape >& rxShape ); sal_Bool implCreateObjectsFromBackground( const Reference< XDrawPage >& rxMasterPage ); OUString implGetDescriptionFromShape( const Reference< XShape >& rxShape ); OUString implGetValidIDFromInterface( const Reference< XInterface >& rxIf ); protected: // XFilter virtual sal_Bool SAL_CALL filter( const Sequence< PropertyValue >& rDescriptor ) throw(RuntimeException); virtual void SAL_CALL cancel( ) throw (RuntimeException); #ifdef SOLAR_JAVA // XImporter virtual void SAL_CALL setTargetDocument( const Reference< XComponent >& xDoc ) throw(IllegalArgumentException, RuntimeException); #endif // XExporter virtual void SAL_CALL setSourceDocument( const Reference< XComponent >& xDoc ) throw(IllegalArgumentException, RuntimeException); // XInitialization virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw(Exception, RuntimeException); // XServiceInfo virtual OUString SAL_CALL getImplementationName() throw(RuntimeException); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(RuntimeException); virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() throw(RuntimeException); public: SVGFilter( const Reference< XMultiServiceFactory > &rxMSF ); virtual ~SVGFilter(); }; // ----------------------------------------------------------------------------- ::rtl::OUString SVGFilter_getImplementationName () throw ( ::com::sun::star::uno::RuntimeException ); // ----------------------------------------------------------------------------- sal_Bool SAL_CALL SVGFilter_supportsService( const ::rtl::OUString& ServiceName ) throw ( ::com::sun::star::uno::RuntimeException ); // ----------------------------------------------------------------------------- ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL SVGFilter_getSupportedServiceNames( ) throw ( ::com::sun::star::uno::RuntimeException ); // ----------------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL SVGFilter_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw ( ::com::sun::star::uno::Exception ); #endif // SVGFILTER_HXX <|endoftext|>
<commit_before>// Copyright (2015) Gustav #include "finans/core/commandline.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace testing; class TestSubParser : public argparse::SubParser { public: TestSubParser() { } void AddParser(argparse::Parser& parser) override { parser.AddOption("-name", name); } void ParseCompleted() override { } std::string name; }; struct CommandlineTest : public Test { std::ostringstream output; std::ostringstream error; argparse::Parser parser; std::string animal; std::string another; TestSubParser sp1; TestSubParser sp2; argparse::Parser sub; CommandlineTest() : parser("description"), sub("description") { parser.AddOption("pos", animal); parser.AddOption("-op", another); sub.AddSubParser("one", &sp1); sub.AddSubParser("two", &sp2); } }; #define GTEST(x) TEST_F(CommandlineTest, x) GTEST(TestEmpty) { argparse::Parser parser("description"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); } GTEST(TestError) { argparse::Parser parser("description"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h]\n", output.str()); EXPECT_EQ("error: All positional arguments have been consumed: hello\n", error.str()); } GTEST(TestOptionalDefault) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(2, op); } GTEST(TestOptionalValue) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValue) { int op = 2; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValueErr) { int op = 42; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: too few arguments.\n", error.str()); EXPECT_EQ("Usage: [-h] op\n", output.str()); EXPECT_EQ(42, op); // not touched } GTEST(TestStdVector) { std::vector<std::string> strings; argparse::Parser parser("description"); parser.AddGreedy("-strings", strings, "string"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-strings", "cat", "dog", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } GTEST(TestStdVectorInts) { std::vector<int> ints; argparse::Parser parser("description"); parser.AddGreedy("-ints", ints, "string"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4)); } GTEST(TestNonGreedyVector) { std::vector<std::string> strings; argparse::Parser parser("description"); parser.AddOption("-s", strings); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } enum class Day { TODAY, YESTERDAY, TOMORROW }; ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY)) GTEST(TestEnum) { Day op = Day::TOMORROW; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(Day::TODAY, op); } GTEST(TestCommaOp) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-int,-i", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestSpecifyTwice) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-int,-i", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str()); EXPECT_EQ("Usage: [-h] [-int,-i int]\n", output.str()); EXPECT_EQ(42, op); } GTEST(TestPrecedencePos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("", another); } GTEST(TestPrecedencePosOp) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("-dog", animal); EXPECT_EQ("cat", another); } GTEST(TestPrecedenceOpPos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("cat", another); } GTEST(TestStoreConstInt) { int op = 12; argparse::Parser parser("description"); parser.StoreConst("-store", op, 42); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestStoreConstString) { std::string op = ""; argparse::Parser parser("description"); parser.StoreConst<std::string>("-store", op, "dog"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", op); } GTEST(TestSubParserBasic) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "one", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserOptional) { std::string op = ""; sub.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserPositional) { std::string op = ""; sub.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestCallingSubParserWithBadArguments) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "on", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] ONE [-h] [-name name]\n", output.str()); EXPECT_EQ("error: Failed to parse ONE:\nerror: All positional arguments have been consumed: cat\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestCallingInvalidSubParser) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "dog", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] {ONE|TWO}\n", output.str()); EXPECT_EQ("error: Unable to match DOG as a subparser.\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } // todo: test help string when calling -h GTEST(TestCallingHelpBasic) { argparse::Parser parser("Description of app."); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h]\nDescription of app.\n\nOptional arguments:\n -h\tShow this help message and exit.\n\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpBasicCustomName) { argparse::Parser parser("Description of app.", "awesome.exe"); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: awesome.exe [-h]\nDescription of app.\n\nOptional arguments:\n -h\tShow this help message and exit.\n\n", output.str()); EXPECT_EQ("", error.str()); } <commit_msg>added another test case<commit_after>// Copyright (2015) Gustav #include "finans/core/commandline.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace testing; class TestSubParser : public argparse::SubParser { public: TestSubParser() { } void AddParser(argparse::Parser& parser) override { parser.AddOption("-name", name); } void ParseCompleted() override { } std::string name; }; struct CommandlineTest : public Test { std::ostringstream output; std::ostringstream error; argparse::Parser parser; std::string animal; std::string another; TestSubParser sp1; TestSubParser sp2; argparse::Parser sub; CommandlineTest() : parser("description"), sub("description") { parser.AddOption("pos", animal); parser.AddOption("-op", another); sub.AddSubParser("one", &sp1); sub.AddSubParser("two", &sp2); } }; #define GTEST(x) TEST_F(CommandlineTest, x) GTEST(TestEmpty) { argparse::Parser parser("description"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); } GTEST(TestError) { argparse::Parser parser("description"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h]\n", output.str()); EXPECT_EQ("error: All positional arguments have been consumed: hello\n", error.str()); } GTEST(TestOptionalDefault) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(2, op); } GTEST(TestOptionalValue) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValue) { int op = 2; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValueErr) { int op = 42; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: too few arguments.\n", error.str()); EXPECT_EQ("Usage: [-h] op\n", output.str()); EXPECT_EQ(42, op); // not touched } GTEST(TestStdVector) { std::vector<std::string> strings; argparse::Parser parser("description"); parser.AddGreedy("-strings", strings, "string"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-strings", "cat", "dog", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } GTEST(TestStdVectorInts) { std::vector<int> ints; argparse::Parser parser("description"); parser.AddGreedy("-ints", ints, "string"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4)); } GTEST(TestNonGreedyVector) { std::vector<std::string> strings; argparse::Parser parser("description"); parser.AddOption("-s", strings); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } enum class Day { TODAY, YESTERDAY, TOMORROW }; ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY)) GTEST(TestEnum) { Day op = Day::TOMORROW; argparse::Parser parser("description"); parser.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(Day::TODAY, op); } GTEST(TestCommaOp) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-int,-i", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestSpecifyTwice) { int op = 2; argparse::Parser parser("description"); parser.AddOption("-int,-i", op); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str()); EXPECT_EQ("Usage: [-h] [-int,-i int]\n", output.str()); EXPECT_EQ(42, op); } GTEST(TestPrecedencePos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("", another); } GTEST(TestPrecedencePosOp) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("-dog", animal); EXPECT_EQ("cat", another); } GTEST(TestPrecedenceOpPos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("cat", another); } GTEST(TestStoreConstInt) { int op = 12; argparse::Parser parser("description"); parser.StoreConst("-store", op, 42); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestStoreConstString) { std::string op = ""; argparse::Parser parser("description"); parser.StoreConst<std::string>("-store", op, "dog"); const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", op); } GTEST(TestSubParserBasic) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "one", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserOptional) { std::string op = ""; sub.AddOption("-op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserPositional) { std::string op = ""; sub.AddOption("op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestCallingSubParserWithBadArguments) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "on", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] ONE [-h] [-name name]\n", output.str()); EXPECT_EQ("error: Failed to parse ONE:\nerror: All positional arguments have been consumed: cat\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestCallingInvalidSubParser) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "dog", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] {ONE|TWO}\n", output.str()); EXPECT_EQ("error: Unable to match DOG as a subparser.\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } // todo: test help string when calling -h GTEST(TestCallingHelpBasic) { argparse::Parser parser("Description of app."); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h]\nDescription of app.\n\nOptional arguments:\n -h\tShow this help message and exit.\n\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpBasicCustomName) { argparse::Parser parser("Description of app.", "awesome.exe"); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: awesome.exe [-h]\nDescription of app.\n\nOptional arguments:\n -h\tShow this help message and exit.\n\n", output.str()); EXPECT_EQ("", error.str()); } GTEST(TestCallingHelpOp) { argparse::Parser parser("Description of app."); std::string op = ""; std::string ap = ""; parser.AddOption("-op", op); parser.AddOption("-ap", ap); const bool ok = argparse::Parser::ParseQuit == parser.ParseArgs(argparse::Arguments("app.exe", { "-h" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("Usage: app.exe [-h] [-op op] [-ap ap]\nDescription of app.\n\nOptional arguments:\n" " -ap ap\n" " -h\tShow this help message and exit.\n" " -op op\n" "\n", output.str()); EXPECT_EQ("", error.str()); } <|endoftext|>
<commit_before>/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE jobtopology_test #include <boost/test/unit_test.hpp> #include <votca/xtp/jobtopology.h> using namespace votca::xtp; using namespace std; BOOST_AUTO_TEST_SUITE(jobtopology_test) BOOST_AUTO_TEST_CASE(constructor) { ofstream jobstream("job.xml"); jobstream << " <job>" << std::endl; jobstream << " <id>0</id>" << std::endl; jobstream << " <tag>seg0:n</tag>" << std::endl; jobstream << " <input>" << std::endl; jobstream << " <site_energy>0:n</site_energy>" << std::endl; jobstream << " <regions>" << std::endl; jobstream << " <region>" << std::endl; jobstream << " <id>0</id>" << std::endl; jobstream << " <segments>0:n</segments>" << std::endl; jobstream << " </region>" << std::endl; jobstream << " </regions>" << std::endl; jobstream << " </input>" << std::endl; jobstream << " <status>AVAILABLE</status>" << std::endl; jobstream << " </job>" << std::endl; votca::tools::Property prop; votca::tools::load_property_from_xml(prop, "job.xml"); std::string workdir = "."; Logger log; Job job(prop.get("job")); JobTopology top(job, log, workdir); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>fix format<commit_after>/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * */ #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE jobtopology_test #include <boost/test/unit_test.hpp> #include <votca/xtp/jobtopology.h> using namespace votca::xtp; using namespace std; BOOST_AUTO_TEST_SUITE(jobtopology_test) BOOST_AUTO_TEST_CASE(constructor) { ofstream jobstream("job.xml"); jobstream << " <job>" << std::endl; jobstream << " <id>0</id>" << std::endl; jobstream << " <tag>seg0:n</tag>" << std::endl; jobstream << " <input>" << std::endl; jobstream << " <site_energy>0:n</site_energy>" << std::endl; jobstream << " <regions>" << std::endl; jobstream << " <region>" << std::endl; jobstream << " <id>0</id>" << std::endl; jobstream << " <segments>0:n</segments>" << std::endl; jobstream << " </region>" << std::endl; jobstream << " </regions>" << std::endl; jobstream << " </input>" << std::endl; jobstream << " <status>AVAILABLE</status>" << std::endl; jobstream << " </job>" << std::endl; votca::tools::Property prop; votca::tools::load_property_from_xml(prop, "job.xml"); std::string workdir = "."; Logger log; Job job(prop.get("job")); JobTopology top(job, log, workdir); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before> #include <iostream> #include <vector> #include <cmdline.hpp> #include <mergehelper.hpp> #include <merging/automergestrategy.hpp> #include <merging/onesidestrategy.hpp> #include <merging/newkeystrategy.hpp> #include <merging/interactivemergestrategy.hpp> using namespace kdb; using namespace kdb::tools::merging; using namespace std; MergeHelper::MergeHelper() { // TODO: this is just a quickfix, find a better solution // without eager instantiating all the strategies. Maybe even automatically // discover all available strategies // comment markus: the factory could be part of libtools strategyMap.insert (make_pair ("preserve", new AutoMergeStrategy())); strategyMap.insert (make_pair ("ours", new OneSideStrategy(OURS))); strategyMap.insert (make_pair ("theirs", new OneSideStrategy(THEIRS))); strategyMap.insert (make_pair ("base", new OneSideStrategy(BASE))); strategyMap.insert (make_pair ("newkey", new NewKeyStrategy())); strategyMap.insert (make_pair ("ourvalue", new OneSideStrategy(OURS))); strategyMap.insert (make_pair ("theirvalue", new OneSideStrategy(THEIRS))); } MergeHelper::~MergeHelper() { vector<MergeConflictStrategy*> strategies = getAllStrategies(); for (vector<MergeConflictStrategy*>::iterator it = strategies.begin(); it != strategies.end (); ++it) { delete (*it); } } vector<MergeConflictStrategy*> MergeHelper::getAllStrategies() { vector<MergeConflictStrategy*> result; for (map<string, MergeConflictStrategy*>::iterator it = strategyMap.begin (); it != strategyMap.end (); ++it) { result.push_back ((*it).second); } return result; } string MergeHelper::getStrategyList() { ostringstream oss; for (map<string, MergeConflictStrategy*>::iterator it = strategyMap.begin (); it != strategyMap.end (); ++it) { oss << (*it).first << ","; } return oss.str (); } void MergeHelper::parseStrategies(Cmdline const& cl, ThreeWayMerge& merger) { if (cl.interactive) { merger.addConflictStrategy (new InteractiveMergeStrategy (cin, cout)); cout << "Chose interactive merge" << endl; } else { if (cl.strategy.size () > 0) { // strategies are comma separated, split them istringstream sstream (cl.strategy); string current; while (getline (sstream, current, ',')) { if (strategyMap.find (current) == strategyMap.end ()) { throw invalid_argument ( "'" + current + "' is not a valid strategy. Valid strategies are: " + getStrategyList ()); } MergeConflictStrategy *strategy = strategyMap[current]; merger.addConflictStrategy (strategy); } } } } void MergeHelper::reportResult(Cmdline const& cl, MergeResult& result, ostream& out, ostream& err) { if (!result.hasConflicts ()) { if (cl.verbose) { out << result.getMergedKeys().size() << " keys in the result" << endl; out << result.getNumberOfEqualKeys() << " keys were equal" << endl; out << result.getNumberOfResolvedKeys() << " keys were resolved" << endl; } } else { KeySet conflicts = result.getConflictSet(); err << conflicts.size() << " conflicts were detected that could not be resolved automatically:" << endl; conflicts.rewind(); Key current; while ((current = conflicts.next())) { string ourConflict = current.getMeta<string> ("conflict/operation/our"); string theirConflict = current.getMeta<string> ("conflict/operation/their"); err << current << endl; err << "ours: " << ourConflict << ", theirs: " << theirConflict << endl; err << endl; } err << "Merge unsuccessful." << endl; } } <commit_msg>Fixed a merge conflict presentation bug<commit_after> #include <iostream> #include <vector> #include <cmdline.hpp> #include <keysetio.hpp> #include <mergehelper.hpp> #include <merging/automergestrategy.hpp> #include <merging/onesidestrategy.hpp> #include <merging/newkeystrategy.hpp> #include <merging/interactivemergestrategy.hpp> using namespace kdb; using namespace kdb::tools::merging; using namespace std; MergeHelper::MergeHelper() { // TODO: this is just a quickfix, find a better solution // without eager instantiating all the strategies. Maybe even automatically // discover all available strategies // comment markus: the factory could be part of libtools strategyMap.insert (make_pair ("preserve", new AutoMergeStrategy())); strategyMap.insert (make_pair ("ours", new OneSideStrategy(OURS))); strategyMap.insert (make_pair ("theirs", new OneSideStrategy(THEIRS))); strategyMap.insert (make_pair ("base", new OneSideStrategy(BASE))); strategyMap.insert (make_pair ("newkey", new NewKeyStrategy())); strategyMap.insert (make_pair ("ourvalue", new OneSideStrategy(OURS))); strategyMap.insert (make_pair ("theirvalue", new OneSideStrategy(THEIRS))); } MergeHelper::~MergeHelper() { vector<MergeConflictStrategy*> strategies = getAllStrategies(); for (vector<MergeConflictStrategy*>::iterator it = strategies.begin(); it != strategies.end (); ++it) { delete (*it); } } vector<MergeConflictStrategy*> MergeHelper::getAllStrategies() { vector<MergeConflictStrategy*> result; for (map<string, MergeConflictStrategy*>::iterator it = strategyMap.begin (); it != strategyMap.end (); ++it) { result.push_back ((*it).second); } return result; } string MergeHelper::getStrategyList() { ostringstream oss; for (map<string, MergeConflictStrategy*>::iterator it = strategyMap.begin (); it != strategyMap.end (); ++it) { oss << (*it).first << ","; } return oss.str (); } void MergeHelper::parseStrategies(Cmdline const& cl, ThreeWayMerge& merger) { if (cl.interactive) { merger.addConflictStrategy (new InteractiveMergeStrategy (cin, cout)); cout << "Chose interactive merge" << endl; } else { if (cl.strategy.size () > 0) { // strategies are comma separated, split them istringstream sstream (cl.strategy); string current; while (getline (sstream, current, ',')) { if (strategyMap.find (current) == strategyMap.end ()) { throw invalid_argument ( "'" + current + "' is not a valid strategy. Valid strategies are: " + getStrategyList ()); } MergeConflictStrategy *strategy = strategyMap[current]; merger.addConflictStrategy (strategy); } } } } void MergeHelper::reportResult(Cmdline const& cl, MergeResult& result, ostream& out, ostream& err) { if (!result.hasConflicts ()) { if (cl.verbose) { out << result.getMergedKeys().size() << " keys in the result" << endl; out << result.getNumberOfEqualKeys() << " keys were equal" << endl; out << result.getNumberOfResolvedKeys() << " keys were resolved" << endl; } } else { KeySet conflicts = result.getConflictSet(); err << conflicts.size() << " conflicts were detected that could not be resolved automatically:" << endl; conflicts.rewind(); Key current; while ((current = conflicts.next())) { string ourConflict = current.getMeta<string> ("conflict/operation/our"); string theirConflict = current.getMeta<string> ("conflict/operation/their"); err << current << endl; err << "ours: " << ourConflict << ", theirs: " << theirConflict << endl; err << endl; } err << "Merge unsuccessful." << endl; } } <|endoftext|>
<commit_before>#include "WeatherParser.h" #include "JsonListener.h" #include "EWCConfig.h" typedef void (*FunctPtr)(int8_t x); String _lastKey = ""; FunctPtr _temperature; FunctPtr _weather; bool _temperatureDone = false; bool _weatherDone = false; void WeatherListener::weather(FunctPtr callback) { _weather = callback; } void WeatherListener::temperature(FunctPtr callback) { _temperature = callback; } void WeatherListener::whitespace(char c) { // Serial.println("whitespace"); } void WeatherListener::startDocument() { // Serial.println("start document"); _lastKey = ""; _temperatureDone = false; _weatherDone = false; } void WeatherListener::key(String key) { // Serial.println("key: " + key); _lastKey = key; } void WeatherListener::value(String value) { if (_lastKey == "day" && !_temperatureDone) { DEBUG_PRINTLN("-temp: " + value); _temperature((int8_t)ROUND_INT(value.toFloat())); _temperatureDone = true; } else if (_lastKey = "icon" && !_weatherDone) { DEBUG_PRINTLN("-icon: " + value); _weatherDone = true; if (value == "01d") { _weather((int8_t)WEATHER_SONNE); } else if (value == "02d") { _weather((int8_t)WEATHER_SONNEMITWOLKEN); } else if (value == "03d") { _weather((int8_t)WEATHER_WOLKEN); } else if (value == "04d") { _weather((int8_t)WEATHER_WOLKEN); } else if (value == "09d") { _weather((int8_t)WEATHER_REGEN); } else if (value == "10d") { _weather((int8_t)WEATHER_REGEN); } else if (value == "11d") { _weather((int8_t)WEATHER_STURM); } else if (value == "13d") { _weather((int8_t)WEATHER_SCHNEE); } else if (value == "50d") { _weather((int8_t)WEATHER_NEBEL); } } } void WeatherListener::endArray() { // Serial.println("end array. "); } void WeatherListener::endObject() { // Serial.println("end object. "); } void WeatherListener::endDocument() { // Serial.println("end document. "); } void WeatherListener::startArray() { // Serial.println("start array. "); } void WeatherListener::startObject() { // Serial.println("start object. "); } <commit_msg>Fix weather assignment<commit_after>#include "WeatherParser.h" #include "JsonListener.h" #include "EWCConfig.h" typedef void (*FunctPtr)(int8_t x); String _lastKey = ""; FunctPtr _temperature; FunctPtr _weather; bool _temperatureDone = false; bool _weatherDone = false; void WeatherListener::weather(FunctPtr callback) { _weather = callback; } void WeatherListener::temperature(FunctPtr callback) { _temperature = callback; } void WeatherListener::whitespace(char c) { // Serial.println("whitespace"); } void WeatherListener::startDocument() { // Serial.println("start document"); _lastKey = ""; _temperatureDone = false; _weatherDone = false; } void WeatherListener::key(String key) { // Serial.println("key: " + key); _lastKey = key; } void WeatherListener::value(String value) { if (_lastKey == "day" && !_temperatureDone) { DEBUG_PRINTLN("-temp: " + value); _temperature((int8_t)ROUND_INT(value.toFloat())); _temperatureDone = true; } else if (_lastKey == "icon" && !_weatherDone) { DEBUG_PRINTLN("-icon: " + value); _weatherDone = true; if (value == "01d") { _weather((int8_t)WEATHER_SONNE); } else if (value == "02d") { _weather((int8_t)WEATHER_SONNEMITWOLKEN); } else if (value == "03d") { _weather((int8_t)WEATHER_WOLKEN); } else if (value == "04d") { _weather((int8_t)WEATHER_WOLKEN); } else if (value == "09d") { _weather((int8_t)WEATHER_REGEN); } else if (value == "10d") { _weather((int8_t)WEATHER_REGEN); } else if (value == "11d") { _weather((int8_t)WEATHER_STURM); } else if (value == "13d") { _weather((int8_t)WEATHER_SCHNEE); } else if (value == "50d") { _weather((int8_t)WEATHER_NEBEL); } } } void WeatherListener::endArray() { // Serial.println("end array. "); } void WeatherListener::endObject() { // Serial.println("end object. "); } void WeatherListener::endDocument() { // Serial.println("end document. "); } void WeatherListener::startArray() { // Serial.println("start array. "); } void WeatherListener::startObject() { // Serial.println("start object. "); } <|endoftext|>
<commit_before>// $Id: GlobalTypes_test.C,v 1.1 2000/12/13 16:44:38 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/common.h> /////////////////////////// // Verify that the globally defined data types (from // COMMON/global.h) have the correct size on all platforms. // This is required for portable persistence. START_TEST(sizes of the global data types, "$Id: GlobalTypes_test.C,v 1.1 2000/12/13 16:44:38 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; CHECK(size of Distance) TEST_EQUAL(sizeof(Distance), 4) RESULT CHECK(size of Handle) TEST_EQUAL(sizeof(Handle), 4) RESULT CHECK(size of Index) TEST_EQUAL(sizeof(Index), 4) RESULT CHECK(size of Size) TEST_EQUAL(sizeof(Size), 4) RESULT CHECK(size of Time) TEST_EQUAL(sizeof(Size), sizeof(time_t)) RESULT CHECK(size of HashIndex) TEST_EQUAL(sizeof(HashIndex), 4) RESULT CHECK(size of Position) TEST_EQUAL(sizeof(Position), 4) RESULT CHECK(size of Real) TEST_EQUAL(sizeof(Real), 4) RESULT CHECK(size of DoubleReal) TEST_EQUAL(sizeof(DoubleReal), 8) RESULT CHECK(size of Property) TEST_EQUAL(sizeof(Property), 4) RESULT CHECK(size of ErrorCode) TEST_EQUAL(sizeof(ErrorCode), 4) RESULT CHECK(size of Byte) TEST_EQUAL(sizeof(Byte), 1) RESULT CHECK(size of PointerSizeInt) TEST_EQUAL(sizeof(PointerSizeInt), 8) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed: time_t is not platform independent in size (trouble on 64bit machines)<commit_after>// $Id: GlobalTypes_test.C,v 1.2 2001/05/17 18:20:14 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/common.h> /////////////////////////// // Verify that the globally defined data types (from // COMMON/global.h) have the correct size on all platforms. // This is required for portable persistence. START_TEST(sizes of the global data types, "$Id: GlobalTypes_test.C,v 1.2 2001/05/17 18:20:14 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; CHECK(size of Distance) TEST_EQUAL(sizeof(Distance), 4) RESULT CHECK(size of Handle) TEST_EQUAL(sizeof(Handle), 4) RESULT CHECK(size of Index) TEST_EQUAL(sizeof(Index), 4) RESULT CHECK(size of Size) TEST_EQUAL(sizeof(Size), 4) RESULT CHECK(size of Time) TEST_EQUAL(sizeof(Time), sizeof(time_t)) RESULT CHECK(size of HashIndex) TEST_EQUAL(sizeof(HashIndex), 4) RESULT CHECK(size of Position) TEST_EQUAL(sizeof(Position), 4) RESULT CHECK(size of Real) TEST_EQUAL(sizeof(Real), 4) RESULT CHECK(size of DoubleReal) TEST_EQUAL(sizeof(DoubleReal), 8) RESULT CHECK(size of Property) TEST_EQUAL(sizeof(Property), 4) RESULT CHECK(size of ErrorCode) TEST_EQUAL(sizeof(ErrorCode), 4) RESULT CHECK(size of Byte) TEST_EQUAL(sizeof(Byte), 1) RESULT CHECK(size of PointerSizeInt) TEST_EQUAL(sizeof(PointerSizeInt), 8) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>#define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <iostream> #include <fstream> #include <string> #include <vector> #include "DeviceInfo.h" const int COMPLETE = -1; const int READ = 0; const int WRITE = 1; const int QUEUE_SIZE = 16; const char *KERNEL_MACROS = "-D QUEUE_SIZE=16 -D COMPLETE=-1 -D READ=0 -D WRITE=1"; const char *KERNEL_FILE = "kernels/vm.cl"; int main() { std::vector<cl::Platform> platforms; std::vector<cl::Device> devices; cl::Device device; cl::Program program; DeviceInfo dInfo; try { /* Create a vector of available platforms. */ cl::Platform::get(&platforms); /* Create a vector of available devices (GPU Priority). */ try { platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices); } catch (cl::Error error) { platforms[0].getDevices(CL_DEVICE_TYPE_DEFAULT, &devices); } /* Create a platform context for the available devices. */ cl::Context context(devices); /* Use the first available device. */ device = devices[0]; /* Get the number of compute units for the device. */ int computeUnits = dInfo.max_compute_units(device); /* Calculate the number of queues we need. */ int nQueues = computeUnits * computeUnits; /* Create a command queue for the device. */ cl::CommandQueue commandQueue = cl::CommandQueue(context, device); /* Read the kernel program source. */ std::ifstream kernelSourceFile(KERNEL_FILE); std::string kernelSource(std::istreambuf_iterator<char>(kernelSourceFile), (std::istreambuf_iterator<char>())); cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length() + 1)); /* Create a program in the context using the kernel source code. */ program = cl::Program(context, source); /* Build the program for the available devices. */ program.build(devices, KERNEL_MACROS); /* Create the qtest kernel. */ cl::Kernel kernel(program, "vm"); /* Allocate memory for the queues. */ cl_uint2 *queues = new cl_uint2[(nQueues * QUEUE_SIZE) + nQueues]; cl_uint2 *readQueues = new cl_uint2[(nQueues * QUEUE_SIZE) + nQueues]; /* Initialise queue elements to zero. */ for (int i = 0; i < (nQueues * QUEUE_SIZE) + nQueues; i++) { queues[i].x = 0; queues[i].y = 0; readQueues[i].x = 0; readQueues[i].y = 0; } int *state = new int; *state = WRITE; /* Create memory buffers on the device. */ cl::Buffer qBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2)); commandQueue.enqueueWriteBuffer(qBuffer, CL_TRUE, 0, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2), queues); cl::Buffer rqBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2)); commandQueue.enqueueWriteBuffer(rqBuffer, CL_TRUE, 0, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2), readQueues); cl::Buffer stateBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(int)); commandQueue.enqueueWriteBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state); /* Set kernel arguments. */ kernel.setArg(0, qBuffer); kernel.setArg(1, rqBuffer); kernel.setArg(2, computeUnits); kernel.setArg(3, stateBuffer); /* Set the NDRange. */ cl::NDRange global(computeUnits), local(1); /* Run the kernel on NDRange until completion. */ while (*state != COMPLETE) { commandQueue.enqueueNDRangeKernel(kernel, cl::NullRange, global, local); commandQueue.finish(); commandQueue.enqueueReadBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state); } /* Read the modified queue buffer. */ commandQueue.enqueueReadBuffer(qBuffer, CL_TRUE, 0, ((nQueues * QUEUE_SIZE) + nQueues) * sizeof(cl_uint2), queues); for (int i = 0; i < nQueues; i++) { std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " "; } std::cout << std::endl; std::cout << std::endl; /* Print the queues. */ for (int i = nQueues; i < (nQueues * QUEUE_SIZE) + nQueues; i++) { if ((i % QUEUE_SIZE) == 0) std::cout << std::endl; std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " "; } std::cout << std::endl; /* Cleanup */ delete[] queues; } catch (cl::Error error) { std::cout << "EXCEPTION: " << error.what() << " [" << error.err() << "]" << std::endl; std::cout << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl; } return 0; } <commit_msg>Changed some variable names and cleaned up.<commit_after>#define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <iostream> #include <fstream> #include <string> #include <vector> #include "DeviceInfo.h" const int QUEUE_SIZE = 16; const int COMPLETE = -1; const int READ = 0; const int WRITE = 1; const char *KERNEL_MACROS = "-D QUEUE_SIZE=16 -D COMPLETE=-1 -D READ=0 -D WRITE=1"; const char *KERNEL_FILE = "kernels/vm.cl"; int main() { std::vector<cl::Platform> platforms; std::vector<cl::Device> devices; cl::Device device; cl::Program program; DeviceInfo dInfo; try { /* Create a vector of available platforms. */ cl::Platform::get(&platforms); /* Create a vector of available devices (GPU Priority). */ try { platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices); } catch (cl::Error error) { platforms[0].getDevices(CL_DEVICE_TYPE_DEFAULT, &devices); } /* Create a platform context for the available devices. */ cl::Context context(devices); /* Use the first available device. */ device = devices[0]; /* Get the number of compute units for the device. */ int computeUnits = dInfo.max_compute_units(device); /* Calculate the number of queues we need. */ int nQueues = computeUnits * computeUnits; /* Create a command queue for the device. */ cl::CommandQueue commandQueue = cl::CommandQueue(context, device); /* Read the kernel program source. */ std::ifstream kernelSourceFile(KERNEL_FILE); std::string kernelSource(std::istreambuf_iterator<char>(kernelSourceFile), (std::istreambuf_iterator<char>())); cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length() + 1)); /* Create a program in the context using the kernel source code. */ program = cl::Program(context, source); /* Build the program for the available devices. */ program.build(devices, KERNEL_MACROS); /* Create the qtest kernel. */ cl::Kernel kernel(program, "vm"); /* Calculate the memory required to store the queues. */ int qBufSize = (nQueues * QUEUE_SIZE) + nQueues; /* Allocate memory for the queues. */ cl_uint2 *queues = new cl_uint2[qBufSize]; cl_uint2 *readQueues = new cl_uint2[qBufSize]; /* Initialise queue elements to zero. */ for (int i = 0; i < qBufSize; i++) { queues[i].x = 0; queues[i].y = 0; readQueues[i].x = 0; readQueues[i].y = 0; } int *state = new int; *state = WRITE; /* Create memory buffers on the device. */ cl::Buffer qBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, qBufSize * sizeof(cl_uint2)); commandQueue.enqueueWriteBuffer(qBuffer, CL_TRUE, 0, qBufSize * sizeof(cl_uint2), queues); cl::Buffer rqBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, qBufSize * sizeof(cl_uint2)); commandQueue.enqueueWriteBuffer(rqBuffer, CL_TRUE, 0, qBufSize * sizeof(cl_uint2), readQueues); cl::Buffer stateBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(int)); commandQueue.enqueueWriteBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state); /* Set kernel arguments. */ kernel.setArg(0, qBuffer); kernel.setArg(1, rqBuffer); kernel.setArg(2, computeUnits); kernel.setArg(3, stateBuffer); /* Set the NDRange. */ cl::NDRange global(computeUnits), local(1); /* Run the kernel on NDRange until completion. */ while (*state != COMPLETE) { commandQueue.enqueueNDRangeKernel(kernel, cl::NullRange, global, local); commandQueue.finish(); commandQueue.enqueueReadBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state); } /* Read the modified queue buffer. */ commandQueue.enqueueReadBuffer(qBuffer, CL_TRUE, 0, qBufSize * sizeof(cl_uint2), queues); /* Print the queue details. */ for (int i = 0; i < nQueues; i++) { std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " "; } std::cout << std::endl; std::cout << std::endl; /* Print the queues. */ for (int i = nQueues; i < qBufSize; i++) { if ((i % QUEUE_SIZE) == 0) std::cout << std::endl; std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " "; } std::cout << std::endl; /* Cleanup */ delete[] queues; } catch (cl::Error error) { std::cout << "EXCEPTION: " << error.what() << " [" << error.err() << "]" << std::endl; std::cout << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl; } return 0; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // manager.cpp // // Identification: src/backend/catalog/manager.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cassert> #include "backend/catalog/manager.h" #include "backend/storage/database.h" #include "backend/storage/data_table.h" namespace peloton { namespace catalog { Manager &Manager::GetInstance() { static Manager manager; return manager; } //===--------------------------------------------------------------------===// // OBJECT MAP //===--------------------------------------------------------------------===// void Manager::SetTileGroup(const oid_t oid, storage::TileGroup *location) { { std::lock_guard<std::mutex> lock(locator_mutex); locator.insert(std::pair<oid_t, storage::TileGroup *>(oid, location)); } } storage::TileGroup *Manager::GetTileGroup(const oid_t oid) { storage::TileGroup *location = nullptr; { std::lock_guard<std::mutex> lock(locator_mutex); location = locator.at(oid); } return location; } //used for logging test void Manager::ClearTileGroup(){ { std::lock_guard<std::mutex> lock(locator_mutex); locator.clear(); } } //===--------------------------------------------------------------------===// // DATABASE //===--------------------------------------------------------------------===// void Manager::AddDatabase(storage::Database *database) { { std::lock_guard<std::mutex> lock(catalog_mutex); databases.push_back(database); } } storage::Database *Manager::GetDatabaseWithOid(const oid_t database_oid) const { for (auto database : databases) if (database->GetOid() == database_oid) return database; return nullptr; } void Manager::DropDatabaseWithOid(const oid_t database_oid) { { std::lock_guard<std::mutex> lock(catalog_mutex); oid_t database_offset = 0; for (auto database : databases) { if (database->GetOid() == database_oid) { delete database; break; } database_offset++; } assert(database_offset < databases.size()); // Drop the database databases.erase(databases.begin() + database_offset); } } storage::Database *Manager::GetDatabase(const oid_t database_offset) const { assert(database_offset < databases.size()); auto database = databases.at(database_offset); return database; } oid_t Manager::GetDatabaseCount() const { return databases.size(); } //===--------------------------------------------------------------------===// // CONVENIENCE WRAPPERS //===--------------------------------------------------------------------===// storage::DataTable *Manager::GetTableWithOid(const oid_t database_oid, const oid_t table_oid) const { // Lookup DB auto database = GetDatabaseWithOid(database_oid); // Lookup table if (database != nullptr) { auto table = database->GetTableWithOid(table_oid); return table; } return nullptr; } storage::DataTable *Manager::GetTableWithName( const oid_t database_oid, const std::string table_name) const { // Lookup DB auto database = GetDatabaseWithOid(database_oid); // Lookup table if (database != nullptr) { auto table = database->GetTableWithName(table_name); return table; } return nullptr; } index::Index *Manager::GetIndexWithOid(const oid_t database_oid, const oid_t table_oid, const oid_t index_oid) const { // Lookup table auto table = GetTableWithOid(database_oid, table_oid); // Lookup index if (table != nullptr) { auto index = table->GetIndexWithOid(index_oid); return index; } return nullptr; } } // End catalog namespace } // End peloton namespace <commit_msg>Fix GetTileGroup bug<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // manager.cpp // // Identification: src/backend/catalog/manager.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cassert> #include "backend/catalog/manager.h" #include "backend/storage/database.h" #include "backend/storage/data_table.h" namespace peloton { namespace catalog { Manager &Manager::GetInstance() { static Manager manager; return manager; } //===--------------------------------------------------------------------===// // OBJECT MAP //===--------------------------------------------------------------------===// void Manager::SetTileGroup(const oid_t oid, storage::TileGroup *location) { { std::lock_guard<std::mutex> lock(locator_mutex); locator.insert(std::pair<oid_t, storage::TileGroup *>(oid, location)); } } storage::TileGroup *Manager::GetTileGroup(const oid_t oid) { storage::TileGroup *location = nullptr; { std::lock_guard<std::mutex> lock(locator_mutex); if (locator.find(oid) != locator.end()) location = locator.at(oid); } return location; } //used for logging test void Manager::ClearTileGroup(){ { std::lock_guard<std::mutex> lock(locator_mutex); locator.clear(); } } //===--------------------------------------------------------------------===// // DATABASE //===--------------------------------------------------------------------===// void Manager::AddDatabase(storage::Database *database) { { std::lock_guard<std::mutex> lock(catalog_mutex); databases.push_back(database); } } storage::Database *Manager::GetDatabaseWithOid(const oid_t database_oid) const { for (auto database : databases) if (database->GetOid() == database_oid) return database; return nullptr; } void Manager::DropDatabaseWithOid(const oid_t database_oid) { { std::lock_guard<std::mutex> lock(catalog_mutex); oid_t database_offset = 0; for (auto database : databases) { if (database->GetOid() == database_oid) { delete database; break; } database_offset++; } assert(database_offset < databases.size()); // Drop the database databases.erase(databases.begin() + database_offset); } } storage::Database *Manager::GetDatabase(const oid_t database_offset) const { assert(database_offset < databases.size()); auto database = databases.at(database_offset); return database; } oid_t Manager::GetDatabaseCount() const { return databases.size(); } //===--------------------------------------------------------------------===// // CONVENIENCE WRAPPERS //===--------------------------------------------------------------------===// storage::DataTable *Manager::GetTableWithOid(const oid_t database_oid, const oid_t table_oid) const { // Lookup DB auto database = GetDatabaseWithOid(database_oid); // Lookup table if (database != nullptr) { auto table = database->GetTableWithOid(table_oid); return table; } return nullptr; } storage::DataTable *Manager::GetTableWithName( const oid_t database_oid, const std::string table_name) const { // Lookup DB auto database = GetDatabaseWithOid(database_oid); // Lookup table if (database != nullptr) { auto table = database->GetTableWithName(table_name); return table; } return nullptr; } index::Index *Manager::GetIndexWithOid(const oid_t database_oid, const oid_t table_oid, const oid_t index_oid) const { // Lookup table auto table = GetTableWithOid(database_oid, table_oid); // Lookup index if (table != nullptr) { auto index = table->GetIndexWithOid(index_oid); return index; } return nullptr; } } // End catalog namespace } // End peloton namespace <|endoftext|>
<commit_before>// // Realm C++ coding standard - by example // // Lines should never exceed 118 characters -------------------------------------------------------------------------- // Macro names use uppercase and have "REALM_" as prefix. Non-macro // names never use all uppercase. #define REALM_MY_MACRO 1 // A function name uses lowercase and its parts are separated by // underscores. my_type my_func() { // Put the opening brace of a function body in the next line below // the function prototype. This also applies to class member // functions. // Put all other opening braces on the same line as the syntax // element to which the brace is subordinate. // Use 4 spaces per indentation level (no tabs please). if (...) { // ... } else { // ... } // Always put subordinate statements on a new line (to ease // debugging). if (...) return ...; // No space between type and '*' or '&' int* foo1 = ...; int& foo2 = ...; // 'const' goes before the type const int foo3 = ...; // ... but not when 'const' operates on a pointer type const int* foo3 = ...; // 'const' operates on 'int' not 'int*' int* const foo4 = ...; // 'const' operates on 'int*' int* const* const foo5 = ...; } void my_func_2() { // This indentation and brace placement style agrees with K&R // style except for the 'extra' indentation of 'cases' in a switch // statement. switch (...) { case type_Foo: { // ... break; } case type_FooBar: { // ... break; } } try { // ... } catch (...) { // ... } } // A name space name uses lowercase and its parts are separated by // underscores. namespace my_namespace { // No indentation inside name spaces. // A Class name uses CamelCase with uppercase initial. template<class T> class MyClass: public Base { public: MyClass(...): Base(...), m_bar(7), ... { // ... } private: // Static member variables have prefix 's_'. static int s_foo; // Regular member variables have prefix 'm_'. int m_bar; }; } // namespace my_namespace // Names of values of an enumeration are composed of two parts // separated by an underscore. The first part is a common lowercase // prefix. The second part identifies the value and uses CamelCase // with uppercase initial. enum mode { mode_Foo, mode_FooBar }; // Order of class members (roughly): class MyClass2 { public: // Types // Static variables // Regular variables // Static functions // Regular functions protected: // Same as 'public' private: // Same as 'public' // Friends }; // About FIXMEs: // // A FIXME conveys information about a known issue or shortcoming. It // may also include information on how to fix the problem, and on // possible conflicts with anticipated future features. // // A FIXME is often added in the following situations: // // - While working on, or studying a particular part of the code you // uncover an issue or a shortcoming. Additionally, you may have // gained an understanding of how to fix it. // // - While implementing a new feature, you are forced to cut a corner, // but you have some good ideas about how to continue later, and/or // you may have knowledge about a certain planned feature that would // require a more complete solution. // // A FIXME is generally not about a bug or an error, and is should // generally not be considered a task either. Is is simply a memo to // oneself or to some other developer who is going to work on the code // at some later point in time. // // A FIXME should never be deleted unless by somebody who understands // the mening of it and knows that the problem is fixed, or has // otherwise diappeard. <commit_msg>code guidelines<commit_after>// // Realm C++ coding standard - by example // // Lines should never exceed 118 characters -------------------------------------------------------------------------- // Macro names use uppercase and have "REALM_" as prefix. Non-macro // names never use all uppercase. #define REALM_MY_MACRO 1 // A function name uses lowercase and its parts are separated by // underscores. my_type my_func() { // Put the opening brace of a function body in the next line below // the function prototype. This also applies to class member // functions. // Put all other opening braces on the same line as the syntax // element to which the brace is subordinate. // Use 4 spaces per indentation level (no tabs please). if (...) { // ... } else { // ... } // Always put subordinate statements on a new line (to ease // debugging). if (...) return ...; // No space between type and '*' or '&' int* foo1 = ...; int& foo2 = ...; // 'const' goes before the type const int foo3 = ...; // ... but not when 'const' operates on a pointer type const int* foo3 = ...; // 'const' operates on 'int' not 'int*' int* const foo4 = ...; // 'const' operates on 'int*' int* const* const foo5 = ...; } void my_func_2() { // This indentation and brace placement style agrees with K&R // style except for the 'extra' indentation of 'cases' in a switch // statement. switch (...) { case type_Foo: { // ... break; } case type_FooBar: { // ... break; } } try { // ... } catch (...) { // ... } } // A name space name uses lowercase and its parts are separated by // underscores. namespace my_namespace { // No indentation inside name spaces. // A Class name uses CamelCase with uppercase initial. template<class T> class MyClass: public Base { public: MyClass(...): Base(...), m_bar(7), ... { // ... } private: // Static member variables have prefix 's_'. static int s_foo; // Regular member variables have prefix 'm_'. int m_bar; }; } // namespace my_namespace // Names of values of an enumeration are composed of two parts // separated by an underscore. The first part is a common lowercase // prefix. The second part identifies the value and uses CamelCase // with uppercase initial. enum mode { mode_Foo, mode_FooBar }; // Order of class members (roughly): class MyClass2 { public: // Types // Static variables // Regular variables // Static functions // Regular functions protected: // Same as 'public' private: // Same as 'public' // Friends }; // Use of 'auto' keyword: // // 'auto' should *not* be used for trivial cases where the type declaration // is short, non-templated, and non-derived (type_t, int64_t, std::string, // etc. // About FIXMEs: // // A FIXME conveys information about a known issue or shortcoming. It // may also include information on how to fix the problem, and on // possible conflicts with anticipated future features. // // A FIXME is often added in the following situations: // // - While working on, or studying a particular part of the code you // uncover an issue or a shortcoming. Additionally, you may have // gained an understanding of how to fix it. // // - While implementing a new feature, you are forced to cut a corner, // but you have some good ideas about how to continue later, and/or // you may have knowledge about a certain planned feature that would // require a more complete solution. // // A FIXME is generally not about a bug or an error, and is should // generally not be considered a task either. Is is simply a memo to // oneself or to some other developer who is going to work on the code // at some later point in time. // // A FIXME should never be deleted unless by somebody who understands // the mening of it and knows that the problem is fixed, or has // otherwise diappeard. <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: cow_wrapper_clients.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: thb $ $Date: 2006-03-23 15:25:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_COW_WRAPPER_CLIENTS_HXX #define INCLUDED_COW_WRAPPER_CLIENTS_HXX #include "o3tl/cow_wrapper.hxx" /* Definition of Cow_Wrapper_Clients classes */ namespace o3tltests { /** This is a header and a separate compilation unit on purpose - cow_wrapper needs destructor, copy constructor and assignment operator to be outline, when pimpl idiom is used */ /// test non-opaque impl type class cow_wrapper_client1 { public: cow_wrapper_client1() : maImpl() {} explicit cow_wrapper_client1( int nVal ) : maImpl(nVal) {} void modify( int nVal ) { *maImpl = nVal; } int queryUnmodified() const { return *maImpl; } void makeUnique() { maImpl.make_unique(); } bool is_unique() const { return maImpl.is_unique(); } oslInterlockedCount use_count() const { return maImpl.use_count(); } void swap( cow_wrapper_client1& r ) { o3tl::swap(maImpl, r.maImpl); } bool operator==( const cow_wrapper_client1& rRHS ) const { return maImpl == rRHS.maImpl; } bool operator!=( const cow_wrapper_client1& rRHS ) const { return maImpl != rRHS.maImpl; } bool operator<( const cow_wrapper_client1& rRHS ) const { return maImpl < rRHS.maImpl; } private: o3tl::cow_wrapper< int > maImpl; }; class cow_wrapper_client2_impl; /** test opaque impl type - need to explicitely declare lifetime methods */ class cow_wrapper_client2 { public: cow_wrapper_client2(); explicit cow_wrapper_client2( int nVal ); ~cow_wrapper_client2(); cow_wrapper_client2( const cow_wrapper_client2& ); cow_wrapper_client2& operator=( const cow_wrapper_client2& ); void modify( int nVal ); int queryUnmodified() const; void makeUnique(); bool is_unique() const; oslInterlockedCount use_count() const; void swap( cow_wrapper_client2& r ); bool operator==( const cow_wrapper_client2& rRHS ) const; bool operator!=( const cow_wrapper_client2& rRHS ) const; bool operator<( const cow_wrapper_client2& rRHS ) const; private: o3tl::cow_wrapper< cow_wrapper_client2_impl > maImpl; }; /** test MT-safe cow_wrapper - basically the same as cow_wrapper_client2, only with different refcounting policy */ class cow_wrapper_client3 { public: cow_wrapper_client3(); explicit cow_wrapper_client3( int nVal ); ~cow_wrapper_client3(); cow_wrapper_client3( const cow_wrapper_client3& ); cow_wrapper_client3& operator=( const cow_wrapper_client3& ); void modify( int nVal ); int queryUnmodified() const; void makeUnique(); bool is_unique() const; oslInterlockedCount use_count() const; void swap( cow_wrapper_client3& r ); bool operator==( const cow_wrapper_client3& rRHS ) const; bool operator!=( const cow_wrapper_client3& rRHS ) const; bool operator<( const cow_wrapper_client3& rRHS ) const; private: o3tl::cow_wrapper< cow_wrapper_client2_impl, o3tl::ThreadSafeRefCountingPolicy > maImpl; }; } // namespace o3tltests #endif /* INCLUDED_COW_WRAPPER_CLIENTS_HXX */ <commit_msg>INTEGRATION: CWS sixtyfour07 (1.2.2); FILE MERGED 2006/07/26 14:14:33 thb 1.2.2.1: #i67798# Correcting license header<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cow_wrapper_clients.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ihi $ $Date: 2006-08-01 10:15:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_COW_WRAPPER_CLIENTS_HXX #define INCLUDED_COW_WRAPPER_CLIENTS_HXX #include "o3tl/cow_wrapper.hxx" /* Definition of Cow_Wrapper_Clients classes */ namespace o3tltests { /** This is a header and a separate compilation unit on purpose - cow_wrapper needs destructor, copy constructor and assignment operator to be outline, when pimpl idiom is used */ /// test non-opaque impl type class cow_wrapper_client1 { public: cow_wrapper_client1() : maImpl() {} explicit cow_wrapper_client1( int nVal ) : maImpl(nVal) {} void modify( int nVal ) { *maImpl = nVal; } int queryUnmodified() const { return *maImpl; } void makeUnique() { maImpl.make_unique(); } bool is_unique() const { return maImpl.is_unique(); } oslInterlockedCount use_count() const { return maImpl.use_count(); } void swap( cow_wrapper_client1& r ) { o3tl::swap(maImpl, r.maImpl); } bool operator==( const cow_wrapper_client1& rRHS ) const { return maImpl == rRHS.maImpl; } bool operator!=( const cow_wrapper_client1& rRHS ) const { return maImpl != rRHS.maImpl; } bool operator<( const cow_wrapper_client1& rRHS ) const { return maImpl < rRHS.maImpl; } private: o3tl::cow_wrapper< int > maImpl; }; class cow_wrapper_client2_impl; /** test opaque impl type - need to explicitely declare lifetime methods */ class cow_wrapper_client2 { public: cow_wrapper_client2(); explicit cow_wrapper_client2( int nVal ); ~cow_wrapper_client2(); cow_wrapper_client2( const cow_wrapper_client2& ); cow_wrapper_client2& operator=( const cow_wrapper_client2& ); void modify( int nVal ); int queryUnmodified() const; void makeUnique(); bool is_unique() const; oslInterlockedCount use_count() const; void swap( cow_wrapper_client2& r ); bool operator==( const cow_wrapper_client2& rRHS ) const; bool operator!=( const cow_wrapper_client2& rRHS ) const; bool operator<( const cow_wrapper_client2& rRHS ) const; private: o3tl::cow_wrapper< cow_wrapper_client2_impl > maImpl; }; /** test MT-safe cow_wrapper - basically the same as cow_wrapper_client2, only with different refcounting policy */ class cow_wrapper_client3 { public: cow_wrapper_client3(); explicit cow_wrapper_client3( int nVal ); ~cow_wrapper_client3(); cow_wrapper_client3( const cow_wrapper_client3& ); cow_wrapper_client3& operator=( const cow_wrapper_client3& ); void modify( int nVal ); int queryUnmodified() const; void makeUnique(); bool is_unique() const; oslInterlockedCount use_count() const; void swap( cow_wrapper_client3& r ); bool operator==( const cow_wrapper_client3& rRHS ) const; bool operator!=( const cow_wrapper_client3& rRHS ) const; bool operator<( const cow_wrapper_client3& rRHS ) const; private: o3tl::cow_wrapper< cow_wrapper_client2_impl, o3tl::ThreadSafeRefCountingPolicy > maImpl; }; } // namespace o3tltests #endif /* INCLUDED_COW_WRAPPER_CLIENTS_HXX */ <|endoftext|>
<commit_before>#ifndef OMR_INFRA_DOUBLES_HPP_ #define OMR_INFRA_DOUBLES_HPP_ /// @file /// Tools for working with doubles. Especially, for working with the underlying /// representation of doubles. #include <OMR/Infra/BitUtilities.hpp> #include <cmath> #include <cstdint> namespace OMR { namespace Infra { /// raw integer constants for working with doubles. namespace Double { static_assert(sizeof(std::uint64_t) == sizeof(double), "Decoding and encoding expects 64 bit doubles."); /// Decomposition masks. /// @{ static constexpr std::uint64_t SIGN_MASK = 0x8000'0000'0000'0000ul; static constexpr std::uint64_t EXPONENT_MASK = 0x7FF0'0000'0000'0000ul; static constexpr std::uint64_t MANTISSA_MASK = 0x000F'FFFF'FFFF'FFFFul; /// @} /// NaN and +/- Inf /// @{ /// A special value is any double where the exponent is maximized, aka all 1's. /// Note that a special value with a mantissa of zero designates +/- infinity. A /// Non-zero mantissa indicates NaN. static constexpr std::uint64_t SPECIAL_TAG = EXPONENT_MASK; /// There are two kinds of NaN's: signalling and quiet. Using a signalling NaN /// in any floating point arithmetic will result in a FPU interrupt. Quiet NaNs /// propagate through expressions without signaling. Quiet NaNs are /// designated by a positive most-significant-bit in the mantissa. static constexpr std::uint64_t NAN_QUIET_TAG = 0x0008'0000'0000'0000ul; /// A mask for the remaining bits in a NaN after the NAN_TAG and the /// NAN_QUIET_TAG; static constexpr std::uint64_t NAN_EXTRA_BITS_MASK = 0x0007'FFFF'FFFF'FFFFul; /// @} /// True if value is any NaN. False if Inf or a valid number. A double is a NaN /// if it's tagged special and has a non-zero mantissa. static constexpr bool isNaN(std::uint64_t value) { return areAllBitsSet(value, Double::SPECIAL_TAG) && areAnyBitsSet(value, Double::MANTISSA_MASK); } /// True for any quiet NaN. static constexpr bool isQNaN(std::uint64_t value) { return isNaN(value) && areAllBitsSet(value, Double::NAN_QUIET_TAG); } /// True for any signaling NaN. static constexpr bool isSNaN(std::uint64_t value) { return isNaN(value) && areNoBitsSet(value, Double::NAN_QUIET_TAG); } /// Reinterpret std::uint64_t to a double static constexpr double fromRaw(std::uint64_t value) { union { double asDouble; std::uint64_t asRaw; } result{0}; result.asRaw = value; return result.asDouble; } /// Reinterpret a double as a std::uint64_t. static constexpr std::uint64_t toRaw(double d) { union { double asDouble; std::uint64_t asRaw; } result{0}; result.asDouble = d; return result.asRaw; } } // namespace Double } // namespace Infra } // namespace OMR #endif // OMR_INFRA_DOUBLEUTILITIES_HPP_ <commit_msg>Remove Double namespace from constants<commit_after>#ifndef OMR_INFRA_DOUBLES_HPP_ #define OMR_INFRA_DOUBLES_HPP_ /// @file /// Tools for working with doubles. Especially, for working with the underlying /// representation of doubles. #include <OMR/Infra/BitUtilities.hpp> #include <cmath> #include <cstdint> namespace OMR { namespace Infra { /// raw integer constants for working with doubles. namespace Double { static_assert(sizeof(std::uint64_t) == sizeof(double), "Decoding and encoding expects 64 bit doubles."); /// Decomposition masks. /// @{ static constexpr std::uint64_t SIGN_MASK = 0x8000'0000'0000'0000ul; static constexpr std::uint64_t EXPONENT_MASK = 0x7FF0'0000'0000'0000ul; static constexpr std::uint64_t MANTISSA_MASK = 0x000F'FFFF'FFFF'FFFFul; /// @} /// NaN and +/- Inf /// @{ /// A special value is any double where the exponent is maximized, aka all 1's. /// Note that a special value with a mantissa of zero designates +/- infinity. A /// Non-zero mantissa indicates NaN. static constexpr std::uint64_t SPECIAL_TAG = EXPONENT_MASK; /// There are two kinds of NaN's: signalling and quiet. Using a signalling NaN /// in any floating point arithmetic will result in a FPU interrupt. Quiet NaNs /// propagate through expressions without signaling. Quiet NaNs are /// designated by a positive most-significant-bit in the mantissa. static constexpr std::uint64_t NAN_QUIET_TAG = 0x0008'0000'0000'0000ul; /// A mask for the remaining bits in a NaN after the NAN_TAG and the /// NAN_QUIET_TAG; static constexpr std::uint64_t NAN_EXTRA_BITS_MASK = 0x0007'FFFF'FFFF'FFFFul; /// @} /// True if value is any NaN. False if Inf or a valid number. A double is a NaN /// if it's tagged special and has a non-zero mantissa. static constexpr bool isNaN(std::uint64_t value) { return areAllBitsSet(value, SPECIAL_TAG) && areAnyBitsSet(value, MANTISSA_MASK); } /// True for any quiet NaN. static constexpr bool isQNaN(std::uint64_t value) { return isNaN(value) && areAllBitsSet(value, NAN_QUIET_TAG); } /// True for any signaling NaN. static constexpr bool isSNaN(std::uint64_t value) { return isNaN(value) && areNoBitsSet(value, NAN_QUIET_TAG); } /// Reinterpret std::uint64_t to a double static constexpr double fromRaw(std::uint64_t value) { union { double asDouble; std::uint64_t asRaw; } result{0}; result.asRaw = value; return result.asDouble; } /// Reinterpret a double as a std::uint64_t. static constexpr std::uint64_t toRaw(double d) { union { double asDouble; std::uint64_t asRaw; } result{0}; result.asDouble = d; return result.asRaw; } } // namespace Double } // namespace Infra } // namespace OMR #endif // OMR_INFRA_DOUBLEUTILITIES_HPP_ <|endoftext|>
<commit_before>/* * Config class for La Cogita IRC chatbot * Copyright (C) 2009 Joel Pitt <joel@fruitionnz.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "CogitaConfig.h" #include <getopt.h> #include <string> #include <vector> #include <iostream> #include <stdlib.h> #include <opencog/util/StringTokenizer.h> using std::cout; using std::string; using namespace std; namespace opencog { namespace chatbot { CogitaConfig::CogitaConfig() : ircNetwork(COGITA_DEFAULT_SERVER), ircPort(COGITA_DEFAULT_PORT), vstring(COGITA_VSTRING), nick(COGITA_DEFAULT_NICK) { const char* defaultAttns[] = COGITA_DEFAULT_ATTN; const char* defaultSuffixes[] = COGITA_DEFAULT_ATTN_SUFFIXES; const char* defaultChannels[] = COGITA_DEFAULT_CHANNELS; for (int i = 0; defaultAttns[i]; i++) { for (int i = 0; defaultSuffixes[i]; i++) { attn.push_back(string(defaultAttns[i]) + string(defaultSuffixes[i])); } } for (int i = 0; defaultChannels[i]; i++) { ircChannels.push_back(std::string(defaultChannels[i])); } } const char * CogitaConfig::helpOutput = " Cogita - An OpenCog chatbot. \n" " ======\n" " Usage: \n" " -n,--nick \tSet bot nick. (default: %s)\n" " -s,--server \tIRC server to connect to.\n" " -p,--port \tPort of IRC server to connect to.\n" " -c,--channels \tComma separated list of channels (without preceding #) to join\n" " \t(only single channel support implemented).\n" " -v,--version \tPrint version information.\n" " \n"; void CogitaConfig::printHelp() { #define BUFSZ 8190 char buff[BUFSZ]; snprintf(buff, BUFSZ, helpOutput, nick.c_str()); cout << buff; } void CogitaConfig::printVersion() { cout << COGITA_VSTRING << endl; } int CogitaConfig::parseOptions(int argc, char* argv[]) { int c = 0; static const char *optString = "n:s:p:c:vh"; static const struct option longOptions[] = { {"nick", required_argument, 0, 'n'}, {"server", required_argument, 0, 's'}, {"port", required_argument, 0, 's'}, {"channels", required_argument, 0, 'c'}, {"version", 0, 0, 'v'}, {"help", 0, 0, '?'}, {0, 0, 0, 0} }; while (1) { int optionIndex = 0; string channelsTemp; StringTokenizer st; c = getopt_long (argc, argv, optString, longOptions, &optionIndex); /* Detect end of options */ if (c == -1) break; switch (c) { case 'n': nick = string(optarg); createAttnVector(); break; case 's': ircNetwork = string(optarg); break; case 'p': ircPort = atoi(optarg); break; case 'c': ircChannels.clear(); channelsTemp = optarg; st.set_string(channelsTemp); st.set_delimiter(string(",")); for (string channel = st.next_token(); channel.size() > 0; channel = st.next_token()) { ircChannels.push_back("#" + channel); } break; case 'v': printVersion(); return 1; case 'h': printHelp(); return 1; default: printHelp(); return 1; } } return 0; } void CogitaConfig::createAttnVector() { const char* defaultSuffixes[] = COGITA_DEFAULT_ATTN_SUFFIXES; attn.clear(); for (int i = 0; defaultSuffixes[i]; i++) { attn.push_back(nick + string(defaultSuffixes[i])); } } }} // ~namespace opencog::chatbot <commit_msg>More printing of defaults<commit_after>/* * Config class for La Cogita IRC chatbot * Copyright (C) 2009 Joel Pitt <joel@fruitionnz.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "CogitaConfig.h" #include <getopt.h> #include <string> #include <vector> #include <iostream> #include <stdlib.h> #include <opencog/util/StringTokenizer.h> using std::cout; using std::string; using namespace std; namespace opencog { namespace chatbot { CogitaConfig::CogitaConfig() : ircNetwork(COGITA_DEFAULT_SERVER), ircPort(COGITA_DEFAULT_PORT), vstring(COGITA_VSTRING), nick(COGITA_DEFAULT_NICK) { const char* defaultAttns[] = COGITA_DEFAULT_ATTN; const char* defaultSuffixes[] = COGITA_DEFAULT_ATTN_SUFFIXES; const char* defaultChannels[] = COGITA_DEFAULT_CHANNELS; for (int i = 0; defaultAttns[i]; i++) { for (int i = 0; defaultSuffixes[i]; i++) { attn.push_back(string(defaultAttns[i]) + string(defaultSuffixes[i])); } } for (int i = 0; defaultChannels[i]; i++) { ircChannels.push_back(std::string(defaultChannels[i])); } } const char * CogitaConfig::helpOutput = " Cogita - An OpenCog chatbot. \n" " ======\n" " Usage: \n" " -n,--nick \tSet bot nick. (default: %s)\n" " -s,--server \tIRC server to connect to. (default: %s)\n" " -p,--port \tPort of IRC server to connect to. (default: %d)\n" " -c,--channel \tChannel (without #) to join (default: %s)\n" " -v,--version \tPrint version information.\n" " \n"; void CogitaConfig::printHelp() { #define BUFSZ 8190 char buff[BUFSZ]; snprintf(buff, BUFSZ, helpOutput, nick.c_str(), ircNetwork.c_str(), ircPort, ircChannels[0].c_str()); cout << buff; } void CogitaConfig::printVersion() { cout << COGITA_VSTRING << endl; } int CogitaConfig::parseOptions(int argc, char* argv[]) { int c = 0; static const char *optString = "n:s:p:c:vh"; static const struct option longOptions[] = { {"nick", required_argument, 0, 'n'}, {"server", required_argument, 0, 's'}, {"port", required_argument, 0, 's'}, {"channel", required_argument, 0, 'c'}, {"version", 0, 0, 'v'}, {"help", 0, 0, '?'}, {0, 0, 0, 0} }; while (1) { int optionIndex = 0; string channelsTemp; StringTokenizer st; c = getopt_long (argc, argv, optString, longOptions, &optionIndex); /* Detect end of options */ if (c == -1) break; switch (c) { case 'n': nick = string(optarg); createAttnVector(); break; case 's': ircNetwork = string(optarg); break; case 'p': ircPort = atoi(optarg); break; case 'c': ircChannels.clear(); channelsTemp = optarg; st.set_string(channelsTemp); st.set_delimiter(string(",")); for (string channel = st.next_token(); channel.size() > 0; channel = st.next_token()) { ircChannels.push_back("#" + channel); } break; case 'v': printVersion(); return 1; case 'h': printHelp(); return 1; default: printHelp(); return 1; } } return 0; } void CogitaConfig::createAttnVector() { const char* defaultSuffixes[] = COGITA_DEFAULT_ATTN_SUFFIXES; attn.clear(); for (int i = 0; defaultSuffixes[i]; i++) { attn.push_back(nick + string(defaultSuffixes[i])); } } }} // ~namespace opencog::chatbot <|endoftext|>
<commit_before>#include "bilgamesh_internal.hh" #include <utility> #include <valarray> #include <vector> template <class T> _bgm_strategy_monte_carlo<T>::_bgm_strategy_monte_carlo (int g, int m, double km) : num_games (g), num_moves(m), kings_multiplier(km) { } template <class T> _bgm_action<T> _bgm_strategy_monte_carlo<T>::operator () (const _bgm_board<T>& board, const std::vector<_bgm_action<T>>& in) { int num_actions = in.size (); int men, kings; bool black_move = board.is_black_move (); if (black_move) { board.count_black (men, kings); } else { board.count_white (men, kings); } std::valarray<double> men_count (0., num_actions); std::valarray<double> kings_count (0., num_actions); _bgm_board<T> tmp_board; std::vector<_bgm_action<int8_t>> vacts; _bgm_strategy_random<int8_t> rand_strat; for (int act = 0; act < num_actions; act++) { for (int game = 0; game < num_games; game++) { tmp_board = board; tmp_board.apply (in[act]); for (int move = 0; move < num_moves; move++) { tmp_board.get_actions (vacts); if (vacts.empty ()) { break; } tmp_board.apply (rand_strat (board, vacts)); } if (black_move) { tmp_board.count_black (men, kings); men_count[act] += men; kings_count[act] += kings; tmp_board.count_white (men, kings); men_count[act] -= men; kings_count[act] -= kings; } else { tmp_board.count_black (men, kings); men_count[act] -= men; kings_count[act] -= kings; tmp_board.count_white (men, kings); men_count[act] += men; kings_count[act] += kings; } } } std::valarray<double> score(0., num_actions); score = men_count; score += kings_multiplier * kings_count; int max_ind = 0; double max_val = -32.; std::vector<std::pair<int, double>> candidates; for (int i = 0; i < num_actions; i++) { if (score[i] > max_val) { max_ind = i; max_val = score[i]; } } for (int i = 0; i < num_actions; i++) { if (score[i] >= max_val) { candidates.push_back (std::make_pair (i, score[i])); } } int num_cands = candidates.size (); if (num_cands <= 1) { return in[max_ind]; } return in[(int)std::round ((double) (std::rand()*(num_cands - 1)/RAND_MAX))]; } template class _bgm_strategy_monte_carlo<int8_t>; <commit_msg>Properly select candidates and handle victories.<commit_after>#include "bilgamesh_internal.hh" #include <utility> #include <valarray> #include <vector> template <class T> _bgm_strategy_monte_carlo<T>::_bgm_strategy_monte_carlo (int g, int m, double km) : num_games (g), num_moves(m), kings_multiplier(km) { } template <class T> _bgm_action<T> _bgm_strategy_monte_carlo<T>::operator () (const _bgm_board<T>& board, const std::vector<_bgm_action<T>>& in) { int num_actions = in.size (); int men, kings; bool black_move = board.is_black_move (); bool victory_encountered; bool black_victory; if (black_move) { board.count_black (men, kings); } else { board.count_white (men, kings); } std::valarray<double> men_count (0., num_actions); std::valarray<double> kings_count (0., num_actions); _bgm_board<T> tmp_board; std::vector<_bgm_action<int8_t>> vacts; _bgm_strategy_random<int8_t> rand_strat; for (int act = 0; act < num_actions; act++) { for (int game = 0; game < num_games; game++) { victory_encountered = false; tmp_board = board; tmp_board.apply (in[act]); // Play switches to other side. tmp_board.get_actions (vacts); if (vacts.empty ()) { victory_encountered = true; black_victory = !tmp_board.is_black_move (); } else { for (int move = 0; move < num_moves; move++) { tmp_board.apply (rand_strat (board, vacts)); tmp_board.get_actions (vacts); if (vacts.empty ()) { victory_encountered = true; black_victory = !tmp_board.is_black_move (); break; } } } if (!victory_encountered) { if (black_move) { tmp_board.count_black (men, kings); men_count[act] += men; kings_count[act] += kings; tmp_board.count_white (men, kings); men_count[act] -= men; kings_count[act] -= kings; } else { tmp_board.count_black (men, kings); men_count[act] -= men; kings_count[act] -= kings; tmp_board.count_white (men, kings); men_count[act] += men; kings_count[act] += kings; } } else { if (black_victory) { if (black_move) { tmp_board.count_black (men, kings); men_count[act] += men; kings_count[act] += kings; } else { tmp_board.count_black (men, kings); men_count[act] -= men; kings_count[act] -= kings; } } else { if (black_move) { tmp_board.count_white (men, kings); men_count[act] -= men; kings_count[act] -= kings; } else { tmp_board.count_white (men, kings); men_count[act] += men; kings_count[act] += kings; } } } } } std::valarray<double> score(0., num_actions); score = men_count; score += kings_multiplier * kings_count; int max_ind = 0; double max_val = -32.; std::vector<int> candidates; for (int i = 0; i < num_actions; i++) { if (score[i] > max_val) { max_ind = i; max_val = score[i]; } } for (int i = 0; i < num_actions; i++) { if (score[i] >= max_val) { candidates.push_back (i); } } int num_cands = candidates.size (); if (num_cands <= 1) { return in[max_ind]; } int cand_ind = (int)std::round ((double) std::rand()*(num_cands-1)/((double)RAND_MAX)); return in[candidates[cand_ind]]; } template class _bgm_strategy_monte_carlo<int8_t>; <|endoftext|>
<commit_before><commit_msg>3D model insertion: display extensions in the filter selector<commit_after><|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS sj05 (1.16.226); FILE MERGED 2004/02/13 13:25:06 sj 1.16.226.2: RESYNC: (1.16-1.18); FILE MERGED 2004/01/23 17:20:27 cl 1.16.226.1: #i20484# adding autoshape ui<commit_after><|endoftext|>
<commit_before><commit_msg>#105477# Don't show query dialog if print dialog has been shown<commit_after><|endoftext|>
<commit_before>// $Id: NucleicAcid_test.C,v 1.2 2000/01/10 15:51:17 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/KERNEL/nucleicAcid.h> /////////////////////////// START_TEST(NucleicAcid, "$Id: NucleicAcid_test.C,v 1.2 2000/01/10 15:51:17 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; NucleicAcid* na; CHECK(NucleicAcid::NucleicAcid()) na = new NucleicAcid; TEST_NOT_EQUAL(na, 0) RESULT CHECK(NucleicAcid::~NucleicAcid()) delete na; RESULT CHECK(NucleicAcid::NucleicAcid(const NucleicAcid&, bool)) //BAUSTELLE RESULT CHECK(NucleicAcid::NucleicAcid(constr String&, const String&) //BAUSTELLE RESULT CHECK(NucleicAcid::clear()) //BAUSTELLE RESULT CHECK(NucleicAcid::destroy()) //BAUSTELLE RESULT CHECK(NucleicAcid::persistentWrite()) //BAUSTELLE RESULT CHECK(NucleicAcid::persistentRead()) //BAUSTELLE RESULT CHECK(NucleicAcid::set(const NucleicAcid&, bool)) //BAUSTELLE RESULT CHECK(NucleicAcid::operator = (const NucleicAcid&)) //BAUSTELLE RESULT CHECK(NucleicAcid::get(NucleicAcid&, bool)) //BAUSTELLE RESULT CHECK(NucleicAcid::swap(NucleicAcid&)) //BAUSTELLE RESULT CHECK(NucleicAcid::get3Prime()) //BAUSTELLE RESULT CHECK(NucleicAcid::get3Prime() const) //BAUSTELLE RESULT CHECK(NucleicAcid::get5Prime()) //BAUSTELLE RESULT CHECK(NucleicAcid::get5Prime() const) //BAUSTELLE RESULT CHECK(NucleicAcid::getID() const) //BAUSTELLE RESULT CHECK(NucleicAcid::setID(const String&)) //BAUSTELLE RESULT CHECK(NucleicAcid::countNucleotides()) //BAUSTELLE RESULT CHECK(NucleicAcid::isValid()) //BAUSTELLE RESULT CHECK(NucleicAcid::dump(ostream&, Size)) //BAUSTELLE RESULT CHECK(NucleicAcid::read(istream&)) //BAUSTELLE RESULT CHECK(NucleicAcid::write(ostream&) const) //BAUSTELLE RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>added some tests<commit_after>// $Id: NucleicAcid_test.C,v 1.3 2000/05/11 13:34:51 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/KERNEL/nucleicAcid.h> /////////////////////////// START_TEST(NucleicAcid, "$Id: NucleicAcid_test.C,v 1.3 2000/05/11 13:34:51 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; NucleicAcid* r; CHECK(NucleicAcid()) r = new NucleicAcid; TEST_NOT_EQUAL(r, 0) RESULT CHECK(~NucleicAcid()) delete r; RESULT CHECK(NucleicAcid(NucleicAcid&, bool)) NucleicAcid* na1 = new NucleicAcid; na1->setName("testname"); Nucleotide a("a"); na1->insert(a); NucleicAcid* na2 = new NucleicAcid(*na1, true); TEST_NOT_EQUAL(na2, 0) if (na2 != 0) { TEST_EQUAL(na2->getName(), "testname") TEST_EQUAL(na2->getNucleotide(0)->getName(), "a") delete na2; } na2 = new NucleicAcid(*na1, false); TEST_NOT_EQUAL(na2, 0) if (na2 != 0) { TEST_EQUAL(na2->getName(), "testname") delete na2; } delete na1; RESULT CHECK(NucleicAcid(const String& name, const String& id = BALL_NUCLEICACID_DEFAULT_ID)) NucleicAcid* na1 = new NucleicAcid("na1", "id"); TEST_NOT_EQUAL(na1, 0) if (na1 != 0) { TEST_EQUAL(na1->getName(), "na1") TEST_EQUAL(na1->getID(), "id") delete na1; } NucleicAcid* na2 = new NucleicAcid("na1"); TEST_NOT_EQUAL(na2, 0) if (na2 != 0) { TEST_EQUAL(na2->getName(), "na1") TEST_EQUAL(na2->getID(), "") delete na2; } RESULT CHECK(NucleicAcid::clear()) NucleicAcid na("na1", "id"); Nucleotide a("a"); na.insert(a); na.clear(); TEST_EQUAL(na.countNucleotides(), 0) TEST_EQUAL(na.getID(), "") RESULT CHECK(NucleicAcid::destroy()) NucleicAcid na("na1", "id"); Nucleotide a("a"); na.insert(a); na.destroy(); TEST_EQUAL(na.countNucleotides(), 0) TEST_EQUAL(na.getID(), "") RESULT CHECK(NucleicAcid::set(const NucleicAcid& NucleicAcid, bool deep = true)) NucleicAcid na1("na1"); Nucleotide a("a"); na1.insert(a); NucleicAcid na2("na2"); na2.set(na1, false); TEST_EQUAL(na2.getName(), "na1") TEST_EQUAL(na2.countNucleotides(), 0) na2.setName("a"); na2.set(na1); TEST_EQUAL(na2.getName(), "na1") TEST_EQUAL(na2.countNucleotides(), 1) RESULT CHECK(NucleicAcid::NucleicAcid& operator = (const NucleicAcid& NucleicAcid)) NucleicAcid na1("na1"); Nucleotide a("a"); na1.insert(a); NucleicAcid na2("na2"); na2 = na1; TEST_EQUAL(na2.getName(), "na1") TEST_EQUAL(na2.countNucleotides(), 1) RESULT CHECK(NucleicAcid::get(NucleicAcid& NucleicAcid, bool deep = true) const ) NucleicAcid na1("na1"); Nucleotide a("a"); na1.insert(a); NucleicAcid na2("na2"); na1.get(na2, false); TEST_EQUAL(na2.getName(), "na1") TEST_EQUAL(na2.countNucleotides(), 0) na2.setName("a"); na1.get(na2); TEST_EQUAL(na2.getName(), "na1") TEST_EQUAL(na2.countNucleotides(), 1) RESULT CHECK(NucleicAcid::swap(NucleicAcid&)) NucleicAcid na1("na1"); NucleicAcid na2("na2"); Nucleotide n1("n1"); Nucleotide n2("n2"); na1.insert(n1); na2.insert(n2); na1.swap(na2); TEST_EQUAL(na1.getName(), "na2") TEST_EQUAL(na1.getNucleotide(0), &n2) TEST_EQUAL(na2.getName(), "na1") TEST_EQUAL(na2.getNucleotide(0), &n1) RESULT CHECK(NucleicAcid::get3Prime()) NucleicAcid na1("na1"); Nucleotide n1("n1"); na1.insert(n1); na1.get3Prime()->setName("X"); TEST_EQUAL(na1.get3Prime()->getName(), "X") RESULT CHECK(NucleicAcid::get3Prime() const) NucleicAcid na1("na1"); TEST_EQUAL(na1.get3Prime(), 0) Nucleotide n1("n1"); Nucleotide n2("n2"); Nucleotide n3("n3"); na1.insert(n1); TEST_EQUAL(na1.get3Prime(), &n1) na1.insert(n2); TEST_EQUAL(na1.get3Prime(), &n1) na1.prepend(n3); TEST_EQUAL(na1.get3Prime(), &n3) RESULT CHECK(NucleicAcid::get5Prime()) NucleicAcid na1("na1"); Nucleotide n1("n1"); na1.insert(n1); na1.get5Prime()->setName("X"); TEST_EQUAL(na1.get5Prime()->getName(), "X") RESULT CHECK(NucleicAcid::get5Prime() const) NucleicAcid na1("na1"); TEST_EQUAL(na1.get5Prime(), 0) Nucleotide n1("n1"); Nucleotide n2("n2"); Nucleotide n3("n3"); na1.insert(n1); TEST_EQUAL(na1.get5Prime(), &n1) na1.prepend(n2); TEST_EQUAL(na1.get5Prime(), &n1) na1.insert(n3); TEST_EQUAL(na1.get5Prime(), &n3) RESULT CHECK(NucleicAcid::getID() const) NucleicAcid na1("na1"); TEST_EQUAL(na1.getID(), BALL_NUCLEICACID_DEFAULT_ID) na1.setID("X"); TEST_EQUAL(na1.getID(), "X") RESULT CHECK(NucleicAcid::setID(const String&)) NucleicAcid na1("na1"); na1.setID(""); TEST_EQUAL(na1.getID(), BALL_NUCLEICACID_DEFAULT_ID) na1.setID("X"); TEST_EQUAL(na1.getID(), "X") RESULT CHECK(NucleicAcid::countNucleotides()) NucleicAcid na1("na1"); TEST_EQUAL(na1.countNucleotides(), 0) Nucleotide n1("n1"); na1.insert(n1); TEST_EQUAL(na1.countNucleotides(), 1) RESULT CHECK(NucleicAcid::isValid()) NucleicAcid na1(""); TEST_EQUAL(na1.isValid(), true) na1.setID(""); TEST_EQUAL(na1.isValid(), true) na1.setID("X"); TEST_EQUAL(na1.isValid(), true) RESULT CHECK(NucleicAcid::dump(ostream&, Size)) //BAUSTELLE RESULT CHECK(NucleicAcid::read(istream&)) //BAUSTELLE RESULT CHECK(NucleicAcid::write(ostream&) const) //BAUSTELLE RESULT CHECK(NucleicAcid::persistentWrite()) //BAUSTELLE RESULT CHECK(NucleicAcid::persistentRead()) //BAUSTELLE RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "file_directory_index.hxx" #include "Request.hxx" #include "translation/Response.hxx" #include "file_address.hxx" #include <assert.h> #include <sys/stat.h> #include <errno.h> gcc_pure static bool is_dir(const char *path) { struct stat st; return stat(path, &st) == 0 && S_ISDIR(st.st_mode); } gcc_pure static bool IsDirectory(const FileAddress &address) noexcept { return is_dir(address.path); } bool check_directory_index(Request &request, const TranslateResponse &response) { assert(!response.directory_index.IsNull()); if (response.test_path != nullptr) { if (!is_dir(response.test_path)) return true; } else { switch (response.address.type) { case ResourceAddress::Type::NONE: case ResourceAddress::Type::HTTP: case ResourceAddress::Type::LHTTP: case ResourceAddress::Type::PIPE: case ResourceAddress::Type::CGI: case ResourceAddress::Type::FASTCGI: case ResourceAddress::Type::WAS: case ResourceAddress::Type::NFS: request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY, "Resource address not compatible with DIRECTORY_INDEX", 1); return false; case ResourceAddress::Type::LOCAL: if (!IsDirectory(response.address.GetFile())) return true; break; // TODO: implement NFS } } if (++request.translate.n_directory_index > 4) { request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY, "Got too many consecutive DIRECTORY_INDEX packets", 1); return false; } request.translate.request.directory_index = response.directory_index; request.SubmitTranslateRequest(); return false; } <commit_msg>bp/file_directory_index: migrate to statx()<commit_after>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "file_directory_index.hxx" #include "Request.hxx" #include "translation/Response.hxx" #include "file_address.hxx" #include <assert.h> #include <fcntl.h> #include <sys/stat.h> #include <errno.h> gcc_pure static bool is_dir(const char *path) { struct statx st; return statx(AT_FDCWD, path, AT_STATX_DONT_SYNC, STATX_TYPE, &st) == 0 && S_ISDIR(st.stx_mode); } gcc_pure static bool IsDirectory(const FileAddress &address) noexcept { return is_dir(address.path); } bool check_directory_index(Request &request, const TranslateResponse &response) { assert(!response.directory_index.IsNull()); if (response.test_path != nullptr) { if (!is_dir(response.test_path)) return true; } else { switch (response.address.type) { case ResourceAddress::Type::NONE: case ResourceAddress::Type::HTTP: case ResourceAddress::Type::LHTTP: case ResourceAddress::Type::PIPE: case ResourceAddress::Type::CGI: case ResourceAddress::Type::FASTCGI: case ResourceAddress::Type::WAS: case ResourceAddress::Type::NFS: request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY, "Resource address not compatible with DIRECTORY_INDEX", 1); return false; case ResourceAddress::Type::LOCAL: if (!IsDirectory(response.address.GetFile())) return true; break; // TODO: implement NFS } } if (++request.translate.n_directory_index > 4) { request.LogDispatchError(HTTP_STATUS_BAD_GATEWAY, "Got too many consecutive DIRECTORY_INDEX packets", 1); return false; } request.translate.request.directory_index = response.directory_index; request.SubmitTranslateRequest(); return false; } <|endoftext|>
<commit_before>// Copyright 2013 Yangqing Jia #include <stdint.h> #include <leveldb/db.h> #include <pthread.h> #include <string> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/io.hpp" #include "caffe/vision_layers.hpp" using std::string; namespace caffe { cudaStream_t copyStream = 0; int lock = 1; int getLock() { return lock; } template <typename Dtype> void* DataLayerPrefetch(void* layer_pointer) { LOG(INFO) << "Thread prefetch created"; if (!copyStream) { CUDA_CHECK(cudaStreamCreate(&copyStream)); } CHECK(layer_pointer); DataLayer<Dtype>* layer = reinterpret_cast<DataLayer<Dtype>*>(layer_pointer); CHECK(layer); Datum datum; CHECK(layer->prefetch_data_); layer->prefetch_data_->streamedDataToCpu(copyStream); layer->prefetch_label_->streamedDataToCpu(copyStream); Dtype* top_data = layer->prefetch_data_->mutable_cpu_data(); Dtype* top_label = layer->prefetch_label_->mutable_cpu_data(); const Dtype scale = layer->layer_param_.scale(); const int batchsize = layer->layer_param_.batchsize(); const int cropsize = layer->layer_param_.cropsize(); const bool mirror = layer->layer_param_.mirror(); if (mirror && cropsize == 0) { LOG(FATAL) << "Current implementation requires mirror and cropsize to be " << "set at the same time."; } // datum scales const int channels = layer->datum_channels_; const int height = layer->datum_height_; const int width = layer->datum_width_; const int size = layer->datum_size_; const Dtype* mean = layer->data_mean_.cpu_data(); for (int itemid = 0; itemid < batchsize; ++itemid) { // get a blob CHECK(layer->iter_); CHECK(layer->iter_->Valid()); datum.ParseFromString(layer->iter_->value().ToString()); const string& data = datum.data(); if (cropsize) { CHECK(data.size()) << "Image cropping only support uint8 data"; int h_off, w_off; // We only do random crop when we do training. if (Caffe::phase() == Caffe::TRAIN) { // NOLINT_NEXT_LINE(runtime/threadsafe_fn) h_off = rand() % (height - cropsize); // NOLINT_NEXT_LINE(runtime/threadsafe_fn) w_off = rand() % (width - cropsize); } else { h_off = (height - cropsize) / 2; w_off = (width - cropsize) / 2; } // NOLINT_NEXT_LINE(runtime/threadsafe_fn) if (mirror && rand() % 2) { // Copy mirrored version for (int c = 0; c < channels; ++c) { for (int h = 0; h < cropsize; ++h) { for (int w = 0; w < cropsize; ++w) { top_data[((itemid * channels + c) * cropsize + h) * cropsize + cropsize - 1 - w] = (static_cast<Dtype>( (uint8_t)data[(c * height + h + h_off) * width + w + w_off]) - mean[(c * height + h + h_off) * width + w + w_off]) * scale; } } } } else { // Normal copy for (int c = 0; c < channels; ++c) { for (int h = 0; h < cropsize; ++h) { for (int w = 0; w < cropsize; ++w) { top_data[((itemid * channels + c) * cropsize + h) * cropsize + w] = (static_cast<Dtype>( (uint8_t)data[(c * height + h + h_off) * width + w + w_off]) - mean[(c * height + h + h_off) * width + w + w_off]) * scale; } } } } } else { // we will prefer to use data() first, and then try float_data() if (data.size()) { for (int j = 0; j < size; ++j) { top_data[itemid * size + j] = (static_cast<Dtype>((uint8_t)data[j]) - mean[j]) * scale; } } else { for (int j = 0; j < size; ++j) { top_data[itemid * size + j] = (datum.float_data(j) - mean[j]) * scale; } } } top_label[itemid] = datum.label(); // go to the next iter layer->iter_->Next(); if (!layer->iter_->Valid()) { // We have reached the end. Restart from the first. DLOG(INFO) << "Restarting data prefetching from start."; layer->iter_->SeekToFirst(); } } while (!getLock()); LOG(INFO) << "Lock released"; layer->prefetch_data_->streamedDataToGpu(copyStream); layer->prefetch_label_->streamedDataToGpu(copyStream); lock = 0; return reinterpret_cast<void*>(NULL); } template <typename Dtype> DataLayer<Dtype>::~DataLayer<Dtype>() { // Finally, join the thread CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed."; } template <typename Dtype> void DataLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 0) << "Data Layer takes no input blobs."; CHECK_EQ(top->size(), 2) << "Data Layer takes two blobs as output."; // Initialize the leveldb leveldb::DB* db_temp; leveldb::Options options; options.create_if_missing = false; options.max_open_files = 100; LOG(INFO) << "Opening leveldb " << this->layer_param_.source(); leveldb::Status status = leveldb::DB::Open( options, this->layer_param_.source(), &db_temp); CHECK(status.ok()) << "Failed to open leveldb " << this->layer_param_.source() << std::endl << status.ToString(); db_.reset(db_temp); iter_.reset(db_->NewIterator(leveldb::ReadOptions())); iter_->SeekToFirst(); // Check if we would need to randomly skip a few data points if (this->layer_param_.rand_skip()) { // NOLINT_NEXT_LINE(runtime/threadsafe_fn) unsigned int skip = rand() % this->layer_param_.rand_skip(); LOG(INFO) << "Skipping first " << skip << " data points."; while (skip-- > 0) { iter_->Next(); if (!iter_->Valid()) { iter_->SeekToFirst(); } } } // Read a data point, and use it to initialize the top blob. Datum datum; datum.ParseFromString(iter_->value().ToString()); // image int cropsize = this->layer_param_.cropsize(); if (cropsize > 0) { (*top)[0]->Reshape( this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize); prefetch_data_.reset(new Blob<Dtype>( this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize)); } else { (*top)[0]->Reshape( this->layer_param_.batchsize(), datum.channels(), datum.height(), datum.width()); prefetch_data_.reset(new Blob<Dtype>( this->layer_param_.batchsize(), datum.channels(), datum.height(), datum.width())); } LOG(INFO) << "output data size: " << (*top)[0]->num() << "," << (*top)[0]->channels() << "," << (*top)[0]->height() << "," << (*top)[0]->width(); // label (*top)[1]->Reshape(this->layer_param_.batchsize(), 1, 1, 1); prefetch_label_.reset( new Blob<Dtype>(this->layer_param_.batchsize(), 1, 1, 1)); // datum size datum_channels_ = datum.channels(); datum_height_ = datum.height(); datum_width_ = datum.width(); datum_size_ = datum.channels() * datum.height() * datum.width(); CHECK_GT(datum_height_, cropsize); CHECK_GT(datum_width_, cropsize); // check if we want to have mean if (this->layer_param_.has_meanfile()) { BlobProto blob_proto; LOG(INFO) << "Loading mean file from" << this->layer_param_.meanfile(); ReadProtoFromBinaryFile(this->layer_param_.meanfile().c_str(), &blob_proto); data_mean_.FromProto(blob_proto); CHECK_EQ(data_mean_.num(), 1); CHECK_EQ(data_mean_.channels(), datum_channels_); CHECK_EQ(data_mean_.height(), datum_height_); CHECK_EQ(data_mean_.width(), datum_width_); } else { // Simply initialize an all-empty mean. data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_); } // Now, start the prefetch thread. Before calling prefetch, we make two // cpu_data calls so that the prefetch thread does not accidentally make // simultaneous cudaMalloc calls when the main thread is running. In some // GPUs this seems to cause failures if we do not so. prefetch_data_->mutable_cpu_data(); prefetch_label_->mutable_cpu_data(); data_mean_.cpu_data(); DLOG(INFO) << "Initializing prefetch"; CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; DLOG(INFO) << "Prefetch initialized."; } template <typename Dtype> void DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { // First, join the thread CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed."; // Copy the data memcpy((*top)[0]->mutable_cpu_data(), prefetch_data_->cpu_data(), sizeof(Dtype) * prefetch_data_->count()); memcpy((*top)[1]->mutable_cpu_data(), prefetch_label_->cpu_data(), sizeof(Dtype) * prefetch_label_->count()); // Start a new prefetch thread CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; } // The backward operations are dummy - they do not carry any computation. template <typename Dtype> Dtype DataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { return Dtype(0.); } INSTANTIATE_CLASS(DataLayer); } // namespace caffe <commit_msg>[master] Delete output<commit_after>// Copyright 2013 Yangqing Jia #include <stdint.h> #include <leveldb/db.h> #include <pthread.h> #include <string> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/io.hpp" #include "caffe/vision_layers.hpp" using std::string; namespace caffe { cudaStream_t copyStream = 0; int lock = 1; int getLock() { return lock; } template <typename Dtype> void* DataLayerPrefetch(void* layer_pointer) { if (!copyStream) { CUDA_CHECK(cudaStreamCreate(&copyStream)); } CHECK(layer_pointer); DataLayer<Dtype>* layer = reinterpret_cast<DataLayer<Dtype>*>(layer_pointer); CHECK(layer); Datum datum; CHECK(layer->prefetch_data_); layer->prefetch_data_->streamedDataToCpu(copyStream); layer->prefetch_label_->streamedDataToCpu(copyStream); Dtype* top_data = layer->prefetch_data_->mutable_cpu_data(); Dtype* top_label = layer->prefetch_label_->mutable_cpu_data(); const Dtype scale = layer->layer_param_.scale(); const int batchsize = layer->layer_param_.batchsize(); const int cropsize = layer->layer_param_.cropsize(); const bool mirror = layer->layer_param_.mirror(); if (mirror && cropsize == 0) { LOG(FATAL) << "Current implementation requires mirror and cropsize to be " << "set at the same time."; } // datum scales const int channels = layer->datum_channels_; const int height = layer->datum_height_; const int width = layer->datum_width_; const int size = layer->datum_size_; const Dtype* mean = layer->data_mean_.cpu_data(); for (int itemid = 0; itemid < batchsize; ++itemid) { // get a blob CHECK(layer->iter_); CHECK(layer->iter_->Valid()); datum.ParseFromString(layer->iter_->value().ToString()); const string& data = datum.data(); if (cropsize) { CHECK(data.size()) << "Image cropping only support uint8 data"; int h_off, w_off; // We only do random crop when we do training. if (Caffe::phase() == Caffe::TRAIN) { // NOLINT_NEXT_LINE(runtime/threadsafe_fn) h_off = rand() % (height - cropsize); // NOLINT_NEXT_LINE(runtime/threadsafe_fn) w_off = rand() % (width - cropsize); } else { h_off = (height - cropsize) / 2; w_off = (width - cropsize) / 2; } // NOLINT_NEXT_LINE(runtime/threadsafe_fn) if (mirror && rand() % 2) { // Copy mirrored version for (int c = 0; c < channels; ++c) { for (int h = 0; h < cropsize; ++h) { for (int w = 0; w < cropsize; ++w) { top_data[((itemid * channels + c) * cropsize + h) * cropsize + cropsize - 1 - w] = (static_cast<Dtype>( (uint8_t)data[(c * height + h + h_off) * width + w + w_off]) - mean[(c * height + h + h_off) * width + w + w_off]) * scale; } } } } else { // Normal copy for (int c = 0; c < channels; ++c) { for (int h = 0; h < cropsize; ++h) { for (int w = 0; w < cropsize; ++w) { top_data[((itemid * channels + c) * cropsize + h) * cropsize + w] = (static_cast<Dtype>( (uint8_t)data[(c * height + h + h_off) * width + w + w_off]) - mean[(c * height + h + h_off) * width + w + w_off]) * scale; } } } } } else { // we will prefer to use data() first, and then try float_data() if (data.size()) { for (int j = 0; j < size; ++j) { top_data[itemid * size + j] = (static_cast<Dtype>((uint8_t)data[j]) - mean[j]) * scale; } } else { for (int j = 0; j < size; ++j) { top_data[itemid * size + j] = (datum.float_data(j) - mean[j]) * scale; } } } top_label[itemid] = datum.label(); // go to the next iter layer->iter_->Next(); if (!layer->iter_->Valid()) { // We have reached the end. Restart from the first. DLOG(INFO) << "Restarting data prefetching from start."; layer->iter_->SeekToFirst(); } } while (!getLock()); LOG(INFO) << "Lock released"; layer->prefetch_data_->streamedDataToGpu(copyStream); layer->prefetch_label_->streamedDataToGpu(copyStream); lock = 0; return reinterpret_cast<void*>(NULL); } template <typename Dtype> DataLayer<Dtype>::~DataLayer<Dtype>() { // Finally, join the thread CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed."; } template <typename Dtype> void DataLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 0) << "Data Layer takes no input blobs."; CHECK_EQ(top->size(), 2) << "Data Layer takes two blobs as output."; // Initialize the leveldb leveldb::DB* db_temp; leveldb::Options options; options.create_if_missing = false; options.max_open_files = 100; LOG(INFO) << "Opening leveldb " << this->layer_param_.source(); leveldb::Status status = leveldb::DB::Open( options, this->layer_param_.source(), &db_temp); CHECK(status.ok()) << "Failed to open leveldb " << this->layer_param_.source() << std::endl << status.ToString(); db_.reset(db_temp); iter_.reset(db_->NewIterator(leveldb::ReadOptions())); iter_->SeekToFirst(); // Check if we would need to randomly skip a few data points if (this->layer_param_.rand_skip()) { // NOLINT_NEXT_LINE(runtime/threadsafe_fn) unsigned int skip = rand() % this->layer_param_.rand_skip(); LOG(INFO) << "Skipping first " << skip << " data points."; while (skip-- > 0) { iter_->Next(); if (!iter_->Valid()) { iter_->SeekToFirst(); } } } // Read a data point, and use it to initialize the top blob. Datum datum; datum.ParseFromString(iter_->value().ToString()); // image int cropsize = this->layer_param_.cropsize(); if (cropsize > 0) { (*top)[0]->Reshape( this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize); prefetch_data_.reset(new Blob<Dtype>( this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize)); } else { (*top)[0]->Reshape( this->layer_param_.batchsize(), datum.channels(), datum.height(), datum.width()); prefetch_data_.reset(new Blob<Dtype>( this->layer_param_.batchsize(), datum.channels(), datum.height(), datum.width())); } LOG(INFO) << "output data size: " << (*top)[0]->num() << "," << (*top)[0]->channels() << "," << (*top)[0]->height() << "," << (*top)[0]->width(); // label (*top)[1]->Reshape(this->layer_param_.batchsize(), 1, 1, 1); prefetch_label_.reset( new Blob<Dtype>(this->layer_param_.batchsize(), 1, 1, 1)); // datum size datum_channels_ = datum.channels(); datum_height_ = datum.height(); datum_width_ = datum.width(); datum_size_ = datum.channels() * datum.height() * datum.width(); CHECK_GT(datum_height_, cropsize); CHECK_GT(datum_width_, cropsize); // check if we want to have mean if (this->layer_param_.has_meanfile()) { BlobProto blob_proto; LOG(INFO) << "Loading mean file from" << this->layer_param_.meanfile(); ReadProtoFromBinaryFile(this->layer_param_.meanfile().c_str(), &blob_proto); data_mean_.FromProto(blob_proto); CHECK_EQ(data_mean_.num(), 1); CHECK_EQ(data_mean_.channels(), datum_channels_); CHECK_EQ(data_mean_.height(), datum_height_); CHECK_EQ(data_mean_.width(), datum_width_); } else { // Simply initialize an all-empty mean. data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_); } // Now, start the prefetch thread. Before calling prefetch, we make two // cpu_data calls so that the prefetch thread does not accidentally make // simultaneous cudaMalloc calls when the main thread is running. In some // GPUs this seems to cause failures if we do not so. prefetch_data_->mutable_cpu_data(); prefetch_label_->mutable_cpu_data(); data_mean_.cpu_data(); DLOG(INFO) << "Initializing prefetch"; CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; DLOG(INFO) << "Prefetch initialized."; } template <typename Dtype> void DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { // First, join the thread CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed."; // Copy the data memcpy((*top)[0]->mutable_cpu_data(), prefetch_data_->cpu_data(), sizeof(Dtype) * prefetch_data_->count()); memcpy((*top)[1]->mutable_cpu_data(), prefetch_label_->cpu_data(), sizeof(Dtype) * prefetch_label_->count()); // Start a new prefetch thread CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; } // The backward operations are dummy - they do not carry any computation. template <typename Dtype> Dtype DataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { return Dtype(0.); } INSTANTIATE_CLASS(DataLayer); } // namespace caffe <|endoftext|>
<commit_before> #include "tasksystem.hpp" #include "filters.hpp" #include <iostream> #include <cstring> void tag(int argc, char *argv[], sptm::TaskSystem* ts) { if(argc != 4) { std::cerr << "Invalid use of tag command." << std::endl; return; } ts->clearFilters(); sptm::TagFilter filter(argv[3], true); ts->addFilter(&filter); std::vector<sptm::Task*> tasks = ts->applyFilters(); for(sptm::Task* tk : tasks) tk->addTag(argv[2]); } void search(int argc, char *argv[], sptm::TaskSystem* ts) { if(argc <= 2) { std::cerr << "Missing arguments to search command." << std::endl; return; } ts->clearFilters(); for(int i = 2; i < argc; ++i) { sptm::TagFilter filter(argv[i], true); if(argv[i][0] == '-') filter.set(argv[i] + 1, false); ts->addFilter(&filter); } std::vector<sptm::Task*> tasks = ts->applyFilters(); for(sptm::Task* tk : tasks) std::cout << "Task " << tk->stored_id() << " : \"" << tk->action() << "\"." << std::endl; } int main(int argc, char *argv[]) { if(argc <= 1) { std::cerr << "Argument required." << std::endl; return 1; } sptm::TaskSystem ts; ts.config(sptm::TaskSystem::DEFSRC, "Lucas8"); ts.config(sptm::TaskSystem::DEFDST, "Lucas8"); ts.config(sptm::TaskSystem::DEFEXE, "Lucas8"); std::string home = std::getenv("HOME"); ts.config(sptm::TaskSystem::DONEPATH, home + "/.sptm/done"); ts.config(sptm::TaskSystem::UNDONEPATH, home + "/.sptm/undone"); if(!ts.load()) { std::cerr << "Couldn't load SPTM files." << std::endl; return 1; } if(strcmp(argv[1], "tag") == 0) tag(argc, argv, &ts); else if(strcmp(argv[1], "search") == 0) tag(argc, argv, &ts); else { std::cerr << "Invalid command." << std::endl; return 1; } return 0; } <commit_msg>fixed a bug in the test program.<commit_after> #include "tasksystem.hpp" #include "filters.hpp" #include <iostream> #include <cstring> void tag(int argc, char *argv[], sptm::TaskSystem* ts) { if(argc != 4) { std::cerr << "Invalid use of tag command." << std::endl; return; } ts->clearFilters(); sptm::TagFilter filter(argv[3], true); ts->addFilter(&filter); std::vector<sptm::Task*> tasks = ts->applyFilters(); for(sptm::Task* tk : tasks) tk->addTag(argv[2]); } void search(int argc, char *argv[], sptm::TaskSystem* ts) { if(argc <= 2) { std::cerr << "Missing arguments to search command." << std::endl; return; } ts->clearFilters(); for(int i = 2; i < argc; ++i) { sptm::TagFilter filter(argv[i], true); if(argv[i][0] == '-') filter.set(argv[i] + 1, false); ts->addFilter(&filter); } std::vector<sptm::Task*> tasks = ts->applyFilters(); for(sptm::Task* tk : tasks) std::cout << "Task " << tk->stored_id() << " : \"" << tk->action() << "\"." << std::endl; } int main(int argc, char *argv[]) { if(argc <= 1) { std::cerr << "Argument required." << std::endl; return 1; } sptm::TaskSystem ts; ts.config(sptm::TaskSystem::DEFSRC, "Lucas8"); ts.config(sptm::TaskSystem::DEFDST, "Lucas8"); ts.config(sptm::TaskSystem::DEFEXE, "Lucas8"); std::string home = std::getenv("HOME"); ts.config(sptm::TaskSystem::DONEPATH, home + "/.sptm/done"); ts.config(sptm::TaskSystem::UNDONEPATH, home + "/.sptm/undone"); if(!ts.load()) { std::cerr << "Couldn't load SPTM files." << std::endl; return 1; } if(strcmp(argv[1], "tag") == 0) tag(argc, argv, &ts); else if(strcmp(argv[1], "search") == 0) search(argc, argv, &ts); else { std::cerr << "Invalid command." << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#ifndef DOUBLE_D_HPP #define DOUBLE_D_HPP #include <string> #include <cmath> #define STRINGIFY2(...) \ #__VA_ARGS__; \ __VA_ARGS__ namespace stan { namespace math { namespace internal { // \cond const char* double_d_src = STRINGIFY2( // \endcond typedef struct double_d { double high, low; #ifdef __cplusplus double_d() {} double_d(double a) : high(a), low(0) {} double_d(double h, double l) : high(h), low(l) {} #endif } double_d; inline double_d add_quick_d_d(double a, double b) { double_d res; res.high = a + b; res.low = b - (res.high - a); return res; } inline double_d add_d_d(double a, double b) { #ifdef __cplusplus using std::isfinite; #endif double_d res; res.high = a + b; if (isfinite(res.high)) { double v = res.high - a; res.low = (a - (res.high - v)) + (b - v); } else { res.low = 0; } return res; } inline double_d mul_d_d(double a, double b) { double_d res; res.high = a * b; res.low = fma(a, b, -res.high); return res; } inline double_d neg(double_d a) { double_d res; res.high = -a.high; res.low = -a.low; return res; } inline double_d add_dd_dd(double_d a, double_d b) { #ifdef __cplusplus using std::isfinite; #endif // double_d high = add_d_d(a.high, b.high); // if (isfinite(high.high)) { // double_d low = add_d_d(a.low, b.low); // double_d mid = add_d_d(high.low, low.high); // mid.low += low.high; // double_d high2 = add_d_d(high.high, mid.high); // double_d mid2 = add_d_d(mid.low, high2.high); // double_d low2 = add_d_d(high2.low, mid2.low); // return { mid2.high, low2.high } // // double_d v = add_quick_d_d(high.high, high.low + // low.high); // // return add_quick_d_d(high.high, low.low + v.low); // } else { // return high; // } double_d res; double r = a.high + b.high; if (isfinite(r)) { double s; if (fabs(a.high) > fabs(b.high)) { s = a.high - r + b.high; } else { s = b.high - r + a.high; } s += a.low + b.low; res.high = r + s; res.low = r - res.high + s; } else { res.high = r; res.low = 0; } return res; } inline double_d add_dd_d(double_d a, double b) { #ifdef __cplusplus using std::isfinite; #endif // double_d high = add_d_d(a.high, b); // if (isfinite(high.high)) { // double_d low = add_d_d(a.low, b); // double_d high2 = add_d_d(high.high, low.high); // double_d mid2 = add_d_d(low.low, high2.high); // double_d low2 = add_d_d(high2.low, mid2.low); // return {mid2.high, low2.high}; // } else { // return high; // } // // double_d v = add_quick_d_d(high.high, high.low + a.low); // // return add_quick_d_d(high.high, v.low); double_d res; double r = a.high + b; if (isfinite(r)) { double s; if (fabs(a.high) > fabs(b)) { s = a.high - r + b; } else { s = b - r + a.high; } s += a.low; res.high = r + s; res.low = r - res.high + s; } else { res.high = r; res.low = 0; } return res; } inline double_d sub_dd_dd(double_d a, double_d b) { return add_dd_dd(a, neg(b)); } inline double_d sub_dd_d(double_d a, double b) { return add_dd_d(a, -b); } inline double_d sub_d_dd(double a, double_d b) { return add_dd_d(neg(b), a); } inline double_d mul_dd_dd(double_d a, double_d b) { #ifdef __cplusplus using std::isfinite; #endif double_d high = mul_d_d(a.high, b.high); double_d res; if (isfinite(high.high)) { high.low += a.high * b.low + a.low * b.high; res.high = high.high + high.low; res.low = high.high - res.high + high.low; } else { high.low = 0; return high; } return res; } inline double_d mul_dd_d(double_d a, double b) { #ifdef __cplusplus using std::isfinite; #endif double_d high = mul_d_d(a.high, b); double_d res; if (isfinite(high.high)) { high.low += a.low * b; res.high = high.high + high.low; res.low = high.high - res.high + high.low; return res; } else { high.low = 0; return high; } } inline double_d div_dd_dd(double_d a, double_d b) { #ifdef __cplusplus using std::isfinite; #endif double high = a.high / b.high; double_d res; if (isfinite(high)) { double_d u = mul_d_d(high, b.high); double low = (a.high - u.high - u.low + a.low - high * b.low) / b.high; res.high = high + low; res.low = high - res.high + low; } else { res.high = high; res.low = 0; } return res; } inline double_d div_dd_d(double_d a, double b) { #ifdef __cplusplus using std::isfinite; #endif double high = a.high / b; double_d res; if (isfinite(high)) { double_d u = mul_d_d(high, b); double low = (a.high - u.high - u.low + a.low) / b; res.high = high + low; res.low = high - res.high + low; } else { res.high = high; res.low = 0; } return res; } inline double_d div_d_dd(double a, double_d b) { #ifdef __cplusplus using std::isfinite; #endif double high = a / b.high; double_d res; if (isfinite(high)) { double_d u = mul_d_d(high, b.high); double low = (a - u.high - u.low - high * b.low) / b.high; res.high = high + low; res.low = high - res.high + low; } else { res.high = high; res.low = 0; } return res; } inline double copysign(double a, double_d b) { #ifdef __cplusplus using std::copysign; #endif return copysign(a, b.high); } inline double_d fabs(double_d a) { #ifdef __cplusplus using std::fabs; #endif return a.high > 0 ? a : neg(a); } inline bool isnan(double_d a) { #ifdef __cplusplus using std::isnan; #endif return isnan(a.high); } inline bool isinf(double_d a) { #ifdef __cplusplus using std::isinf; #endif return isinf(a.high); } inline bool lt_dd_dd(double_d a, double_d b) { return a.high < b.high || (a.high == b.high && a.low < b.low); } inline bool lt_d_dd(double a, double_d b) { return lt_dd_dd({a, 0}, b); } inline bool lt_dd_d(double_d a, double b) { return lt_dd_dd(a, {b, 0}); } inline bool gt_dd_dd(double_d a, double_d b) { return a.high > b.high || (a.high == b.high && a.low > b.low); } inline bool gt_d_dd(double a, double_d b) { return gt_dd_dd({a, 0}, b); } inline bool gt_dd_d(double_d a, double b) { return gt_dd_dd(a, {b, 0}); } inline bool le_dd_dd(double_d a, double_d b) { return !gt_dd_dd(a, b); } inline bool le_d_dd(double a, double_d b) { return !gt_d_dd(a, b); } inline bool le_dd_d(double_d a, double b) { return !gt_dd_d(a, b); } inline bool ge_dd_dd(double_d a, double_d b) { return !lt_dd_dd(a, b); } inline bool ge_d_dd(double a, double_d b) { return !lt_d_dd(a, b); } inline bool ge_dd_d(double_d a, double b) { return !lt_dd_d(a, b); } // \cond ); // \endcond inline double_d operator+(double_d a, double b) { return add_dd_d(a, b); } inline double_d operator+(double a, double_d b) { return add_dd_d(b, a); } inline double_d operator+(double_d a, double_d b) { return add_dd_dd(a, b); } inline double_d operator-(double a, double_d b) { return sub_d_dd(a, b); } inline double_d operator-(double_d a, double b) { return sub_dd_d(a, b); } inline double_d operator-(double_d a, double_d b) { return sub_dd_dd(a, b); } inline double_d operator*(double_d a, double b) { return mul_dd_d(a, b); } inline double_d operator*(double a, double_d b) { return mul_dd_d(b, a); } inline double_d operator*(double_d a, double_d b) { return mul_dd_dd(a, b); } inline double_d operator/(double_d a, double b) { return div_dd_d(a, b); } inline double_d operator/(double a, double_d b) { return div_dd_d(b, a); } inline double_d operator/(double_d a, double_d b) { return div_dd_dd(a, b); } inline double_d operator-(double_d a) { return neg(a); } inline bool operator<(double_d a, double_d b) { return lt_dd_dd(a, b); } inline bool operator<(double a, double_d b) { return lt_d_dd(a, b); } inline bool operator<(double_d a, double b) { return lt_dd_d(a, b); } inline bool operator>(double_d a, double_d b) { return gt_dd_dd(a, b); } inline bool operator>(double a, double_d b) { return gt_d_dd(a, b); } inline bool operator>(double_d a, double b) { return gt_dd_d(a, b); } inline bool operator<=(double_d a, double_d b) { return le_dd_dd(a, b); } inline bool operator<=(double a, double_d b) { return le_d_dd(a, b); } inline bool operator<=(double_d a, double b) { return le_dd_d(a, b); } inline bool operator>=(double_d a, double_d b) { return ge_dd_dd(a, b); } inline bool operator>=(double a, double_d b) { return ge_d_dd(a, b); } inline bool operator>=(double_d a, double b) { return ge_dd_d(a, b); } } // namespace internal } // namespace math } // namespace stan #endif // DOUBLE_D_HPP <commit_msg>fixed double double division<commit_after>#ifndef DOUBLE_D_HPP #define DOUBLE_D_HPP #include <string> #include <cmath> #define STRINGIFY2(...) \ #__VA_ARGS__; \ __VA_ARGS__ namespace stan { namespace math { namespace internal { // \cond //const char* double_d_src = STRINGIFY2( // \endcond typedef struct double_d { double high, low; #ifdef __cplusplus double_d() {} double_d(double a) : high(a), low(0) {} double_d(double h, double l) : high(h), low(l) {} #endif } double_d; inline double_d add_quick_d_d(double a, double b) { double_d res; res.high = a + b; res.low = b - (res.high - a); return res; } inline double_d add_d_d(double a, double b) { #ifdef __cplusplus using std::isfinite; #endif double_d res; res.high = a + b; if (isfinite(res.high)) { double v = res.high - a; res.low = (a - (res.high - v)) + (b - v); } else { res.low = 0; } return res; } inline double_d mul_d_d(double a, double b) { double_d res; res.high = a * b; res.low = fma(a, b, -res.high); return res; } inline double_d neg(double_d a) { double_d res; res.high = -a.high; res.low = -a.low; return res; } inline double_d add_dd_dd(double_d a, double_d b) { #ifdef __cplusplus using std::isfinite; #endif // double_d high = add_d_d(a.high, b.high); // if (isfinite(high.high)) { // double_d low = add_d_d(a.low, b.low); // double_d mid = add_d_d(high.low, low.high); // mid.low += low.high; // double_d high2 = add_d_d(high.high, mid.high); // double_d mid2 = add_d_d(mid.low, high2.high); // double_d low2 = add_d_d(high2.low, mid2.low); // return { mid2.high, low2.high } // // double_d v = add_quick_d_d(high.high, high.low + // low.high); // // return add_quick_d_d(high.high, low.low + v.low); // } else { // return high; // } double_d res; double r = a.high + b.high; if (isfinite(r)) { double s; if (fabs(a.high) > fabs(b.high)) { s = a.high - r + b.high; } else { s = b.high - r + a.high; } s += a.low + b.low; res.high = r + s; res.low = r - res.high + s; } else { res.high = r; res.low = 0; } return res; } inline double_d add_dd_d(double_d a, double b) { #ifdef __cplusplus using std::isfinite; #endif // double_d high = add_d_d(a.high, b); // if (isfinite(high.high)) { // double_d low = add_d_d(a.low, b); // double_d high2 = add_d_d(high.high, low.high); // double_d mid2 = add_d_d(low.low, high2.high); // double_d low2 = add_d_d(high2.low, mid2.low); // return {mid2.high, low2.high}; // } else { // return high; // } // // double_d v = add_quick_d_d(high.high, high.low + a.low); // // return add_quick_d_d(high.high, v.low); double_d res; double r = a.high + b; if (isfinite(r)) { double s; if (fabs(a.high) > fabs(b)) { s = a.high - r + b; } else { s = b - r + a.high; } s += a.low; res.high = r + s; res.low = r - res.high + s; } else { res.high = r; res.low = 0; } return res; } inline double_d sub_dd_dd(double_d a, double_d b) { return add_dd_dd(a, neg(b)); } inline double_d sub_dd_d(double_d a, double b) { return add_dd_d(a, -b); } inline double_d sub_d_dd(double a, double_d b) { return add_dd_d(neg(b), a); } inline double_d mul_dd_dd(double_d a, double_d b) { #ifdef __cplusplus using std::isfinite; #endif double_d high = mul_d_d(a.high, b.high); double_d res; if (isfinite(high.high)) { high.low += a.high * b.low + a.low * b.high; res.high = high.high + high.low; res.low = high.high - res.high + high.low; } else { high.low = 0; return high; } return res; } inline double_d mul_dd_d(double_d a, double b) { #ifdef __cplusplus using std::isfinite; #endif double_d high = mul_d_d(a.high, b); double_d res; if (isfinite(high.high)) { high.low += a.low * b; res.high = high.high + high.low; res.low = high.high - res.high + high.low; return res; } else { high.low = 0; return high; } } inline double_d div_dd_dd(double_d a, double_d b) { #ifdef __cplusplus using std::isfinite; #endif double high = a.high / b.high; double_d res; if (isfinite(high)) { double_d u = mul_d_d(high, b.high); double low = (a.high - u.high - u.low + a.low - high * b.low) / b.high; res.high = high + low; res.low = high - res.high + low; } else { res.high = high; res.low = 0; } return res; } inline double_d div_dd_d(double_d a, double b) { #ifdef __cplusplus using std::isfinite; #endif double high = a.high / b; double_d res; if (isfinite(high)) { double_d u = mul_d_d(high, b); double low = (a.high - u.high - u.low + a.low) / b; res.high = high + low; res.low = high - res.high + low; } else { res.high = high; res.low = 0; } return res; } inline double_d div_d_dd(double a, double_d b) { #ifdef __cplusplus using std::isfinite; #endif double high = a / b.high; double_d res; if (isfinite(high)) { double_d u = mul_d_d(high, b.high); double low = (a - u.high - u.low - high * b.low) / b.high; res.high = high + low; res.low = high - res.high + low; } else { res.high = high; res.low = 0; } return res; } inline double copysign(double a, double_d b) { #ifdef __cplusplus using std::copysign; #endif return copysign(a, b.high); } inline double_d fabs(double_d a) { #ifdef __cplusplus using std::fabs; #endif return a.high > 0 ? a : neg(a); } inline bool isnan(double_d a) { #ifdef __cplusplus using std::isnan; #endif return isnan(a.high); } inline bool isinf(double_d a) { #ifdef __cplusplus using std::isinf; #endif return isinf(a.high); } inline bool lt_dd_dd(double_d a, double_d b) { return a.high < b.high || (a.high == b.high && a.low < b.low); } inline bool lt_d_dd(double a, double_d b) { return lt_dd_dd({a, 0}, b); } inline bool lt_dd_d(double_d a, double b) { return lt_dd_dd(a, {b, 0}); } inline bool gt_dd_dd(double_d a, double_d b) { return a.high > b.high || (a.high == b.high && a.low > b.low); } inline bool gt_d_dd(double a, double_d b) { return gt_dd_dd({a, 0}, b); } inline bool gt_dd_d(double_d a, double b) { return gt_dd_dd(a, {b, 0}); } inline bool le_dd_dd(double_d a, double_d b) { return !gt_dd_dd(a, b); } inline bool le_d_dd(double a, double_d b) { return !gt_d_dd(a, b); } inline bool le_dd_d(double_d a, double b) { return !gt_dd_d(a, b); } inline bool ge_dd_dd(double_d a, double_d b) { return !lt_dd_dd(a, b); } inline bool ge_d_dd(double a, double_d b) { return !lt_d_dd(a, b); } inline bool ge_dd_d(double_d a, double b) { return !lt_dd_d(a, b); } // \cond //); // \endcond inline double_d operator+(double_d a, double b) { return add_dd_d(a, b); } inline double_d operator+(double a, double_d b) { return add_dd_d(b, a); } inline double_d operator+(double_d a, double_d b) { return add_dd_dd(a, b); } inline double_d operator-(double a, double_d b) { return sub_d_dd(a, b); } inline double_d operator-(double_d a, double b) { return sub_dd_d(a, b); } inline double_d operator-(double_d a, double_d b) { return sub_dd_dd(a, b); } inline double_d operator*(double_d a, double b) { return mul_dd_d(a, b); } inline double_d operator*(double a, double_d b) { return mul_dd_d(b, a); } inline double_d operator*(double_d a, double_d b) { return mul_dd_dd(a, b); } inline double_d operator/(double_d a, double b) { return div_dd_d(a, b); } inline double_d operator/(double a, double_d b) { return div_d_dd(a, b); } inline double_d operator/(double_d a, double_d b) { return div_dd_dd(a, b); } inline double_d operator-(double_d a) { return neg(a); } inline bool operator<(double_d a, double_d b) { return lt_dd_dd(a, b); } inline bool operator<(double a, double_d b) { return lt_d_dd(a, b); } inline bool operator<(double_d a, double b) { return lt_dd_d(a, b); } inline bool operator>(double_d a, double_d b) { return gt_dd_dd(a, b); } inline bool operator>(double a, double_d b) { return gt_d_dd(a, b); } inline bool operator>(double_d a, double b) { return gt_dd_d(a, b); } inline bool operator<=(double_d a, double_d b) { return le_dd_dd(a, b); } inline bool operator<=(double a, double_d b) { return le_d_dd(a, b); } inline bool operator<=(double_d a, double b) { return le_dd_d(a, b); } inline bool operator>=(double_d a, double_d b) { return ge_dd_dd(a, b); } inline bool operator>=(double a, double_d b) { return ge_d_dd(a, b); } inline bool operator>=(double_d a, double b) { return ge_dd_d(a, b); } } // namespace internal } // namespace math } // namespace stan #endif // DOUBLE_D_HPP <|endoftext|>
<commit_before>#include "game.hpp" void Game::sortMoves(MoveArray& result, int depth) { int num_attacks = result.num_attacks; if(result.num_attacks >= 0 && result.num_attacks < result.moveArray.size() && result.count >= 1 && result.count < result.moveArray.size()) { if(game_board.whiteMove) { for(unsigned int i = result.num_attacks + 1; i < result.count - 1; ++i) { for(int j = i - 1; j >= num_attacks && whiteHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < whiteHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) { std::swap(result.moveArray[j], result.moveArray[j+1]); } } } else { for(unsigned int i = num_attacks + 1; i < result.count - 1; ++i) { for(int j = i - 1; j >= num_attacks && blackHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < blackHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) { std::swap(result.moveArray[j], result.moveArray[j+1]); } } } } for(unsigned int i = num_attacks; i < result.count; ++i) { if(game_board.whiteMove) { if(result.moveArray[i].equal(whiteKiller[depth].move) && whiteKiller[depth].enable) { result.moveArray.erase(result.moveArray.begin() + i); result.moveArray.emplace(result.moveArray.begin() + num_attacks, whiteKiller[depth].move); break; } } else { if(result.moveArray[i].equal(blackKiller[depth].move) && blackKiller[depth].enable) { result.moveArray.erase(result.moveArray.begin() + i); result.moveArray.emplace(result.moveArray.begin() + num_attacks, blackKiller[depth].move); break; } } } uint64_t hash = game_board.getColorHash(); if(boardHash[hash & hash_cutter].flag != EMPTY /*&& boardHash[hash & hash_cutter].flag != ALPHA*/) { if(boardHash[hash & hash_cutter].key == hash) { for(unsigned int i = 0; i < result.count; ++i) { if(boardHash[hash & hash_cutter].move.equal(result.moveArray[i])) { BitMove tmp = (BitMove)result.moveArray[i]; result.moveArray.erase(result.moveArray.begin() + i); result.moveArray.emplace(result.moveArray.begin(), tmp); result.moveArray[0].fromHash = true; break; } } } } } void Game::sortAttacks(MoveArray& moves) { std::sort(moves.moveArray.begin(), moves.moveArray.begin() + moves.num_attacks); } <commit_msg>last upd.<commit_after>#include "game.hpp" void Game::sortMoves(MoveArray& result, int depth) { int num_attacks = result.num_attacks; /*if(result.num_attacks >= 0 && result.num_attacks < result.moveArray.size() && result.count >= 1 && result.count < result.moveArray.size()) { if(game_board.whiteMove) { for(unsigned int i = result.num_attacks + 1; i < result.count - 1; ++i) { for(int j = i - 1; j >= num_attacks && whiteHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < whiteHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) { std::swap(result.moveArray[j], result.moveArray[j+1]); } } } else { for(unsigned int i = num_attacks + 1; i < result.count - 1; ++i) { for(int j = i - 1; j >= num_attacks && blackHistorySort[result.moveArray[j].fromY][result.moveArray[j].fromX][result.moveArray[j].toY][result.moveArray[j].toX] < blackHistorySort[result.moveArray[j+1].fromY][result.moveArray[j+1].fromX][result.moveArray[j+1].toY][result.moveArray[j+1].toX]; --j) { std::swap(result.moveArray[j], result.moveArray[j+1]); } } } }*/ for(unsigned int i = num_attacks; i < result.count; ++i) { if(game_board.whiteMove) { if(result.moveArray[i].equal(whiteKiller[depth].move) && whiteKiller[depth].enable) { result.moveArray.erase(result.moveArray.begin() + i); result.moveArray.emplace(result.moveArray.begin() + num_attacks, whiteKiller[depth].move); break; } } else { if(result.moveArray[i].equal(blackKiller[depth].move) && blackKiller[depth].enable) { result.moveArray.erase(result.moveArray.begin() + i); result.moveArray.emplace(result.moveArray.begin() + num_attacks, blackKiller[depth].move); break; } } } uint64_t hash = game_board.getColorHash(); if(boardHash[hash & hash_cutter].flag != EMPTY /*&& boardHash[hash & hash_cutter].flag != ALPHA*/) { if(boardHash[hash & hash_cutter].key == hash) { for(unsigned int i = 0; i < result.count; ++i) { if(boardHash[hash & hash_cutter].move.equal(result.moveArray[i])) { BitMove tmp = (BitMove)result.moveArray[i]; result.moveArray.erase(result.moveArray.begin() + i); result.moveArray.emplace(result.moveArray.begin(), tmp); result.moveArray[0].fromHash = true; break; } } } } } void Game::sortAttacks(MoveArray& moves) { std::sort(moves.moveArray.begin(), moves.moveArray.begin() + moves.num_attacks); } <|endoftext|>
<commit_before>// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef OPERATOR_040729_HPP #define OPERATOR_040729_HPP #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/apply_wrap.hpp> #include <boost/preprocessor/repetition/enum_trailing.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/type_traits/is_same.hpp> #include <luabind/detail/other.hpp> #include <luabind/raw_policy.hpp> #if defined(__GNUC__) && __GNUC__ < 3 # define LUABIND_NO_STRINGSTREAM #else # if defined(BOOST_NO_STRINGSTREAM) # define LUABIND_NO_STRINGSTREAM # endif #endif #ifdef LUABIND_NO_STRINGSTREAM #include <strstream> #else #include <sstream> #endif namespace luabind { namespace detail { template<class W, class T> struct unwrap_parameter_type; template<class Derived> struct operator_ {}; struct operator_void_return {}; #if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300) template<class T> inline T const& operator,(T const& x, operator_void_return) { return x; } #endif }} // namespace luabind namespace luabind { namespace operators { #define BOOST_PP_ITERATION_PARAMS_1 (3, \ (0, LUABIND_MAX_ARITY, <luabind/detail/call_operator_iterate.hpp>)) #include BOOST_PP_ITERATE() }} // namespace luabind::operators #include <boost/preprocessor/iteration/local.hpp> namespace luabind { template<class Derived> struct self_base { operators::call_operator0<Derived> operator()() const { return 0; } #define BOOST_PP_LOCAL_MACRO(n) \ template<BOOST_PP_ENUM_PARAMS(n, class A)> \ BOOST_PP_CAT(operators::call_operator, n)< \ Derived \ BOOST_PP_ENUM_TRAILING_PARAMS(n, A) \ >\ operator()( \ BOOST_PP_ENUM_BINARY_PARAMS(n, A, const& BOOST_PP_INTERCEPT) \ ) const \ { \ return 0; \ } #define BOOST_PP_LOCAL_LIMITS (1, LUABIND_MAX_ARITY) #include BOOST_PP_LOCAL_ITERATE() }; struct self_type : self_base<self_type> { }; struct const_self_type : self_base<const_self_type> { }; namespace detail { template<class W, class T> struct unwrap_parameter_type { typedef typename boost::mpl::eval_if< boost::is_same<T, self_type> , boost::mpl::identity<W&> , boost::mpl::eval_if< boost::is_same<T, const_self_type> , boost::mpl::identity<W const&> , unwrap_other<T> > >::type type; }; template<class Derived, class A, class B> struct binary_operator : operator_<binary_operator<Derived, A, B> > { binary_operator(int) {} template<class T, class Policies> struct apply { typedef typename unwrap_parameter_type<T, A>::type arg0; typedef typename unwrap_parameter_type<T, B>::type arg1; static void execute(lua_State* L, arg0 _0, arg1 _1) { Derived::template apply<arg0, arg1, Policies>::execute( L, _0, _1); } }; static char const* name() { return Derived::name(); } }; template<class Derived, class A> struct unary_operator : operator_<unary_operator<Derived, A> > { unary_operator(int) {} template<class T, class Policies> struct apply { typedef typename unwrap_parameter_type<T, A>::type arg0; static void execute(lua_State* L, arg0 _0) { Derived::template apply<arg0, Policies>::execute(L, _0); } }; static char const* name() { return Derived::name(); } }; template<class Policies> inline void operator_result(lua_State* L, operator_void_return, Policies*) { } namespace mpl = boost::mpl; template<class T, class Policies> inline void operator_result(lua_State* L, T const& x, Policies*) { typedef typename find_conversion_policy< 0 , Policies >::type cv_policy; typename mpl::apply_wrap2<cv_policy,T,cpp_to_lua>::type cv; cv.apply(L, x); } }} // namespace detail::luabind namespace luabind { #define LUABIND_BINARY_OPERATOR(name_, op) \ namespace operators { \ \ struct name_ \ { \ template<class T0, class T1, class Policies> \ struct apply \ { \ static void execute(lua_State* L, T0 _0, T1 _1) \ { \ detail::operator_result(L, _0 op _1, (Policies*)0); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template<class T, class U> \ detail::binary_operator< \ operators::name_ \ , U \ , T \ > \ inline operator op(self_base<U>, T const&) \ { \ return 0; \ } \ \ template<class T, class U> \ detail::binary_operator< \ operators::name_ \ , T \ , U \ > \ inline operator op(T const&, self_base<U>) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , self_type \ > \ inline operator op(self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , const_self_type \ > \ inline operator op(self_type, const_self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , self_type \ > \ inline operator op(const_self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , const_self_type \ > \ inline operator op(const_self_type, const_self_type) \ { \ return 0; \ } LUABIND_BINARY_OPERATOR(add, +) LUABIND_BINARY_OPERATOR(sub, -) LUABIND_BINARY_OPERATOR(mul, *) LUABIND_BINARY_OPERATOR(div, /) LUABIND_BINARY_OPERATOR(pow, ^) LUABIND_BINARY_OPERATOR(lt, <) LUABIND_BINARY_OPERATOR(le, <=) LUABIND_BINARY_OPERATOR(eq, ==) #undef LUABIND_UNARY_OPERATOR #define LUABIND_UNARY_OPERATOR(name_, op, fn) \ namespace operators { \ \ struct name_ \ { \ template<class T, class Policies> \ struct apply \ { \ static void execute(lua_State* L, T x) \ { \ detail::operator_result(L, op(x), (Policies*)0); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template<class T> \ detail::unary_operator< \ operators::name_ \ , T \ > \ inline fn(self_base<T>) \ { \ return 0; \ } template<class T> std::string tostring_operator(T const& x) { #ifdef LUABIND_NO_STRINGSTREAM std::strstream s; s << x << std::ends; #else std::stringstream s; s << x; #endif return s.str(); } LUABIND_UNARY_OPERATOR(tostring, tostring_operator, tostring) LUABIND_UNARY_OPERATOR(unm, -, operator-) #undef LUABIND_BINARY_OPERATOR namespace { LUABIND_ANONYMOUS_FIX self_type self; LUABIND_ANONYMOUS_FIX const_self_type const_self; } // namespace unnamed } // namespace luabind #endif // OPERATOR_040729_HPP <commit_msg>fix header compile of operator.hpp<commit_after>// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef OPERATOR_040729_HPP #define OPERATOR_040729_HPP #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/apply_wrap.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_trailing.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/type_traits/is_same.hpp> #include <luabind/detail/other.hpp> #include <luabind/raw_policy.hpp> #if defined(__GNUC__) && __GNUC__ < 3 # define LUABIND_NO_STRINGSTREAM #else # if defined(BOOST_NO_STRINGSTREAM) # define LUABIND_NO_STRINGSTREAM # endif #endif #ifdef LUABIND_NO_STRINGSTREAM #include <strstream> #else #include <sstream> #endif namespace luabind { namespace detail { template<class W, class T> struct unwrap_parameter_type; template<class Derived> struct operator_ {}; struct operator_void_return {}; #if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300) template<class T> inline T const& operator,(T const& x, operator_void_return) { return x; } #endif }} // namespace luabind #include <boost/preprocessor/iteration/iterate.hpp> namespace luabind { namespace operators { #define BOOST_PP_ITERATION_PARAMS_1 (3, \ (0, LUABIND_MAX_ARITY, <luabind/detail/call_operator_iterate.hpp>)) #include BOOST_PP_ITERATE() }} // namespace luabind::operators #include <boost/preprocessor/iteration/local.hpp> namespace luabind { template<class Derived> struct self_base { operators::call_operator0<Derived> operator()() const { return 0; } #define BOOST_PP_LOCAL_MACRO(n) \ template<BOOST_PP_ENUM_PARAMS(n, class A)> \ BOOST_PP_CAT(operators::call_operator, n)< \ Derived \ BOOST_PP_ENUM_TRAILING_PARAMS(n, A) \ >\ operator()( \ BOOST_PP_ENUM_BINARY_PARAMS(n, A, const& BOOST_PP_INTERCEPT) \ ) const \ { \ return 0; \ } #define BOOST_PP_LOCAL_LIMITS (1, LUABIND_MAX_ARITY) #include BOOST_PP_LOCAL_ITERATE() }; struct self_type : self_base<self_type> { }; struct const_self_type : self_base<const_self_type> { }; namespace detail { template<class W, class T> struct unwrap_parameter_type { typedef typename boost::mpl::eval_if< boost::is_same<T, self_type> , boost::mpl::identity<W&> , boost::mpl::eval_if< boost::is_same<T, const_self_type> , boost::mpl::identity<W const&> , unwrap_other<T> > >::type type; }; template<class Derived, class A, class B> struct binary_operator : operator_<binary_operator<Derived, A, B> > { binary_operator(int) {} template<class T, class Policies> struct apply { typedef typename unwrap_parameter_type<T, A>::type arg0; typedef typename unwrap_parameter_type<T, B>::type arg1; static void execute(lua_State* L, arg0 _0, arg1 _1) { Derived::template apply<arg0, arg1, Policies>::execute( L, _0, _1); } }; static char const* name() { return Derived::name(); } }; template<class Derived, class A> struct unary_operator : operator_<unary_operator<Derived, A> > { unary_operator(int) {} template<class T, class Policies> struct apply { typedef typename unwrap_parameter_type<T, A>::type arg0; static void execute(lua_State* L, arg0 _0) { Derived::template apply<arg0, Policies>::execute(L, _0); } }; static char const* name() { return Derived::name(); } }; template<class Policies> inline void operator_result(lua_State* L, operator_void_return, Policies*) { } namespace mpl = boost::mpl; template<class T, class Policies> inline void operator_result(lua_State* L, T const& x, Policies*) { typedef typename find_conversion_policy< 0 , Policies >::type cv_policy; typename mpl::apply_wrap2<cv_policy,T,cpp_to_lua>::type cv; cv.apply(L, x); } }} // namespace detail::luabind namespace luabind { #define LUABIND_BINARY_OPERATOR(name_, op) \ namespace operators { \ \ struct name_ \ { \ template<class T0, class T1, class Policies> \ struct apply \ { \ static void execute(lua_State* L, T0 _0, T1 _1) \ { \ detail::operator_result(L, _0 op _1, (Policies*)0); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template<class T, class U> \ detail::binary_operator< \ operators::name_ \ , U \ , T \ > \ inline operator op(self_base<U>, T const&) \ { \ return 0; \ } \ \ template<class T, class U> \ detail::binary_operator< \ operators::name_ \ , T \ , U \ > \ inline operator op(T const&, self_base<U>) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , self_type \ > \ inline operator op(self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , const_self_type \ > \ inline operator op(self_type, const_self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , self_type \ > \ inline operator op(const_self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , const_self_type \ > \ inline operator op(const_self_type, const_self_type) \ { \ return 0; \ } LUABIND_BINARY_OPERATOR(add, +) LUABIND_BINARY_OPERATOR(sub, -) LUABIND_BINARY_OPERATOR(mul, *) LUABIND_BINARY_OPERATOR(div, /) LUABIND_BINARY_OPERATOR(pow, ^) LUABIND_BINARY_OPERATOR(lt, <) LUABIND_BINARY_OPERATOR(le, <=) LUABIND_BINARY_OPERATOR(eq, ==) #undef LUABIND_UNARY_OPERATOR #define LUABIND_UNARY_OPERATOR(name_, op, fn) \ namespace operators { \ \ struct name_ \ { \ template<class T, class Policies> \ struct apply \ { \ static void execute(lua_State* L, T x) \ { \ detail::operator_result(L, op(x), (Policies*)0); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template<class T> \ detail::unary_operator< \ operators::name_ \ , T \ > \ inline fn(self_base<T>) \ { \ return 0; \ } template<class T> std::string tostring_operator(T const& x) { #ifdef LUABIND_NO_STRINGSTREAM std::strstream s; s << x << std::ends; #else std::stringstream s; s << x; #endif return s.str(); } LUABIND_UNARY_OPERATOR(tostring, tostring_operator, tostring) LUABIND_UNARY_OPERATOR(unm, -, operator-) #undef LUABIND_BINARY_OPERATOR namespace { LUABIND_ANONYMOUS_FIX self_type self; LUABIND_ANONYMOUS_FIX const_self_type const_self; } // namespace unnamed } // namespace luabind #endif // OPERATOR_040729_HPP <|endoftext|>
<commit_before>// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef OPERATOR_040729_HPP #define OPERATOR_040729_HPP #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/apply_wrap.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_trailing.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/type_traits/is_same.hpp> #include <luabind/detail/other.hpp> #include <luabind/raw_policy.hpp> #if defined(__GNUC__) && __GNUC__ < 3 # define LUABIND_NO_STRINGSTREAM #else # if defined(BOOST_NO_STRINGSTREAM) # define LUABIND_NO_STRINGSTREAM # endif #endif #ifdef LUABIND_NO_STRINGSTREAM #include <strstream> #else #include <sstream> #endif namespace luabind { namespace detail { template<class W, class T> struct unwrap_parameter_type; template<class Derived> struct operator_ {}; struct operator_void_return {}; #if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300) template<class T> inline T const& operator,(T const& x, operator_void_return) { return x; } #endif }} // namespace luabind #include <boost/preprocessor/iteration/iterate.hpp> namespace luabind { namespace operators { #define BOOST_PP_ITERATION_PARAMS_1 (3, \ (0, LUABIND_MAX_ARITY, <luabind/detail/call_operator_iterate.hpp>)) #include BOOST_PP_ITERATE() }} // namespace luabind::operators #include <boost/preprocessor/iteration/local.hpp> namespace luabind { template<class Derived> struct self_base { operators::call_operator0<Derived> operator()() const { return 0; } #define BOOST_PP_LOCAL_MACRO(n) \ template<BOOST_PP_ENUM_PARAMS(n, class A)> \ BOOST_PP_CAT(operators::call_operator, n)< \ Derived \ BOOST_PP_ENUM_TRAILING_PARAMS(n, A) \ >\ operator()( \ BOOST_PP_ENUM_BINARY_PARAMS(n, A, const& BOOST_PP_INTERCEPT) \ ) const \ { \ return 0; \ } #define BOOST_PP_LOCAL_LIMITS (1, LUABIND_MAX_ARITY) #include BOOST_PP_LOCAL_ITERATE() }; struct self_type : self_base<self_type> { }; struct const_self_type : self_base<const_self_type> { }; namespace detail { template<class W, class T> struct unwrap_parameter_type { typedef typename boost::mpl::eval_if< boost::is_same<T, self_type> , boost::mpl::identity<W&> , boost::mpl::eval_if< boost::is_same<T, const_self_type> , boost::mpl::identity<W const&> , unwrap_other<T> > >::type type; }; template<class Derived, class A, class B> struct binary_operator : operator_<binary_operator<Derived, A, B> > { binary_operator(int) {} template<class T, class Policies> struct apply { typedef typename unwrap_parameter_type<T, A>::type arg0; typedef typename unwrap_parameter_type<T, B>::type arg1; static void execute(lua_State* L, arg0 _0, arg1 _1) { Derived::template apply<arg0, arg1, Policies>::execute( L, _0, _1); } }; static char const* name() { return Derived::name(); } }; template<class Derived, class A> struct unary_operator : operator_<unary_operator<Derived, A> > { unary_operator(int) {} template<class T, class Policies> struct apply { typedef typename unwrap_parameter_type<T, A>::type arg0; static void execute(lua_State* L, arg0 _0) { Derived::template apply<arg0, Policies>::execute(L, _0); } }; static char const* name() { return Derived::name(); } }; template<class Policies> inline void operator_result(lua_State*, operator_void_return, Policies*) { } namespace mpl = boost::mpl; template<class T, class Policies> inline void operator_result(lua_State* L, T const& x, Policies*) { typedef typename find_conversion_policy< 0 , Policies >::type cv_policy; typename mpl::apply_wrap2<cv_policy,T,cpp_to_lua>::type cv; cv.apply(L, x); } }} // namespace detail::luabind namespace luabind { #define LUABIND_BINARY_OPERATOR(name_, op) \ namespace operators { \ \ struct name_ \ { \ template<class T0, class T1, class Policies> \ struct apply \ { \ static void execute(lua_State* L, T0 _0, T1 _1) \ { \ detail::operator_result(L, _0 op _1, (Policies*)0); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template<class T, class U> \ detail::binary_operator< \ operators::name_ \ , U \ , T \ > \ inline operator op(self_base<U>, T const&) \ { \ return 0; \ } \ \ template<class T, class U> \ detail::binary_operator< \ operators::name_ \ , T \ , U \ > \ inline operator op(T const&, self_base<U>) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , self_type \ > \ inline operator op(self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , const_self_type \ > \ inline operator op(self_type, const_self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , self_type \ > \ inline operator op(const_self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , const_self_type \ > \ inline operator op(const_self_type, const_self_type) \ { \ return 0; \ } LUABIND_BINARY_OPERATOR(add, +) LUABIND_BINARY_OPERATOR(sub, -) LUABIND_BINARY_OPERATOR(mul, *) LUABIND_BINARY_OPERATOR(div, /) LUABIND_BINARY_OPERATOR(pow, ^) LUABIND_BINARY_OPERATOR(lt, <) LUABIND_BINARY_OPERATOR(le, <=) LUABIND_BINARY_OPERATOR(eq, ==) #undef LUABIND_UNARY_OPERATOR #define LUABIND_UNARY_OPERATOR(name_, op, fn) \ namespace operators { \ \ struct name_ \ { \ template<class T, class Policies> \ struct apply \ { \ static void execute(lua_State* L, T x) \ { \ detail::operator_result(L, op(x), (Policies*)0); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template<class T> \ detail::unary_operator< \ operators::name_ \ , T \ > \ inline fn(self_base<T>) \ { \ return 0; \ } template<class T> std::string tostring_operator(T const& x) { #ifdef LUABIND_NO_STRINGSTREAM std::strstream s; s << x << std::ends; #else std::stringstream s; s << x; #endif return s.str(); } LUABIND_UNARY_OPERATOR(tostring, tostring_operator, tostring) LUABIND_UNARY_OPERATOR(unm, -, operator-) #undef LUABIND_BINARY_OPERATOR namespace { LUABIND_ANONYMOUS_FIX self_type self; LUABIND_ANONYMOUS_FIX const_self_type const_self; } // namespace unnamed } // namespace luabind #endif // OPERATOR_040729_HPP <commit_msg>Don't leave our macros defined when they're for internal use.<commit_after>// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef OPERATOR_040729_HPP #define OPERATOR_040729_HPP #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/apply_wrap.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_trailing.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/type_traits/is_same.hpp> #include <luabind/detail/other.hpp> #include <luabind/raw_policy.hpp> #if defined(__GNUC__) && __GNUC__ < 3 # define LUABIND_NO_STRINGSTREAM #else # if defined(BOOST_NO_STRINGSTREAM) # define LUABIND_NO_STRINGSTREAM # endif #endif #ifdef LUABIND_NO_STRINGSTREAM #include <strstream> #else #include <sstream> #endif namespace luabind { namespace detail { template<class W, class T> struct unwrap_parameter_type; template<class Derived> struct operator_ {}; struct operator_void_return {}; #if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300) template<class T> inline T const& operator,(T const& x, operator_void_return) { return x; } #endif }} // namespace luabind #include <boost/preprocessor/iteration/iterate.hpp> namespace luabind { namespace operators { #define BOOST_PP_ITERATION_PARAMS_1 (3, \ (0, LUABIND_MAX_ARITY, <luabind/detail/call_operator_iterate.hpp>)) #include BOOST_PP_ITERATE() }} // namespace luabind::operators #include <boost/preprocessor/iteration/local.hpp> namespace luabind { template<class Derived> struct self_base { operators::call_operator0<Derived> operator()() const { return 0; } #define BOOST_PP_LOCAL_MACRO(n) \ template<BOOST_PP_ENUM_PARAMS(n, class A)> \ BOOST_PP_CAT(operators::call_operator, n)< \ Derived \ BOOST_PP_ENUM_TRAILING_PARAMS(n, A) \ >\ operator()( \ BOOST_PP_ENUM_BINARY_PARAMS(n, A, const& BOOST_PP_INTERCEPT) \ ) const \ { \ return 0; \ } #define BOOST_PP_LOCAL_LIMITS (1, LUABIND_MAX_ARITY) #include BOOST_PP_LOCAL_ITERATE() }; struct self_type : self_base<self_type> { }; struct const_self_type : self_base<const_self_type> { }; namespace detail { template<class W, class T> struct unwrap_parameter_type { typedef typename boost::mpl::eval_if< boost::is_same<T, self_type> , boost::mpl::identity<W&> , boost::mpl::eval_if< boost::is_same<T, const_self_type> , boost::mpl::identity<W const&> , unwrap_other<T> > >::type type; }; template<class Derived, class A, class B> struct binary_operator : operator_<binary_operator<Derived, A, B> > { binary_operator(int) {} template<class T, class Policies> struct apply { typedef typename unwrap_parameter_type<T, A>::type arg0; typedef typename unwrap_parameter_type<T, B>::type arg1; static void execute(lua_State* L, arg0 _0, arg1 _1) { Derived::template apply<arg0, arg1, Policies>::execute( L, _0, _1); } }; static char const* name() { return Derived::name(); } }; template<class Derived, class A> struct unary_operator : operator_<unary_operator<Derived, A> > { unary_operator(int) {} template<class T, class Policies> struct apply { typedef typename unwrap_parameter_type<T, A>::type arg0; static void execute(lua_State* L, arg0 _0) { Derived::template apply<arg0, Policies>::execute(L, _0); } }; static char const* name() { return Derived::name(); } }; template<class Policies> inline void operator_result(lua_State*, operator_void_return, Policies*) { } namespace mpl = boost::mpl; template<class T, class Policies> inline void operator_result(lua_State* L, T const& x, Policies*) { typedef typename find_conversion_policy< 0 , Policies >::type cv_policy; typename mpl::apply_wrap2<cv_policy,T,cpp_to_lua>::type cv; cv.apply(L, x); } }} // namespace detail::luabind namespace luabind { #define LUABIND_BINARY_OPERATOR(name_, op) \ namespace operators { \ \ struct name_ \ { \ template<class T0, class T1, class Policies> \ struct apply \ { \ static void execute(lua_State* L, T0 _0, T1 _1) \ { \ detail::operator_result(L, _0 op _1, (Policies*)0); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template<class T, class U> \ detail::binary_operator< \ operators::name_ \ , U \ , T \ > \ inline operator op(self_base<U>, T const&) \ { \ return 0; \ } \ \ template<class T, class U> \ detail::binary_operator< \ operators::name_ \ , T \ , U \ > \ inline operator op(T const&, self_base<U>) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , self_type \ > \ inline operator op(self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , self_type \ , const_self_type \ > \ inline operator op(self_type, const_self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , self_type \ > \ inline operator op(const_self_type, self_type) \ { \ return 0; \ } \ \ detail::binary_operator< \ operators::name_ \ , const_self_type \ , const_self_type \ > \ inline operator op(const_self_type, const_self_type) \ { \ return 0; \ } LUABIND_BINARY_OPERATOR(add, +) LUABIND_BINARY_OPERATOR(sub, -) LUABIND_BINARY_OPERATOR(mul, *) LUABIND_BINARY_OPERATOR(div, /) LUABIND_BINARY_OPERATOR(pow, ^) LUABIND_BINARY_OPERATOR(lt, <) LUABIND_BINARY_OPERATOR(le, <=) LUABIND_BINARY_OPERATOR(eq, ==) #undef LUABIND_BINARY_OPERATOR #define LUABIND_UNARY_OPERATOR(name_, op, fn) \ namespace operators { \ \ struct name_ \ { \ template<class T, class Policies> \ struct apply \ { \ static void execute(lua_State* L, T x) \ { \ detail::operator_result(L, op(x), (Policies*)0); \ } \ }; \ \ static char const* name() \ { \ return "__" # name_; \ } \ }; \ \ } \ \ template<class T> \ detail::unary_operator< \ operators::name_ \ , T \ > \ inline fn(self_base<T>) \ { \ return 0; \ } template<class T> std::string tostring_operator(T const& x) { #ifdef LUABIND_NO_STRINGSTREAM std::strstream s; s << x << std::ends; #else std::stringstream s; s << x; #endif return s.str(); } LUABIND_UNARY_OPERATOR(tostring, tostring_operator, tostring) LUABIND_UNARY_OPERATOR(unm, -, operator-) #undef LUABIND_UNARY_OPERATOR namespace { LUABIND_ANONYMOUS_FIX self_type self; LUABIND_ANONYMOUS_FIX const_self_type const_self; } // namespace unnamed } // namespace luabind #endif // OPERATOR_040729_HPP <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <algorithm> #include <iomanip> #include <utility> #include "components/command_line.hpp" #include "utils.hpp" enum { /* * Same order as they are initialized * in main(). Perhaps we should have a * getter funtion instead? * * These (or well, only main) are used in * validate_arguments() to get the group of * main arguments so that we can find if any of * those are passed. * * I'm a bit unsure if it's worth the time to * implement a better way to do this. This will work * as long as they are in the same order as they are * initialized in in main(). */ main, excl, exact, misc }; enum { /* magic padding numbers */ padding_margin = 4, desc_align_magic = 7 }; cliparser::cli_type cliparser::make(const string &&progname, const groups &&groups) { return std::make_unique<cliparser>( "Usage: " + progname + " option... download_path", std::forward<decltype(groups)>(groups) ); } void cliparser::usage() const { std::cout << synopsis_ << "\n\n"; size_t maxlen = 0; /* * Get the length of the longest string in the flag column * which is used to align the description fields. */ for (const auto &group : valid_groups_) { for (const auto &opt : group.options) { size_t len = opt.flag_long.length() + opt.flag.length() + opt.token.length() + padding_margin; maxlen = std::max(len, maxlen); } } /* * Print each option group, its options, the options' * descriptions, token and possible values for said token (if any). */ for (const auto &group : valid_groups_) { std::cout << group.name << " arguments" << (group.synopsis.empty() ? ":" : " - " + group.synopsis + ":") << '\n'; for (const auto &opt : group.options) { /* Padding between flags and description. */ size_t pad = maxlen - opt.flag_long.length() - opt.token.length(); std::cout << " " << opt.flag << ", " << opt.flag_long; if (!opt.token.empty()) { std::cout << ' ' << opt.token; pad--; } /* * Print the list with accepted values. * This line is printed below the description. */ if (!opt.values.empty()) { std::cout << std::setw(pad + opt.desc.length()) << opt.desc << '\n'; pad += opt.flag_long.length() + opt.token.length() + desc_align_magic; std::cout << string(pad, ' ') << opt.token << " is one of: " << utils::vector_to_string(opt.values); } else { std::cout << std::setw(pad + opt.desc.length()) << opt.desc; } std::cout << '\n'; } std::cout << std::endl; } } string cliparser::get(string opt) const { if (has(std::forward<string>(opt))) return passed_opts_.find(opt)->second; return ""; } vector<string> cliparser::get_many(const string &&opt) const { vector<string> values; if (has(opt)) { auto range = passed_opts_.equal_range(opt); /* Can't we just return {range.first, range.second} somehow? */ for (auto &opt = range.first; opt != range.second; opt++) values.push_back(opt->second); } return values; } void cliparser::process_arguments(const vector<string> &args) { for (size_t i = 0; i < args.size(); i++) { const string_view &arg = args[i]; const string_view &next_arg = args.size() > i + 1 ? args[i + 1] : ""; parse(arg, next_arg); } } void cliparser::validate_arguments() const { if (!has(0)) throw argument_error("you must specify a download path"); if (positional_args_.size() > 1) throw argument_error("only one positional argument is allowed"); vector<string> passed_opts, required_opts; for (const auto &opt : passed_opts_) { /* We don't want the value, only the flag. */ passed_opts.emplace_back(opt.first); } for (const auto &opt : valid_groups_[main].options) required_opts.emplace_back(opt.flag_long.substr(2)); /* Has any required arguments been passed? */ const bool req_match = utils::any_intersection(passed_opts, required_opts); const bool ident_passed = std::find(passed_opts.cbegin(), passed_opts.cend(), "ident") != passed_opts.cend(); if (ident_passed && passed_opts.size() > 1) throw argument_error("ident flag is exclusive and may not be passed with another flag"); else if (!req_match) throw argument_error("at least one main argument must be specified"); } auto cliparser::check_value(const string_view &flag, const string_view &value, const vector<string> &values) { if (value.empty()) throw value_error("missing value for " + string(flag.data())); if (!values.empty() && std::find(values.cbegin(), values.cend(), value) == values.cend()) { throw value_error( "invalid value '" + string(value.data()) + "' for argument " + string(flag.data()) + "; valid options are: " + utils::vector_to_string(values) ); } return value; } void cliparser::parse(const string_view &input, const string_view &input_next) { if (skipnext_) { /* The next input is a value, which we've already used. */ skipnext_ = false; return; } for (const auto &group : valid_groups_) { for (const auto &opt : group.options) { if (is(input, opt.flag, opt.flag_long)) { if (opt.token.empty()) { /* The option is only a flag. */ passed_opts_.emplace(opt.flag_long.substr(2), ""); } else { /* * The option should have an accompanied value. * And may be that it must be an element in opt.values. */ const auto value = check_value(input, input_next, opt.values); skipnext_ = (value == input_next); passed_opts_.emplace(opt.flag_long.substr(2), value); } return; } } } if (input[0] == '-') throw argument_error("unrecognized option " + string(input.data())); positional_args_.emplace_back(input); } <commit_msg>command_line: remove rogue newline<commit_after>/* * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <algorithm> #include <iomanip> #include <utility> #include "components/command_line.hpp" #include "utils.hpp" enum { /* * Same order as they are initialized * in main(). Perhaps we should have a * getter funtion instead? * * These (or well, only main) are used in * validate_arguments() to get the group of * main arguments so that we can find if any of * those are passed. * * I'm a bit unsure if it's worth the time to * implement a better way to do this. This will work * as long as they are in the same order as they are * initialized in in main(). */ main, excl, exact, misc }; enum { /* magic padding numbers */ padding_margin = 4, desc_align_magic = 7 }; cliparser::cli_type cliparser::make(const string &&progname, const groups &&groups) { return std::make_unique<cliparser>( "Usage: " + progname + " option... download_path", std::forward<decltype(groups)>(groups) ); } void cliparser::usage() const { std::cout << synopsis_ << "\n\n"; size_t maxlen = 0; /* * Get the length of the longest string in the flag column * which is used to align the description fields. */ for (const auto &group : valid_groups_) { for (const auto &opt : group.options) { size_t len = opt.flag_long.length() + opt.flag.length() + opt.token.length() + padding_margin; maxlen = std::max(len, maxlen); } } /* * Print each option group, its options, the options' * descriptions, token and possible values for said token (if any). */ for (const auto &group : valid_groups_) { std::cout << group.name << " arguments" << (group.synopsis.empty() ? ":" : " - " + group.synopsis + ":") << '\n'; for (const auto &opt : group.options) { /* Padding between flags and description. */ size_t pad = maxlen - opt.flag_long.length() - opt.token.length(); std::cout << " " << opt.flag << ", " << opt.flag_long; if (!opt.token.empty()) { std::cout << ' ' << opt.token; pad--; } /* * Print the list with accepted values. * This line is printed below the description. */ if (!opt.values.empty()) { std::cout << std::setw(pad + opt.desc.length()) << opt.desc << '\n'; pad += opt.flag_long.length() + opt.token.length() + desc_align_magic; std::cout << string(pad, ' ') << opt.token << " is one of: " << utils::vector_to_string(opt.values); } else { std::cout << std::setw(pad + opt.desc.length()) << opt.desc; } std::cout << '\n'; } std::cout << std::endl; } } string cliparser::get(string opt) const { if (has(std::forward<string>(opt))) return passed_opts_.find(opt)->second; return ""; } vector<string> cliparser::get_many(const string &&opt) const { vector<string> values; if (has(opt)) { auto range = passed_opts_.equal_range(opt); /* Can't we just return {range.first, range.second} somehow? */ for (auto &opt = range.first; opt != range.second; opt++) values.push_back(opt->second); } return values; } void cliparser::process_arguments(const vector<string> &args) { for (size_t i = 0; i < args.size(); i++) { const string_view &arg = args[i]; const string_view &next_arg = args.size() > i + 1 ? args[i + 1] : ""; parse(arg, next_arg); } } void cliparser::validate_arguments() const { if (!has(0)) throw argument_error("you must specify a download path"); if (positional_args_.size() > 1) throw argument_error("only one positional argument is allowed"); vector<string> passed_opts, required_opts; for (const auto &opt : passed_opts_) { /* We don't want the value, only the flag. */ passed_opts.emplace_back(opt.first); } for (const auto &opt : valid_groups_[main].options) required_opts.emplace_back(opt.flag_long.substr(2)); /* Has any required arguments been passed? */ const bool req_match = utils::any_intersection(passed_opts, required_opts); const bool ident_passed = std::find(passed_opts.cbegin(), passed_opts.cend(), "ident") != passed_opts.cend(); if (ident_passed && passed_opts.size() > 1) throw argument_error("ident flag is exclusive and may not be passed with another flag"); else if (!req_match) throw argument_error("at least one main argument must be specified"); } auto cliparser::check_value(const string_view &flag, const string_view &value, const vector<string> &values) { if (value.empty()) throw value_error("missing value for " + string(flag.data())); if (!values.empty() && std::find(values.cbegin(), values.cend(), value) == values.cend()) { throw value_error( "invalid value '" + string(value.data()) + "' for argument " + string(flag.data()) + "; valid options are: " + utils::vector_to_string(values) ); } return value; } void cliparser::parse(const string_view &input, const string_view &input_next) { if (skipnext_) { /* The next input is a value, which we've already used. */ skipnext_ = false; return; } for (const auto &group : valid_groups_) { for (const auto &opt : group.options) { if (is(input, opt.flag, opt.flag_long)) { if (opt.token.empty()) { /* The option is only a flag. */ passed_opts_.emplace(opt.flag_long.substr(2), ""); } else { /* * The option should have an accompanied value. * And may be that it must be an element in opt.values. */ const auto value = check_value(input, input_next, opt.values); skipnext_ = (value == input_next); passed_opts_.emplace(opt.flag_long.substr(2), value); } return; } } } if (input[0] == '-') throw argument_error("unrecognized option " + string(input.data())); positional_args_.emplace_back(input); } <|endoftext|>
<commit_before>#pragma once #include "fwd.hpp" #include <configure/log.hpp> #include <string> #include <typeinfo> #include <type_traits> #include <stdexcept> namespace configure { namespace lua { template<typename T> struct Converter { typedef T& extract_type; static std::string const& type_name() { static std::string name = std::string("typeid-") + typeid(T).name(); return name; } static extract_type extract(lua_State* state, int index) { T* value = extract_ptr(state, index); if (value == nullptr) { std::string err = "Expected value of type '" + type_name() + "', got '" + luaL_tolstring(state, index, nullptr) + "'"; throw std::runtime_error(err); } return *value; } static T* extract_ptr(lua_State* state, int index) { void* mem = luaL_testudata(state, index, type_name().c_str()); return ((T*) mem); } static bool push_metatable(lua_State* state) { std::string name = type_name(); if (!luaL_newmetatable(state, name.c_str())) return false; if (!std::is_trivially_destructible<T>::value) { lua_pushstring(state, "__gc"); lua_pushcfunction(state, &_call_destructor); lua_settable(state, -3); } return true; } static bool push_metatable(lua_State* state, std::string const& friendly_name) { bool is_new = push_metatable(state); if (is_new && !friendly_name.empty()) { lua_pushvalue(state, -1); lua_setglobal(state, friendly_name.c_str()); } return is_new; } static int _call_destructor(lua_State* L) { if (T* object = reinterpret_cast<T*>(lua_touserdata(L, 1))) object->~T(); return 0; } template<typename... Args> static T& push(lua_State* state, Args&&... args) { void* mem = lua_newuserdata(state, sizeof(T)); T* data = new (mem) T(std::forward<Args>(args)...); push_metatable(state); lua_setmetatable(state, -2); return *data; } }; template<typename T> struct Converter<T*> : Converter<T> {}; template<typename T> struct Converter<T&> : Converter<T> {}; template<typename T> struct Converter<T const> : Converter<T> {}; template<> struct Converter<std::string> { typedef std::string extract_type; static extract_type extract(lua_State* state, int index) { return lua_tostring(state, index); } static void push(lua_State* state, std::string const& value) { lua_pushstring(state, value.c_str()); } }; template<> struct Converter<char const*> : Converter<std::string> { static void push(lua_State* state, char const* value) { lua_pushstring(state, value); } }; template<unsigned size> struct Converter<const char[size]> : Converter<char const*> {}; template<> struct Converter<int32_t> { typedef int32_t extract_type; static extract_type extract(lua_State* state, int index) { return lua_tointeger(state, index); } static void push(lua_State* state, extract_type value) { lua_pushinteger(state, value); } }; template<> struct Converter<int64_t> { typedef int extract_type; static extract_type extract(lua_State* state, int index) { return lua_tointeger(state, index); } static void push(lua_State* state, extract_type value) { lua_pushinteger(state, value); } }; template<> struct Converter<double> { typedef double extract_type; static extract_type extract(lua_State* state, int index) { return lua_tonumber(state, index); } static void push(lua_State* state, double value) { lua_pushnumber(state, value); } }; template<> struct Converter<bool> { typedef bool extract_type; static extract_type extract(lua_State* state, int index) { return lua_toboolean(state, index) != 0; } static void push(lua_State* state, bool value) { lua_pushboolean(state, value); } }; }} <commit_msg>Add missing include.<commit_after>#pragma once #include "fwd.hpp" #include <configure/log.hpp> #include <string> #include <typeinfo> #include <type_traits> #include <stdexcept> #include <cstdint> namespace configure { namespace lua { template<typename T> struct Converter { typedef T& extract_type; static std::string const& type_name() { static std::string name = std::string("typeid-") + typeid(T).name(); return name; } static extract_type extract(lua_State* state, int index) { T* value = extract_ptr(state, index); if (value == nullptr) { std::string err = "Expected value of type '" + type_name() + "', got '" + luaL_tolstring(state, index, nullptr) + "'"; throw std::runtime_error(err); } return *value; } static T* extract_ptr(lua_State* state, int index) { void* mem = luaL_testudata(state, index, type_name().c_str()); return ((T*) mem); } static bool push_metatable(lua_State* state) { std::string name = type_name(); if (!luaL_newmetatable(state, name.c_str())) return false; if (!std::is_trivially_destructible<T>::value) { lua_pushstring(state, "__gc"); lua_pushcfunction(state, &_call_destructor); lua_settable(state, -3); } return true; } static bool push_metatable(lua_State* state, std::string const& friendly_name) { bool is_new = push_metatable(state); if (is_new && !friendly_name.empty()) { lua_pushvalue(state, -1); lua_setglobal(state, friendly_name.c_str()); } return is_new; } static int _call_destructor(lua_State* L) { if (T* object = reinterpret_cast<T*>(lua_touserdata(L, 1))) object->~T(); return 0; } template<typename... Args> static T& push(lua_State* state, Args&&... args) { void* mem = lua_newuserdata(state, sizeof(T)); T* data = new (mem) T(std::forward<Args>(args)...); push_metatable(state); lua_setmetatable(state, -2); return *data; } }; template<typename T> struct Converter<T*> : Converter<T> {}; template<typename T> struct Converter<T&> : Converter<T> {}; template<typename T> struct Converter<T const> : Converter<T> {}; template<> struct Converter<std::string> { typedef std::string extract_type; static extract_type extract(lua_State* state, int index) { return lua_tostring(state, index); } static void push(lua_State* state, std::string const& value) { lua_pushstring(state, value.c_str()); } }; template<> struct Converter<char const*> : Converter<std::string> { static void push(lua_State* state, char const* value) { lua_pushstring(state, value); } }; template<unsigned size> struct Converter<const char[size]> : Converter<char const*> {}; template<> struct Converter<int32_t> { typedef int32_t extract_type; static extract_type extract(lua_State* state, int index) { return lua_tointeger(state, index); } static void push(lua_State* state, extract_type value) { lua_pushinteger(state, value); } }; template<> struct Converter<int64_t> { typedef int extract_type; static extract_type extract(lua_State* state, int index) { return lua_tointeger(state, index); } static void push(lua_State* state, extract_type value) { lua_pushinteger(state, value); } }; template<> struct Converter<double> { typedef double extract_type; static extract_type extract(lua_State* state, int index) { return lua_tonumber(state, index); } static void push(lua_State* state, double value) { lua_pushnumber(state, value); } }; template<> struct Converter<bool> { typedef bool extract_type; static extract_type extract(lua_State* state, int index) { return lua_toboolean(state, index) != 0; } static void push(lua_State* state, bool value) { lua_pushboolean(state, value); } }; }} <|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. */ #include "ExpirationTest.h" #include <integration/common/IntegrationCommon.h> CPPUNIT_TEST_SUITE_REGISTRATION( integration::expiration::ExpirationTest ); #include <sstream> #include <activemq/core/ActiveMQConnectionFactory.h> #include <activemq/exceptions/ActiveMQException.h> #include <activemq/concurrent/Thread.h> #include <activemq/connector/stomp/StompConnector.h> #include <activemq/util/SimpleProperties.h> #include <activemq/transport/TransportFactory.h> #include <activemq/util/Guid.h> #include <activemq/util/SimpleProperties.h> #include <activemq/util/StringTokenizer.h> #include <activemq/connector/ConnectorFactoryMap.h> #include <activemq/network/SocketFactory.h> #include <activemq/transport/TransportFactory.h> #include <activemq/network/Socket.h> #include <activemq/exceptions/NullPointerException.h> #include <activemq/core/ActiveMQConnection.h> #include <activemq/core/ActiveMQConsumer.h> #include <activemq/core/ActiveMQProducer.h> #include <activemq/util/StringTokenizer.h> #include <activemq/util/Boolean.h> #include <cms/Connection.h> #include <cms/MessageConsumer.h> #include <cms/MessageProducer.h> #include <cms/MessageListener.h> #include <cms/Startable.h> #include <cms/Closeable.h> #include <cms/MessageListener.h> #include <cms/ExceptionListener.h> #include <cms/Topic.h> #include <cms/Queue.h> #include <cms/TemporaryTopic.h> #include <cms/TemporaryQueue.h> #include <cms/Session.h> #include <cms/BytesMessage.h> #include <cms/TextMessage.h> #include <cms/MapMessage.h> #include <cms/Session.h> using namespace activemq::connector::stomp; using namespace activemq::transport; using namespace activemq::util; using namespace std; using namespace cms; using namespace activemq; using namespace activemq::core; using namespace activemq::util; using namespace activemq::connector; using namespace activemq::exceptions; using namespace activemq::network; using namespace activemq::transport; using namespace activemq::concurrent; using namespace std; using namespace integration; using namespace integration::expiration; using namespace integration::common; class Producer : public Runnable { private: Connection* connection; Session* session; Topic* destination; MessageProducer* producer; int numMessages; long long timeToLive; bool disableTimeStamps; public: Producer( int numMessages, long long timeToLive ){ connection = NULL; session = NULL; destination = NULL; producer = NULL; this->numMessages = numMessages; this->timeToLive = timeToLive; this->disableTimeStamps = false; } virtual ~Producer(){ cleanup(); } virtual bool getDisableTimeStamps() const { return disableTimeStamps; } virtual void setDisableTimeStamps( bool value ) { this->disableTimeStamps = value; } virtual void run() { try { // Create a ConnectionFactory ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61613"); // Create a Connection connection = connectionFactory->createConnection(); connection->start(); string sss=connection->getClientId(); cout << sss << endl; session = connection->createSession( Session::AUTO_ACKNOWLEDGE); destination = session->createTopic( "expirationTopic" ); producer = session->createProducer( destination ); producer->setDeliveryMode( DeliveryMode::PERSISTANT ); producer->setDisableMessageTimeStamp( disableTimeStamps ); //unsigned long ttt=getcurt(); producer->setTimeToLive( 1); // Create the Thread Id String string threadIdStr = Integer::toString( Thread::getId() ); // Create a messages string text = (string)"Hello world! from thread " + threadIdStr; for( int ix=0; ix<numMessages; ++ix ){ TextMessage* message = session->createTextMessage( text ); producer->send( message ); delete message; } }catch ( CMSException& e ) { e.printStackTrace(); } } private: void cleanup(){ // Destroy resources. try{ if( destination != NULL ) delete destination; }catch ( CMSException& e ) {} destination = NULL; try{ if( producer != NULL ) delete producer; }catch ( CMSException& e ) {} producer = NULL; // Close open resources. try{ if( session != NULL ) session->close(); if( connection != NULL ) connection->close(); }catch ( CMSException& e ) {} try{ if( session != NULL ) delete session; }catch ( CMSException& e ) {} session = NULL; try{ if( connection != NULL ) delete connection; }catch ( CMSException& e ) {} connection = NULL; } }; class Consumer : public MessageListener, public Runnable { private: Connection* connection; Session* session; Topic* destination; MessageConsumer* consumer; long waitMillis; int numReceived; public: Consumer( long waitMillis ){ connection = NULL; session = NULL; destination = NULL; consumer = NULL; this->waitMillis = waitMillis; numReceived = 0; } virtual ~Consumer(){ cleanup(); } virtual int getNumReceived() const{ return numReceived; } virtual void run() { try { string user,passwd,sID; user="default"; passwd=""; sID="lsgID"; // Create a ConnectionFactory ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61613",user,passwd,sID); // Create a Connection connection = connectionFactory->createConnection(); delete connectionFactory; connection->start(); // Create a Session session = connection->createSession( Session::AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) destination = session->createTopic( "expirationTopic?consumer.retroactive=true"); consumer = session->createConsumer( destination ); consumer->setMessageListener( this ); // Sleep while asynchronous messages come in. Thread::sleep( waitMillis ); } catch (CMSException& e) { e.printStackTrace(); } } virtual void onMessage( const Message* message ){ try { const TextMessage* textMessage = dynamic_cast< const TextMessage* >( message ); string text = textMessage->getText(); numReceived++; } catch (CMSException& e) { e.printStackTrace(); } } private: void cleanup(){ // Destroy resources. try{ if( destination != NULL ) delete destination; }catch (CMSException& e) {} destination = NULL; try{ if( consumer != NULL ) delete consumer; }catch (CMSException& e) {} consumer = NULL; // Close open resources. try{ if( session != NULL ) session->close(); if( connection != NULL ) connection->close(); }catch (CMSException& e) {} try{ if( session != NULL ) delete session; }catch (CMSException& e) {} session = NULL; try{ if( connection != NULL ) delete connection; }catch (CMSException& e) {} connection = NULL; } }; void ExpirationTest::testExpired() { Producer producer( 1, 1 ); Thread producerThread( &producer ); producerThread.start(); producerThread.join(); Thread::sleep( 100 ); Consumer consumer( 2000 ); Thread consumerThread( &consumer ); consumerThread.start(); consumerThread.join(); Thread::sleep( 100 ); CPPUNIT_ASSERT( consumer.getNumReceived() == 0 ); } void ExpirationTest::testNotExpired() { Producer producer( 2, 2000 ); producer.setDisableTimeStamps( true ); Thread producerThread( &producer ); producerThread.start(); producerThread.join(); Consumer consumer( 3000 ); Thread consumerThread( &consumer ); consumerThread.start(); consumerThread.join(); Thread::sleep( 50 ); CPPUNIT_ASSERT( consumer.getNumReceived() == 2 ); } <commit_msg>tweak to expiration test to allow multiple successive runs without collision with previous runs<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. */ #include "ExpirationTest.h" #include <integration/common/IntegrationCommon.h> CPPUNIT_TEST_SUITE_REGISTRATION( integration::expiration::ExpirationTest ); #include <sstream> #include <activemq/core/ActiveMQConnectionFactory.h> #include <activemq/exceptions/ActiveMQException.h> #include <activemq/concurrent/Thread.h> #include <activemq/connector/stomp/StompConnector.h> #include <activemq/util/SimpleProperties.h> #include <activemq/transport/TransportFactory.h> #include <activemq/util/Guid.h> #include <activemq/util/SimpleProperties.h> #include <activemq/util/StringTokenizer.h> #include <activemq/connector/ConnectorFactoryMap.h> #include <activemq/network/SocketFactory.h> #include <activemq/transport/TransportFactory.h> #include <activemq/network/Socket.h> #include <activemq/exceptions/NullPointerException.h> #include <activemq/core/ActiveMQConnection.h> #include <activemq/core/ActiveMQConsumer.h> #include <activemq/core/ActiveMQProducer.h> #include <activemq/util/StringTokenizer.h> #include <activemq/util/Boolean.h> #include <cms/Connection.h> #include <cms/MessageConsumer.h> #include <cms/MessageProducer.h> #include <cms/MessageListener.h> #include <cms/Startable.h> #include <cms/Closeable.h> #include <cms/MessageListener.h> #include <cms/ExceptionListener.h> #include <cms/Topic.h> #include <cms/Queue.h> #include <cms/TemporaryTopic.h> #include <cms/TemporaryQueue.h> #include <cms/Session.h> #include <cms/BytesMessage.h> #include <cms/TextMessage.h> #include <cms/MapMessage.h> #include <cms/Session.h> using namespace activemq::connector::stomp; using namespace activemq::transport; using namespace activemq::util; using namespace std; using namespace cms; using namespace activemq; using namespace activemq::core; using namespace activemq::util; using namespace activemq::connector; using namespace activemq::exceptions; using namespace activemq::network; using namespace activemq::transport; using namespace activemq::concurrent; using namespace std; using namespace integration; using namespace integration::expiration; using namespace integration::common; std::string messageTag = Guid().createGUID(); class Producer : public Runnable { private: Connection* connection; Session* session; Topic* destination; MessageProducer* producer; int numMessages; long long timeToLive; bool disableTimeStamps; public: Producer( int numMessages, long long timeToLive ){ connection = NULL; session = NULL; destination = NULL; producer = NULL; this->numMessages = numMessages; this->timeToLive = timeToLive; this->disableTimeStamps = false; } virtual ~Producer(){ cleanup(); } virtual bool getDisableTimeStamps() const { return disableTimeStamps; } virtual void setDisableTimeStamps( bool value ) { this->disableTimeStamps = value; } virtual void run() { try { // Create a ConnectionFactory ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61613"); // Create a Connection connection = connectionFactory->createConnection(); connection->start(); string sss=connection->getClientId(); cout << sss << endl; session = connection->createSession( Session::AUTO_ACKNOWLEDGE); destination = session->createTopic( "expirationTopic" ); producer = session->createProducer( destination ); producer->setDeliveryMode( DeliveryMode::PERSISTANT ); producer->setDisableMessageTimeStamp( disableTimeStamps ); //unsigned long ttt=getcurt(); producer->setTimeToLive( 1); // Create the Thread Id String string threadIdStr = Integer::toString( Thread::getId() ); // Create a messages string text = (string)"Hello world! from thread " + threadIdStr; for( int ix=0; ix<numMessages; ++ix ){ TextMessage* message = session->createTextMessage( text ); message->setStringProperty( "messageTag", messageTag ); producer->send( message ); delete message; } }catch ( CMSException& e ) { e.printStackTrace(); } } private: void cleanup(){ // Destroy resources. try{ if( destination != NULL ) delete destination; }catch ( CMSException& e ) {} destination = NULL; try{ if( producer != NULL ) delete producer; }catch ( CMSException& e ) {} producer = NULL; // Close open resources. try{ if( session != NULL ) session->close(); if( connection != NULL ) connection->close(); }catch ( CMSException& e ) {} try{ if( session != NULL ) delete session; }catch ( CMSException& e ) {} session = NULL; try{ if( connection != NULL ) delete connection; }catch ( CMSException& e ) {} connection = NULL; } }; class Consumer : public MessageListener, public Runnable { private: Connection* connection; Session* session; Topic* destination; MessageConsumer* consumer; long waitMillis; int numReceived; public: Consumer( long waitMillis ){ connection = NULL; session = NULL; destination = NULL; consumer = NULL; this->waitMillis = waitMillis; numReceived = 0; } virtual ~Consumer(){ cleanup(); } virtual int getNumReceived() const{ return numReceived; } virtual void run() { try { string user,passwd,sID; user="default"; passwd=""; sID="lsgID"; // Create a ConnectionFactory ActiveMQConnectionFactory* connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61613",user,passwd,sID); // Create a Connection connection = connectionFactory->createConnection(); delete connectionFactory; connection->start(); // Create a Session session = connection->createSession( Session::AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) destination = session->createTopic( "expirationTopic?consumer.retroactive=true"); consumer = session->createConsumer( destination ); consumer->setMessageListener( this ); // Sleep while asynchronous messages come in. Thread::sleep( waitMillis ); } catch (CMSException& e) { e.printStackTrace(); } } virtual void onMessage( const Message* message ){ try { if( !message->propertyExists( "messageTag" ) || message->getStringProperty("messageTag") != messageTag ){ return; } const TextMessage* textMessage = dynamic_cast< const TextMessage* >( message ); string text = textMessage->getText(); numReceived++; } catch (CMSException& e) { e.printStackTrace(); } } private: void cleanup(){ // Destroy resources. try{ if( destination != NULL ) delete destination; }catch (CMSException& e) {} destination = NULL; try{ if( consumer != NULL ) delete consumer; }catch (CMSException& e) {} consumer = NULL; // Close open resources. try{ if( session != NULL ) session->close(); if( connection != NULL ) connection->close(); }catch (CMSException& e) {} try{ if( session != NULL ) delete session; }catch (CMSException& e) {} session = NULL; try{ if( connection != NULL ) delete connection; }catch (CMSException& e) {} connection = NULL; } }; void ExpirationTest::testExpired() { Producer producer( 1, 1 ); Thread producerThread( &producer ); producerThread.start(); producerThread.join(); Thread::sleep( 100 ); Consumer consumer( 2000 ); Thread consumerThread( &consumer ); consumerThread.start(); consumerThread.join(); Thread::sleep( 100 ); CPPUNIT_ASSERT( consumer.getNumReceived() == 0 ); } void ExpirationTest::testNotExpired() { Producer producer( 2, 2000 ); producer.setDisableTimeStamps( true ); Thread producerThread( &producer ); producerThread.start(); producerThread.join(); Consumer consumer( 3000 ); Thread consumerThread( &consumer ); consumerThread.start(); consumerThread.join(); Thread::sleep( 50 ); CPPUNIT_ASSERT( consumer.getNumReceived() == 2 ); } <|endoftext|>
<commit_before>#include <pwd.h> #include <grp.h> #include <iostream> #include <unistd.h> #include <sys/stat.h> #include <stdio.h> #include <vector> #include <sstream> #include <dirent.h> #include <errno.h> #include <sys/types.h> using namespace std; bool isDirectory(char* directoryName) { struct stat directoryInCurrent; if (-1 == (stat(directoryName, &directoryInCurrent))) { return false; } if (directoryInCurrent.st_mode & S_IFDIR) { return true; } else { return false; } } int ls(char* directoryName) { char const *dirName = directoryName; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; } dirent *direntp; while ((direntp = readdir(dirp))) { if (direntp->d_name[0] != '.') { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); return 0; } int lsWithFlags(char* directoryName, vector<string> flags) { char const *dirName = directoryName; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; return errno; } bool isA = false; bool isL = false; bool isR = false; for (unsigned i = 0; i < flags.size(); ++i) { for (unsigned k = 0; k < flags.at(i).size(); ++k) { if (flags.at(i).at(k) == 'a') isA = true; // there's an -a flag else if (flags.at(i).at(k) == 'l') isL = true; // there's an -l flag else if (flags.at(i).at(k) == 'R') isR = true; // there's an -R flag } } dirent *direntp; if (isL) { //run -l flag struct stat current; struct passwd *x; struct group *y; while ((direntp = readdir(dirp))) { //cout << "direntp: " << direntp->d_name << endl; char curdir[1000]; strcpy(curdir, directoryName); strcat(curdir, "/"); strcat(curdir, direntp->d_name); //cout << curdir << endl; if (-1 == (stat(/*toCur*/curdir, &current))) { perror("stat failed"); return -1; } if (direntp->d_name[0] == '.' && !isA) // if there's no -a flag, don't print files // starting with . continue; else { if (current.st_mode & S_IFDIR) cout << "d"; if (current.st_mode & S_IFLNK) cout << "l"; if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK)) cout << "-"; if (current.st_mode & S_IRUSR) cout << "r"; else cout << "-"; if (current.st_mode & S_IWUSR) cout << "w"; else cout << "-"; if (current.st_mode & S_IXUSR) cout << "x"; else cout << "-"; if (current.st_mode & S_IRGRP) cout << "r"; else cout << "-"; if (current.st_mode & S_IWGRP) cout << "w"; else cout << "-"; if (current.st_mode & S_IXGRP) cout << "x"; else cout << "-"; if (current.st_mode & S_IROTH) cout << "r"; else cout << "-"; if (current.st_mode & S_IWOTH) cout << "w"; else cout << "-"; if (current.st_mode & S_IXOTH) cout << "x"; else cout << "-"; cout << " "; cout << current.st_nlink << " "; if ((x = getpwuid(current.st_uid)) != NULL) cout << x->pw_name << " "; else { cerr << "error: " << errno << endl; exit(0); } if ((y = getgrgid(current.st_gid)) != NULL) cout << y->gr_name << " "; else { cerr << "error: " << errno << endl; exit(0); } cout << current.st_size << " "; char buff[20]; struct tm * timeinfo; timeinfo = localtime(&(current.st_mtime)); strftime(buff, 20, "%b %d %H:%M", timeinfo); printf("%s",buff); cout << " " << direntp->d_name; if (isR) lsWithFlags(curdir, flags); } cout << endl; } closedir(dirp); } else if (isA) { while ((direntp = readdir(dirp))) { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } closedir(dirp); } return 0; } int main(int argc, char* argv[]) { if (argc == 1) { if (errno == ls(".")) { return errno; } } else { vector<string> directories; vector<string> flags; string toInsert = "./"; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { flags.push_back(argv[i]); } else { directories.push_back(argv[i]); } } for (unsigned i = 0; i < directories.size(); ++i) { directories.at(i).insert(0, toInsert); } if (flags.size() == 0) { for (unsigned i = 0; i < directories.size(); ++i) { char* directoryName = new char[directories.at(i).size() + 1]; strcpy(directoryName, directories.at(i).c_str()); ls(directoryName); delete [] directoryName; } } else if (directories.size() == 0) { lsWithFlags(".", flags); } else { //cout << "directories: "; //for (unsigned i = 0; i < directories.size(); ++i) //cout << directories.at(i) << " "; //cout << endl; if (directories.size() == 1) { char* directoryName = new char[directories.at(0).size() + 1]; strcpy(directoryName, directories.at(0).c_str()); lsWithFlags(directoryName, flags); delete [] directoryName; } else { for (unsigned int i = 0; i < directories.size(); ++i) { //cout << 145 << endl; char* directoryName = new char[directories.at(i).size() + 1]; strcpy(directoryName, directories.at(i).c_str()); lsWithFlags(directoryName, flags); delete [] directoryName; } } } } } <commit_msg>added -l protection functionality<commit_after>#include <pwd.h> #include <grp.h> #include <iostream> #include <unistd.h> #include <sys/stat.h> #include <stdio.h> #include <vector> #include <sstream> #include <dirent.h> #include <errno.h> #include <sys/types.h> using namespace std; bool isDirectory(char* directoryName) { struct stat directoryInCurrent; if (-1 == (stat(directoryName, &directoryInCurrent))) { return false; } if (directoryInCurrent.st_mode & S_IFDIR) { return true; } else { return false; } } int ls(char* directoryName) { char const *dirName = directoryName; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; } dirent *direntp; while ((direntp = readdir(dirp))) { if (direntp->d_name[0] != '.') { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } } cout << endl; closedir(dirp); return 0; } int lsWithFlags(char* directoryName, vector<string> flags) { char const *dirName = directoryName; DIR *dirp; if (!(dirp = opendir(dirName))) { cerr << "Error(" << errno << ") opening " << dirName << endl; return errno; } bool isA = false; bool isL = false; bool isR = false; for (unsigned i = 0; i < flags.size(); ++i) { for (unsigned k = 0; k < flags.at(i).size(); ++k) { if (flags.at(i).at(k) == 'a') isA = true; // there's an -a flag else if (flags.at(i).at(k) == 'l') isL = true; // there's an -l flag else if (flags.at(i).at(k) == 'R') isR = true; // there's an -R flag } } dirent *direntp; if (isL) { //run -l flag struct stat current; struct passwd *x; struct group *y; while ((direntp = readdir(dirp))) { //cout << "direntp: " << direntp->d_name << endl; char curdir[1000]; strcpy(curdir, directoryName); strcat(curdir, "/"); strcat(curdir, direntp->d_name); //cout << curdir << endl; if (-1 == (stat(/*toCur*/curdir, &current))) { perror("stat failed"); return -1; } if (direntp->d_name[0] == '.' && !isA) // if there's no -a flag, don't print files // starting with . continue; else { if (current.st_mode & S_IFDIR) cout << "d"; if (current.st_mode & S_IFLNK) cout << "l"; if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK)) cout << "-"; if (current.st_mode & S_IRUSR) cout << "r"; else cout << "-"; if (current.st_mode & S_IWUSR) cout << "w"; else cout << "-"; if (current.st_mode & S_IXUSR) cout << "x"; else cout << "-"; if (current.st_mode & S_IRGRP) cout << "r"; else cout << "-"; if (current.st_mode & S_IWGRP) cout << "w"; else cout << "-"; if (current.st_mode & S_IXGRP) cout << "x"; else cout << "-"; if (current.st_mode & S_IROTH) cout << "r"; else cout << "-"; if (current.st_mode & S_IWOTH) cout << "w"; else cout << "-"; if (current.st_mode & S_IXOTH) cout << "x"; else cout << "-"; cout << " "; cout << current.st_nlink << " "; if ((x = getpwuid(current.st_uid)) != NULL) cout << x->pw_name << " "; else { cerr << "error: " << errno << endl; exit(0); } if ((y = getgrgid(current.st_gid)) != NULL) cout << y->gr_name << " "; else { cerr << "error: " << errno << endl; exit(0); } cout << current.st_size << " "; char buff[20]; struct tm * timeinfo; timeinfo = localtime(&(current.st_mtime)); strftime(buff, 20, "%b %d %H:%M", timeinfo); printf("%s",buff); cout << " " << direntp->d_name; if (isR) lsWithFlags(curdir, flags); } cout << endl; } closedir(dirp); } else if (isA) { while ((direntp = readdir(dirp))) { //cout << direntp->d_name << endl; // use stat here to find attributes of a file printf(direntp->d_name, 8); cout << " "; } closedir(dirp); } return 0; } int main(int argc, char* argv[]) { if (argc == 1) { if (errno == ls(".")) { return errno; } } else { vector<string> directories; vector<string> flags; string toInsert = "./"; for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { flags.push_back(argv[i]); } else { directories.push_back(argv[i]); } } for (unsigned i = 0; i < directories.size(); ++i) { directories.at(i).insert(0, toInsert); } if (flags.size() == 0) { for (unsigned i = 0; i < directories.size(); ++i) { char* directoryName = new char[directories.at(i).size() + 1]; strcpy(directoryName, directories.at(i).c_str()); ls(directoryName); delete [] directoryName; } } else if (directories.size() == 0) { lsWithFlags(".", flags); } else { //cout << "directories: "; //for (unsigned i = 0; i < directories.size(); ++i) //cout << directories.at(i) << " "; //cout << endl; if (directories.size() == 1) { char* directoryName = new char[directories.at(0).size() + 1]; strcpy(directoryName, directories.at(0).c_str()); lsWithFlags(directoryName, flags); delete [] directoryName; } else { for (unsigned int i = 0; i < directories.size(); ++i) { //cout << 145 << endl; char* directoryName = new char[directories.at(i).size() + 1]; strcpy(directoryName, directories.at(i).c_str()); cout << directoryName << ":" << endl; lsWithFlags(directoryName, flags); delete [] directoryName; cout << endl; } } } } } <|endoftext|>
<commit_before><commit_msg>Take into account merge of branch 'asl/hydro_porting_741' in GUI module.<commit_after><|endoftext|>
<commit_before>/******************************************************************************* * thrill/data/fetching_block_queue.hpp * * Part of Project Thrill. * * Copyright (C) 2015 Tobias Sturm <mail@tobiassturm.de> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_DATA_PREFETCHING_BLOCK_QUEUE_HEADER #define THRILL_DATA_PREFETCHING_BLOCK_QUEUE_HEADER #include <thrill/common/concurrent_bounded_queue.hpp> namespace thrill { namespace data { //! \addtogroup data Data Subsystem //! \{ class PrefetchingBlockQueue final { protected: mutable std::mutex mutex_; std::queue<Block> unpinned_queue_; std::queue<Block> pinned_queue_; std::condition_variable cv_; std::atomic<size_t> currently_fetching_ = { 0 }; const size_t desired_; public: PrefetchingBlockQueue(size_t desired_prefetched) : desired_(desired_prefetched) {} //we cannod move since callbacks would break (?) PrefetchingBlockQueue(PrefetchingBlockQueue&& other) = delete; //! If pinned_queue_ holds less than the desired_ number of blocks //! MaybePrefetch starts the pin process for the required amount of //! blocks (or unpinned_queue_ is empty). currently_fetching_ //! is used to prevent too many pin calls by two consecutove calls to //! MaybePrefetch. MaybePrefetch notifies the condition variable cv_ void MaybePrefetch() { while(currently_fetching_ + pinned_queue_.size() < desired_ && !unpinned_queue_.empty()) { //block is valid (not end-of-x block) if (unpinned_queue_.front().byte_block_) { currently_fetching_++; // we have a block which is not swapped in //copy block since http://stackoverflow.com/a/14763579/359326 unpinned_queue_.front().byte_block_->Prefetch([&, block = unpinned_queue_.pop()](){ currently_fetching_--; pinned_queue_.push(block); cv_.notify_one(); }); } else { // for end-of-x blocks or already in memory pinned_queue_.push_back(unpinned_queue_.front()); unpinned_queue_.pop(); cv_.notify_one(); } } } //! Pushes a copy of source onto back of the queue. void push(const Block& source) { std::unique_lock<std::mutex> lock(other.mutex_); unpinned_queue_.push(source); MaybePrefetch(); } //! Pushes given element into the queue by utilizing element's move //! constructor void push(Block&& source) { std::unique_lock<std::mutex> lock(other.mutex_); unpinned_queue_.push(std::move(source)); MaybePrefetch(); } //! Pushes a new element into the queue. The element is constructed with //! given arguments. template <typename ... Arguments> void emplace(Arguments&& ... args) { std::unique_lock<std::mutex> lock(mutex_); unpinned_queue_.emplace(args ...); MaybePrefetch(); } //! Returns: true if queue has no items; false otherwise. bool empty() const { std::unique_lock<std::mutex> lock(mutex_); return unpinned_queue_.empty() && pinned_queue_.empty(); } //! Clears the queue. void clear() { std::unique_lock<std::mutex> lock(mutex_); unpinned_queue_.clear(); pinned_queue_.clear(); } //! If a fetched Block is available, pops it from the queue, move it to destination, //! destroying the original position. Otherwise does nothing. bool try_pop(Block& destination) { std::unique_lock<std::mutex> lock(mutex_); if (pinned_queue_.empty()) return false; destination = std::move(pinned_queue_.front()); pinned_queue_.pop(); return true; } //! If value is available, pops it from the queue, move it to //! destination. If no item is in the queue, wait until there is one. void pop(Block& destination) { std::unique_lock<std::mutex> lock(mutex_); cv_.wait(lock, [=]() { return !queue_.empty(); }); destination = std::move(queue_.front()); queue_.pop(); } //! return number of items available in the queue (tbb says "can return //! negative size", due to pending pop()s, but we ignore that here). //! \returns number of blocks (includes pinned, unpinned and currently fetching) size_t size() { std::unique_lock<std::mutex> lock(mutex_); return pinned_queue_.size() + unpinned_queue_.size() + currently_fetching_; } }; } // namespace data } // namespace thrill #endif // !THRILL_DATA_PREFETCHING_BLOCK_QUEUE_HEADER /******************************************************************************/ <commit_msg>idea with prefetching block queue was a bad idea - incorpate that into BlockQueue directly<commit_after><|endoftext|>
<commit_before>/* httpmessage.cpp Copyright (C) 2003-2005 Tommi Maekitalo This file is part of tntnet. Tntnet is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Tntnet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with tntnet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <tnt/httpmessage.h> #include <cxxtools/log.h> #include <list> #include <sstream> namespace tnt { size_t HttpMessage::maxRequestSize = 0; //////////////////////////////////////////////////////////////////////// // HttpMessage // log_define("tntnet.httpmessage") void HttpMessage::clear() { method.clear(); url.clear(); queryString.clear(); header.clear(); body.clear(); majorVersion = 0; minorVersion = 0; contentSize = 0; } std::string HttpMessage::getHeader(const std::string& key, const std::string& def) const { header_type::const_iterator i = header.find(key); return i == header.end() ? def : i->second; } void HttpMessage::setHeader(const std::string& key, const std::string& value) { log_debug("HttpMessage::setHeader(\"" << key << "\", \"" << value << "\")"); header.insert(header_type::value_type(key, value)); } std::string HttpMessage::dumpHeader() const { std::ostringstream h; dumpHeader(h); return h.str(); } void HttpMessage::dumpHeader(std::ostream& out) const { for (header_type::const_iterator it = header.begin(); it != header.end(); ++it) out << it->first << ' ' << it->second << '\n'; } std::string HttpMessage::htdate(time_t t) { struct ::tm tm; localtime_r(&t, &tm); return htdate(&tm); } std::string HttpMessage::htdate(struct ::tm* tm) { const char* wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; const char* monthn[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; char buffer[80]; mktime(tm); sprintf(buffer, "%s, %02d %s %d %02d:%02d:%02d GMT", wday[tm->tm_wday], tm->tm_mday, monthn[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); return buffer; } namespace { class Pstr { const char* start; const char* end; public: typedef size_t size_type; Pstr(const char* s, const char* e) : start(s), end(e) { } size_type size() const { return end - start; } bool operator== (const Pstr& s) const { return size() == s.size() && std::equal(start, end, s.start); } bool operator== (const char* str) const { size_type i; for (i = 0; i < size() && str[i] != '\0'; ++i) if (start[i] != str[i]) return false; return i == size() && str[i] == '\0'; } }; } bool HttpMessage::checkUrl(const std::string& url) { typedef std::list<Pstr> tokens_type; // teile in Komponenten auf enum state_type { state_start, state_token, state_end }; state_type state = state_start; tokens_type tokens; const char* p = url.data(); const char* e = p + url.size(); const char* s = p; for (; state != state_end && p != e; ++p) { switch (state) { case state_start: if (*p != '/') { s = p; state = state_token; } break; case state_token: if (*p == '/') { tokens.push_back(Pstr(s, p)); state = state_start; } else if (p == e) { tokens.push_back(Pstr(s, p)); state = state_end; } break; case state_end: break; } } // entferne jedes .. inklusive der vorhergehenden Komponente tokens_type::iterator i = tokens.begin(); while (i != tokens.end()) { if (*i == "..") { if (i == tokens.begin()) return false; --i; i = tokens.erase(i); // lösche 2 Komponenten i = tokens.erase(i); } else { ++i; } } return true; } } <commit_msg>bugfix - check for /./../<commit_after>/* httpmessage.cpp Copyright (C) 2003-2005 Tommi Maekitalo This file is part of tntnet. Tntnet is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Tntnet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with tntnet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <tnt/httpmessage.h> #include <cxxtools/log.h> #include <list> #include <sstream> namespace tnt { size_t HttpMessage::maxRequestSize = 0; //////////////////////////////////////////////////////////////////////// // HttpMessage // log_define("tntnet.httpmessage") void HttpMessage::clear() { method.clear(); url.clear(); queryString.clear(); header.clear(); body.clear(); majorVersion = 0; minorVersion = 0; contentSize = 0; } std::string HttpMessage::getHeader(const std::string& key, const std::string& def) const { header_type::const_iterator i = header.find(key); return i == header.end() ? def : i->second; } void HttpMessage::setHeader(const std::string& key, const std::string& value) { log_debug("HttpMessage::setHeader(\"" << key << "\", \"" << value << "\")"); header.insert(header_type::value_type(key, value)); } std::string HttpMessage::dumpHeader() const { std::ostringstream h; dumpHeader(h); return h.str(); } void HttpMessage::dumpHeader(std::ostream& out) const { for (header_type::const_iterator it = header.begin(); it != header.end(); ++it) out << it->first << ' ' << it->second << '\n'; } std::string HttpMessage::htdate(time_t t) { struct ::tm tm; localtime_r(&t, &tm); return htdate(&tm); } std::string HttpMessage::htdate(struct ::tm* tm) { const char* wday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; const char* monthn[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; char buffer[80]; mktime(tm); sprintf(buffer, "%s, %02d %s %d %02d:%02d:%02d GMT", wday[tm->tm_wday], tm->tm_mday, monthn[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); return buffer; } namespace { class Pstr { const char* start; const char* end; public: typedef size_t size_type; Pstr(const char* s, const char* e) : start(s), end(e) { } size_type size() const { return end - start; } bool operator== (const Pstr& s) const { return size() == s.size() && std::equal(start, end, s.start); } bool operator== (const char* str) const { size_type i; for (i = 0; i < size() && str[i] != '\0'; ++i) if (start[i] != str[i]) return false; return i == size() && str[i] == '\0'; } }; } bool HttpMessage::checkUrl(const std::string& url) { typedef std::list<Pstr> tokens_type; // teile in Komponenten auf enum state_type { state_start, state_token, state_end }; state_type state = state_start; tokens_type tokens; const char* p = url.data(); const char* e = p + url.size(); const char* s = p; for (; state != state_end && p != e; ++p) { switch (state) { case state_start: if (*p != '/') { s = p; state = state_token; } break; case state_token: if (*p == '/') { if (p - s != 1 || *s != '.') tokens.push_back(Pstr(s, p)); state = state_start; } else if (p == e) { tokens.push_back(Pstr(s, p)); state = state_end; } break; case state_end: break; } } // entferne jedes .. inklusive der vorhergehenden Komponente tokens_type::iterator i = tokens.begin(); while (i != tokens.end()) { if (*i == "..") { if (i == tokens.begin()) return false; --i; i = tokens.erase(i); // lösche 2 Komponenten i = tokens.erase(i); } else { ++i; } } return true; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tnt/httprequest.h> #include <tnt/httpparser.h> #include <tnt/httperror.h> #include <tnt/util.h> #include <sstream> #include <cxxtools/log.h> #include <cxxtools/mutex.h> #include <cxxtools/base64stream.h> #include <sys/socket.h> #include <arpa/inet.h> #include <tnt/sessionscope.h> #include <tnt/socketif.h> #include <pthread.h> #include "config.h" #include <tnt/stringlessignorecase.h> #include <cstring> namespace tnt { log_define("tntnet.httprequest") //////////////////////////////////////////////////////////////////////// // HttpRequest // cxxtools::atomic_t HttpRequest::serial_ = 0; HttpRequest::HttpRequest(Tntnet& application_, const SocketIf* socketIf_) : socketIf(socketIf_), locale_init(false), encodingRead(false), requestScope(0), applicationScope(0), sessionScope(0), secureSessionScope(0), threadContext(0), applicationScopeLocked(false), sessionScopeLocked(false), secureSessionScopeLocked(false), application(application_) { } HttpRequest::HttpRequest(Tntnet& application_, const std::string& url_, const SocketIf* socketIf_) : socketIf(socketIf_), locale_init(false), requestScope(0), applicationScope(0), sessionScope(0), secureSessionScope(0), threadContext(0), applicationScopeLocked(false), sessionScopeLocked(false), secureSessionScopeLocked(false), application(application_) { std::istringstream s("GET " + url_ + " HTTP/1.1\r\n\r\n"); parse(s); } HttpRequest::HttpRequest(const HttpRequest& r) : methodLen(0), pathinfo(r.pathinfo), args(r.args), qparam(r.qparam), socketIf(r.socketIf), ct(r.ct), mp(r.mp), serial(r.serial), locale_init(r.locale_init), locale(r.locale), requestScope(r.requestScope), applicationScope(r.applicationScope), sessionScope(r.sessionScope), secureSessionScope(r.secureSessionScope), threadContext(r.threadContext), applicationScopeLocked(false), sessionScopeLocked(false), secureSessionScopeLocked(false), application(r.application) { if (requestScope) requestScope->addRef(); if (applicationScope) applicationScope->addRef(); if (sessionScope) sessionScope->addRef(); if (secureSessionScope) secureSessionScope->addRef(); } HttpRequest::~HttpRequest() { releaseLocks(); if (requestScope) requestScope->release(); if (applicationScope) applicationScope->release(); if (sessionScope) sessionScope->release(); if (secureSessionScope) secureSessionScope->release(); } HttpRequest& HttpRequest::operator= (const HttpRequest& r) { pathinfo = r.pathinfo; args = r.args; qparam = r.qparam; ct = r.ct; mp = r.mp; socketIf = r.socketIf; serial = r.serial; locale_init = r.locale_init; locale = r.locale; requestScope = r.requestScope; applicationScope = r.applicationScope; sessionScope = r.sessionScope; secureSessionScope = r.secureSessionScope; threadContext = r.threadContext; applicationScopeLocked = false; sessionScopeLocked = false; secureSessionScopeLocked = false; if (requestScope) requestScope->addRef(); if (applicationScope) applicationScope->addRef(); if (sessionScope) sessionScope->addRef(); if (secureSessionScope) secureSessionScope->addRef(); return *this; } void HttpRequest::clear() { HttpMessage::clear(); body.clear(); methodLen = 0; method[0] = '\0'; url.clear(); queryString.clear(); contentSize = 0; pathinfo.clear(); args.clear(); qparam.clear(); ct = Contenttype(); mp = Multipart(); locale_init = false; if (requestScope) { requestScope->release(); requestScope = 0; } httpcookies.clear(); encodingRead = false; username.clear(); password.clear(); releaseLocks(); if (applicationScope) { applicationScope->release(); applicationScope = 0; } if (sessionScope) { sessionScope->release(); sessionScope = 0; } if (secureSessionScope) { secureSessionScope->release(); secureSessionScope = 0; } threadContext = 0; } void HttpRequest::setMethod(const char* m) { if (strlen(m) >= 7) throw HttpError(HTTP_BAD_REQUEST, "invalid method"); std::strcpy(method, m); } std::string HttpRequest::getArg(const std::string& name, const std::string& def) const { for (args_type::const_iterator it = args.begin(); it != args.end(); ++it) if (it->size() > name.size() && it->compare(0, name.size(), name) == 0 && it->at(name.size()) == '=') return it->substr(name.size() + 1); return def; } void HttpRequest::parse(std::istream& in) { Parser p(*this); p.parse(in); if (!p.failed()) doPostParse(); } void HttpRequest::doPostParse() { if (hasHeader("Expect:")) throw HttpError(HTTP_EXPECTATION_FAILED, "expectation failed", "Expect not supported by this server"); qparam.parse_url(getQueryString()); if (isMethodPOST()) { std::istringstream in(getHeader(httpheader::contentType)); in >> ct; if (in) { if (ct.isMultipart()) { mp.set(ct.getBoundary(), getBody()); for (Multipart::const_iterator it = mp.begin(); it != mp.end(); ++it) { // don't copy uploaded files into qparam to prevent unnecessery // copies of large chunks if (it->getFilename().empty()) { std::string multipartBody(it->getBodyBegin(), it->getBodyEnd()); qparam.add(it->getName(), multipartBody); } } } else if (ct.getType() == "application" && ct.getSubtype() == "x-www-form-urlencoded") { qparam.parse_url(getBody()); } } } serial = cxxtools::atomicIncrement(serial_); } namespace { const std::locale& getCacheLocale(const std::string& lang) { static std::locale stdlocale; static bool stdlocale_init = false; typedef std::map<std::string, std::locale> locale_map_type; static locale_map_type locale_map; static cxxtools::Mutex locale_monitor; if (!stdlocale_init) { cxxtools::MutexLock lock(locale_monitor); if (!stdlocale_init) { stdlocale_init = true; try { stdlocale = std::locale(""); } catch (const std::exception& e) { log_warn("error initializing standard-locale - using locale \"C\""); } } } if (lang.empty() || lang == stdlocale.name()) return stdlocale; try { cxxtools::MutexLock lock(locale_monitor); locale_map_type::const_iterator it = locale_map.find(lang); if (it == locale_map.end()) { std::locale loc = std::locale(lang.c_str()); return locale_map.insert(locale_map_type::value_type(lang, loc)).first->second; } else return it->second; } catch (const std::exception& e) { log_warn("unknown locale " << lang << ": " << e.what()); locale_map.insert(locale_map_type::value_type(lang, stdlocale)); return stdlocale; } } } const std::locale& HttpRequest::getLocale() const { if (!locale_init) { static const std::string LANG = "LANG"; lang = qparam[LANG]; locale = getCacheLocale(qparam[LANG]); if (lang.empty()) lang = locale.name(); locale_init = true; } return locale; } void HttpRequest::setLocale(const std::locale& loc) { locale_init = true; locale = loc; lang = loc.name(); } void HttpRequest::setLang(const std::string& lang_) { lang = lang_; locale = getCacheLocale(lang_); locale_init = true; } const Cookies& HttpRequest::getCookies() const { if (!httpcookies.hasCookies()) { header_type::const_iterator it = header.find(httpheader::cookie); if (it != header.end()) const_cast<HttpRequest*>(this)->httpcookies.set(it->second); } return httpcookies; } const Encoding& HttpRequest::getEncoding() const { if (!encodingRead) { encoding.parse(getHeader(httpheader::acceptEncoding)); encodingRead = true; } return encoding; } const std::string& HttpRequest::getUsername() const { if (username.empty() && hasHeader(httpheader::authorization)) { std::istringstream authHeader(getHeader(httpheader::authorization)); while (authHeader && authHeader.get() != ' ') ; cxxtools::Base64istream in(authHeader); std::getline(in, username, ':'); std::getline(in, password); } return username; } const std::string& HttpRequest::getPassword() const { getUsername(); return password; } bool HttpRequest::verifyPassword(const std::string& password_) const { getUsername(); return password == password_; } bool HttpRequest::keepAlive() const { // request is keep alive when either a connection header is explicitely set to keep alive // or the http version is 1.1 Messageheader::const_iterator it = header.find(httpheader::connection); return it == header.end() ? getMinorVersion() >= 1 && getMajorVersion() >= 1 : tnt::StringCompareIgnoreCase<const char*>(it->second, httpheader::connectionKeepAlive) == 0; } const Contenttype& HttpRequest::getContentTypePriv() const { std::istringstream in(getHeader(httpheader::contentType)); in >> ct; return ct; } void HttpRequest::setApplicationScope(Scope* s) { if (applicationScope == s) return; if (applicationScope) { releaseApplicationScopeLock(); applicationScope->release(); } if (s) s->addRef(); applicationScope = s; } void HttpRequest::setSessionScope(Sessionscope* s) { if (sessionScope == s) return; if (sessionScope) { if (sessionScopeLocked) { sessionScope->unlock(); sessionScopeLocked = false; } sessionScope->release(); } if (s) s->addRef(); sessionScope = s; } void HttpRequest::setSecureSessionScope(Sessionscope* s) { if (secureSessionScope == s) return; if (secureSessionScope) { if (secureSessionScopeLocked) { secureSessionScope->unlock(); secureSessionScopeLocked = false; } secureSessionScope->release(); } if (s) s->addRef(); secureSessionScope = s; } void HttpRequest::clearSession() { log_info("end session"); if (sessionScope) { if (sessionScopeLocked) { sessionScope->unlock(); sessionScopeLocked = false; } sessionScope->release(); sessionScope = 0; } if (secureSessionScope) { if (secureSessionScopeLocked) { secureSessionScope->unlock(); secureSessionScopeLocked = false; } secureSessionScope->release(); secureSessionScope = 0; } } void HttpRequest::ensureApplicationScopeLock() { ensureSessionScopeLock(); if (applicationScope && !applicationScopeLocked) { applicationScope->lock(); applicationScopeLocked = true; } } void HttpRequest::ensureSessionScopeLock() { if (sessionScope && !sessionScopeLocked) { sessionScope->lock(); sessionScopeLocked = true; } if (secureSessionScope && !secureSessionScopeLocked) { secureSessionScope->lock(); secureSessionScopeLocked = true; } } void HttpRequest::releaseApplicationScopeLock() { releaseSessionScopeLock(); if (applicationScope && applicationScopeLocked) { applicationScopeLocked = false; applicationScope->unlock(); } } void HttpRequest::releaseSessionScopeLock() { if (secureSessionScope && secureSessionScopeLocked) { secureSessionScopeLocked = false; secureSessionScope->unlock(); } if (sessionScope && sessionScopeLocked) { sessionScopeLocked = false; sessionScope->unlock(); } } Scope& HttpRequest::getRequestScope() { if (requestScope == 0) requestScope = new Scope(); return *requestScope; } Scope& HttpRequest::getThreadScope() { if (threadContext == 0) throwRuntimeError("threadcontext not set"); return threadContext->getScope(); } Scope& HttpRequest::getApplicationScope() { ensureApplicationScopeLock(); return *applicationScope; } Sessionscope& HttpRequest::getSessionScope() { if (!sessionScope) sessionScope = new Sessionscope(); ensureSessionScopeLock(); return *sessionScope; } Sessionscope& HttpRequest::getSecureSessionScope() { if (!secureSessionScope) secureSessionScope = new Sessionscope(); ensureSessionScopeLock(); return *secureSessionScope; } bool HttpRequest::hasSessionScope() const { return secureSessionScope != 0 && !secureSessionScope->empty(); } bool HttpRequest::hasSecureSessionScope() const { return secureSessionScope != 0 && !secureSessionScope->empty(); } } <commit_msg>session handling was broken after implementation of secure session scope<commit_after>/* * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tnt/httprequest.h> #include <tnt/httpparser.h> #include <tnt/httperror.h> #include <tnt/util.h> #include <sstream> #include <cxxtools/log.h> #include <cxxtools/mutex.h> #include <cxxtools/base64stream.h> #include <sys/socket.h> #include <arpa/inet.h> #include <tnt/sessionscope.h> #include <tnt/socketif.h> #include <pthread.h> #include "config.h" #include <tnt/stringlessignorecase.h> #include <cstring> namespace tnt { log_define("tntnet.httprequest") //////////////////////////////////////////////////////////////////////// // HttpRequest // cxxtools::atomic_t HttpRequest::serial_ = 0; HttpRequest::HttpRequest(Tntnet& application_, const SocketIf* socketIf_) : socketIf(socketIf_), locale_init(false), encodingRead(false), requestScope(0), applicationScope(0), sessionScope(0), secureSessionScope(0), threadContext(0), applicationScopeLocked(false), sessionScopeLocked(false), secureSessionScopeLocked(false), application(application_) { } HttpRequest::HttpRequest(Tntnet& application_, const std::string& url_, const SocketIf* socketIf_) : socketIf(socketIf_), locale_init(false), requestScope(0), applicationScope(0), sessionScope(0), secureSessionScope(0), threadContext(0), applicationScopeLocked(false), sessionScopeLocked(false), secureSessionScopeLocked(false), application(application_) { std::istringstream s("GET " + url_ + " HTTP/1.1\r\n\r\n"); parse(s); } HttpRequest::HttpRequest(const HttpRequest& r) : methodLen(0), pathinfo(r.pathinfo), args(r.args), qparam(r.qparam), socketIf(r.socketIf), ct(r.ct), mp(r.mp), serial(r.serial), locale_init(r.locale_init), locale(r.locale), requestScope(r.requestScope), applicationScope(r.applicationScope), sessionScope(r.sessionScope), secureSessionScope(r.secureSessionScope), threadContext(r.threadContext), applicationScopeLocked(false), sessionScopeLocked(false), secureSessionScopeLocked(false), application(r.application) { if (requestScope) requestScope->addRef(); if (applicationScope) applicationScope->addRef(); if (sessionScope) sessionScope->addRef(); if (secureSessionScope) secureSessionScope->addRef(); } HttpRequest::~HttpRequest() { releaseLocks(); if (requestScope) requestScope->release(); if (applicationScope) applicationScope->release(); if (sessionScope) sessionScope->release(); if (secureSessionScope) secureSessionScope->release(); } HttpRequest& HttpRequest::operator= (const HttpRequest& r) { pathinfo = r.pathinfo; args = r.args; qparam = r.qparam; ct = r.ct; mp = r.mp; socketIf = r.socketIf; serial = r.serial; locale_init = r.locale_init; locale = r.locale; requestScope = r.requestScope; applicationScope = r.applicationScope; sessionScope = r.sessionScope; secureSessionScope = r.secureSessionScope; threadContext = r.threadContext; applicationScopeLocked = false; sessionScopeLocked = false; secureSessionScopeLocked = false; if (requestScope) requestScope->addRef(); if (applicationScope) applicationScope->addRef(); if (sessionScope) sessionScope->addRef(); if (secureSessionScope) secureSessionScope->addRef(); return *this; } void HttpRequest::clear() { HttpMessage::clear(); body.clear(); methodLen = 0; method[0] = '\0'; url.clear(); queryString.clear(); contentSize = 0; pathinfo.clear(); args.clear(); qparam.clear(); ct = Contenttype(); mp = Multipart(); locale_init = false; if (requestScope) { requestScope->release(); requestScope = 0; } httpcookies.clear(); encodingRead = false; username.clear(); password.clear(); releaseLocks(); if (applicationScope) { applicationScope->release(); applicationScope = 0; } if (sessionScope) { sessionScope->release(); sessionScope = 0; } if (secureSessionScope) { secureSessionScope->release(); secureSessionScope = 0; } threadContext = 0; } void HttpRequest::setMethod(const char* m) { if (strlen(m) >= 7) throw HttpError(HTTP_BAD_REQUEST, "invalid method"); std::strcpy(method, m); } std::string HttpRequest::getArg(const std::string& name, const std::string& def) const { for (args_type::const_iterator it = args.begin(); it != args.end(); ++it) if (it->size() > name.size() && it->compare(0, name.size(), name) == 0 && it->at(name.size()) == '=') return it->substr(name.size() + 1); return def; } void HttpRequest::parse(std::istream& in) { Parser p(*this); p.parse(in); if (!p.failed()) doPostParse(); } void HttpRequest::doPostParse() { if (hasHeader("Expect:")) throw HttpError(HTTP_EXPECTATION_FAILED, "expectation failed", "Expect not supported by this server"); qparam.parse_url(getQueryString()); if (isMethodPOST()) { std::istringstream in(getHeader(httpheader::contentType)); in >> ct; if (in) { if (ct.isMultipart()) { mp.set(ct.getBoundary(), getBody()); for (Multipart::const_iterator it = mp.begin(); it != mp.end(); ++it) { // don't copy uploaded files into qparam to prevent unnecessery // copies of large chunks if (it->getFilename().empty()) { std::string multipartBody(it->getBodyBegin(), it->getBodyEnd()); qparam.add(it->getName(), multipartBody); } } } else if (ct.getType() == "application" && ct.getSubtype() == "x-www-form-urlencoded") { qparam.parse_url(getBody()); } } } serial = cxxtools::atomicIncrement(serial_); } namespace { const std::locale& getCacheLocale(const std::string& lang) { static std::locale stdlocale; static bool stdlocale_init = false; typedef std::map<std::string, std::locale> locale_map_type; static locale_map_type locale_map; static cxxtools::Mutex locale_monitor; if (!stdlocale_init) { cxxtools::MutexLock lock(locale_monitor); if (!stdlocale_init) { stdlocale_init = true; try { stdlocale = std::locale(""); } catch (const std::exception& e) { log_warn("error initializing standard-locale - using locale \"C\""); } } } if (lang.empty() || lang == stdlocale.name()) return stdlocale; try { cxxtools::MutexLock lock(locale_monitor); locale_map_type::const_iterator it = locale_map.find(lang); if (it == locale_map.end()) { std::locale loc = std::locale(lang.c_str()); return locale_map.insert(locale_map_type::value_type(lang, loc)).first->second; } else return it->second; } catch (const std::exception& e) { log_warn("unknown locale " << lang << ": " << e.what()); locale_map.insert(locale_map_type::value_type(lang, stdlocale)); return stdlocale; } } } const std::locale& HttpRequest::getLocale() const { if (!locale_init) { static const std::string LANG = "LANG"; lang = qparam[LANG]; locale = getCacheLocale(qparam[LANG]); if (lang.empty()) lang = locale.name(); locale_init = true; } return locale; } void HttpRequest::setLocale(const std::locale& loc) { locale_init = true; locale = loc; lang = loc.name(); } void HttpRequest::setLang(const std::string& lang_) { lang = lang_; locale = getCacheLocale(lang_); locale_init = true; } const Cookies& HttpRequest::getCookies() const { if (!httpcookies.hasCookies()) { header_type::const_iterator it = header.find(httpheader::cookie); if (it != header.end()) const_cast<HttpRequest*>(this)->httpcookies.set(it->second); } return httpcookies; } const Encoding& HttpRequest::getEncoding() const { if (!encodingRead) { encoding.parse(getHeader(httpheader::acceptEncoding)); encodingRead = true; } return encoding; } const std::string& HttpRequest::getUsername() const { if (username.empty() && hasHeader(httpheader::authorization)) { std::istringstream authHeader(getHeader(httpheader::authorization)); while (authHeader && authHeader.get() != ' ') ; cxxtools::Base64istream in(authHeader); std::getline(in, username, ':'); std::getline(in, password); } return username; } const std::string& HttpRequest::getPassword() const { getUsername(); return password; } bool HttpRequest::verifyPassword(const std::string& password_) const { getUsername(); return password == password_; } bool HttpRequest::keepAlive() const { // request is keep alive when either a connection header is explicitely set to keep alive // or the http version is 1.1 Messageheader::const_iterator it = header.find(httpheader::connection); return it == header.end() ? getMinorVersion() >= 1 && getMajorVersion() >= 1 : tnt::StringCompareIgnoreCase<const char*>(it->second, httpheader::connectionKeepAlive) == 0; } const Contenttype& HttpRequest::getContentTypePriv() const { std::istringstream in(getHeader(httpheader::contentType)); in >> ct; return ct; } void HttpRequest::setApplicationScope(Scope* s) { if (applicationScope == s) return; if (applicationScope) { releaseApplicationScopeLock(); applicationScope->release(); } if (s) s->addRef(); applicationScope = s; } void HttpRequest::setSessionScope(Sessionscope* s) { if (sessionScope == s) return; if (sessionScope) { if (sessionScopeLocked) { sessionScope->unlock(); sessionScopeLocked = false; } sessionScope->release(); } if (s) s->addRef(); sessionScope = s; } void HttpRequest::setSecureSessionScope(Sessionscope* s) { if (secureSessionScope == s) return; if (secureSessionScope) { if (secureSessionScopeLocked) { secureSessionScope->unlock(); secureSessionScopeLocked = false; } secureSessionScope->release(); } if (s) s->addRef(); secureSessionScope = s; } void HttpRequest::clearSession() { log_info("end session"); if (sessionScope) { if (sessionScopeLocked) { sessionScope->unlock(); sessionScopeLocked = false; } sessionScope->release(); sessionScope = 0; } if (secureSessionScope) { if (secureSessionScopeLocked) { secureSessionScope->unlock(); secureSessionScopeLocked = false; } secureSessionScope->release(); secureSessionScope = 0; } } void HttpRequest::ensureApplicationScopeLock() { ensureSessionScopeLock(); if (applicationScope && !applicationScopeLocked) { applicationScope->lock(); applicationScopeLocked = true; } } void HttpRequest::ensureSessionScopeLock() { if (sessionScope && !sessionScopeLocked) { sessionScope->lock(); sessionScopeLocked = true; } if (secureSessionScope && !secureSessionScopeLocked) { secureSessionScope->lock(); secureSessionScopeLocked = true; } } void HttpRequest::releaseApplicationScopeLock() { releaseSessionScopeLock(); if (applicationScope && applicationScopeLocked) { applicationScopeLocked = false; applicationScope->unlock(); } } void HttpRequest::releaseSessionScopeLock() { if (secureSessionScope && secureSessionScopeLocked) { secureSessionScopeLocked = false; secureSessionScope->unlock(); } if (sessionScope && sessionScopeLocked) { sessionScopeLocked = false; sessionScope->unlock(); } } Scope& HttpRequest::getRequestScope() { if (requestScope == 0) requestScope = new Scope(); return *requestScope; } Scope& HttpRequest::getThreadScope() { if (threadContext == 0) throwRuntimeError("threadcontext not set"); return threadContext->getScope(); } Scope& HttpRequest::getApplicationScope() { ensureApplicationScopeLock(); return *applicationScope; } Sessionscope& HttpRequest::getSessionScope() { if (!sessionScope) sessionScope = new Sessionscope(); ensureSessionScopeLock(); return *sessionScope; } Sessionscope& HttpRequest::getSecureSessionScope() { if (!secureSessionScope) secureSessionScope = new Sessionscope(); ensureSessionScopeLock(); return *secureSessionScope; } bool HttpRequest::hasSessionScope() const { return sessionScope != 0 && !sessionScope->empty(); } bool HttpRequest::hasSecureSessionScope() const { return secureSessionScope != 0 && !secureSessionScope->empty(); } } <|endoftext|>
<commit_before> // $Id: QueryResults.cpp 3456 2013-06-14 02:11:13Z jiaying $ /* * The Software is made available solely for use according to the License Agreement. Any reproduction * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the * maximum extent possible. * * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF SOFTWARE. * Copyright © 2010 SRCH2 Inc. All rights reserved */ #include "QueryResultsInternal.h" #include "operation/QueryEvaluatorInternal.h" #include "util/RecordSerializerUtil.h" using srch2::util::Logger; namespace srch2 { namespace instantsearch { QueryResultFactory::QueryResultFactory(){ impl = new QueryResultFactoryInternal(); } QueryResultFactory::~QueryResultFactory(){ delete impl; } QueryResults::QueryResults(){ impl = new QueryResultsInternal(); } void QueryResults::init(QueryResultFactory * resultsFactory, const QueryEvaluator* queryEvaluator, Query* query){ impl->init(resultsFactory,queryEvaluator->impl,query); } /** * Creates a QueryResults object. * @param[in] indexSearcher the reference to an IndexSearcher object. * @param[in] query the reference to a Query object. */ QueryResults::QueryResults(QueryResultFactory * resultsFactory, const QueryEvaluator* queryEvaluator, Query* query){ impl = new QueryResultsInternal(resultsFactory,queryEvaluator->impl,query ); } QueryResults::~QueryResults(){ delete impl; } /** * Checks if the iterator reaches the end. @return false if * there is no next item in the QueryResults. */ /*virtual bool next() = 0;*/ /** * Gets the number of result items in the QueryResults object. */ unsigned QueryResults::getNumberOfResults() const{ return impl->sortedFinalResults.size(); } /** * Gets the current record id while iterating through the QueryResults object. */ /*virtual int getRecordId() = 0;*/ /** * Gets the record id of the 'position'-th item in the QueryResults object. */ std::string QueryResults::getRecordId(unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->externalRecordId; } /** * Gets the record id of the 'position'-th item in the QueryResults object. * TODO: Move/remove getInternalRecordId to internal include files. There should be a mapping from external * Used to access the InMemoryData. */ unsigned QueryResults::getInternalRecordId(unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->internalRecordId; } /* * this function is called from unit test. Do not use it in wrapper layer. */ std::string QueryResults::getInMemoryRecordString(unsigned position) const { unsigned internalRecordId = this->getInternalRecordId(position); StoredRecordBuffer buffer = impl->queryEvaluatorInternal->getInMemoryData(internalRecordId); string inMemoryString = ""; if (buffer.start) inMemoryString = string(buffer.start.get(), buffer.length); return inMemoryString; } /** * Gets the score of the 'position'-th item in the QueryResults object. */ std::string QueryResults::getResultScoreString(unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->_score.toString(); } TypedValue QueryResults::getResultScore(unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->_score; } /** * * Gets the matching keywords of the 'position'-th item in * the QueryResults object. For each query keyword return a matching * keyword in a record. If the query keyword is prefix then return a * matching prefix. In the case of multiple matching keywords for a * query keyword,the best match based on edit distance is returned. * * For example, for the query "ulman compilor", a result * record with keywords "ullman principles compiler" will * return ["ullman","compiler"] in the matchingKeywords * vector. In particular, "compiler" is the best matching * keyword in the record for the second query keyword * "compilor". */ void QueryResults::getMatchingKeywords(const unsigned position, std::vector<std::string> &matchingKeywords) const { matchingKeywords.assign(impl->sortedFinalResults[position]->matchingKeywords.begin(), impl->sortedFinalResults[position]->matchingKeywords.end()); } /** * Gets the edit distances of the 'position'-th item in the * QueryResults object. * @param[in] position the position of a result in the returned * results (starting from 0). * @param[out] editDistances a vector of edit distances of the * best matching keywords in this result record with respect * to the query keywords. * * For example, for the query "ulman compilor", a result * recorprivate: struct Impl; Impl *impl;d with keywords "ullman principles conpiler" will * return [1,2] in the editDistances vector. In particular, * "2" means that the best matching keyword ("conpiler") in * this record has an edit distance 2 to the second query * keyword "compilor". */ void QueryResults::getEditDistances(const unsigned position, std::vector<unsigned> &editDistances) const { editDistances.assign(impl->sortedFinalResults[position]->editDistances.begin(), impl->sortedFinalResults[position]->editDistances.end()); } // The following two functions only work for attribute based search void QueryResults::getMatchedAttributeBitmaps(const unsigned position, std::vector<unsigned> &matchedAttributeBitmaps) const { matchedAttributeBitmaps.assign(impl->sortedFinalResults[position]->attributeBitmaps.begin(), impl->sortedFinalResults[position]->attributeBitmaps.end()); } void QueryResults::getMatchedAttributes(const unsigned position, std::vector<std::vector<unsigned> > &matchedAttributes) const { //TODO opt const vector<unsigned> &matchedAttributeBitmaps = impl->sortedFinalResults[position]->attributeBitmaps; matchedAttributes.resize(matchedAttributeBitmaps.size()); for(int i = 0; i < matchedAttributeBitmaps.size(); i++) { unsigned idx = 0; unsigned matchedAttributeBitmap = matchedAttributeBitmaps[i]; matchedAttributes[i].clear(); while(matchedAttributeBitmap) { if(matchedAttributeBitmap & 0x1) { matchedAttributes[i].push_back(idx); } matchedAttributeBitmap >>= 1; ++idx; } } } void QueryResults::getTermTypes(unsigned position, vector<TermType>& tt) const{ tt.assign(impl->sortedFinalResults[position]->termTypes.begin(), impl->sortedFinalResults[position]->termTypes.end()); } /* * In Geo search return distance between location of the result and center of the query rank. * TODO: Change the name to getGeoDistance() * // only the results of MapQuery have this */ double QueryResults::getPhysicalDistance(const unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->physicalDistance; } const std::map<std::string, std::pair< FacetType , std::vector<std::pair<std::string, float> > > > * QueryResults::getFacetResults() const{ return &impl->facetResults; } // pass information to the destination QueryResults object // can be seen as this := sourceQueryResults (only for structures related to post processing) void QueryResults::copyForPostProcessing(QueryResults * sourceQueryResults) const { this->impl->sortedFinalResults = sourceQueryResults->impl->sortedFinalResults ; this->impl->facetResults = sourceQueryResults->impl->facetResults ; this->impl->resultsApproximated = sourceQueryResults->impl->resultsApproximated; this->impl->estimatedNumberOfResults = sourceQueryResults->impl->estimatedNumberOfResults; } void QueryResults::clear(){ this->impl->sortedFinalResults.clear(); this->impl->facetResults.clear(); } bool QueryResults::isResultsApproximated() const{ return this->impl->resultsApproximated; } long int QueryResults::getEstimatedNumberOfResults() const{ return this->impl->estimatedNumberOfResults; } //TODO: These three functions for internal debugging. remove from the header void QueryResults::printStats() const { impl->stat->print(); } void QueryResults::printResult() const { // show attributeBitmaps vector<unsigned> attributeBitmaps; vector<vector<unsigned> > attributes; vector<string> matchedKeywords; Logger::debug("Result count %d" ,this->getNumberOfResults()); for(int i = 0; i < this->getNumberOfResults(); i++) { Logger::debug("Result #%d" ,i); this->getMatchedAttributeBitmaps(i, attributeBitmaps); this->getMatchingKeywords(i, matchedKeywords); this->getMatchedAttributes(i, attributes); for(int j = 0; j < attributeBitmaps.size(); j++) { Logger::debug("%s %d {", matchedKeywords[j].c_str(), attributeBitmaps[j]); for(int k = 0; k < attributes[j].size(); k++) Logger::debug("%d", attributes[j][k]); Logger::debug("}"); } } } void QueryResults::addMessage(const char* msg) { impl->stat->addMessage(msg); } }} <commit_msg>minor review comment<commit_after> // $Id: QueryResults.cpp 3456 2013-06-14 02:11:13Z jiaying $ /* * The Software is made available solely for use according to the License Agreement. Any reproduction * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the * maximum extent possible. * * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF SOFTWARE. * Copyright © 2010 SRCH2 Inc. All rights reserved */ #include "QueryResultsInternal.h" #include "operation/QueryEvaluatorInternal.h" #include "util/RecordSerializerUtil.h" using srch2::util::Logger; namespace srch2 { namespace instantsearch { QueryResultFactory::QueryResultFactory(){ impl = new QueryResultFactoryInternal(); } QueryResultFactory::~QueryResultFactory(){ delete impl; } QueryResults::QueryResults(){ impl = new QueryResultsInternal(); } void QueryResults::init(QueryResultFactory * resultsFactory, const QueryEvaluator* queryEvaluator, Query* query){ impl->init(resultsFactory,queryEvaluator->impl,query); } /** * Creates a QueryResults object. * @param[in] indexSearcher the reference to an IndexSearcher object. * @param[in] query the reference to a Query object. */ QueryResults::QueryResults(QueryResultFactory * resultsFactory, const QueryEvaluator* queryEvaluator, Query* query){ impl = new QueryResultsInternal(resultsFactory,queryEvaluator->impl,query ); } QueryResults::~QueryResults(){ delete impl; } /** * Checks if the iterator reaches the end. @return false if * there is no next item in the QueryResults. */ /*virtual bool next() = 0;*/ /** * Gets the number of result items in the QueryResults object. */ unsigned QueryResults::getNumberOfResults() const{ return impl->sortedFinalResults.size(); } /** * Gets the current record id while iterating through the QueryResults object. */ /*virtual int getRecordId() = 0;*/ /** * Gets the record id of the 'position'-th item in the QueryResults object. */ std::string QueryResults::getRecordId(unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->externalRecordId; } /** * Gets the record id of the 'position'-th item in the QueryResults object. * TODO: Move/remove getInternalRecordId to internal include files. There should be a mapping from external * Used to access the InMemoryData. */ unsigned QueryResults::getInternalRecordId(unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->internalRecordId; } /* * this function is called from unit test. Do not use it in wrapper layer. */ std::string QueryResults::getInMemoryRecordString(unsigned position) const { unsigned internalRecordId = this->getInternalRecordId(position); StoredRecordBuffer buffer = impl->queryEvaluatorInternal->getInMemoryData(internalRecordId); string inMemoryString = ""; if (!buffer.start) inMemoryString = string(buffer.start.get(), buffer.length); return inMemoryString; } /** * Gets the score of the 'position'-th item in the QueryResults object. */ std::string QueryResults::getResultScoreString(unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->_score.toString(); } TypedValue QueryResults::getResultScore(unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->_score; } /** * * Gets the matching keywords of the 'position'-th item in * the QueryResults object. For each query keyword return a matching * keyword in a record. If the query keyword is prefix then return a * matching prefix. In the case of multiple matching keywords for a * query keyword,the best match based on edit distance is returned. * * For example, for the query "ulman compilor", a result * record with keywords "ullman principles compiler" will * return ["ullman","compiler"] in the matchingKeywords * vector. In particular, "compiler" is the best matching * keyword in the record for the second query keyword * "compilor". */ void QueryResults::getMatchingKeywords(const unsigned position, std::vector<std::string> &matchingKeywords) const { matchingKeywords.assign(impl->sortedFinalResults[position]->matchingKeywords.begin(), impl->sortedFinalResults[position]->matchingKeywords.end()); } /** * Gets the edit distances of the 'position'-th item in the * QueryResults object. * @param[in] position the position of a result in the returned * results (starting from 0). * @param[out] editDistances a vector of edit distances of the * best matching keywords in this result record with respect * to the query keywords. * * For example, for the query "ulman compilor", a result * recorprivate: struct Impl; Impl *impl;d with keywords "ullman principles conpiler" will * return [1,2] in the editDistances vector. In particular, * "2" means that the best matching keyword ("conpiler") in * this record has an edit distance 2 to the second query * keyword "compilor". */ void QueryResults::getEditDistances(const unsigned position, std::vector<unsigned> &editDistances) const { editDistances.assign(impl->sortedFinalResults[position]->editDistances.begin(), impl->sortedFinalResults[position]->editDistances.end()); } // The following two functions only work for attribute based search void QueryResults::getMatchedAttributeBitmaps(const unsigned position, std::vector<unsigned> &matchedAttributeBitmaps) const { matchedAttributeBitmaps.assign(impl->sortedFinalResults[position]->attributeBitmaps.begin(), impl->sortedFinalResults[position]->attributeBitmaps.end()); } void QueryResults::getMatchedAttributes(const unsigned position, std::vector<std::vector<unsigned> > &matchedAttributes) const { //TODO opt const vector<unsigned> &matchedAttributeBitmaps = impl->sortedFinalResults[position]->attributeBitmaps; matchedAttributes.resize(matchedAttributeBitmaps.size()); for(int i = 0; i < matchedAttributeBitmaps.size(); i++) { unsigned idx = 0; unsigned matchedAttributeBitmap = matchedAttributeBitmaps[i]; matchedAttributes[i].clear(); while(matchedAttributeBitmap) { if(matchedAttributeBitmap & 0x1) { matchedAttributes[i].push_back(idx); } matchedAttributeBitmap >>= 1; ++idx; } } } void QueryResults::getTermTypes(unsigned position, vector<TermType>& tt) const{ tt.assign(impl->sortedFinalResults[position]->termTypes.begin(), impl->sortedFinalResults[position]->termTypes.end()); } /* * In Geo search return distance between location of the result and center of the query rank. * TODO: Change the name to getGeoDistance() * // only the results of MapQuery have this */ double QueryResults::getPhysicalDistance(const unsigned position) const { ASSERT (position < this->getNumberOfResults()); return impl->sortedFinalResults.at(position)->physicalDistance; } const std::map<std::string, std::pair< FacetType , std::vector<std::pair<std::string, float> > > > * QueryResults::getFacetResults() const{ return &impl->facetResults; } // pass information to the destination QueryResults object // can be seen as this := sourceQueryResults (only for structures related to post processing) void QueryResults::copyForPostProcessing(QueryResults * sourceQueryResults) const { this->impl->sortedFinalResults = sourceQueryResults->impl->sortedFinalResults ; this->impl->facetResults = sourceQueryResults->impl->facetResults ; this->impl->resultsApproximated = sourceQueryResults->impl->resultsApproximated; this->impl->estimatedNumberOfResults = sourceQueryResults->impl->estimatedNumberOfResults; } void QueryResults::clear(){ this->impl->sortedFinalResults.clear(); this->impl->facetResults.clear(); } bool QueryResults::isResultsApproximated() const{ return this->impl->resultsApproximated; } long int QueryResults::getEstimatedNumberOfResults() const{ return this->impl->estimatedNumberOfResults; } //TODO: These three functions for internal debugging. remove from the header void QueryResults::printStats() const { impl->stat->print(); } void QueryResults::printResult() const { // show attributeBitmaps vector<unsigned> attributeBitmaps; vector<vector<unsigned> > attributes; vector<string> matchedKeywords; Logger::debug("Result count %d" ,this->getNumberOfResults()); for(int i = 0; i < this->getNumberOfResults(); i++) { Logger::debug("Result #%d" ,i); this->getMatchedAttributeBitmaps(i, attributeBitmaps); this->getMatchingKeywords(i, matchedKeywords); this->getMatchedAttributes(i, attributes); for(int j = 0; j < attributeBitmaps.size(); j++) { Logger::debug("%s %d {", matchedKeywords[j].c_str(), attributeBitmaps[j]); for(int k = 0; k < attributes[j].size(); k++) Logger::debug("%d", attributes[j][k]); Logger::debug("}"); } } } void QueryResults::addMessage(const char* msg) { impl->stat->addMessage(msg); } }} <|endoftext|>
<commit_before>/* * DesktopMain.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <QtGui> #include <QPushButton> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/scoped_ptr.hpp> #include <core/Log.hpp> #include <core/system/FileScanner.hpp> #include <core/SafeConvert.hpp> #include <core/StringUtils.hpp> #include <core/system/System.hpp> #include <core/system/Environment.hpp> #include <core/r_util/RProjectFile.hpp> #include <core/r_util/RUserData.hpp> #include "DesktopApplicationLaunch.hpp" #include "DesktopSlotBinders.hpp" #include "DesktopDetectRHome.hpp" #include "DesktopUtils.hpp" #include "DesktopSessionLauncher.hpp" #include "DesktopProgressActivator.hpp" #include "DesktopNetworkProxyFactory.hpp" #include "DesktopActivationOverlay.hpp" QProcess* pRSessionProcess; QString sharedSecret; using namespace rstudio; using namespace rstudio::core; using namespace rstudio::desktop; namespace { void initializeSharedSecret() { sharedSecret = QString::number(rand()) + QString::number(rand()) + QString::number(rand()); std::string value = sharedSecret.toUtf8().constData(); core::system::setenv("RS_SHARED_SECRET", value); } void initializeWorkingDirectory(int argc, char* argv[], const QString& filename) { // bail if we've already got a working directory as a result of // a call to openSessionInNewWindow if (!core::system::getenv(kRStudioInitialWorkingDir).empty()) return; // calculate what our initial working directory should be std::string workingDir; // if there is a filename passed to us then use it's path if (filename != QString()) { FilePath filePath(filename.toUtf8().constData()); if (filePath.exists()) { if (filePath.isDirectory()) workingDir = filePath.absolutePath(); else workingDir = filePath.parent().absolutePath(); } } // do additinal detection if necessary if (workingDir.empty()) { // get current path FilePath currentPath = FilePath::safeCurrentPath( core::system::userHomePath()); #if defined(_WIN32) || defined(__APPLE__) // detect whether we were launched from the system application menu // (e.g. Dock, Program File icon, etc.). we do this by checking // whether the executable path is within the current path. if we // weren't launched from the system app menu that set the initial // wd to the current path FilePath exePath; Error error = core::system::executablePath(argv[0], &exePath); if (!error) { if (!exePath.isWithin(currentPath)) workingDir = currentPath.absolutePath(); } else { LOG_ERROR(error); } #else // on linux we take the current working dir if we were launched // from within a terminal if (core::system::stdoutIsTerminal() && (currentPath != core::system::userHomePath())) { workingDir = currentPath.absolutePath(); } #endif } // set the working dir if we have one if (!workingDir.empty()) core::system::setenv(kRStudioInitialWorkingDir, workingDir); } void setInitialProject(const FilePath& projectFile, QString* pFilename) { core::system::setenv(kRStudioInitialProject, projectFile.absolutePath()); pFilename->clear(); } void initializeStartupEnvironment(QString* pFilename) { // if the filename ends with .RData or .rda then this is an // environment file. if it ends with .Rproj then it is // a project file. we handle both cases by setting an environment // var and then resetting the pFilename so it isn't processed // using the standard open file logic FilePath filePath(pFilename->toUtf8().constData()); if (filePath.exists()) { std::string ext = filePath.extensionLowerCase(); // if it is a directory or just an .rdata file then we can see // whether there is a project file we can automatically attach to if (filePath.isDirectory()) { FilePath projectFile = r_util::projectFromDirectory(filePath); if (!projectFile.empty()) { setInitialProject(projectFile, pFilename); } } else if (ext == ".rproj") { setInitialProject(filePath, pFilename); } else if (ext == ".rdata" || ext == ".rda") { core::system::setenv(kRStudioInitialEnvironment, filePath.absolutePath()); pFilename->clear(); } } } QString verifyAndNormalizeFilename(const QString &filename) { if (filename.isNull() || filename.isEmpty()) return QString(); QFileInfo fileInfo(filename); if (fileInfo.exists()) return fileInfo.absoluteFilePath(); else return QString(); } bool isNonProjectFilename(const QString &filename) { if (filename.isNull() || filename.isEmpty()) return false; FilePath filePath(filename.toUtf8().constData()); return filePath.exists() && filePath.extensionLowerCase() != ".rproj"; } bool useChromiumDevtools() { // disable by default due to security concerns // https://bugreports.qt.io/browse/QTBUG-50725 bool useDevtools = false; #ifndef NDEBUG // but enable by default for development builds useDevtools = true; #endif // enable when environment variable is set if (!core::system::getenv("RSTUDIO_USE_CHROMIUM_DEVTOOLS").empty()) { useDevtools = true; } return useDevtools; } } // anonymous namespace int main(int argc, char* argv[]) { core::system::initHook(); try { initializeLang(); if (useChromiumDevtools()) { // use QTcpSocket to find an open port. this is unfortunately a bit racey // but AFAICS there isn't a better solution for port selection QByteArray port; QTcpSocket* pSocket = new QTcpSocket(); if (pSocket->bind()) { quint16 port = pSocket->localPort(); desktopInfo().setChromiumDevtoolsPort(port); core::system::setenv("QTWEBENGINE_REMOTE_DEBUGGING", safe_convert::numberToString(port)); pSocket->close(); } } // initialize log core::system::initializeLog("rdesktop", core::system::kLogLevelWarning, desktop::userLogPath()); // ignore SIGPIPE Error error = core::system::ignoreSignal(core::system::SigPipe); if (error) LOG_ERROR(error); // set application attributes QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // prepare command line arguments static std::vector<char*> arguments(argv, argv + argc); #ifndef NDEBUG // disable web security for development builds (so we can // get access to sourcemaps) static char disableWebSecurity[] = "--disable-web-security"; arguments.push_back(disableWebSecurity); #endif // disable chromium renderer accessibility by default (it can cause // slowdown when used in conjunction with some applications; see e.g. // https://github.com/rstudio/rstudio/issues/1990) if (core::system::getenv("RSTUDIO_ACCESSIBILITY").empty()) { static char disableRendererAccessibility[] = "--disable-renderer-accessibility"; arguments.push_back(disableRendererAccessibility); } #ifdef Q_OS_LINUX // workaround for Qt 5.10.1 bug "Could not find QtWebEngineProcess" // https://bugreports.qt.io/browse/QTBUG-67023 // https://bugreports.qt.io/browse/QTBUG-66346 static char noSandbox[] = "--no-sandbox"; arguments.push_back(noSandbox); #endif #ifdef Q_OS_MAC // don't prefer compositing to LCD text rendering. when enabled, this causes the compositor to // be used too aggressively on Retina displays on macOS, with the side effect that the // scrollbar doesn't auto-hide because a compositor layer is present. // https://github.com/rstudio/rstudio/issues/1953 static char disableCompositorPref[] = "--disable-prefer-compositing-to-lcd-text"; arguments.push_back(disableCompositorPref); // speculative fixes for rendering issues on macOS // https://bugs.chromium.org/p/chromium/issues/detail?id=773705 static char disableNativeGpuMemoryBuffers[] = "--disable-native-gpu-memory-buffers"; arguments.push_back(disableNativeGpuMemoryBuffers); static char disableZeroCopy[] = "--disable-zero-copy"; arguments.push_back(disableZeroCopy); static char disableGpuMemoryBufferVideoFrames[] = "--disable-gpu-memory-buffer-video-frames"; arguments.push_back(disableGpuMemoryBufferVideoFrames); #endif // re-assign command line arguments argc = (int) arguments.size(); argv = &arguments[0]; // prepare application for launch boost::scoped_ptr<QApplication> pApp; boost::scoped_ptr<ApplicationLaunch> pAppLaunch; ApplicationLaunch::init(QString::fromUtf8("RStudio"), argc, argv, &pApp, &pAppLaunch); // determine the filename that was passed to us QString filename; #ifdef __APPLE__ // get filename from OpenFile apple-event (pump to ensure delivery) pApp->processEvents(); filename = verifyAndNormalizeFilename( pAppLaunch->startupOpenFileRequest()); #endif // allow all platforms (including OSX) to check the command line. // we include OSX because the way Qt handles apple events is to // re-route them to the first instance to register for events. in // this case (for projects) we use this to initiate a launch // of the application with the project filename on the command line if (filename.isEmpty()) { // get filename from command line arguments if (pApp->arguments().size() > 1) { QString arg = pApp->arguments().at(1); if (arg != QString::fromUtf8(kRunDiagnosticsOption)) filename = verifyAndNormalizeFilename(arg); } } // if we have a filename and it is NOT a project file then see // if we can open it within an existing instance if (isNonProjectFilename(filename)) { if (pAppLaunch->sendMessage(filename)) return 0; } else { // try to register ourselves as a peer for others pAppLaunch->attemptToRegisterPeer(); } // init options from command line desktop::options().initFromCommandLine(pApp->arguments()); // reset log if we are in run-diagnostics mode if (desktop::options().runDiagnostics()) { desktop::reattachConsoleIfNecessary(); initializeStderrLog("rdesktop", core::system::kLogLevelWarning); } initializeSharedSecret(); initializeWorkingDirectory(argc, argv, filename); initializeStartupEnvironment(&filename); Options& options = desktop::options(); if (!prepareEnvironment(options)) return 1; // get install path FilePath installPath; error = core::system::installPath("..", argv[0], &installPath); if (error) { LOG_ERROR(error); return EXIT_FAILURE; } #ifdef _WIN32 RVersion version = detectRVersion(false); #endif // calculate paths to config file, rsession, and desktop scripts FilePath confPath, sessionPath, scriptsPath; bool devMode = false; // check for debug configuration FilePath currentPath = FilePath::safeCurrentPath(installPath); if (currentPath.complete("conf/rdesktop-dev.conf").exists()) { confPath = currentPath.complete("conf/rdesktop-dev.conf"); sessionPath = currentPath.complete("session/rsession"); scriptsPath = currentPath.complete("desktop"); devMode = true; #ifdef _WIN32 if (version.architecture() == ArchX64) sessionPath = installPath.complete("session/x64/rsession"); #endif } // if there is no conf path then release mode if (confPath.empty()) { // default paths (then tweak) sessionPath = installPath.complete("bin/rsession"); scriptsPath = installPath.complete("bin"); // check for win64 binary on windows #ifdef _WIN32 if (version.architecture() == ArchX64) sessionPath = installPath.complete("bin/x64/rsession"); #endif // check for running in a bundle on OSX #ifdef __APPLE__ if (installPath.complete("Info.plist").exists()) { sessionPath = installPath.complete("MacOS/rsession"); scriptsPath = installPath.complete("MacOS"); } #endif } core::system::fixupExecutablePath(&sessionPath); auto* pProxyFactory = new NetworkProxyFactory(); QNetworkProxyFactory::setApplicationProxyFactory(pProxyFactory); // set the scripts path in options desktop::options().setScriptsPath(scriptsPath); // launch session SessionLauncher sessionLauncher(sessionPath, confPath, filename, pAppLaunch.get()); sessionLauncher.launchFirstSession(installPath, devMode, pApp->arguments()); ProgressActivator progressActivator; int result = pApp->exec(); desktop::activation().releaseLicense(); options.cleanUpScratchTempDir(); return result; } CATCH_UNEXPECTED_EXCEPTION } #ifdef _WIN32 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { return main(__argc, __argv); } #endif <commit_msg>disable GPU rasterization (#2093)<commit_after>/* * DesktopMain.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <QtGui> #include <QPushButton> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/scoped_ptr.hpp> #include <core/Log.hpp> #include <core/system/FileScanner.hpp> #include <core/SafeConvert.hpp> #include <core/StringUtils.hpp> #include <core/system/System.hpp> #include <core/system/Environment.hpp> #include <core/r_util/RProjectFile.hpp> #include <core/r_util/RUserData.hpp> #include "DesktopApplicationLaunch.hpp" #include "DesktopSlotBinders.hpp" #include "DesktopDetectRHome.hpp" #include "DesktopUtils.hpp" #include "DesktopSessionLauncher.hpp" #include "DesktopProgressActivator.hpp" #include "DesktopNetworkProxyFactory.hpp" #include "DesktopActivationOverlay.hpp" QProcess* pRSessionProcess; QString sharedSecret; using namespace rstudio; using namespace rstudio::core; using namespace rstudio::desktop; namespace { void initializeSharedSecret() { sharedSecret = QString::number(rand()) + QString::number(rand()) + QString::number(rand()); std::string value = sharedSecret.toUtf8().constData(); core::system::setenv("RS_SHARED_SECRET", value); } void initializeWorkingDirectory(int argc, char* argv[], const QString& filename) { // bail if we've already got a working directory as a result of // a call to openSessionInNewWindow if (!core::system::getenv(kRStudioInitialWorkingDir).empty()) return; // calculate what our initial working directory should be std::string workingDir; // if there is a filename passed to us then use it's path if (filename != QString()) { FilePath filePath(filename.toUtf8().constData()); if (filePath.exists()) { if (filePath.isDirectory()) workingDir = filePath.absolutePath(); else workingDir = filePath.parent().absolutePath(); } } // do additinal detection if necessary if (workingDir.empty()) { // get current path FilePath currentPath = FilePath::safeCurrentPath( core::system::userHomePath()); #if defined(_WIN32) || defined(__APPLE__) // detect whether we were launched from the system application menu // (e.g. Dock, Program File icon, etc.). we do this by checking // whether the executable path is within the current path. if we // weren't launched from the system app menu that set the initial // wd to the current path FilePath exePath; Error error = core::system::executablePath(argv[0], &exePath); if (!error) { if (!exePath.isWithin(currentPath)) workingDir = currentPath.absolutePath(); } else { LOG_ERROR(error); } #else // on linux we take the current working dir if we were launched // from within a terminal if (core::system::stdoutIsTerminal() && (currentPath != core::system::userHomePath())) { workingDir = currentPath.absolutePath(); } #endif } // set the working dir if we have one if (!workingDir.empty()) core::system::setenv(kRStudioInitialWorkingDir, workingDir); } void setInitialProject(const FilePath& projectFile, QString* pFilename) { core::system::setenv(kRStudioInitialProject, projectFile.absolutePath()); pFilename->clear(); } void initializeStartupEnvironment(QString* pFilename) { // if the filename ends with .RData or .rda then this is an // environment file. if it ends with .Rproj then it is // a project file. we handle both cases by setting an environment // var and then resetting the pFilename so it isn't processed // using the standard open file logic FilePath filePath(pFilename->toUtf8().constData()); if (filePath.exists()) { std::string ext = filePath.extensionLowerCase(); // if it is a directory or just an .rdata file then we can see // whether there is a project file we can automatically attach to if (filePath.isDirectory()) { FilePath projectFile = r_util::projectFromDirectory(filePath); if (!projectFile.empty()) { setInitialProject(projectFile, pFilename); } } else if (ext == ".rproj") { setInitialProject(filePath, pFilename); } else if (ext == ".rdata" || ext == ".rda") { core::system::setenv(kRStudioInitialEnvironment, filePath.absolutePath()); pFilename->clear(); } } } QString verifyAndNormalizeFilename(const QString &filename) { if (filename.isNull() || filename.isEmpty()) return QString(); QFileInfo fileInfo(filename); if (fileInfo.exists()) return fileInfo.absoluteFilePath(); else return QString(); } bool isNonProjectFilename(const QString &filename) { if (filename.isNull() || filename.isEmpty()) return false; FilePath filePath(filename.toUtf8().constData()); return filePath.exists() && filePath.extensionLowerCase() != ".rproj"; } bool useChromiumDevtools() { // disable by default due to security concerns // https://bugreports.qt.io/browse/QTBUG-50725 bool useDevtools = false; #ifndef NDEBUG // but enable by default for development builds useDevtools = true; #endif // enable when environment variable is set if (!core::system::getenv("RSTUDIO_USE_CHROMIUM_DEVTOOLS").empty()) { useDevtools = true; } return useDevtools; } } // anonymous namespace int main(int argc, char* argv[]) { core::system::initHook(); try { initializeLang(); if (useChromiumDevtools()) { // use QTcpSocket to find an open port. this is unfortunately a bit racey // but AFAICS there isn't a better solution for port selection QByteArray port; QTcpSocket* pSocket = new QTcpSocket(); if (pSocket->bind()) { quint16 port = pSocket->localPort(); desktopInfo().setChromiumDevtoolsPort(port); core::system::setenv("QTWEBENGINE_REMOTE_DEBUGGING", safe_convert::numberToString(port)); pSocket->close(); } } // initialize log core::system::initializeLog("rdesktop", core::system::kLogLevelWarning, desktop::userLogPath()); // ignore SIGPIPE Error error = core::system::ignoreSignal(core::system::SigPipe); if (error) LOG_ERROR(error); // set application attributes QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // prepare command line arguments static std::vector<char*> arguments(argv, argv + argc); #ifndef NDEBUG // disable web security for development builds (so we can // get access to sourcemaps) static char disableWebSecurity[] = "--disable-web-security"; arguments.push_back(disableWebSecurity); #endif // disable chromium renderer accessibility by default (it can cause // slowdown when used in conjunction with some applications; see e.g. // https://github.com/rstudio/rstudio/issues/1990) if (core::system::getenv("RSTUDIO_ACCESSIBILITY").empty()) { static char disableRendererAccessibility[] = "--disable-renderer-accessibility"; arguments.push_back(disableRendererAccessibility); } #ifdef Q_OS_LINUX // workaround for Qt 5.10.1 bug "Could not find QtWebEngineProcess" // https://bugreports.qt.io/browse/QTBUG-67023 // https://bugreports.qt.io/browse/QTBUG-66346 static char noSandbox[] = "--no-sandbox"; arguments.push_back(noSandbox); #endif #ifdef Q_OS_MAC // don't prefer compositing to LCD text rendering. when enabled, this causes the compositor to // be used too aggressively on Retina displays on macOS, with the side effect that the // scrollbar doesn't auto-hide because a compositor layer is present. // https://github.com/rstudio/rstudio/issues/1953 static char disableCompositorPref[] = "--disable-prefer-compositing-to-lcd-text"; arguments.push_back(disableCompositorPref); // disable gpu rasterization. this appears to successfully work around // some of the weird rendering issues seen while using RStudio. // // https://bugs.chromium.org/p/chromium/issues/detail?id=773705 // https://github.com/rstudio/rstudio/issues/2093 static char disableGpuRasterization[] = "--disable-gpu-rasterization"; arguments.push_back(disableGpuRasterization); #endif // re-assign command line arguments argc = (int) arguments.size(); argv = &arguments[0]; // prepare application for launch boost::scoped_ptr<QApplication> pApp; boost::scoped_ptr<ApplicationLaunch> pAppLaunch; ApplicationLaunch::init(QString::fromUtf8("RStudio"), argc, argv, &pApp, &pAppLaunch); // determine the filename that was passed to us QString filename; #ifdef __APPLE__ // get filename from OpenFile apple-event (pump to ensure delivery) pApp->processEvents(); filename = verifyAndNormalizeFilename( pAppLaunch->startupOpenFileRequest()); #endif // allow all platforms (including OSX) to check the command line. // we include OSX because the way Qt handles apple events is to // re-route them to the first instance to register for events. in // this case (for projects) we use this to initiate a launch // of the application with the project filename on the command line if (filename.isEmpty()) { // get filename from command line arguments if (pApp->arguments().size() > 1) { QString arg = pApp->arguments().at(1); if (arg != QString::fromUtf8(kRunDiagnosticsOption)) filename = verifyAndNormalizeFilename(arg); } } // if we have a filename and it is NOT a project file then see // if we can open it within an existing instance if (isNonProjectFilename(filename)) { if (pAppLaunch->sendMessage(filename)) return 0; } else { // try to register ourselves as a peer for others pAppLaunch->attemptToRegisterPeer(); } // init options from command line desktop::options().initFromCommandLine(pApp->arguments()); // reset log if we are in run-diagnostics mode if (desktop::options().runDiagnostics()) { desktop::reattachConsoleIfNecessary(); initializeStderrLog("rdesktop", core::system::kLogLevelWarning); } initializeSharedSecret(); initializeWorkingDirectory(argc, argv, filename); initializeStartupEnvironment(&filename); Options& options = desktop::options(); if (!prepareEnvironment(options)) return 1; // get install path FilePath installPath; error = core::system::installPath("..", argv[0], &installPath); if (error) { LOG_ERROR(error); return EXIT_FAILURE; } #ifdef _WIN32 RVersion version = detectRVersion(false); #endif // calculate paths to config file, rsession, and desktop scripts FilePath confPath, sessionPath, scriptsPath; bool devMode = false; // check for debug configuration FilePath currentPath = FilePath::safeCurrentPath(installPath); if (currentPath.complete("conf/rdesktop-dev.conf").exists()) { confPath = currentPath.complete("conf/rdesktop-dev.conf"); sessionPath = currentPath.complete("session/rsession"); scriptsPath = currentPath.complete("desktop"); devMode = true; #ifdef _WIN32 if (version.architecture() == ArchX64) sessionPath = installPath.complete("session/x64/rsession"); #endif } // if there is no conf path then release mode if (confPath.empty()) { // default paths (then tweak) sessionPath = installPath.complete("bin/rsession"); scriptsPath = installPath.complete("bin"); // check for win64 binary on windows #ifdef _WIN32 if (version.architecture() == ArchX64) sessionPath = installPath.complete("bin/x64/rsession"); #endif // check for running in a bundle on OSX #ifdef __APPLE__ if (installPath.complete("Info.plist").exists()) { sessionPath = installPath.complete("MacOS/rsession"); scriptsPath = installPath.complete("MacOS"); } #endif } core::system::fixupExecutablePath(&sessionPath); auto* pProxyFactory = new NetworkProxyFactory(); QNetworkProxyFactory::setApplicationProxyFactory(pProxyFactory); // set the scripts path in options desktop::options().setScriptsPath(scriptsPath); // launch session SessionLauncher sessionLauncher(sessionPath, confPath, filename, pAppLaunch.get()); sessionLauncher.launchFirstSession(installPath, devMode, pApp->arguments()); ProgressActivator progressActivator; int result = pApp->exec(); desktop::activation().releaseLicense(); options.cleanUpScratchTempDir(); return result; } CATCH_UNEXPECTED_EXCEPTION } #ifdef _WIN32 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { return main(__argc, __argv); } #endif <|endoftext|>
<commit_before>#include <torrentsync/utils/Buffer.h> #include <torrentsync/dht/RoutingTable.h> #include <torrentsync/dht/message/query/Ping.h> #include <torrentsync/dht/message/query/FindNode.h> #include <torrentsync/dht/Callback.h> #include <torrentsync/utils/log/Logger.h> #include <exception> // for not implemented stuff namespace torrentsync { namespace dht { using namespace torrentsync; namespace msg = dht::message; void RoutingTable::recvMessage( const boost::system::error_code& error, utils::Buffer buffer, std::size_t bytes_transferred, const boost::asio::ip::udp::endpoint& sender) { namespace msg = dht::message; buffer.resize(bytes_transferred); LOG(DEBUG,"Routingtable * received a message from " << sender << " e:" << error.message()); LOG(DATA,"RoutingTable * " << sender << " received " << bytes_transferred << " " << pretty_print(buffer)); // check for errors if (error) { LOG(ERROR, "RoutingTable * recvMessage error: " << error << " " << error.message()); return; } // parse the message try { msg::AnyMessage message = msg::parseMessage(buffer); LOG(DATA, "RoutingTable * message parsed: " << msg::getString(message)); processIncomingMessage(message, buffer, sender); } catch (const msg::MessageException& e) { LOG(ERROR, "RoutingTable * message parsing failed" << e.what()); LOG(DATA, "RoutingTable * message parsing failed: " << pretty_print(buffer)); // @TODO send malformed message error } } void RoutingTable::processIncomingMessage( torrentsync::dht::message::AnyMessage& message, const utils::Buffer& buffer, const boost::asio::ip::udp::endpoint& sender) { const auto type = msg::getType(message); // fetch the node from the tree table boost::optional<NodeSPtr> node; { std::lock_guard<std::mutex> lock_table(_table_mutex); node = _table.getNode(NodeData(msg::getID(message))); } if (!!node) // we already know the node { const auto endpoint = (*node)->getEndpoint(); // message dropped if t he data is still fresh but with a different IP. if (!!endpoint && *endpoint != sender) return; } else { // create new node const utils::Buffer id = msg::getID(message); LOG(DEBUG, "New node: " << pretty_print(id) << " addr: " << sender); node = boost::optional<NodeSPtr>(NodeSPtr(new Node(id, sender))); } // if a callback is registered call it instead of the normal flow auto callback = getCallback(message); if(!!callback) { callback->call(message, **node); } else { LOG(DEBUG,"Callback not found"); const auto* query = boost::get<msg::query::Query>(&message); if (query != nullptr) { try { const auto* ping = boost::get<msg::query::Ping>(query); if (ping != nullptr) { handleQuery(*ping, **node); } const auto* find_node = boost::get<msg::query::FindNode>(query); if (find_node != nullptr) { handleQuery(*find_node, **node); } else { LOG(ERROR, "RoutingTable * unknown query type: " << pretty_print(buffer) << " - " << msg::getString(message)); } } catch ( const dht::message::MessageException& e ) { LOG(ERROR, " RoutingTable * malformed message: " << msg::getString(message)); } } else if (type == msg::Type::Reply) { // Replies should be all managed by a Callback // Log the message and drop it, it's an unexpected reply. // Maybe it's a reply that came to late or what not. LOG(INFO, "RoutingTable * received unexpected reply: \n" << msg::getString(message) << " " << sender); } else if ( type == msg::Type::Error ) { // same be behaviour as a Reply without a callback LOG(WARN, "RoutingTable * received unexpected error: \n" << msg::getString(message) << " " << sender); } else { LOG(ERROR, "RoutingTable * unknown message type: " << pretty_print(buffer) << " - " << msg::getString(message)); } } // @TODO post-process // - add the node to the known addresses // - update node statistics // - add the node to the tree in case it's missing, or set it good // - update transaction id if it was a query } } // dht } // torrentsync <commit_msg>Removed \n from log lines<commit_after>#include <torrentsync/utils/Buffer.h> #include <torrentsync/dht/RoutingTable.h> #include <torrentsync/dht/message/query/Ping.h> #include <torrentsync/dht/message/query/FindNode.h> #include <torrentsync/dht/Callback.h> #include <torrentsync/utils/log/Logger.h> #include <exception> // for not implemented stuff namespace torrentsync { namespace dht { using namespace torrentsync; namespace msg = dht::message; void RoutingTable::recvMessage( const boost::system::error_code& error, utils::Buffer buffer, std::size_t bytes_transferred, const boost::asio::ip::udp::endpoint& sender) { namespace msg = dht::message; buffer.resize(bytes_transferred); LOG(DEBUG,"Routingtable * received a message from " << sender << " e:" << error.message()); LOG(DATA,"RoutingTable * " << sender << " received " << bytes_transferred << " " << pretty_print(buffer)); // check for errors if (error) { LOG(ERROR, "RoutingTable * recvMessage error: " << error << " " << error.message()); return; } // parse the message try { msg::AnyMessage message = msg::parseMessage(buffer); LOG(DATA, "RoutingTable * message parsed: " << msg::getString(message)); processIncomingMessage(message, buffer, sender); } catch (const msg::MessageException& e) { LOG(ERROR, "RoutingTable * message parsing failed" << e.what()); LOG(DATA, "RoutingTable * message parsing failed: " << pretty_print(buffer)); // @TODO send malformed message error } } void RoutingTable::processIncomingMessage( torrentsync::dht::message::AnyMessage& message, const utils::Buffer& buffer, const boost::asio::ip::udp::endpoint& sender) { const auto type = msg::getType(message); // fetch the node from the tree table boost::optional<NodeSPtr> node; { std::lock_guard<std::mutex> lock_table(_table_mutex); node = _table.getNode(NodeData(msg::getID(message))); } if (!!node) // we already know the node { const auto endpoint = (*node)->getEndpoint(); // message dropped if t he data is still fresh but with a different IP. if (!!endpoint && *endpoint != sender) return; } else { // create new node const utils::Buffer id = msg::getID(message); LOG(DEBUG, "New node: " << pretty_print(id) << " addr: " << sender); node = boost::optional<NodeSPtr>(NodeSPtr(new Node(id, sender))); } // if a callback is registered call it instead of the normal flow auto callback = getCallback(message); if(!!callback) { callback->call(message, **node); } else { LOG(DEBUG,"Callback not found"); const auto* query = boost::get<msg::query::Query>(&message); if (query != nullptr) { try { const auto* ping = boost::get<msg::query::Ping>(query); if (ping != nullptr) { handleQuery(*ping, **node); } const auto* find_node = boost::get<msg::query::FindNode>(query); if (find_node != nullptr) { handleQuery(*find_node, **node); } else { LOG(ERROR, "RoutingTable * unknown query type: " << pretty_print(buffer) << " - " << msg::getString(message)); } } catch ( const dht::message::MessageException& e ) { LOG(ERROR, " RoutingTable * malformed message: " << msg::getString(message)); } } else if (type == msg::Type::Reply) { // Replies should be all managed by a Callback // Log the message and drop it, it's an unexpected reply. // Maybe it's a reply that came to late or what not. LOG(INFO, "RoutingTable * received unexpected reply: n" << msg::getString(message) << " " << sender); } else if ( type == msg::Type::Error ) { // same be behaviour as a Reply without a callback LOG(WARN, "RoutingTable * received unexpected error: n" << msg::getString(message) << " " << sender); } else { LOG(ERROR, "RoutingTable * unknown message type: " << pretty_print(buffer) << " - " << msg::getString(message)); } } // @TODO post-process // - add the node to the known addresses // - update node statistics // - add the node to the tree in case it's missing, or set it good // - update transaction id if it was a query } } // dht } // torrentsync <|endoftext|>
<commit_before>// MIT License // // Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl // // 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 "spaghetti/registry.h" #include <vector> #include "filesystem.h" #include "shared_library.h" #include "elements/all.h" #include "nodes/all.h" #include "spaghetti/logger.h" #include "spaghetti/version.h" inline void init_resources() { Q_INIT_RESOURCE(icons); } namespace spaghetti { struct Registry::PIMPL { using Plugins = std::vector<std::shared_ptr<SharedLibrary>>; using MetaInfos = std::vector<MetaInfo>; MetaInfos metaInfos{}; Plugins plugins{}; }; Registry &Registry::get() { static Registry s_registry{}; return s_registry; } Registry::~Registry() = default; Registry::Registry() : m_pimpl{ std::make_unique<PIMPL>() } { log::init(); log::info("Spaghetti version: {}, git: {}@{}, build date: {}, {}", version::STRING, version::BRANCH, version::COMMIT_SHORT_HASH, __DATE__, __TIME__); } void Registry::registerInternalElements() { init_resources(); using namespace elements; registerElement<Package>("Package", ":/logic/package.png"); registerElement<gates::And>("AND (Bool)", ":/gates/and.png"); registerElement<gates::Nand>("NAND (Bool)", ":/gates/nand.png"); registerElement<gates::Nor>("NOR (Bool)", ":/gates/nor.png"); registerElement<gates::Not>("NOT (Bool)", ":/gates/not.png"); registerElement<gates::Or>("OR (Bool)", ":/gates/or.png"); registerElement<logic::IfGreaterEqual>("If A >= B (Float)", ":/unknown.png"); registerElement<logic::IfGreater>("If A > B (Float)", ":/unknown.png"); registerElement<logic::IfEqual>("If A == B (Float)", ":/unknown.png"); registerElement<logic::IfLower>("If A < B (Float)", ":/unknown.png"); registerElement<logic::IfLowerEqual>("If A <= B (Float)", ":/unknown.png"); registerElement<logic::MultiplexerInt>("Multiplexer (Int)", ":/unknown.png"); registerElement<logic::DemultiplexerInt>("Demultiplexer (Int)", ":/unknown.png"); registerElement<logic::Blinker, nodes::logic::Blinker>("Blinker (Bool)", ":/unknown.png"); registerElement<logic::Clock, nodes::logic::Clock>("Clock (ms)", ":/logic/clock.png"); registerElement<logic::Switch>("Switch (Int)", ":/logic/switch.png"); registerElement<math::Abs>("Abs (Float)", ":/unknown.png"); registerElement<math::Add>("Add (Float)", ":/unknown.png"); registerElement<math::AddIf>("Add If (Float)", ":/unknown.png"); registerElement<math::Subtract>("Subtract (Float)", ":/unknown.png"); registerElement<math::SubtractIf>("Subtract If (Float)", ":/unknown.png"); registerElement<math::Divide>("Divide (Float)", ":/unknown.png"); registerElement<math::DivideIf>("Divide If (Float)", ":/unknown.png"); registerElement<math::Multiply>("Multiply (Float)", ":/unknown.png"); registerElement<math::MultiplyIf>("Multiply If (Float)", ":/unknown.png"); registerElement<math::Cos>("Cos (Rad)", ":/unknown.png"); registerElement<math::Sin>("Sin (Rad)", ":/unknown.png"); registerElement<ui::FloatInfo, nodes::ui::FloatInfo>("Info (Float)", ":/values/const_float.png"); registerElement<ui::IntInfo, nodes::ui::IntInfo>("Info (Int)", ":/values/const_int.png"); registerElement<ui::PushButton, nodes::ui::PushButton>("Push Button (Bool)", ":/ui/push_button.png"); registerElement<ui::ToggleButton, nodes::ui::ToggleButton>("Toggle Button (Bool)", ":/ui/toggle_button.png"); registerElement<values::ConstBool, nodes::values::ConstBool>("Const value (Bool)", ":/values/const_bool.png"); registerElement<values::ConstFloat, nodes::values::ConstFloat>("Const value (Float)", ":/values/const_float.png"); registerElement<values::ConstInt, nodes::values::ConstInt>("Const value (Int)", ":/values/const_int.png"); registerElement<values::RandomBool>("Random value (Bool)", ":/values/random_value.png"); registerElement<values::Degree2Radian>("Convert angle (Deg2Rad)", ":/unknown.png"); registerElement<values::Radian2Degree>("Convert angle (Rad2Deg)", ":/unknown.png"); registerElement<values::Int2Float>("Convert value (Int2Float)", ":/unknown.png"); registerElement<values::Float2Int>("Convert value (Float2Int)", ":/unknown.png"); registerElement<values::MinInt>("Minimum value (Int)", ":/unknown.png"); registerElement<values::MaxInt>("Maximum value (Int)", ":/unknown.png"); registerElement<values::MinFloat>("Minimum value (Float)", ":/unknown.png"); registerElement<values::MaxFloat>("Maximum value (Float)", ":/unknown.png"); registerElement<values::ClampFloat>("Clamp value (Float)", ":/unknown.png"); registerElement<values::ClampInt>("Clamp value (Int)", ":/unknown.png"); } static std::string get_application_path() { #ifndef MAX_PATH #define MAX_PATH 4098 #endif std::string name{}; name.resize(MAX_PATH); #if defined(_WIN64) || defined(_WIN32) GetModuleFileNameA(0, const_cast<LPSTR>(name.c_str()), MAX_PATH); #elif defined(__linux__) readlink("/proc/self/exe", &name[0], MAX_PATH); #endif name.resize(strlen(name.data())); return name; } void Registry::loadPlugins() { fs::path const APP_PATH{ fs::path{ get_application_path() }.parent_path() }; fs::path const LIB_PATH{ fs::canonical(fs::path{ APP_PATH.string() + "/../lib" }) }; fs::path const SYSTEM_PLUGINS_DIR{ LIB_PATH / "spaghetti" }; fs::path const HOME_DIR{ getenv("HOME") }; fs::path const USER_PLUGINS_DIR{ fs::absolute(HOME_DIR / ".config/spaghetti/plugins") }; fs::create_directories(USER_PLUGINS_DIR); auto loadFrom = [this](fs::path const &a_path) { spaghetti::log::info("Loading plugins from {}", a_path.string()); if (!fs::is_directory(a_path)) return; for (auto const &ENTRY : fs::directory_iterator(a_path)) { spaghetti::log::info("Loading {}..", ENTRY.path().string()); if (!(fs::is_regular_file(ENTRY) || fs::is_symlink(ENTRY))) continue; std::error_code error{}; auto plugin = std::make_shared<SharedLibrary>(ENTRY, error); if (error.value() != 0 || !plugin->has("register_plugin")) continue; auto registerPlugin = plugin->get<void(Registry &)>("register_plugin"); registerPlugin(*this); m_pimpl->plugins.emplace_back(std::move(plugin)); } }; loadFrom(USER_PLUGINS_DIR); loadFrom(SYSTEM_PLUGINS_DIR); } Element *Registry::createElement(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); assert(META_INFO.cloneElement); return META_INFO.cloneElement(); } Node *Registry::createNode(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); assert(META_INFO.cloneNode); return META_INFO.cloneNode(); } std::string Registry::elementName(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); return META_INFO.name; } std::string Registry::elementIcon(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); return META_INFO.icon; } void Registry::addElement(MetaInfo &a_metaInfo) { auto &metaInfos = m_pimpl->metaInfos; metaInfos.push_back(std::move(a_metaInfo)); } bool Registry::hasElement(string::hash_t const a_hash) const { auto const &META_INFOS = m_pimpl->metaInfos; auto const IT = std::find_if(std::begin(META_INFOS), std::end(META_INFOS), [a_hash](auto const &a_metaInfo) { return a_metaInfo.hash == a_hash; }); return IT != std::end(META_INFOS); } size_t Registry::size() const { auto const &META_INFOS = m_pimpl->metaInfos; return META_INFOS.size(); } Registry::MetaInfo const &Registry::metaInfoFor(string::hash_t const a_hash) const { auto &metaInfos = m_pimpl->metaInfos; assert(hasElement(a_hash)); auto const IT = std::find_if(std::begin(metaInfos), std::end(metaInfos), [a_hash](auto const &a_metaInfo) { return a_metaInfo.hash == a_hash; }); return *IT; } Registry::MetaInfo const &Registry::metaInfoAt(size_t const a_index) const { auto const &META_INFOS = m_pimpl->metaInfos; return META_INFOS[a_index]; } } // namespace spaghetti <commit_msg>Move get_application_path to the top<commit_after>// MIT License // // Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl // // 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 "spaghetti/registry.h" #include <vector> #include "filesystem.h" #include "shared_library.h" #include "elements/all.h" #include "nodes/all.h" #include "spaghetti/logger.h" #include "spaghetti/version.h" inline void init_resources() { Q_INIT_RESOURCE(icons); } static std::string get_application_path() { #ifndef MAX_PATH #define MAX_PATH 4098 #endif std::string name{}; name.resize(MAX_PATH); #if defined(_WIN64) || defined(_WIN32) GetModuleFileNameA(0, const_cast<LPSTR>(name.c_str()), MAX_PATH); #elif defined(__linux__) readlink("/proc/self/exe", &name[0], MAX_PATH); #endif name.resize(strlen(name.data())); return name; } namespace spaghetti { struct Registry::PIMPL { using Plugins = std::vector<std::shared_ptr<SharedLibrary>>; using MetaInfos = std::vector<MetaInfo>; MetaInfos metaInfos{}; Plugins plugins{}; }; Registry &Registry::get() { static Registry s_registry{}; return s_registry; } Registry::~Registry() = default; Registry::Registry() : m_pimpl{ std::make_unique<PIMPL>() } { log::init(); log::info("Spaghetti version: {}, git: {}@{}, build date: {}, {}", version::STRING, version::BRANCH, version::COMMIT_SHORT_HASH, __DATE__, __TIME__); } void Registry::registerInternalElements() { init_resources(); using namespace elements; registerElement<Package>("Package", ":/logic/package.png"); registerElement<gates::And>("AND (Bool)", ":/gates/and.png"); registerElement<gates::Nand>("NAND (Bool)", ":/gates/nand.png"); registerElement<gates::Nor>("NOR (Bool)", ":/gates/nor.png"); registerElement<gates::Not>("NOT (Bool)", ":/gates/not.png"); registerElement<gates::Or>("OR (Bool)", ":/gates/or.png"); registerElement<logic::IfGreaterEqual>("If A >= B (Float)", ":/unknown.png"); registerElement<logic::IfGreater>("If A > B (Float)", ":/unknown.png"); registerElement<logic::IfEqual>("If A == B (Float)", ":/unknown.png"); registerElement<logic::IfLower>("If A < B (Float)", ":/unknown.png"); registerElement<logic::IfLowerEqual>("If A <= B (Float)", ":/unknown.png"); registerElement<logic::MultiplexerInt>("Multiplexer (Int)", ":/unknown.png"); registerElement<logic::DemultiplexerInt>("Demultiplexer (Int)", ":/unknown.png"); registerElement<logic::Blinker, nodes::logic::Blinker>("Blinker (Bool)", ":/unknown.png"); registerElement<logic::Clock, nodes::logic::Clock>("Clock (ms)", ":/logic/clock.png"); registerElement<logic::Switch>("Switch (Int)", ":/logic/switch.png"); registerElement<math::Abs>("Abs (Float)", ":/unknown.png"); registerElement<math::Add>("Add (Float)", ":/unknown.png"); registerElement<math::AddIf>("Add If (Float)", ":/unknown.png"); registerElement<math::Subtract>("Subtract (Float)", ":/unknown.png"); registerElement<math::SubtractIf>("Subtract If (Float)", ":/unknown.png"); registerElement<math::Divide>("Divide (Float)", ":/unknown.png"); registerElement<math::DivideIf>("Divide If (Float)", ":/unknown.png"); registerElement<math::Multiply>("Multiply (Float)", ":/unknown.png"); registerElement<math::MultiplyIf>("Multiply If (Float)", ":/unknown.png"); registerElement<math::Cos>("Cos (Rad)", ":/unknown.png"); registerElement<math::Sin>("Sin (Rad)", ":/unknown.png"); registerElement<ui::FloatInfo, nodes::ui::FloatInfo>("Info (Float)", ":/values/const_float.png"); registerElement<ui::IntInfo, nodes::ui::IntInfo>("Info (Int)", ":/values/const_int.png"); registerElement<ui::PushButton, nodes::ui::PushButton>("Push Button (Bool)", ":/ui/push_button.png"); registerElement<ui::ToggleButton, nodes::ui::ToggleButton>("Toggle Button (Bool)", ":/ui/toggle_button.png"); registerElement<values::ConstBool, nodes::values::ConstBool>("Const value (Bool)", ":/values/const_bool.png"); registerElement<values::ConstFloat, nodes::values::ConstFloat>("Const value (Float)", ":/values/const_float.png"); registerElement<values::ConstInt, nodes::values::ConstInt>("Const value (Int)", ":/values/const_int.png"); registerElement<values::RandomBool>("Random value (Bool)", ":/values/random_value.png"); registerElement<values::Degree2Radian>("Convert angle (Deg2Rad)", ":/unknown.png"); registerElement<values::Radian2Degree>("Convert angle (Rad2Deg)", ":/unknown.png"); registerElement<values::Int2Float>("Convert value (Int2Float)", ":/unknown.png"); registerElement<values::Float2Int>("Convert value (Float2Int)", ":/unknown.png"); registerElement<values::MinInt>("Minimum value (Int)", ":/unknown.png"); registerElement<values::MaxInt>("Maximum value (Int)", ":/unknown.png"); registerElement<values::MinFloat>("Minimum value (Float)", ":/unknown.png"); registerElement<values::MaxFloat>("Maximum value (Float)", ":/unknown.png"); registerElement<values::ClampFloat>("Clamp value (Float)", ":/unknown.png"); registerElement<values::ClampInt>("Clamp value (Int)", ":/unknown.png"); } void Registry::loadPlugins() { fs::path const APP_PATH{ fs::path{ get_application_path() }.parent_path() }; fs::path const LIB_PATH{ fs::canonical(fs::path{ APP_PATH.string() + "/../lib" }) }; fs::path const SYSTEM_PLUGINS_DIR{ LIB_PATH / "spaghetti" }; fs::path const HOME_DIR{ getenv("HOME") }; fs::path const USER_PLUGINS_DIR{ fs::absolute(HOME_DIR / ".config/spaghetti/plugins") }; fs::create_directories(USER_PLUGINS_DIR); auto loadFrom = [this](fs::path const &a_path) { spaghetti::log::info("Loading plugins from {}", a_path.string()); if (!fs::is_directory(a_path)) return; for (auto const &ENTRY : fs::directory_iterator(a_path)) { spaghetti::log::info("Loading {}..", ENTRY.path().string()); if (!(fs::is_regular_file(ENTRY) || fs::is_symlink(ENTRY))) continue; std::error_code error{}; auto plugin = std::make_shared<SharedLibrary>(ENTRY, error); if (error.value() != 0 || !plugin->has("register_plugin")) continue; auto registerPlugin = plugin->get<void(Registry &)>("register_plugin"); registerPlugin(*this); m_pimpl->plugins.emplace_back(std::move(plugin)); } }; loadFrom(USER_PLUGINS_DIR); loadFrom(SYSTEM_PLUGINS_DIR); } Element *Registry::createElement(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); assert(META_INFO.cloneElement); return META_INFO.cloneElement(); } Node *Registry::createNode(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); assert(META_INFO.cloneNode); return META_INFO.cloneNode(); } std::string Registry::elementName(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); return META_INFO.name; } std::string Registry::elementIcon(string::hash_t const a_hash) { auto const &META_INFO = metaInfoFor(a_hash); return META_INFO.icon; } void Registry::addElement(MetaInfo &a_metaInfo) { auto &metaInfos = m_pimpl->metaInfos; metaInfos.push_back(std::move(a_metaInfo)); } bool Registry::hasElement(string::hash_t const a_hash) const { auto const &META_INFOS = m_pimpl->metaInfos; auto const IT = std::find_if(std::begin(META_INFOS), std::end(META_INFOS), [a_hash](auto const &a_metaInfo) { return a_metaInfo.hash == a_hash; }); return IT != std::end(META_INFOS); } size_t Registry::size() const { auto const &META_INFOS = m_pimpl->metaInfos; return META_INFOS.size(); } Registry::MetaInfo const &Registry::metaInfoFor(string::hash_t const a_hash) const { auto &metaInfos = m_pimpl->metaInfos; assert(hasElement(a_hash)); auto const IT = std::find_if(std::begin(metaInfos), std::end(metaInfos), [a_hash](auto const &a_metaInfo) { return a_metaInfo.hash == a_hash; }); return *IT; } Registry::MetaInfo const &Registry::metaInfoAt(size_t const a_index) const { auto const &META_INFOS = m_pimpl->metaInfos; return META_INFOS[a_index]; } } // namespace spaghetti <|endoftext|>
<commit_before>/** * @file CallableTcp.hpp * @brief CallableTcp class prototype. * @author zer0 * @date 2016-12-29 * @date 2017-02-01 (Move package: libtbag/uv -> libtbag/uvpp) */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_UVPP_EX_CALLABLETCP_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_UVPP_EX_CALLABLETCP_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/uvpp/Loop.hpp> #include <libtbag/uvpp/Tcp.hpp> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace uvpp { namespace ex { /** * CallableTcp class prototype. * * @author zer0 * @date 2016-12-29 */ class TBAG_API CallableTcp : public Tcp { public: // @formatter:off struct TBAG_API Callback { // Event of Tcp. virtual void onConnect(ConnectRequest & request, uerr code) { /* EMPTY. */ } // Event of Stream. virtual void onShutdown(ShutdownRequest & request, uerr code) { /* EMPTY. */ } virtual void onConnection(uerr code) { /* EMPTY. */ } virtual binf onAlloc(std::size_t suggested_size) { return binf(); } virtual void onRead(uerr code, char const * buffer, std::size_t size) { /* EMPTY. */ } virtual void onWrite(WriteRequest & request, uerr code) { /* EMPTY. */ } // Event of Handle. virtual void onClose() { /* EMPTY. */ } virtual void onWalk(void * arg) { /* EMPTY. */ } }; // @formatter:on private: Callback * _cb; public: // @formatter:off CallableTcp() : Tcp(), _cb(nullptr) { /* EMPTY. */ } CallableTcp(Loop & l, Callback * c = nullptr) : Tcp(l), _cb(c) { /* EMPTY. */ } virtual ~CallableTcp() { /* EMPTY. */ } // @formatter:on public: inline void setCallback(Callback * callback) TBAG_NOEXCEPT { _cb = callback; } public: // @formatter:off virtual void onConnect(ConnectRequest & request, uerr code) override { if (_cb != nullptr) { _cb->onConnect(request, code); } } virtual void onShutdown(ShutdownRequest & request, uerr code) override { if (_cb != nullptr) { _cb->onShutdown(request, code); } } virtual void onConnection(uerr code) override { if (_cb != nullptr) { _cb->onConnection(code); } } virtual binf onAlloc(std::size_t suggested_size) override { if (_cb != nullptr) { return _cb->onAlloc(suggested_size); } return binf(); } virtual void onRead(uerr code, char const * buffer, std::size_t size) override { if (_cb != nullptr) { _cb->onRead(code, buffer, size); } } virtual void onWrite(WriteRequest & request, uerr code) override { if (_cb != nullptr) { _cb->onWrite(request, code); } } virtual void onClose() override { if (_cb != nullptr) { _cb->onClose(); } } virtual void onWalk(void * arg) override { if (_cb != nullptr) { _cb->onWalk(arg); } } // @formatter:on }; } // namespace ex } // namespace uvpp // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_UVPP_EX_CALLABLETCP_HPP__ <commit_msg>Remove unused header file.<commit_after><|endoftext|>
<commit_before>/* * Copyright 2011 Thomas Fidler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/lexical_cast.hpp> #include <iostream> #include "../Data.h" #include "../Exception.h" #include "../Node.h" #include "../Operator.h" #include "../Thread.h" #include "XmlWriterImpl.h" using namespace xercesc; namespace stream { namespace impl { XmlWriterImpl::XmlWriterImpl() : m_stream(0), m_impl(0), m_doc(0), m_strElement(0), m_filename("") { try { XMLPlatformUtils::Initialize(); // Initialize Xerces infrastructure } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); std::cerr << "Error during initialization! :\n" << message << "\n"; XMLString::release(&message); return; } try { m_impl = DOMImplementationRegistry::getDOMImplementation(Str2Xml("")); } catch(DOMException& e) { throw InternalError("Error in Xerces-C."); } catch(XMLException& e) { throw InternalError("Error in Xerces-C."); } } const unsigned int XmlWriterImpl::translateOperatorPointerToID(const Operator* const op) const { unsigned int count_op = 0; for(std::vector<Operator*>::const_iterator iter_op = m_stream->operators().begin(); iter_op != m_stream->operators().end(); ++iter_op, ++count_op) { if ((*iter_op) == op) { return count_op; } } throw InternalError("Operator does not exist."); } void XmlWriterImpl::createInputNodes(const Thread* const currThr, DOMElement* const thrElement) { //Add InputNode branches (tree structure: Stream:Thread:InputNode) //Processed for each InputNode belonging to Thread (multiple entries for each Thread possible) for(std::vector<Node>::const_iterator iter_inNodes = currThr->nodeSequence().begin(); iter_inNodes != currThr->nodeSequence().end(); ++iter_inNodes) { //Create current InputNode being child of Thread DOMElement* inNodeElement = m_doc->createElement(Str2Xml("InputNode")); thrElement->appendChild(inNodeElement); //Create attribute operator of current InputNode (one for each InputNode possible) DOMAttr* opAttr = m_doc->createAttribute(Str2Xml("operator")); unsigned int opId = translateOperatorPointerToID((*iter_inNodes).op()); opAttr->setValue(Str2Xml(boost::lexical_cast<std::string>(opId).c_str())); inNodeElement->setAttributeNode(opAttr); //Create attribute input of current InputNode (one for each InputNode possible) DOMAttr* inputAttr = m_doc->createAttribute(Str2Xml("input")); inputAttr->setValue(Str2Xml(boost::lexical_cast<std::string>((*iter_inNodes).id()).c_str())); inNodeElement->setAttributeNode(inputAttr); } } void XmlWriterImpl::createThreads(const std::vector<Thread*> threads) { //Add Thread branches (tree structure: Stream:Thread) //Processed for each thread belonging to the stream object (multiple entries for stream possible) for(std::vector<Thread*>::const_iterator iter_thr = threads.begin(); iter_thr != threads.end(); ++iter_thr) { //Create current Thread being child of Stream (one for each Thread possible) DOMElement* thrElement = m_doc->createElement(Str2Xml("Thread")); m_strElement->appendChild(thrElement); //Create attribute name of Thread (one for each Thread possible) DOMAttr* nameAttr = m_doc->createAttribute(Str2Xml("name")); nameAttr->setValue(Str2Xml((*iter_thr)->name().c_str())); thrElement->setAttributeNode(nameAttr); //Create InputNodes of Thread (multiple entries for each Thread possible) createInputNodes((*iter_thr), thrElement); } } void XmlWriterImpl::createParameters(const Operator* const currOp, DOMElement* const opElement) { //Add parameter branches (tree structure: stream:operator:parameter) //Processed for each parameter belonging to current operator currOp (multiple entries for each operator possible) for(std::vector<const Parameter*>::const_iterator iter_par = currOp->info()->parameters().begin(); iter_par != currOp->info()->parameters().end(); ++iter_par) { //Create current parameter entry param being child of current operator op (one for each parameter possible) DOMElement* parElement = m_doc->createElement(Str2Xml("Parameter")); opElement->appendChild(parElement); //Create attribute id of current parameter param (one for each parameter possible) DOMAttr* id = m_doc->createAttribute(Str2Xml("id")); id->setValue(Str2Xml(boost::lexical_cast<std::string>((*iter_par)->id()).c_str())); parElement->setAttributeNode(id); createData(*iter_par, currOp, parElement); } } void XmlWriterImpl::createData(const Parameter*const currPar, const Operator*const currOp, DOMElement*const parElement) { //Add Data branch //Create Data entry data being child of current param (one for each parameter possible) DOMElement* dataElement = m_doc->createElement(Str2Xml("Data")); parElement->appendChild(dataElement); //Create attribute type of current parameter param (one for each parameter possible) DOMAttr* typeAttr = m_doc->createAttribute(Str2Xml("type")); typeAttr->setValue(Str2Xml(currOp->getParameter(currPar->id()).type().c_str())); dataElement->setAttributeNode(typeAttr); //Create attribute package of current parameter param (one for each parameter possible) DOMAttr* packageAttr = m_doc->createAttribute(Str2Xml("package")); packageAttr->setValue(Str2Xml(currOp->getParameter(currPar->id()).package().c_str())); dataElement->setAttributeNode(packageAttr); //Create value of current parameter param (one for each parameter possible) //First, create unique input parameter name for function Data::serialize() std::string str = m_stream->name() + "_" + "op" + boost::lexical_cast<std::string>(translateOperatorPointerToID(currOp)) + "_" + "parameter" + boost::lexical_cast<std::string>(currPar->id()); DOMText* value = m_doc->createTextNode(Str2Xml(currOp->getParameter(currPar->id()).serialize(str, impl::XmlUtilities::computePath(m_filename)).c_str())); dataElement->appendChild(value); } void XmlWriterImpl::createInputs(const stream::Operator*const currOp, DOMElement*const opElement) { for(std::vector<const Description*>::const_iterator iter_in = currOp->info()->inputs().begin(); iter_in != currOp->info()->inputs().end(); ++iter_in) { //Get the source node Node node = m_stream->source(currOp, (*iter_in)->id()); //Create Input only for connected operators if (! node.empty()) { //Create Input entry in being child of current operator op (one for each parameter possible) DOMElement* inElement = m_doc->createElement(Str2Xml("Input")); opElement->appendChild(inElement); //Create attribute id of current input in (one for each input possible) DOMAttr* idAttr = m_doc->createAttribute(Str2Xml("id")); idAttr->setValue(Str2Xml(boost::lexical_cast<std::string>((*iter_in)->id()).c_str())); inElement->setAttributeNode(idAttr); //Get the id of the source operator unsigned sourceOp = translateOperatorPointerToID(node.op()); //Write the id of the source operator DOMAttr* opAttr = m_doc->createAttribute(Str2Xml("operator")); opAttr->setValue(Str2Xml(boost::lexical_cast<std::string>(sourceOp).c_str())); inElement->setAttributeNode(opAttr); //Write the id of the output DOMAttr* outAttr = m_doc->createAttribute(Str2Xml("output")); outAttr->setValue(Str2Xml(boost::lexical_cast<std::string>(node.id()).c_str())); inElement->setAttributeNode(outAttr); } } } void XmlWriterImpl::createOperators(const std::vector<Operator*> operators) { //Add operator branches (tree structure: stream:operator) //Processed for each operator belonging to the stream object (multiple entries for stream possible) for(std::vector<Operator*>::const_iterator iter_op = operators.begin(); iter_op != operators.end(); ++iter_op) { //Create current operator entry op being child of stream (one for each operator possible) DOMElement* opElement = m_doc->createElement(Str2Xml("Operator")); m_strElement->appendChild(opElement); //Create attribute id of current operator op (one for each operator possible) DOMAttr* idAttr = m_doc->createAttribute(Str2Xml("id")); idAttr->setValue(Str2Xml(boost::lexical_cast<std::string>(translateOperatorPointerToID(*iter_op)).c_str())); opElement->setAttributeNode(idAttr); //Create attribute package of current operator op (one for each operator possible) DOMAttr* packAttr = m_doc->createAttribute(Str2Xml("package")); packAttr->setValue(Str2Xml((*iter_op)->info()->package().c_str())); opElement->setAttributeNode(packAttr); //Create attribute type of current operator op (one for each operator possible) DOMAttr* typeAttr = m_doc->createAttribute(Str2Xml("type")); typeAttr->setValue(Str2Xml((*iter_op)->info()->type().c_str())); opElement->setAttributeNode(typeAttr); //Create attribute name of current operator op (one for each operator possible) DOMAttr* nameAttr = m_doc->createAttribute(Str2Xml("name")); nameAttr->setValue(Str2Xml((*iter_op)->name().c_str())); opElement->setAttributeNode(nameAttr); createParameters((*iter_op), opElement); createInputs((*iter_op), opElement); } } void XmlWriterImpl::write(const std::string& filename, Stream& stream) { if (filename.empty()) { throw WrongArgument("Invalid file name."); } if (&stream == 0) { throw WrongArgument("Invalid argument: Null pointer."); } m_stream = &stream; m_filename = filename; try { //Create Stream branch m_doc = m_impl->createDocument(0, Str2Xml("Stream"), 0); m_strElement = m_doc->getDocumentElement(); //Create attribute name of Stream DOMAttr* nameAttr = m_doc->createAttribute(Str2Xml("name")); nameAttr->setValue(Str2Xml(m_stream->name().c_str())); m_strElement->setAttributeNode(nameAttr); //Create Operators of Stream (multiple entries for Stream possible) createOperators(m_stream->operators()); //Create Threads of Stream (multiple entries for Stream possible) createThreads(m_stream->threads()); DOMLSSerializer* serializer = m_impl->createLSSerializer(); serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); char* content = XMLString::transcode(serializer->writeToString(m_doc)); std::cout << content << std::endl; XMLString::release(&content); serializer->release(); // done with the document, must call release() to release the entire document resources m_doc->release(); } catch(DOMException& e) { throw InternalError("Error in Xerces-C."); } catch(XMLException& e) { throw InternalError("Error in Xerces-C."); } try { XMLPlatformUtils::Terminate(); // Terminate after release of memory } catch(XMLException&) { } } } } <commit_msg> XmlWriter minor changes<commit_after>/* * Copyright 2011 Thomas Fidler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <boost/lexical_cast.hpp> #include <iostream> #include "../Data.h" #include "../Exception.h" #include "../Node.h" #include "../Operator.h" #include "../Thread.h" #include "XmlWriterImpl.h" using namespace xercesc; namespace stream { namespace impl { XmlWriterImpl::XmlWriterImpl() : m_stream(0), m_impl(0), m_doc(0), m_strElement(0), m_filename("") { try { XMLPlatformUtils::Initialize(); // Initialize Xerces infrastructure } catch (const XMLException& toCatch) { char* message = XMLString::transcode(toCatch.getMessage()); std::cerr << "Error during initialization! :\n" << message << "\n"; XMLString::release(&message); return; } try { m_impl = DOMImplementationRegistry::getDOMImplementation(Str2Xml("")); } catch(DOMException& e) { throw InternalError("Error in Xerces-C."); } catch(XMLException& e) { throw InternalError("Error in Xerces-C."); } } const unsigned int XmlWriterImpl::translateOperatorPointerToID(const Operator* const op) const { unsigned int count_op = 0; for(std::vector<Operator*>::const_iterator iter_op = m_stream->operators().begin(); iter_op != m_stream->operators().end(); ++iter_op, ++count_op) { if ((*iter_op) == op) { return count_op; } } throw InternalError("Operator does not exist."); } void XmlWriterImpl::createInputNodes(const Thread* const currThr, DOMElement* const thrElement) { //Add InputNode branches (tree structure: Stream:Thread:InputNode) //Processed for each InputNode belonging to Thread (multiple entries for each Thread possible) for(std::vector<Node>::const_iterator iter_inNodes = currThr->nodeSequence().begin(); iter_inNodes != currThr->nodeSequence().end(); ++iter_inNodes) { //Create current InputNode being child of Thread DOMElement* inNodeElement = m_doc->createElement(Str2Xml("InputNode")); thrElement->appendChild(inNodeElement); //Create attribute operator of current InputNode (one for each InputNode possible) DOMAttr* opAttr = m_doc->createAttribute(Str2Xml("operator")); unsigned int opId = translateOperatorPointerToID((*iter_inNodes).op()); opAttr->setValue(Str2Xml(boost::lexical_cast<std::string>(opId).c_str())); inNodeElement->setAttributeNode(opAttr); //Create attribute input of current InputNode (one for each InputNode possible) DOMAttr* inputAttr = m_doc->createAttribute(Str2Xml("input")); inputAttr->setValue(Str2Xml(boost::lexical_cast<std::string>((*iter_inNodes).id()).c_str())); inNodeElement->setAttributeNode(inputAttr); } } void XmlWriterImpl::createThreads(const std::vector<Thread*> threads) { //Add Thread branches (tree structure: Stream:Thread) //Processed for each thread belonging to the stream object (multiple entries for stream possible) for(std::vector<Thread*>::const_iterator iter_thr = threads.begin(); iter_thr != threads.end(); ++iter_thr) { //Create current Thread being child of Stream (one for each Thread possible) DOMElement* thrElement = m_doc->createElement(Str2Xml("Thread")); m_strElement->appendChild(thrElement); //Create attribute name of Thread (one for each Thread possible) DOMAttr* nameAttr = m_doc->createAttribute(Str2Xml("name")); nameAttr->setValue(Str2Xml((*iter_thr)->name().c_str())); thrElement->setAttributeNode(nameAttr); //Create InputNodes of Thread (multiple entries for each Thread possible) createInputNodes((*iter_thr), thrElement); } } void XmlWriterImpl::createParameters(const Operator* const currOp, DOMElement* const opElement) { //Add parameter branches (tree structure: stream:operator:parameter) //Processed for each parameter belonging to current operator currOp (multiple entries for each operator possible) for(std::vector<const Parameter*>::const_iterator iter_par = currOp->info()->parameters().begin(); iter_par != currOp->info()->parameters().end(); ++iter_par) { //Create current parameter entry param being child of current operator op (one for each parameter possible) DOMElement* parElement = m_doc->createElement(Str2Xml("Parameter")); opElement->appendChild(parElement); //Create attribute id of current parameter param (one for each parameter possible) DOMAttr* id = m_doc->createAttribute(Str2Xml("id")); id->setValue(Str2Xml(boost::lexical_cast<std::string>((*iter_par)->id()).c_str())); parElement->setAttributeNode(id); createData(*iter_par, currOp, parElement); } } void XmlWriterImpl::createData(const Parameter*const currPar, const Operator*const currOp, DOMElement*const parElement) { //Add Data branch //Create Data entry data being child of current param (one for each parameter possible) DOMElement* dataElement = m_doc->createElement(Str2Xml("Data")); parElement->appendChild(dataElement); //Create attribute type of current parameter param (one for each parameter possible) DOMAttr* typeAttr = m_doc->createAttribute(Str2Xml("type")); typeAttr->setValue(Str2Xml(currOp->getParameter(currPar->id()).type().c_str())); dataElement->setAttributeNode(typeAttr); //Create attribute package of current parameter param (one for each parameter possible) DOMAttr* packageAttr = m_doc->createAttribute(Str2Xml("package")); packageAttr->setValue(Str2Xml(currOp->getParameter(currPar->id()).package().c_str())); dataElement->setAttributeNode(packageAttr); //Create value of current parameter param (one for each parameter possible) //First, create unique input parameter name for function Data::serialize() std::string str = m_stream->name() + "_" + "op" + boost::lexical_cast<std::string>(translateOperatorPointerToID(currOp)) + "_" + "parameter" + boost::lexical_cast<std::string>(currPar->id()); DOMText* value = m_doc->createTextNode(Str2Xml(currOp->getParameter(currPar->id()).serialize(str, impl::XmlUtilities::computePath(m_filename)).c_str())); dataElement->appendChild(value); } void XmlWriterImpl::createInputs(const stream::Operator*const currOp, DOMElement*const opElement) { for(std::vector<const Description*>::const_iterator iter_in = currOp->info()->inputs().begin(); iter_in != currOp->info()->inputs().end(); ++iter_in) { //Get the source node Node node = m_stream->source(currOp, (*iter_in)->id()); //Create Input only for connected operators if (! node.empty()) { //Create Input entry in being child of current operator op (one for each parameter possible) DOMElement* inElement = m_doc->createElement(Str2Xml("Input")); opElement->appendChild(inElement); //Create attribute id of current input in (one for each input possible) DOMAttr* idAttr = m_doc->createAttribute(Str2Xml("id")); idAttr->setValue(Str2Xml(boost::lexical_cast<std::string>((*iter_in)->id()).c_str())); inElement->setAttributeNode(idAttr); //Get the id of the source operator unsigned sourceOp = translateOperatorPointerToID(node.op()); //Write the id of the source operator DOMAttr* opAttr = m_doc->createAttribute(Str2Xml("operator")); opAttr->setValue(Str2Xml(boost::lexical_cast<std::string>(sourceOp).c_str())); inElement->setAttributeNode(opAttr); //Write the id of the output DOMAttr* outAttr = m_doc->createAttribute(Str2Xml("output")); outAttr->setValue(Str2Xml(boost::lexical_cast<std::string>(node.id()).c_str())); inElement->setAttributeNode(outAttr); } } } void XmlWriterImpl::createOperators(const std::vector<Operator*> operators) { //Add operator branches (tree structure: stream:operator) //Processed for each operator belonging to the stream object (multiple entries for stream possible) for(std::vector<Operator*>::const_iterator iter_op = operators.begin(); iter_op != operators.end(); ++iter_op) { //Create current operator entry op being child of stream (one for each operator possible) DOMElement* opElement = m_doc->createElement(Str2Xml("Operator")); m_strElement->appendChild(opElement); //Create attribute id of current operator op (one for each operator possible) DOMAttr* idAttr = m_doc->createAttribute(Str2Xml("id")); idAttr->setValue(Str2Xml(boost::lexical_cast<std::string>(translateOperatorPointerToID(*iter_op)).c_str())); opElement->setAttributeNode(idAttr); //Create attribute package of current operator op (one for each operator possible) DOMAttr* packAttr = m_doc->createAttribute(Str2Xml("package")); packAttr->setValue(Str2Xml((*iter_op)->info()->package().c_str())); opElement->setAttributeNode(packAttr); //Create attribute type of current operator op (one for each operator possible) DOMAttr* typeAttr = m_doc->createAttribute(Str2Xml("type")); typeAttr->setValue(Str2Xml((*iter_op)->info()->type().c_str())); opElement->setAttributeNode(typeAttr); //Create attribute name of current operator op (one for each operator possible) DOMAttr* nameAttr = m_doc->createAttribute(Str2Xml("name")); nameAttr->setValue(Str2Xml((*iter_op)->name().c_str())); opElement->setAttributeNode(nameAttr); createParameters((*iter_op), opElement); createInputs((*iter_op), opElement); } } void XmlWriterImpl::write(const std::string& filename, Stream& stream) { if (filename.empty()) { throw WrongArgument("Invalid file name."); } m_stream = &stream; m_filename = filename; try { //Create Stream branch m_doc = m_impl->createDocument(0, Str2Xml("Stream"), 0); m_strElement = m_doc->getDocumentElement(); //Create attribute name of Stream DOMAttr* nameAttr = m_doc->createAttribute(Str2Xml("name")); nameAttr->setValue(Str2Xml(m_stream->name().c_str())); m_strElement->setAttributeNode(nameAttr); //Create Operators of Stream (multiple entries for Stream possible) createOperators(m_stream->operators()); //Create Threads of Stream (multiple entries for Stream possible) createThreads(m_stream->threads()); DOMLSSerializer* serializer = m_impl->createLSSerializer(); serializer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); char* content = XMLString::transcode(serializer->writeToString(m_doc)); std::cout << content << std::endl; XMLString::release(&content); serializer->release(); // done with the document, must call release() to release the entire document resources m_doc->release(); } catch(DOMException& e) { throw InternalError("Error in Xerces-C."); } catch(XMLException& e) { throw InternalError("Error in Xerces-C."); } try { XMLPlatformUtils::Terminate(); // Terminate after release of memory } catch(XMLException&) { } } } } <|endoftext|>
<commit_before>#include <unistd.h> // ::close #include "event_loop.h" #include "inet_addr.h" #include "socket.h" #include "connector.h" #include "tcp_connection.h" namespace cube { namespace net { int Connector::Connect(const InetAddr &server_addr, int &sockfd) { sockfd = sockets::CreateNonBlockStreamSocket(); if (sockfd < 0) { return CUBE_ERR; } if (::connect(sockfd, server_addr.SockAddr(), sizeof(*server_addr.SockAddr()))) { if (errno == EINPROGRESS) { // it is ok. } else { // error ::close(sockfd); return CUBE_ERR; } } return CUBE_OK; } std::shared_ptr<TcpConnection> Connector::Connect(EventLoop *event_loop, const InetAddr &server_addr) { int sockfd; int ret = Connect(server_addr, sockfd); if (ret != CUBE_OK) { return NULL; } auto conn = std::make_shared<TcpConnection>( event_loop, sockfd, sockets::GetLocalAddr(sockfd), sockets::GetPeerAddr(sockfd)); conn->m_state = TcpConnection::ConnState_Connecting; return conn; } } } <commit_msg>update connector (#8)<commit_after>#include <unistd.h> // ::close #include "event_loop.h" #include "inet_addr.h" #include "socket.h" #include "connector.h" #include "tcp_connection.h" namespace cube { namespace net { int Connector::Connect(const InetAddr &server_addr, int &sockfd) { sockfd = sockets::CreateNonBlockStreamSocket(); if (sockfd < 0) { return CUBE_ERR; } if (::connect(sockfd, server_addr.SockAddr(), sizeof(*server_addr.SockAddr()))) { if (errno == EINPROGRESS) { // it is ok. } else { // error ::close(sockfd); return CUBE_ERR; } } return CUBE_OK; } std::shared_ptr<TcpConnection> Connector::Connect(EventLoop *event_loop, const InetAddr &server_addr) { int sockfd; int ret = Connect(server_addr, sockfd); if (ret != CUBE_OK) { return std::shared_ptr<TcpConnection>(); } auto conn = std::make_shared<TcpConnection>( event_loop, sockfd, sockets::GetLocalAddr(sockfd), sockets::GetPeerAddr(sockfd)); conn->m_state = TcpConnection::ConnState_Connecting; return conn; } } } <|endoftext|>
<commit_before>#include <netlib/channel.h> #include <sys/epoll.h> // EPOLL* #include <netlib/event_loop.h> // EventLoop #include <netlib/logging.h> // Log using std::string; using std::shared_ptr; using netlib::EventLoop; using netlib::Channel; // EPOLLIN // fd is available for read(2): data other than high-priority data can be read. // EPOLLPRI // There is urgent data available for read(2): high-priority data can be read. // EPOLLRDHUP // Stream socket peer closes connection, or shut down writing half of connection. // This flag is useful to detect peer shutdown when using Edge Triggered. // EPOLLOUT // fd is available for write(2): normal data can be read. // EPOLLHUP // Hang up happened on the fd. epoll_wait(2) always wait for this event; // it is not necessary to set it in events. // EPOLLERR // Error condition happened on the fd. epoll_wait(2) always wait for this event, // it is not necessary to set it in events. // EPOLLET // Set the Edge Triggered behavior for fd. Default is Level Triggered. // EPOLLONESHOT // Set the one-shot behavior for the fd(Disable monitoring after event notification). // After an event is pulled out with epoll_wait(2), the associated fd is disabled and // no other events will be reported by the epoll interface. The user must call epoll_ctl() // with EPOLL_CTL_MOD to rearm the fd with a new event mask. const int Channel::kNoneEvent = 0; const int Channel::kReadEvent = EPOLLIN | EPOLLPRI | EPOLLRDHUP; const int Channel::kWriteEvent = EPOLLOUT; const int Channel::kCloseEvent = EPOLLHUP; const int Channel::kErrorEvent = EPOLLERR; // declaration of ‘fd’ shadows a member of 'this' [-Werror=shadow] Channel::Channel(EventLoop *loop, int file_descriptor): owner_loop_(loop), fd_(file_descriptor), requested_event_(kNoneEvent), returned_event_(kNoneEvent), state_in_epoller_(-1), // Epoller::kRaw. tied_(false) {} Channel::~Channel() { if(owner_loop_->IsInLoopThread() == true) { assert(owner_loop_->HasChannel(this) == false); } } void Channel::set_requested_event(RequestedEventType type) { switch(type) { case READ_EVENT: requested_event_ |= kReadEvent; break; case NOT_READ: requested_event_ &= ~kReadEvent; break; case WRITE_EVENT: requested_event_ |= kWriteEvent; break; case NOT_WRITE: requested_event_ &= ~kWriteEvent; break; case NONE_EVENT: requested_event_ = kNoneEvent; break; default: LOG_FATAL("Unknown RequestedEventType"); } AddOrUpdateChannel(); } void Channel::AddOrUpdateChannel() { owner_loop_->AddOrUpdateChannel(this); // Invoke `void Epoller::AddOrUpdateChannel(Channel*)` } void Channel::set_tie(const shared_ptr<void> &object) { tie_ = object; tied_ = true; } void Channel::set_event_callback(EventCallbackType type, const EventCallback &callback) { switch(type) { case READ_CALLBACK: read_callback_ = callback; break; case WRITE_CALLBACK: write_callback_ = callback; break; case CLOSE_CALLBACK: close_callback_ = callback; break; case ERROR_CALLBACK: error_callback_ = callback; break; default: LOG_FATAL("Unknown EventCallbackType!"); } } bool Channel::IsRequestedArgumentEvent(RequestedEventType type) { switch(type) { case READ_EVENT: return requested_event_ & kReadEvent; case WRITE_EVENT: return requested_event_ & kWriteEvent; case NONE_EVENT: return requested_event_ == kNoneEvent; default: LOG_FATAL("Unknown RequestedEventType"); return true; } } void Channel::HandleEvent(TimeStamp receive_time) { if(tied_ == true) { shared_ptr<void> guard = tie_.lock(); // NOTE: Not `shared_ptr<void> &` if(guard) { HandleEventWithGuard(receive_time); } } else { HandleEventWithGuard(receive_time); } } // Call different callbacks based on the value of returned_event_. // Invoked by EventLoop::Loop(). void Channel::HandleEventWithGuard(TimeStamp receive_time) { LOG_TRACE("%s", ReturnedEventToString().c_str()); if((returned_event_ & kReadEvent) && read_callback_) { read_callback_(receive_time); } if((returned_event_ & kWriteEvent) && write_callback_) { write_callback_(receive_time); } if((returned_event_ & kCloseEvent) && !(returned_event_ & EPOLLIN) && close_callback_) { close_callback_(receive_time); } if((returned_event_ & kErrorEvent ) && error_callback_) { error_callback_(receive_time); } } void Channel::RemoveChannel() { assert(IsRequestedArgumentEvent(NONE_EVENT) == true); owner_loop_->RemoveChannel(this); } string Channel::RequestedEventToString() const { return EventToString(fd_, requested_event_); } string Channel::ReturnedEventToString() const { return EventToString(fd_, returned_event_); } string Channel::EventToString(int fd, int event) { char buffer[32] = ""; char *ptr = buffer, *buffer_end = buffer + sizeof buffer; ptr += snprintf(ptr, buffer_end - ptr, "%d: ", fd); if(event & EPOLLIN) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "IN "); } if(event & EPOLLPRI) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "PRI "); } if(event & EPOLLRDHUP) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "RDHUP "); } if(event & EPOLLOUT) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "OUT "); } if(event & EPOLLHUP) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "HUP "); } if(event & EPOLLERR) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "ERR "); } return buffer; } <commit_msg>feat: add event_handling to help control the life of Channel<commit_after>#include <netlib/channel.h> #include <sys/epoll.h> // EPOLL* #include <netlib/event_loop.h> // EventLoop #include <netlib/logging.h> // Log using std::string; using std::shared_ptr; using netlib::EventLoop; using netlib::Channel; // EPOLLIN // fd is available for read(2): data other than high-priority data can be read. // EPOLLPRI // There is urgent data available for read(2): high-priority data can be read. // EPOLLRDHUP // Stream socket peer closes connection, or shut down writing half of connection. // This flag is useful to detect peer shutdown when using Edge Triggered. // EPOLLOUT // fd is available for write(2): normal data can be read. // EPOLLHUP // Hang up happened on the fd. epoll_wait(2) always wait for this event; // it is not necessary to set it in events. // EPOLLERR // Error condition happened on the fd. epoll_wait(2) always wait for this event, // it is not necessary to set it in events. // EPOLLET // Set the Edge Triggered behavior for fd. Default is Level Triggered. // EPOLLONESHOT // Set the one-shot behavior for the fd(Disable monitoring after event notification). // After an event is pulled out with epoll_wait(2), the associated fd is disabled and // no other events will be reported by the epoll interface. The user must call epoll_ctl() // with EPOLL_CTL_MOD to rearm the fd with a new event mask. const int Channel::kNoneEvent = 0; const int Channel::kReadEvent = EPOLLIN | EPOLLPRI | EPOLLRDHUP; const int Channel::kWriteEvent = EPOLLOUT; const int Channel::kCloseEvent = EPOLLHUP; const int Channel::kErrorEvent = EPOLLERR; // declaration of ‘fd’ shadows a member of 'this' [-Werror=shadow] Channel::Channel(EventLoop *loop, int file_descriptor): owner_loop_(loop), fd_(file_descriptor), requested_event_(kNoneEvent), returned_event_(kNoneEvent), state_in_epoller_(-1), // Epoller::kRaw. tied_(false), event_handling_(false) {} Channel::~Channel() { // Assert that this channel object won't destruct in the process of event handling. assert(event_handling_ == false); if(owner_loop_->IsInLoopThread() == true) { assert(owner_loop_->HasChannel(this) == false); } } void Channel::set_requested_event(RequestedEventType type) { switch(type) { case READ_EVENT: requested_event_ |= kReadEvent; break; case NOT_READ: requested_event_ &= ~kReadEvent; break; case WRITE_EVENT: requested_event_ |= kWriteEvent; break; case NOT_WRITE: requested_event_ &= ~kWriteEvent; break; case NONE_EVENT: requested_event_ = kNoneEvent; break; default: LOG_FATAL("Unknown RequestedEventType"); } AddOrUpdateChannel(); } void Channel::AddOrUpdateChannel() { owner_loop_->AddOrUpdateChannel(this); // Invoke `void Epoller::AddOrUpdateChannel(Channel*)` } void Channel::set_tie(const shared_ptr<void> &object) { tie_ = object; tied_ = true; } void Channel::set_event_callback(EventCallbackType type, const EventCallback &callback) { switch(type) { case READ_CALLBACK: read_callback_ = callback; break; case WRITE_CALLBACK: write_callback_ = callback; break; case CLOSE_CALLBACK: close_callback_ = callback; break; case ERROR_CALLBACK: error_callback_ = callback; break; default: LOG_FATAL("Unknown EventCallbackType!"); } } bool Channel::IsRequestedArgumentEvent(RequestedEventType type) { switch(type) { case READ_EVENT: return requested_event_ & kReadEvent; case WRITE_EVENT: return requested_event_ & kWriteEvent; case NONE_EVENT: return requested_event_ == kNoneEvent; default: LOG_FATAL("Unknown RequestedEventType"); return true; } } void Channel::HandleEvent(TimeStamp receive_time) { if(tied_ == true) { shared_ptr<void> guard = tie_.lock(); // NOTE: Not `shared_ptr<void> &` if(guard) { HandleEventWithGuard(receive_time); } } else { HandleEventWithGuard(receive_time); } } // Call different callbacks based on the value of returned_event_. // Invoked by EventLoop::Loop(). void Channel::HandleEventWithGuard(TimeStamp receive_time) { event_handling_ = true; LOG_TRACE("%s", ReturnedEventToString().c_str()); if((returned_event_ & kReadEvent) && read_callback_) { read_callback_(receive_time); } if((returned_event_ & kWriteEvent) && write_callback_) { write_callback_(receive_time); } if((returned_event_ & kCloseEvent) && !(returned_event_ & EPOLLIN) && close_callback_) { close_callback_(receive_time); } if((returned_event_ & kErrorEvent ) && error_callback_) { error_callback_(receive_time); } event_handling_ = false; } void Channel::RemoveChannel() { assert(IsRequestedArgumentEvent(NONE_EVENT) == true); owner_loop_->RemoveChannel(this); } string Channel::RequestedEventToString() const { return EventToString(fd_, requested_event_); } string Channel::ReturnedEventToString() const { return EventToString(fd_, returned_event_); } string Channel::EventToString(int fd, int event) { char buffer[32] = ""; char *ptr = buffer, *buffer_end = buffer + sizeof buffer; ptr += snprintf(ptr, buffer_end - ptr, "%d: ", fd); if(event & EPOLLIN) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "IN "); } if(event & EPOLLPRI) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "PRI "); } if(event & EPOLLRDHUP) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "RDHUP "); } if(event & EPOLLOUT) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "OUT "); } if(event & EPOLLHUP) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "HUP "); } if(event & EPOLLERR) { ptr += snprintf(ptr, buffer_end - ptr, "%s", "ERR "); } return buffer; } <|endoftext|>
<commit_before><commit_msg>Refine MSE and sample increment calculations.<commit_after><|endoftext|>
<commit_before>// // Created by Edd on 04/11/2017. // #include <leveldb/db.h> #include <leveldb/filter_policy.h> #include <unordered_set> #include <stor/document/document.h> #include "leveldb_driver.h" #include "utils.h" namespace esft { namespace stor { namespace bmark { #pragma GCC push_options #pragma GCC optimize ("O0") leveldb_driver::leveldb_driver(std::size_t key_size, std::size_t value_size, std::size_t ops): _home{"_leveldb_benchmark"}, _key_size{key_size}, _value_size{value_size}, _ops{ops} { mkdir(_home); } leveldb_driver::~leveldb_driver() { rmdir(_home); } std::unordered_map<std::string, double> leveldb_driver::writes() const { std::string db_name = _home + "/bmark_db"; leveldb::Options opt; opt.create_if_missing = true; opt.filter_policy = leveldb::NewBloomFilterPolicy(10); leveldb::DB *db; try{ leveldb::Status conn = leveldb::DB::Open(opt, db_name,&db); if (!conn.ok()){ throw std::runtime_error{"Failed opening LevelDB"}; } value_generator kg1(_key_size); value_generator vg1(_value_size - 7 - 1); leveldb::WriteOptions wo; wo.sync = false; auto runner = [this, db, &wo, &kg1, &vg1]() { std::size_t some_value_to_prevent_optimizaton = 0; for (std::size_t i = 0; i < _ops; ++i){ std::string id = kg1(); std::string jsn = json_generator(vg1); document doc(jsn, id); some_value_to_prevent_optimizaton += doc.id().size(); auto s = db->Put(wo,id, jsn); some_value_to_prevent_optimizaton += (std::size_t) &s; } return some_value_to_prevent_optimizaton; }; auto elapsed = timer<std::chrono::microseconds>{}(runner); delete db; delete opt.filter_policy; leveldb::DestroyDB(db_name, opt); rmdir(db_name); return result(elapsed,_ops,_key_size+_value_size); }catch (...){ delete db; delete opt.filter_policy; leveldb::DestroyDB(db_name, opt); rmdir(db_name); throw; } } std::unordered_map<std::string, double> leveldb_driver::reads_by_key() const { std::string db_name = _home + "/bmark_db"; leveldb::Options opt; opt.create_if_missing = true; opt.filter_policy = leveldb::NewBloomFilterPolicy(10); leveldb::DB *db; try{ leveldb::Status conn = leveldb::DB::Open(opt, db_name,&db); if (!conn.ok()){ throw std::runtime_error{"Failed opening LevelDB"}; } //fill { value_generator kg1(_key_size); value_generator vg1(_value_size); leveldb::WriteOptions wo; wo.sync = false; for (std::size_t i = 0; i < _ops; ++i){ auto s = db->Put(wo,kg1(),json_generator(vg1)); } } value_generator kg1(_key_size); value_generator vg1(_value_size); leveldb::ReadOptions ro; ro.snapshot = db->GetSnapshot(); auto runner = [this, db, &ro, &kg1, &vg1]() { std::size_t some_value_to_prevent_optimizaton = 0; for (std::size_t i = 0; i < _ops; ++i){ std::string json; std::string id = kg1(); db->Get(ro,id, &json); std::unordered_set<document> docs; auto p = docs.emplace(json,id); some_value_to_prevent_optimizaton += (std::size_t) &p.first; } db->ReleaseSnapshot(ro.snapshot); return some_value_to_prevent_optimizaton; }; auto elapsed = timer<std::chrono::microseconds>{}(runner); delete db; delete opt.filter_policy; leveldb::DestroyDB(db_name, opt); rmdir(db_name); return result(elapsed,_ops,_key_size+_value_size); }catch (...){ delete db; delete opt.filter_policy; leveldb::DestroyDB(db_name, opt); rmdir(db_name); throw; } } #pragma GCC pop_options } } }<commit_msg>fixed leveldb read key benchmark<commit_after>// // Created by Edd on 04/11/2017. // #include <leveldb/db.h> #include <leveldb/filter_policy.h> #include <unordered_set> #include <stor/document/document.h> #include "leveldb_driver.h" #include "utils.h" namespace esft { namespace stor { namespace bmark { #pragma GCC push_options #pragma GCC optimize ("O0") leveldb_driver::leveldb_driver(std::size_t key_size, std::size_t value_size, std::size_t ops): _home{"_leveldb_benchmark"}, _key_size{key_size}, _value_size{value_size}, _ops{ops} { mkdir(_home); } leveldb_driver::~leveldb_driver() { rmdir(_home); } std::unordered_map<std::string, double> leveldb_driver::writes() const { std::string db_name = _home + "/bmark_db"; leveldb::Options opt; opt.create_if_missing = true; opt.filter_policy = leveldb::NewBloomFilterPolicy(10); leveldb::DB *db; try{ leveldb::Status conn = leveldb::DB::Open(opt, db_name,&db); if (!conn.ok()){ throw std::runtime_error{"Failed opening LevelDB"}; } value_generator kg1(_key_size); value_generator vg1(_value_size - 7 - 1); leveldb::WriteOptions wo; wo.sync = false; auto runner = [this, db, &wo, &kg1, &vg1]() { std::size_t some_value_to_prevent_optimizaton = 0; for (std::size_t i = 0; i < _ops; ++i){ std::string id = kg1(); std::string jsn = json_generator(vg1); document doc(jsn, id); some_value_to_prevent_optimizaton += doc.id().size(); auto s = db->Put(wo,id, jsn); some_value_to_prevent_optimizaton += (std::size_t) &s; } return some_value_to_prevent_optimizaton; }; auto elapsed = timer<std::chrono::microseconds>{}(runner); delete db; delete opt.filter_policy; leveldb::DestroyDB(db_name, opt); rmdir(db_name); return result(elapsed,_ops,_key_size+_value_size); }catch (...){ delete db; delete opt.filter_policy; leveldb::DestroyDB(db_name, opt); rmdir(db_name); throw; } } std::unordered_map<std::string, double> leveldb_driver::reads_by_key() const { std::string db_name = _home + "/bmark_db"; leveldb::Options opt; opt.create_if_missing = true; opt.filter_policy = leveldb::NewBloomFilterPolicy(10); leveldb::DB *db; try{ leveldb::Status conn = leveldb::DB::Open(opt, db_name,&db); if (!conn.ok()){ throw std::runtime_error{"Failed opening LevelDB"}; } //fill { value_generator kg1(_key_size); value_generator vg1(_value_size); leveldb::WriteOptions wo; wo.sync = false; for (std::size_t i = 0; i < _ops; ++i){ auto s = db->Put(wo,kg1(),json_generator(vg1)); } } value_generator kg1(_key_size); value_generator vg1(_value_size); auto runner = [this, db, &kg1, &vg1]() { std::size_t some_value_to_prevent_optimizaton = 0; for (std::size_t i = 0; i < _ops; ++i){ leveldb::ReadOptions ro; ro.snapshot = db->GetSnapshot(); std::string json; std::string id = kg1(); db->Get(leveldb::ReadOptions{}, id, &json); db->ReleaseSnapshot(ro.snapshot); auto p = document(json,id); some_value_to_prevent_optimizaton += p.id().size(); } return some_value_to_prevent_optimizaton; }; auto elapsed = timer<std::chrono::microseconds>{}(runner); delete db; delete opt.filter_policy; leveldb::DestroyDB(db_name, opt); rmdir(db_name); return result(elapsed,_ops,_key_size+_value_size); }catch (...){ delete db; delete opt.filter_policy; leveldb::DestroyDB(db_name, opt); rmdir(db_name); throw; } } #pragma GCC pop_options } } }<|endoftext|>
<commit_before>//===-- DNBDataRef.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Created by Greg Clayton on 1/11/06. // //===----------------------------------------------------------------------===// #include "DNBDataRef.h" #include "DNBLog.h" #include <assert.h> #include <ctype.h> #include <libkern/OSByteOrder.h> //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- DNBDataRef::DNBDataRef() : m_start(NULL), m_end(NULL), m_swap(false), m_ptrSize(0), m_addrPCRelative(INVALID_NUB_ADDRESS), m_addrTEXT(INVALID_NUB_ADDRESS), m_addrDATA(INVALID_NUB_ADDRESS) {} //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- DNBDataRef::DNBDataRef(const uint8_t *start, size_t size, bool swap) : m_start(start), m_end(start + size), m_swap(swap), m_ptrSize(0), m_addrPCRelative(INVALID_NUB_ADDRESS), m_addrTEXT(INVALID_NUB_ADDRESS), m_addrDATA(INVALID_NUB_ADDRESS) {} //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- DNBDataRef::~DNBDataRef() {} //---------------------------------------------------------------------- // Get8 //---------------------------------------------------------------------- uint8_t DNBDataRef::Get8(offset_t *offset_ptr) const { uint8_t val = 0; if (ValidOffsetForDataOfSize(*offset_ptr, sizeof(val))) { val = *(m_start + *offset_ptr); *offset_ptr += sizeof(val); } return val; } //---------------------------------------------------------------------- // Get16 //---------------------------------------------------------------------- uint16_t DNBDataRef::Get16(offset_t *offset_ptr) const { uint16_t val = 0; if (ValidOffsetForDataOfSize(*offset_ptr, sizeof(val))) { const uint8_t *p = m_start + *offset_ptr; val = *(uint16_t *)p; if (m_swap) val = OSSwapInt16(val); // Advance the offset *offset_ptr += sizeof(val); } return val; } //---------------------------------------------------------------------- // Get32 //---------------------------------------------------------------------- uint32_t DNBDataRef::Get32(offset_t *offset_ptr) const { uint32_t val = 0; if (ValidOffsetForDataOfSize(*offset_ptr, sizeof(val))) { const uint8_t *p = m_start + *offset_ptr; val = *(uint32_t *)p; if (m_swap) val = OSSwapInt32(val); // Advance the offset *offset_ptr += sizeof(val); } return val; } //---------------------------------------------------------------------- // Get64 //---------------------------------------------------------------------- uint64_t DNBDataRef::Get64(offset_t *offset_ptr) const { uint64_t val = 0; if (ValidOffsetForDataOfSize(*offset_ptr, sizeof(val))) { const uint8_t *p = m_start + *offset_ptr; val = *(uint64_t *)p; if (m_swap) val = OSSwapInt64(val); // Advance the offset *offset_ptr += sizeof(val); } return val; } //---------------------------------------------------------------------- // GetMax32 // // Used for calls when the size can vary. Fill in extra cases if they // are ever needed. //---------------------------------------------------------------------- uint32_t DNBDataRef::GetMax32(offset_t *offset_ptr, uint32_t byte_size) const { switch (byte_size) { case 1: return Get8(offset_ptr); break; case 2: return Get16(offset_ptr); break; case 4: return Get32(offset_ptr); break; default: assert(!"GetMax32 unhandled case!"); break; } return 0; } //---------------------------------------------------------------------- // GetMax64 // // Used for calls when the size can vary. Fill in extra cases if they // are ever needed. //---------------------------------------------------------------------- uint64_t DNBDataRef::GetMax64(offset_t *offset_ptr, uint32_t size) const { switch (size) { case 1: return Get8(offset_ptr); break; case 2: return Get16(offset_ptr); break; case 4: return Get32(offset_ptr); break; case 8: return Get64(offset_ptr); break; default: assert(!"GetMax64 unhandled case!"); break; } return 0; } //---------------------------------------------------------------------- // GetPointer // // Extract a pointer value from the buffer. The pointer size must be // set prior to using this using one of the SetPointerSize functions. //---------------------------------------------------------------------- uint64_t DNBDataRef::GetPointer(offset_t *offset_ptr) const { // Must set pointer size prior to using this call assert(m_ptrSize != 0); return GetMax64(offset_ptr, m_ptrSize); } //---------------------------------------------------------------------- // GetCStr //---------------------------------------------------------------------- const char *DNBDataRef::GetCStr(offset_t *offset_ptr, uint32_t fixed_length) const { const char *s = NULL; if (m_start < m_end) { s = (char *)m_start + *offset_ptr; // Advance the offset if (fixed_length) *offset_ptr += fixed_length; else *offset_ptr += strlen(s) + 1; } return s; } //---------------------------------------------------------------------- // GetData //---------------------------------------------------------------------- const uint8_t *DNBDataRef::GetData(offset_t *offset_ptr, uint32_t length) const { const uint8_t *data = NULL; if (length > 0 && ValidOffsetForDataOfSize(*offset_ptr, length)) { data = m_start + *offset_ptr; *offset_ptr += length; } return data; } //---------------------------------------------------------------------- // Get_ULEB128 //---------------------------------------------------------------------- uint64_t DNBDataRef::Get_ULEB128(offset_t *offset_ptr) const { uint64_t result = 0; if (m_start < m_end) { int shift = 0; const uint8_t *src = m_start + *offset_ptr; uint8_t byte; int bytecount = 0; while (src < m_end) { bytecount++; byte = *src++; result |= (uint64_t)(byte & 0x7f) << shift; shift += 7; if ((byte & 0x80) == 0) break; } *offset_ptr += bytecount; } return result; } //---------------------------------------------------------------------- // Get_SLEB128 //---------------------------------------------------------------------- int64_t DNBDataRef::Get_SLEB128(offset_t *offset_ptr) const { int64_t result = 0; if (m_start < m_end) { int shift = 0; int size = sizeof(uint32_t) * 8; const uint8_t *src = m_start + *offset_ptr; uint8_t byte = 0; int bytecount = 0; while (src < m_end) { bytecount++; byte = *src++; result |= (int64_t)(byte & 0x7f) << shift; shift += 7; if ((byte & 0x80) == 0) break; } // Sign bit of byte is 2nd high order bit (0x40) if (shift < size && (byte & 0x40)) result |= -(1ll << shift); *offset_ptr += bytecount; } return result; } //---------------------------------------------------------------------- // Skip_LEB128 // // Skips past ULEB128 and SLEB128 numbers (just updates the offset) //---------------------------------------------------------------------- void DNBDataRef::Skip_LEB128(offset_t *offset_ptr) const { if (m_start < m_end) { const uint8_t *start = m_start + *offset_ptr; const uint8_t *src = start; while ((src < m_end) && (*src++ & 0x80)) /* Do nothing */; *offset_ptr += src - start; } } uint32_t DNBDataRef::Dump(uint32_t startOffset, uint32_t endOffset, uint64_t offsetBase, DNBDataRef::Type type, uint32_t numPerLine, const char *format) { uint32_t offset; uint32_t count; char str[1024]; str[0] = '\0'; size_t str_offset = 0; for (offset = startOffset, count = 0; ValidOffset(offset) && offset < endOffset; ++count) { if ((count % numPerLine) == 0) { // Print out any previous string if (str[0] != '\0') DNBLog("%s", str); // Reset string offset and fill the current line string with address: str_offset = 0; str_offset += snprintf(str, sizeof(str), "0x%8.8llx:", (uint64_t)(offsetBase + (offset - startOffset))); } // Make sure we don't pass the bounds of our current string buffer on each // iteration through this loop if (str_offset >= sizeof(str)) { // The last snprintf consumed our string buffer, we will need to dump this // out // and reset the string with no address DNBLog("%s", str); str_offset = 0; str[0] = '\0'; } // We already checked that there is at least some room in the string str // above, so it is safe to make // the snprintf call each time through this loop switch (type) { case TypeUInt8: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %2.2x", Get8(&offset)); break; case TypeChar: { char ch = Get8(&offset); str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %c", isprint(ch) ? ch : ' '); } break; case TypeUInt16: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %4.4x", Get16(&offset)); break; case TypeUInt32: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %8.8x", Get32(&offset)); break; case TypeUInt64: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %16.16llx", Get64(&offset)); break; case TypePointer: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " 0x%llx", GetPointer(&offset)); break; case TypeULEB128: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " 0x%llx", Get_ULEB128(&offset)); break; case TypeSLEB128: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %lld", Get_SLEB128(&offset)); break; } } if (str[0] != '\0') DNBLog("%s", str); return offset; // Return the offset at which we ended up } <commit_msg>Fix warnings in DNBDataRef.cpp, NFC<commit_after>//===-- DNBDataRef.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Created by Greg Clayton on 1/11/06. // //===----------------------------------------------------------------------===// #include "DNBDataRef.h" #include "DNBLog.h" #include <assert.h> #include <ctype.h> #include <libkern/OSByteOrder.h> //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- DNBDataRef::DNBDataRef() : m_start(NULL), m_end(NULL), m_swap(false), m_ptrSize(0), m_addrPCRelative(INVALID_NUB_ADDRESS), m_addrTEXT(INVALID_NUB_ADDRESS), m_addrDATA(INVALID_NUB_ADDRESS) {} //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- DNBDataRef::DNBDataRef(const uint8_t *start, size_t size, bool swap) : m_start(start), m_end(start + size), m_swap(swap), m_ptrSize(0), m_addrPCRelative(INVALID_NUB_ADDRESS), m_addrTEXT(INVALID_NUB_ADDRESS), m_addrDATA(INVALID_NUB_ADDRESS) {} //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- DNBDataRef::~DNBDataRef() {} //---------------------------------------------------------------------- // Get8 //---------------------------------------------------------------------- uint8_t DNBDataRef::Get8(offset_t *offset_ptr) const { uint8_t val = 0; if (ValidOffsetForDataOfSize(*offset_ptr, sizeof(val))) { val = *(m_start + *offset_ptr); *offset_ptr += sizeof(val); } return val; } //---------------------------------------------------------------------- // Get16 //---------------------------------------------------------------------- uint16_t DNBDataRef::Get16(offset_t *offset_ptr) const { uint16_t val = 0; if (ValidOffsetForDataOfSize(*offset_ptr, sizeof(val))) { const uint8_t *p = m_start + *offset_ptr; memcpy(&val, p, sizeof(uint16_t)); if (m_swap) val = OSSwapInt16(val); // Advance the offset *offset_ptr += sizeof(val); } return val; } //---------------------------------------------------------------------- // Get32 //---------------------------------------------------------------------- uint32_t DNBDataRef::Get32(offset_t *offset_ptr) const { uint32_t val = 0; if (ValidOffsetForDataOfSize(*offset_ptr, sizeof(val))) { const uint8_t *p = m_start + *offset_ptr; memcpy(&val, p, sizeof(uint32_t)); if (m_swap) val = OSSwapInt32(val); // Advance the offset *offset_ptr += sizeof(val); } return val; } //---------------------------------------------------------------------- // Get64 //---------------------------------------------------------------------- uint64_t DNBDataRef::Get64(offset_t *offset_ptr) const { uint64_t val = 0; if (ValidOffsetForDataOfSize(*offset_ptr, sizeof(val))) { const uint8_t *p = m_start + *offset_ptr; memcpy(&val, p, sizeof(uint64_t)); if (m_swap) val = OSSwapInt64(val); // Advance the offset *offset_ptr += sizeof(val); } return val; } //---------------------------------------------------------------------- // GetMax32 // // Used for calls when the size can vary. Fill in extra cases if they // are ever needed. //---------------------------------------------------------------------- uint32_t DNBDataRef::GetMax32(offset_t *offset_ptr, uint32_t byte_size) const { switch (byte_size) { case 1: return Get8(offset_ptr); break; case 2: return Get16(offset_ptr); break; case 4: return Get32(offset_ptr); break; default: assert(false && "GetMax32 unhandled case!"); break; } return 0; } //---------------------------------------------------------------------- // GetMax64 // // Used for calls when the size can vary. Fill in extra cases if they // are ever needed. //---------------------------------------------------------------------- uint64_t DNBDataRef::GetMax64(offset_t *offset_ptr, uint32_t size) const { switch (size) { case 1: return Get8(offset_ptr); break; case 2: return Get16(offset_ptr); break; case 4: return Get32(offset_ptr); break; case 8: return Get64(offset_ptr); break; default: assert(false && "GetMax64 unhandled case!"); break; } return 0; } //---------------------------------------------------------------------- // GetPointer // // Extract a pointer value from the buffer. The pointer size must be // set prior to using this using one of the SetPointerSize functions. //---------------------------------------------------------------------- uint64_t DNBDataRef::GetPointer(offset_t *offset_ptr) const { // Must set pointer size prior to using this call assert(m_ptrSize != 0); return GetMax64(offset_ptr, m_ptrSize); } //---------------------------------------------------------------------- // GetCStr //---------------------------------------------------------------------- const char *DNBDataRef::GetCStr(offset_t *offset_ptr, uint32_t fixed_length) const { const char *s = NULL; if (m_start < m_end) { s = (const char *)m_start + *offset_ptr; // Advance the offset if (fixed_length) *offset_ptr += fixed_length; else *offset_ptr += strlen(s) + 1; } return s; } //---------------------------------------------------------------------- // GetData //---------------------------------------------------------------------- const uint8_t *DNBDataRef::GetData(offset_t *offset_ptr, uint32_t length) const { const uint8_t *data = NULL; if (length > 0 && ValidOffsetForDataOfSize(*offset_ptr, length)) { data = m_start + *offset_ptr; *offset_ptr += length; } return data; } //---------------------------------------------------------------------- // Get_ULEB128 //---------------------------------------------------------------------- uint64_t DNBDataRef::Get_ULEB128(offset_t *offset_ptr) const { uint64_t result = 0; if (m_start < m_end) { int shift = 0; const uint8_t *src = m_start + *offset_ptr; uint8_t byte; int bytecount = 0; while (src < m_end) { bytecount++; byte = *src++; result |= (uint64_t)(byte & 0x7f) << shift; shift += 7; if ((byte & 0x80) == 0) break; } *offset_ptr += bytecount; } return result; } //---------------------------------------------------------------------- // Get_SLEB128 //---------------------------------------------------------------------- int64_t DNBDataRef::Get_SLEB128(offset_t *offset_ptr) const { int64_t result = 0; if (m_start < m_end) { int shift = 0; int size = sizeof(uint32_t) * 8; const uint8_t *src = m_start + *offset_ptr; uint8_t byte = 0; int bytecount = 0; while (src < m_end) { bytecount++; byte = *src++; result |= (int64_t)(byte & 0x7f) << shift; shift += 7; if ((byte & 0x80) == 0) break; } // Sign bit of byte is 2nd high order bit (0x40) if (shift < size && (byte & 0x40)) result |= -(1ll << shift); *offset_ptr += bytecount; } return result; } //---------------------------------------------------------------------- // Skip_LEB128 // // Skips past ULEB128 and SLEB128 numbers (just updates the offset) //---------------------------------------------------------------------- void DNBDataRef::Skip_LEB128(offset_t *offset_ptr) const { if (m_start < m_end) { const uint8_t *start = m_start + *offset_ptr; const uint8_t *src = start; while ((src < m_end) && (*src++ & 0x80)) /* Do nothing */; *offset_ptr += src - start; } } uint32_t DNBDataRef::Dump(uint32_t startOffset, uint32_t endOffset, uint64_t offsetBase, DNBDataRef::Type type, uint32_t numPerLine, const char *format) { uint32_t offset; uint32_t count; char str[1024]; str[0] = '\0'; size_t str_offset = 0; for (offset = startOffset, count = 0; ValidOffset(offset) && offset < endOffset; ++count) { if ((count % numPerLine) == 0) { // Print out any previous string if (str[0] != '\0') DNBLog("%s", str); // Reset string offset and fill the current line string with address: str_offset = 0; str_offset += snprintf(str, sizeof(str), "0x%8.8llx:", (uint64_t)(offsetBase + (offset - startOffset))); } // Make sure we don't pass the bounds of our current string buffer on each // iteration through this loop if (str_offset >= sizeof(str)) { // The last snprintf consumed our string buffer, we will need to dump this // out // and reset the string with no address DNBLog("%s", str); str_offset = 0; str[0] = '\0'; } // We already checked that there is at least some room in the string str // above, so it is safe to make // the snprintf call each time through this loop switch (type) { case TypeUInt8: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %2.2x", Get8(&offset)); break; case TypeChar: { char ch = Get8(&offset); str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %c", isprint(ch) ? ch : ' '); } break; case TypeUInt16: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %4.4x", Get16(&offset)); break; case TypeUInt32: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %8.8x", Get32(&offset)); break; case TypeUInt64: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %16.16llx", Get64(&offset)); break; case TypePointer: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " 0x%llx", GetPointer(&offset)); break; case TypeULEB128: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " 0x%llx", Get_ULEB128(&offset)); break; case TypeSLEB128: str_offset += snprintf(str + str_offset, sizeof(str) - str_offset, format ? format : " %lld", Get_SLEB128(&offset)); break; } } if (str[0] != '\0') DNBLog("%s", str); return offset; // Return the offset at which we ended up } <|endoftext|>
<commit_before><commit_msg>core: scene: session: cp<commit_after><|endoftext|>
<commit_before>/// HEADER #include "apex_ros_interface.h" /// PROJECT #include <csapex/utility/register_apex_plugin.h> #include <csapex_ros/ros_handler.h> #include "import_ros.h" #include <csapex/model/graph.h> #include <csapex/model/node_state.h> #include <csapex/factory/message_factory.h> #include <csapex_ros/ros_message_conversion.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex_ros/yaml_io.hpp> #include <csapex/model/graph_facade.h> #include <csapex/model/node_handle.h> #include <csapex/model/node.h> #include <csapex/signal/event.h> #include <csapex/msg/no_message.h> #include <csapex/model/token.h> #include <csapex/msg/any_message.h> /// SYSTEM #include <boost/regex.hpp> #include <boost/algorithm/string/replace.hpp> #include <std_msgs/Int32.h> #include <std_msgs/Bool.h> #include <std_msgs/String.h> #include <std_msgs/Float64.h> #include <QMimeData> CSAPEX_REGISTER_CLASS(csapex::APEXRosInterface, csapex::CorePlugin) using namespace csapex; template <typename RosType, typename ApexType> struct ConvertIntegral { static typename connection_types::GenericValueMessage<ApexType>::Ptr ros2apex(const typename RosType::ConstPtr &ros_msg) { typename connection_types::GenericValueMessage<ApexType>::Ptr out(new connection_types::GenericValueMessage<ApexType>); out->value = ros_msg->data; return out; } static typename RosType::Ptr apex2ros(const typename connection_types::GenericValueMessage<ApexType>::ConstPtr& apex_msg) { typename RosType::Ptr out(new RosType); out->data = apex_msg->value; return out; } }; APEXRosInterface::APEXRosInterface() : core_(nullptr), disabled_(false) { last_clock_ = ros::Time(0); } APEXRosInterface::~APEXRosInterface() { } void APEXRosInterface::prepare(Settings &settings) { ROSHandler::createInstance(settings); } void APEXRosInterface::init(CsApexCore &core) { core_ = &core; ROSHandler::instance().registerConnectionCallback([this]() { registerCommandListener(); registerClockWatchdog(); }); RosMessageConversion::registerConversion<std_msgs::Bool, connection_types::GenericValueMessage<bool>, ConvertIntegral<std_msgs::Bool, bool> >(); RosMessageConversion::registerConversion<std_msgs::Int32, connection_types::GenericValueMessage<int>, ConvertIntegral<std_msgs::Int32, int> >(); RosMessageConversion::registerConversion<std_msgs::Float64, connection_types::GenericValueMessage<double>, ConvertIntegral<std_msgs::Float64, double> >(); RosMessageConversion::registerConversion<std_msgs::String, connection_types::GenericValueMessage<std::string>, ConvertIntegral<std_msgs::String, std::string> >(); core_->loaded.connect([this](){ if(ROSHandler::instance().isConnected()) { XmlRpc::XmlRpcValue params, result, payload; params[0] = ros::this_node::getName(); std::string prefix = ros::this_node::getName(); if (ros::master::execute("getParamNames", params, result, payload, true)) { if(result.getType() != XmlRpc::XmlRpcValue::TypeArray) { return; } std::string name = result[1]; if(name != "Parameter names") { return; } XmlRpc::XmlRpcValue data = result[2]; for(std::size_t i = 0, total = data.size(); i < total; ++i) { std::string parameter_name = data[i]; if(parameter_name.substr(0, prefix.size()) != prefix) { continue; } try { XmlRpc::XmlRpcValue parameter_value; ros::param::getCached(parameter_name, parameter_value); loadParameterValue(prefix, parameter_name, parameter_value); } catch (std::exception e) { // silence } } } } }); } void APEXRosInterface::setupGraph(Graph *graph) { clock_reset_event_ = graph->createInternalEvent(connection_types::makeEmpty<connection_types::AnyMessage>(), graph->makeUUID("event_ros_time_reset"), "ros time reset"); } void APEXRosInterface::loadParameterValue(const std::string& prefix, const std::string& parameter_name, const XmlRpc::XmlRpcValue& parameter_value) { std::string apex_name = parameter_name.substr(prefix.size()); Graph* graph = core_->getRoot()->getGraph(); std::vector<std::string> levels; std::size_t delim = 0; while(delim != std::string::npos) { delim = apex_name.find('/'); std::string subname = apex_name.substr(0, delim); if(!subname.empty()) { levels.push_back(subname); } apex_name = apex_name.substr(delim+1); } if(levels.empty()) { return; } NodeHandle* nh = nullptr; std::string param_name; for(std::size_t i = 0, n = levels.size(); i < n - 1; ++i) { const std::string subname = levels.at(i); std::cerr << "searching for " << subname << std::endl; nh = graph->findNodeHandleWithLabel(subname); if(!nh) { std::cerr << "no parameter for " << parameter_name << ", label " << subname << " non-existent" << std::endl; return; } if (NodePtr node = nh->getNode().lock()) { std::ostringstream param_name_builder; std::copy(std::next(levels.begin(), i + 1), levels.end(), std::ostream_iterator<std::string>(param_name_builder, "/")); param_name = param_name_builder.str(); param_name = param_name.substr(0, param_name.size() - 1); std::cerr << "searching for param " << param_name << std::endl; if (node->hasParameter(param_name)) break; boost::algorithm::replace_all(param_name, " ", "_"); std::cerr << "searching for param " << param_name << " (fallback)" << std::endl; if (node->hasParameter(param_name)) break; } if(i < n - 2) { graph = dynamic_cast<Graph*>(nh->getNode().lock().get()); if(!graph) { std::cerr << "no parameter for " << parameter_name << ", child " << subname << " is not a graph" << std::endl; return; } } } if(!nh) { return; } NodePtr node = nh->getNode().lock(); if(!node) { return; } if(!node->hasParameter(param_name)) { std::cerr << "node " << nh->getUUID() << " doesn't have a parameter called " << param_name << std::endl; return; } param::ParameterPtr p = node->getParameter(param_name); switch(parameter_value.getType()) { case XmlRpc::XmlRpcValue::TypeInt: { int val; ros::param::get(parameter_name, val); p->set(val); } break; case XmlRpc::XmlRpcValue::TypeDouble: { double val; ros::param::get(parameter_name, val); p->set(val); } break; case XmlRpc::XmlRpcValue::TypeBoolean: { bool val; ros::param::get(parameter_name, val); p->set(val); } break; case XmlRpc::XmlRpcValue::TypeString: { std::string val; ros::param::get(parameter_name, val); p->set(val); } break; default: break; } } void APEXRosInterface::registerCommandListener() { assert(ROSHandler::instance().isConnected()); global_command_sub_ = ROSHandler::instance().nh()->subscribe <std_msgs::String>("/syscommand", 10, std::bind(&APEXRosInterface::command, this, std::placeholders::_1, true)); private_command_sub_ = ROSHandler::instance().nh()->subscribe <std_msgs::String>("command", 10, std::bind(&APEXRosInterface::command, this, std::placeholders::_1, false)); ros::spinOnce(); } void APEXRosInterface::command(const std_msgs::StringConstPtr& cmd, bool global_cmd) { std::string command = cmd->data; bool local_cmd = !global_cmd; /* * pause / unpause: * - temporary disable everything to conserve computational power * - globally accepted, if this node is not disabled * * stop / resume * - completely disable / enable this subsystem, when it is not needed * - only locally accepted * - overwrites pause -> a disabled instance cannot be unpaused */ if(!disabled_) { // disabled state is stronger than pause / unpause if(command == "pause") { core_->setPause(true); } else if(command == "unpause"){ core_->setPause(false); } } if(local_cmd) { if(command == "stop") { disabled_ = true; core_->setPause(true); } else if(command == "resume") { disabled_ = false; core_->setPause(false); } } } void APEXRosInterface::registerClockWatchdog() { clock_sub_ = ROSHandler::instance().nh()->subscribe <rosgraph_msgs::Clock>("/clock", 10, std::bind(&APEXRosInterface::clock, this, std::placeholders::_1)); } void APEXRosInterface::clock(const rosgraph_msgs::ClockConstPtr &clock) { ros::Time now = clock->clock; if(now < last_clock_) { std::cerr << "time reset" << std::endl; TokenDataConstPtr data(new connection_types::AnyMessage); TokenPtr token = std::make_shared<Token>(data); token->setActive(true); clock_reset_event_->triggerWith(token); } last_clock_ = now; } void APEXRosInterface::shutdown() { ROSHandler::instance().stop(); RosMessageConversion::instance().shutdown(); } <commit_msg>using mapped parameters for roslaunch support<commit_after>/// HEADER #include "apex_ros_interface.h" /// PROJECT #include <csapex/utility/register_apex_plugin.h> #include <csapex_ros/ros_handler.h> #include "import_ros.h" #include <csapex/model/graph.h> #include <csapex/model/node_state.h> #include <csapex/factory/message_factory.h> #include <csapex_ros/ros_message_conversion.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex_ros/yaml_io.hpp> #include <csapex/model/graph_facade.h> #include <csapex/model/node_handle.h> #include <csapex/model/node.h> #include <csapex/signal/event.h> #include <csapex/msg/no_message.h> #include <csapex/model/token.h> #include <csapex/msg/any_message.h> /// SYSTEM #include <boost/regex.hpp> #include <boost/algorithm/string/replace.hpp> #include <std_msgs/Int32.h> #include <std_msgs/Bool.h> #include <std_msgs/String.h> #include <std_msgs/Float64.h> #include <QMimeData> CSAPEX_REGISTER_CLASS(csapex::APEXRosInterface, csapex::CorePlugin) using namespace csapex; template <typename RosType, typename ApexType> struct ConvertIntegral { static typename connection_types::GenericValueMessage<ApexType>::Ptr ros2apex(const typename RosType::ConstPtr &ros_msg) { typename connection_types::GenericValueMessage<ApexType>::Ptr out(new connection_types::GenericValueMessage<ApexType>); out->value = ros_msg->data; return out; } static typename RosType::Ptr apex2ros(const typename connection_types::GenericValueMessage<ApexType>::ConstPtr& apex_msg) { typename RosType::Ptr out(new RosType); out->data = apex_msg->value; return out; } }; APEXRosInterface::APEXRosInterface() : core_(nullptr), disabled_(false) { last_clock_ = ros::Time(0); } APEXRosInterface::~APEXRosInterface() { } void APEXRosInterface::prepare(Settings &settings) { ROSHandler::createInstance(settings); } void APEXRosInterface::init(CsApexCore &core) { core_ = &core; ROSHandler::instance().registerConnectionCallback([this]() { registerCommandListener(); registerClockWatchdog(); }); RosMessageConversion::registerConversion<std_msgs::Bool, connection_types::GenericValueMessage<bool>, ConvertIntegral<std_msgs::Bool, bool> >(); RosMessageConversion::registerConversion<std_msgs::Int32, connection_types::GenericValueMessage<int>, ConvertIntegral<std_msgs::Int32, int> >(); RosMessageConversion::registerConversion<std_msgs::Float64, connection_types::GenericValueMessage<double>, ConvertIntegral<std_msgs::Float64, double> >(); RosMessageConversion::registerConversion<std_msgs::String, connection_types::GenericValueMessage<std::string>, ConvertIntegral<std_msgs::String, std::string> >(); core_->loaded.connect([this](){ if(ROSHandler::instance().isConnected()) { XmlRpc::XmlRpcValue params, result, payload; params[0] = ros::this_node::getName(); std::string prefix = ros::this_node::getName(); if (ros::master::execute("getParamNames", params, result, payload, true)) { if(result.getType() != XmlRpc::XmlRpcValue::TypeArray) { return; } std::string name = result[1]; if(name != "Parameter names") { return; } XmlRpc::XmlRpcValue data = result[2]; for(std::size_t i = 0, total = data.size(); i < total; ++i) { std::string parameter_name = data[i]; if(parameter_name.substr(0, prefix.size()) != prefix) { continue; } try { XmlRpc::XmlRpcValue parameter_value; ros::param::getCached(parameter_name, parameter_value); loadParameterValue(prefix, parameter_name, parameter_value); } catch (std::exception e) { // silence } } } } }); } void APEXRosInterface::setupGraph(Graph *graph) { clock_reset_event_ = graph->createInternalEvent(connection_types::makeEmpty<connection_types::AnyMessage>(), graph->makeUUID("event_ros_time_reset"), "ros time reset"); } void APEXRosInterface::loadParameterValue(const std::string& prefix, const std::string& parameter_name, const XmlRpc::XmlRpcValue& parameter_value) { std::string apex_name = parameter_name.substr(prefix.size()); Graph* graph = core_->getRoot()->getGraph(); std::vector<std::string> levels; std::cerr << "analyzing parameter " << parameter_name << std::endl; std::size_t delim = 0; while(delim != std::string::npos) { delim = apex_name.find('/'); std::string subname = apex_name.substr(0, delim); if(!subname.empty()) { levels.push_back(subname); } apex_name = apex_name.substr(delim+1); } if(levels.empty()) { return; } NodeHandle* nh = nullptr; std::string param_name; for(std::size_t i = 0, n = levels.size(); i < n - 1; ++i) { const std::string subname = levels.at(i); std::cerr << "searching for " << subname << std::endl; nh = graph->findNodeHandleWithLabel(subname); if(!nh) { std::cerr << "no parameter for " << parameter_name << ", label " << subname << " non-existent" << std::endl; return; } if (NodePtr node = nh->getNode().lock()) { std::ostringstream param_name_builder; std::copy(std::next(levels.begin(), i + 1), levels.end(), std::ostream_iterator<std::string>(param_name_builder, "/")); param_name = param_name_builder.str(); param_name = param_name.substr(0, param_name.size() - 1); std::cerr << "searching for param " << param_name << " in node " << node->getUUID() << std::endl; if (node->hasParameter(param_name)) break; boost::algorithm::replace_all(param_name, " ", "_"); std::cerr << "searching for param " << param_name << " (fallback)" << std::endl; if (node->hasParameter(param_name)) break; } if(i < n - 2) { graph = dynamic_cast<Graph*>(nh->getNode().lock().get()); if(!graph) { std::cerr << "no parameter for " << parameter_name << ", child " << subname << " is not a graph" << std::endl; return; } } } std::cerr << "found parameter " << param_name << std::endl; if(!nh) { std::cerr << "cannot set parameter " << param_name << ", no node handle exists" << std::endl; return; } NodePtr node = nh->getNode().lock(); if(!node) { std::cerr << "cannot set parameter " << param_name << ", no node exists" << std::endl; return; } if(!node->hasParameter(param_name)) { std::cerr << "node " << nh->getUUID() << " doesn't have a parameter called " << param_name << std::endl; return; } param::ParameterPtr p = node->getMappedParameter(param_name); switch(parameter_value.getType()) { case XmlRpc::XmlRpcValue::TypeInt: { int val; ros::param::get(parameter_name, val); std::cerr << "setting int parameter for " << nh->getUUID() << ":" << param_name << std::endl; p->set(val); } break; case XmlRpc::XmlRpcValue::TypeDouble: { double val; ros::param::get(parameter_name, val); std::cerr << "setting double parameter for " << nh->getUUID() << ":" << param_name << std::endl; p->set(val); } break; case XmlRpc::XmlRpcValue::TypeBoolean: { bool val; ros::param::get(parameter_name, val); std::cerr << "setting bool parameter for " << nh->getUUID() << ":" << param_name << std::endl; p->set(val); } break; case XmlRpc::XmlRpcValue::TypeString: { std::string val; ros::param::get(parameter_name, val); std::cerr << "setting string parameter for " << nh->getUUID() << ":" << param_name << std::endl; p->set(val); } break; default: std::cerr << "cannot set parameter for " << nh->getUUID() << ":" << param_name << " is of unknown type " << (int) parameter_value.getType() << std::endl; break; } } void APEXRosInterface::registerCommandListener() { assert(ROSHandler::instance().isConnected()); global_command_sub_ = ROSHandler::instance().nh()->subscribe <std_msgs::String>("/syscommand", 10, std::bind(&APEXRosInterface::command, this, std::placeholders::_1, true)); private_command_sub_ = ROSHandler::instance().nh()->subscribe <std_msgs::String>("command", 10, std::bind(&APEXRosInterface::command, this, std::placeholders::_1, false)); ros::spinOnce(); } void APEXRosInterface::command(const std_msgs::StringConstPtr& cmd, bool global_cmd) { std::string command = cmd->data; bool local_cmd = !global_cmd; /* * pause / unpause: * - temporary disable everything to conserve computational power * - globally accepted, if this node is not disabled * * stop / resume * - completely disable / enable this subsystem, when it is not needed * - only locally accepted * - overwrites pause -> a disabled instance cannot be unpaused */ if(!disabled_) { // disabled state is stronger than pause / unpause if(command == "pause") { core_->setPause(true); } else if(command == "unpause"){ core_->setPause(false); } } if(local_cmd) { if(command == "stop") { disabled_ = true; core_->setPause(true); } else if(command == "resume") { disabled_ = false; core_->setPause(false); } } } void APEXRosInterface::registerClockWatchdog() { clock_sub_ = ROSHandler::instance().nh()->subscribe <rosgraph_msgs::Clock>("/clock", 10, std::bind(&APEXRosInterface::clock, this, std::placeholders::_1)); } void APEXRosInterface::clock(const rosgraph_msgs::ClockConstPtr &clock) { ros::Time now = clock->clock; if(now < last_clock_) { std::cerr << "time reset" << std::endl; TokenDataConstPtr data(new connection_types::AnyMessage); TokenPtr token = std::make_shared<Token>(data); token->setActive(true); clock_reset_event_->triggerWith(token); } last_clock_ = now; } void APEXRosInterface::shutdown() { ROSHandler::instance().stop(); RosMessageConversion::instance().shutdown(); } <|endoftext|>
<commit_before> /* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com) */ #include "pcl/gpu/containers/device_memory.hpp" #include "cuda_runtime_api.h" #include "assert.h" //temporary dependence, should eliminated in future //Replace with THROW_PCL_EXCEPTION from PCL2.0 API #include "pcl/gpu/utils/safe_call.hpp" #define HAVE_CUDA //#include "pcl_config.h" #if !defined(HAVE_CUDA) void throw_nogpu() { throw "PCL 2.0 exception"; } pcl::gpu::DeviceMemory::DeviceMemory() { throw_nogpu(); } pcl::gpu::DeviceMemory::DeviceMemory(void *, size_t) { throw_nogpu(); } pcl::gpu::DeviceMemory::DeviceMemory(size_t) { throw_nogpu(); } pcl::gpu::DeviceMemory::~DeviceMemory() { throw_nogpu(); } pcl::gpu::DeviceMemory::DeviceMemory(const DeviceMemory& ) { throw_nogpu(); } pcl::gpu::DeviceMemory& pcl::gpu::DeviceMemory::operator=(const pcl::gpu::DeviceMemory&) { throw_nogpu(); return *this;} void pcl::gpu::DeviceMemory::create(size_t) { throw_nogpu(); } void pcl::gpu::DeviceMemory::release() { throw_nogpu(); } void pcl::gpu::DeviceMemory::copyTo(DeviceMemory&) const { throw_nogpu(); } void pcl::gpu::DeviceMemory::upload(const void*, size_t) { throw_nogpu(); } void pcl::gpu::DeviceMemory::download(void*) const { throw_nogpu(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D() { throw_nogpu(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(int, int) { throw_nogpu(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(int, int, void*, size_t) { throw_nogpu(); } pcl::gpu::DeviceMemory2D::~DeviceMemory2D() { throw_nogpu(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(const DeviceMemory2D&) { throw_nogpu(); } pcl::gpu::DeviceMemory2D& pcl::gpu::DeviceMemory2D::operator=(const pcl::gpu::DeviceMemory2D&) { throw_nogpu(); return *this;} void pcl::gpu::DeviceMemory2D::create(int, int ) { throw_nogpu(); } void pcl::gpu::DeviceMemory2D::release() { throw_nogpu(); } void pcl::gpu::DeviceMemory2D::copyTo(DeviceMemory2D&) const { throw_nogpu(); } void pcl::gpu::DeviceMemory2D::upload(const void *, size_t, int, int ) { throw_nogpu(); } void pcl::gpu::DeviceMemory2D::download(void *, size_t ) const { throw_nogpu(); } #else ////////////////////////// XADD /////////////////////////////// #ifdef __GNUC__ #if __GNUC__*10 + __GNUC_MINOR__ >= 42 #if !defined WIN32 && (defined __i486__ || defined __i586__ || defined __i686__ || defined __MMX__ || defined __SSE__ || defined __ppc__) #define CV_XADD __sync_fetch_and_add #else #include <ext/atomicity.h> #define CV_XADD __gnu_cxx::__exchange_and_add #endif #else #include <bits/atomicity.h> #if __GNUC__*10 + __GNUC_MINOR__ >= 34 #define CV_XADD __gnu_cxx::__exchange_and_add #else #define CV_XADD __exchange_and_add #endif #endif #elif defined WIN32 || defined _WIN32 #include <intrin.h> #define CV_XADD(addr,delta) _InterlockedExchangeAdd((long volatile*)(addr), (delta)) #else template<typename _Tp> static inline _Tp CV_XADD(_Tp* addr, _Tp delta) { int tmp = *addr; *addr += delta; return tmp; } #endif //////////////////////// DeviceArray ///////////////////////////// pcl::gpu::DeviceMemory::DeviceMemory() : data(0), sizeBytes(0), refcount(0) {} pcl::gpu::DeviceMemory::DeviceMemory(void *ptr_arg, size_t sizeBytes_arg) : data((char*)ptr_arg), sizeBytes(sizeBytes_arg), refcount(0){} pcl::gpu::DeviceMemory::DeviceMemory(size_t sizeBtes_arg) : data(0), sizeBytes(0), refcount(0) { create(sizeBtes_arg); } pcl::gpu::DeviceMemory::~DeviceMemory() { release(); } pcl::gpu::DeviceMemory::DeviceMemory(const DeviceMemory& other_arg) : data(other_arg.data), sizeBytes(other_arg.sizeBytes), refcount(other_arg.refcount) { if( refcount ) CV_XADD(refcount, 1); } pcl::gpu::DeviceMemory& pcl::gpu::DeviceMemory::operator = (const pcl::gpu::DeviceMemory& other_arg) { if( this != &other_arg ) { if( other_arg.refcount ) CV_XADD(other_arg.refcount, 1); release(); data = other_arg.data; sizeBytes = other_arg.sizeBytes; refcount = other_arg.refcount; } return *this; } void pcl::gpu::DeviceMemory::create(size_t sizeBytes_arg) { if (sizeBytes_arg == sizeBytes) return; if( sizeBytes_arg > 0) { if( data ) release(); sizeBytes = sizeBytes_arg; cudaSafeCall( cudaMalloc((void**)&data, sizeBytes) ); //refcount_ = (int*)cv::fastMalloc(sizeof(*refcount_)); refcount = new int; *refcount = 1; } } void pcl::gpu::DeviceMemory::copyTo(DeviceMemory& other) const { assert(!this.data); other.create(sizeBytes); cudaSafeCall( cudaMemcpy(other.data, data, sizeBytes, cudaMemcpyDeviceToDevice) ); cudaSafeCall( cudaDeviceSynchronize() ); } void pcl::gpu::DeviceMemory::release() { if( refcount && CV_XADD(refcount, -1) == 1 ) { //cv::fastFree(refcount); delete refcount; cudaSafeCall( cudaFree(data) ); } data = 0; sizeBytes = 0; refcount = 0; } void pcl::gpu::DeviceMemory::upload(const void *host_ptr_arg, size_t sizeBytes_arg) { create(sizeBytes_arg); cudaSafeCall( cudaMemcpy(data, host_ptr_arg, sizeBytes, cudaMemcpyHostToDevice) ); } void pcl::gpu::DeviceMemory::download(void *host_ptr_arg) const { cudaSafeCall( cudaMemcpy(host_ptr_arg, data, sizeBytes, cudaMemcpyDeviceToHost) ); } //////////////////////// DeviceArray2D ///////////////////////////// pcl::gpu::DeviceMemory2D::DeviceMemory2D() : colsBytes(0), rows(0), data(0), step(0), refcount(0) {} pcl::gpu::DeviceMemory2D::DeviceMemory2D(int rows_arg, int colsBytes_arg) : colsBytes(0), rows(0), data(0), step(0), refcount(0) { create(rows_arg, colsBytes_arg); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(int rows_arg, int colsBytes_arg, void *data_arg, size_t step_arg) : colsBytes(colsBytes_arg), rows(rows_arg), data((char*)data_arg), step(step_arg), refcount(0) {} pcl::gpu::DeviceMemory2D::~DeviceMemory2D() { release(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(const DeviceMemory2D& other_arg) : colsBytes(other_arg.colsBytes), rows(other_arg.rows), data(other_arg.data), step(other_arg.step), refcount(other_arg.refcount) { if( refcount ) CV_XADD(refcount, 1); } pcl::gpu::DeviceMemory2D& pcl::gpu::DeviceMemory2D::operator = (const pcl::gpu::DeviceMemory2D& other_arg) { if( this != &other_arg ) { if( other_arg.refcount ) CV_XADD(other_arg.refcount, 1); release(); colsBytes = other_arg.colsBytes; rows = other_arg.rows; data = other_arg.data; step = other_arg.step; refcount = other_arg.refcount; } return *this; } void pcl::gpu::DeviceMemory2D::create(int rows_arg, int colsBytes_arg) { if (colsBytes == colsBytes_arg && rows == rows_arg) return; if( rows_arg > 0 && colsBytes_arg > 0) { if( data ) release(); colsBytes = colsBytes_arg; rows = rows_arg; cudaSafeCall( cudaMallocPitch( (void**)&data, &step, colsBytes, rows) ); //refcount = (int*)cv::fastMalloc(sizeof(*refcount)); refcount = new int; *refcount = 1; } } void pcl::gpu::DeviceMemory2D::release() { if( refcount && CV_XADD(refcount, -1) == 1 ) { //cv::fastFree(refcount); delete refcount; cudaSafeCall( cudaFree(data) ); } colsBytes = 0; rows = 0; data = 0; step = 0; refcount = 0; } void pcl::gpu::DeviceMemory2D::copyTo(DeviceMemory2D& other) const { assert(!this.data); other.create(rows, colsBytes); cudaSafeCall( cudaMemcpy2D(other.data, other.step, data, step, colsBytes, rows, cudaMemcpyDeviceToDevice) ); cudaSafeCall( cudaDeviceSynchronize() ); } void pcl::gpu::DeviceMemory2D::upload(const void *host_ptr_arg, size_t host_step_arg, int rows_arg, int colsBytes_arg) { create(rows_arg, colsBytes_arg); cudaSafeCall( cudaMemcpy2D(data, step, host_ptr_arg, host_step_arg, colsBytes, rows, cudaMemcpyHostToDevice) ); } void pcl::gpu::DeviceMemory2D::download(void *host_ptr_arg, size_t host_step_arg) const { cudaSafeCall( cudaMemcpy2D(host_ptr_arg, host_step_arg, data, step, colsBytes, rows, cudaMemcpyDeviceToHost) ); } #endif<commit_msg>misprint(compilation)<commit_after> /* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Anatoly Baskeheev, Itseez Ltd, (myname.mysurname@mycompany.com) */ #include "pcl/gpu/containers/device_memory.hpp" #include "cuda_runtime_api.h" #include "assert.h" //temporary dependence, should eliminated in future //Replace with THROW_PCL_EXCEPTION from PCL2.0 API #include "pcl/gpu/utils/safe_call.hpp" #define HAVE_CUDA //#include "pcl_config.h" #if !defined(HAVE_CUDA) void throw_nogpu() { throw "PCL 2.0 exception"; } pcl::gpu::DeviceMemory::DeviceMemory() { throw_nogpu(); } pcl::gpu::DeviceMemory::DeviceMemory(void *, size_t) { throw_nogpu(); } pcl::gpu::DeviceMemory::DeviceMemory(size_t) { throw_nogpu(); } pcl::gpu::DeviceMemory::~DeviceMemory() { throw_nogpu(); } pcl::gpu::DeviceMemory::DeviceMemory(const DeviceMemory& ) { throw_nogpu(); } pcl::gpu::DeviceMemory& pcl::gpu::DeviceMemory::operator=(const pcl::gpu::DeviceMemory&) { throw_nogpu(); return *this;} void pcl::gpu::DeviceMemory::create(size_t) { throw_nogpu(); } void pcl::gpu::DeviceMemory::release() { throw_nogpu(); } void pcl::gpu::DeviceMemory::copyTo(DeviceMemory&) const { throw_nogpu(); } void pcl::gpu::DeviceMemory::upload(const void*, size_t) { throw_nogpu(); } void pcl::gpu::DeviceMemory::download(void*) const { throw_nogpu(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D() { throw_nogpu(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(int, int) { throw_nogpu(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(int, int, void*, size_t) { throw_nogpu(); } pcl::gpu::DeviceMemory2D::~DeviceMemory2D() { throw_nogpu(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(const DeviceMemory2D&) { throw_nogpu(); } pcl::gpu::DeviceMemory2D& pcl::gpu::DeviceMemory2D::operator=(const pcl::gpu::DeviceMemory2D&) { throw_nogpu(); return *this;} void pcl::gpu::DeviceMemory2D::create(int, int ) { throw_nogpu(); } void pcl::gpu::DeviceMemory2D::release() { throw_nogpu(); } void pcl::gpu::DeviceMemory2D::copyTo(DeviceMemory2D&) const { throw_nogpu(); } void pcl::gpu::DeviceMemory2D::upload(const void *, size_t, int, int ) { throw_nogpu(); } void pcl::gpu::DeviceMemory2D::download(void *, size_t ) const { throw_nogpu(); } #else ////////////////////////// XADD /////////////////////////////// #ifdef __GNUC__ #if __GNUC__*10 + __GNUC_MINOR__ >= 42 #if !defined WIN32 && (defined __i486__ || defined __i586__ || defined __i686__ || defined __MMX__ || defined __SSE__ || defined __ppc__) #define CV_XADD __sync_fetch_and_add #else #include <ext/atomicity.h> #define CV_XADD __gnu_cxx::__exchange_and_add #endif #else #include <bits/atomicity.h> #if __GNUC__*10 + __GNUC_MINOR__ >= 34 #define CV_XADD __gnu_cxx::__exchange_and_add #else #define CV_XADD __exchange_and_add #endif #endif #elif defined WIN32 || defined _WIN32 #include <intrin.h> #define CV_XADD(addr,delta) _InterlockedExchangeAdd((long volatile*)(addr), (delta)) #else template<typename _Tp> static inline _Tp CV_XADD(_Tp* addr, _Tp delta) { int tmp = *addr; *addr += delta; return tmp; } #endif //////////////////////// DeviceArray ///////////////////////////// pcl::gpu::DeviceMemory::DeviceMemory() : data(0), sizeBytes(0), refcount(0) {} pcl::gpu::DeviceMemory::DeviceMemory(void *ptr_arg, size_t sizeBytes_arg) : data((char*)ptr_arg), sizeBytes(sizeBytes_arg), refcount(0){} pcl::gpu::DeviceMemory::DeviceMemory(size_t sizeBtes_arg) : data(0), sizeBytes(0), refcount(0) { create(sizeBtes_arg); } pcl::gpu::DeviceMemory::~DeviceMemory() { release(); } pcl::gpu::DeviceMemory::DeviceMemory(const DeviceMemory& other_arg) : data(other_arg.data), sizeBytes(other_arg.sizeBytes), refcount(other_arg.refcount) { if( refcount ) CV_XADD(refcount, 1); } pcl::gpu::DeviceMemory& pcl::gpu::DeviceMemory::operator = (const pcl::gpu::DeviceMemory& other_arg) { if( this != &other_arg ) { if( other_arg.refcount ) CV_XADD(other_arg.refcount, 1); release(); data = other_arg.data; sizeBytes = other_arg.sizeBytes; refcount = other_arg.refcount; } return *this; } void pcl::gpu::DeviceMemory::create(size_t sizeBytes_arg) { if (sizeBytes_arg == sizeBytes) return; if( sizeBytes_arg > 0) { if( data ) release(); sizeBytes = sizeBytes_arg; cudaSafeCall( cudaMalloc((void**)&data, sizeBytes) ); //refcount_ = (int*)cv::fastMalloc(sizeof(*refcount_)); refcount = new int; *refcount = 1; } } void pcl::gpu::DeviceMemory::copyTo(DeviceMemory& other) const { assert(data); other.create(sizeBytes); cudaSafeCall( cudaMemcpy(other.data, data, sizeBytes, cudaMemcpyDeviceToDevice) ); cudaSafeCall( cudaDeviceSynchronize() ); } void pcl::gpu::DeviceMemory::release() { if( refcount && CV_XADD(refcount, -1) == 1 ) { //cv::fastFree(refcount); delete refcount; cudaSafeCall( cudaFree(data) ); } data = 0; sizeBytes = 0; refcount = 0; } void pcl::gpu::DeviceMemory::upload(const void *host_ptr_arg, size_t sizeBytes_arg) { create(sizeBytes_arg); cudaSafeCall( cudaMemcpy(data, host_ptr_arg, sizeBytes, cudaMemcpyHostToDevice) ); } void pcl::gpu::DeviceMemory::download(void *host_ptr_arg) const { cudaSafeCall( cudaMemcpy(host_ptr_arg, data, sizeBytes, cudaMemcpyDeviceToHost) ); } //////////////////////// DeviceArray2D ///////////////////////////// pcl::gpu::DeviceMemory2D::DeviceMemory2D() : colsBytes(0), rows(0), data(0), step(0), refcount(0) {} pcl::gpu::DeviceMemory2D::DeviceMemory2D(int rows_arg, int colsBytes_arg) : colsBytes(0), rows(0), data(0), step(0), refcount(0) { create(rows_arg, colsBytes_arg); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(int rows_arg, int colsBytes_arg, void *data_arg, size_t step_arg) : colsBytes(colsBytes_arg), rows(rows_arg), data((char*)data_arg), step(step_arg), refcount(0) {} pcl::gpu::DeviceMemory2D::~DeviceMemory2D() { release(); } pcl::gpu::DeviceMemory2D::DeviceMemory2D(const DeviceMemory2D& other_arg) : colsBytes(other_arg.colsBytes), rows(other_arg.rows), data(other_arg.data), step(other_arg.step), refcount(other_arg.refcount) { if( refcount ) CV_XADD(refcount, 1); } pcl::gpu::DeviceMemory2D& pcl::gpu::DeviceMemory2D::operator = (const pcl::gpu::DeviceMemory2D& other_arg) { if( this != &other_arg ) { if( other_arg.refcount ) CV_XADD(other_arg.refcount, 1); release(); colsBytes = other_arg.colsBytes; rows = other_arg.rows; data = other_arg.data; step = other_arg.step; refcount = other_arg.refcount; } return *this; } void pcl::gpu::DeviceMemory2D::create(int rows_arg, int colsBytes_arg) { if (colsBytes == colsBytes_arg && rows == rows_arg) return; if( rows_arg > 0 && colsBytes_arg > 0) { if( data ) release(); colsBytes = colsBytes_arg; rows = rows_arg; cudaSafeCall( cudaMallocPitch( (void**)&data, &step, colsBytes, rows) ); //refcount = (int*)cv::fastMalloc(sizeof(*refcount)); refcount = new int; *refcount = 1; } } void pcl::gpu::DeviceMemory2D::release() { if( refcount && CV_XADD(refcount, -1) == 1 ) { //cv::fastFree(refcount); delete refcount; cudaSafeCall( cudaFree(data) ); } colsBytes = 0; rows = 0; data = 0; step = 0; refcount = 0; } void pcl::gpu::DeviceMemory2D::copyTo(DeviceMemory2D& other) const { assert(data); other.create(rows, colsBytes); cudaSafeCall( cudaMemcpy2D(other.data, other.step, data, step, colsBytes, rows, cudaMemcpyDeviceToDevice) ); cudaSafeCall( cudaDeviceSynchronize() ); } void pcl::gpu::DeviceMemory2D::upload(const void *host_ptr_arg, size_t host_step_arg, int rows_arg, int colsBytes_arg) { create(rows_arg, colsBytes_arg); cudaSafeCall( cudaMemcpy2D(data, step, host_ptr_arg, host_step_arg, colsBytes, rows, cudaMemcpyHostToDevice) ); } void pcl::gpu::DeviceMemory2D::download(void *host_ptr_arg, size_t host_step_arg) const { cudaSafeCall( cudaMemcpy2D(host_ptr_arg, host_step_arg, data, step, colsBytes, rows, cudaMemcpyDeviceToHost) ); } #endif<|endoftext|>
<commit_before>#include <Salamandre-daemon/Daemon.hpp> #include <iostream> #include <csignal> #define GUI_PORT 1 #define SERVER_PORT 2 #define NB_ARGS (SERVER_PORT + 1) salamandre::Daemon* server = nullptr; void stop_server_handler(int sig) { std::cout<<"Recv signal "<<sig<<". Stoping server.\n Please wait."<<std::endl; if(server) server->stop(); } int main(int argc,char* argv[]) { int gui_port = 3842; int server_port = 3843; if(argc < NB_ARGS) { std::cout<<"Usage is:\n\t"<<argv[0]<<"<gui port> <server port>"<<std::endl; if(argc <= GUI_PORT) std::cout<<"Use "<<gui_port<<"as default gui port"<<std::endl; if(argc <= SERVER_PORT) std::cout<<"Use "<<server_port<<"as default server port"<<std::endl; } if(argc > GUI_PORT) gui_port = atoi(argv[GUI_PORT]); if(argc > SERVER_PORT) server_port = atoi(argv[SERVER_PORT]); std::cout<<"Daemon start on:" <<"\n\tgui port : "<<gui_port <<"\n\tfile server port : "<<server_port <<"\nPress ^C to exit" <<std::endl; std::signal(SIGINT, stop_server_handler); try { ntw::Socket::init(); server = new salamandre::Daemon(gui_port,server_port); server->start(); server->wait(); delete server; server = nullptr; ntw::Socket::close(); } catch(ntw::SocketExeption& e) { std::cout<<e.what()<<std::endl; } std::cout<<"Daemon is now close. Good bye"<<std::endl; return 0; } <commit_msg>add base files<commit_after>#include <Salamandre-daemon/Daemon.hpp> #include <iostream> #include <csignal> #define GUI_PORT 1 #define SERVER_PORT 2 #define NB_ARGS (SERVER_PORT + 1) salamandre::Daemon* server = nullptr; void stop_server_handler(int sig) { std::cout<<"Recv signal "<<sig<<". Stoping server.\n Please wait."<<std::endl; if(server) server->stop(); } int main(int argc,char* argv[]) { int gui_port = 3842; int server_port = 3843; if(argc < NB_ARGS) { std::cout<<"Usage is:\n\t"<<argv[0]<<"<gui port> <server port>"<<std::endl; if(argc <= GUI_PORT) std::cout<<"Use "<<gui_port<<"as default gui port"<<std::endl; if(argc <= SERVER_PORT) std::cout<<"Use "<<server_port<<"as default server port"<<std::endl; } if(argc > GUI_PORT) gui_port = atoi(argv[GUI_PORT]); if(argc > SERVER_PORT) server_port = atoi(argv[SERVER_PORT]); std::cout<<"Daemon start on:" <<"\n\tgui port : "<<gui_port <<"\n\tfile server port : "<<server_port <<"\nPress ^C to exit" <<std::endl<<std::endl; std::signal(SIGINT, stop_server_handler); try { ntw::Socket::init(); server = new salamandre::Daemon(gui_port,server_port); server->start(); server->wait(); delete server; server = nullptr; ntw::Socket::close(); } catch(ntw::SocketExeption& e) { std::cout<<e.what()<<std::endl; } std::cout<<"Daemon is now close. Good bye"<<std::endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Actor.h" #include "Vector3.h" #include "Quaternion.h" #include "Matrix4x4.h" #include "Unit.h" #include "Device.h" #include "Physics.h" #include "Log.h" #include "SceneGraph.h" #include "PxPhysicsAPI.h" using physx::PxRigidDynamicFlag; using physx::PxMat44; using physx::PxTransform; using physx::PxActorFlag; using physx::PxVec3; using physx::PxReal; using physx::PxRigidBody; using physx::PxRigidDynamic; using physx::PxPlaneGeometry; using physx::PxSphereGeometry; using physx::PxBoxGeometry; using physx::PxRigidBodyExt; using physx::PxD6Joint; using physx::PxD6JointCreate; using physx::PxD6Axis; using physx::PxD6Motion; namespace crown { //----------------------------------------------------------------------------- Actor::Actor(PxScene* scene, SceneGraph& sg, int32_t node, ActorType::Enum type, const Vector3& pos, const Quaternion& rot) : m_scene(scene) , m_scene_graph(sg) , m_node(node) , m_type(type) { Matrix4x4 m(rot, pos); m.transpose(); PxMat44 pose((PxReal*)(m.to_float_ptr())); switch (type) { case ActorType::STATIC: { m_actor = device()->physx()->createRigidStatic(PxTransform(pose)); break; } case ActorType::DYNAMIC_PHYSICAL: case ActorType::DYNAMIC_KINEMATIC: { m_actor = device()->physx()->createRigidDynamic(PxTransform(pose)); if (type == ActorType::DYNAMIC_KINEMATIC) { static_cast<PxRigidDynamic*>(m_actor)->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true); } break; } default: { CE_FATAL("Oops, unknown actor type"); break; } } m_actor->userData = this; m_mat = device()->physx()->createMaterial(0.5f, 0.5f, 0.5f); create_box(Vector3(0, 0, 0), .5, .5, .5); PxRigidBodyExt::setMassAndUpdateInertia(*static_cast<PxRigidDynamic*>(m_actor), 500.0f); PxD6Joint* joint = PxD6JointCreate(*device()->physx(), m_actor, PxTransform(pose), NULL, PxTransform(pose)); joint->setMotion(PxD6Axis::eX, PxD6Motion::eFREE); joint->setMotion(PxD6Axis::eY, PxD6Motion::eFREE); //joint->setMotion(PxD6Axis::eZ, PxD6Motion::eFREE); //joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); m_scene->addActor(*m_actor); } //----------------------------------------------------------------------------- Actor::~Actor() { if (m_actor) { m_scene->removeActor(*m_actor); m_actor->release(); } } //----------------------------------------------------------------------------- void Actor::create_sphere(const Vector3& position, float radius) { m_actor->createShape(PxSphereGeometry(radius), *m_mat); } //----------------------------------------------------------------------------- void Actor::create_box(const Vector3& position, float a, float b, float c) { m_actor->createShape(PxBoxGeometry(a, b, c), *m_mat); } //----------------------------------------------------------------------------- void Actor::create_plane(const Vector3& /*position*/, const Vector3& /*normal*/) { m_actor->createShape(PxPlaneGeometry(), *m_mat); } //----------------------------------------------------------------------------- void Actor::enable_gravity() { m_actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, false); } //----------------------------------------------------------------------------- void Actor::disable_gravity() { m_actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); } //----------------------------------------------------------------------------- bool Actor::is_static() const { return m_type == ActorType::STATIC; } //----------------------------------------------------------------------------- bool Actor::is_dynamic() const { return m_type == ActorType::DYNAMIC_PHYSICAL || m_type == ActorType::DYNAMIC_KINEMATIC; } //----------------------------------------------------------------------------- bool Actor::is_kinematic() const { return m_type == ActorType::DYNAMIC_KINEMATIC; } //----------------------------------------------------------------------------- bool Actor::is_physical() const { return m_type == ActorType::DYNAMIC_PHYSICAL; } //----------------------------------------------------------------------------- float Actor::linear_damping() const { return ((PxRigidDynamic*)m_actor)->getLinearDamping(); } //----------------------------------------------------------------------------- void Actor::set_linear_damping(float rate) { ((PxRigidDynamic*)m_actor)->setLinearDamping(rate); } //----------------------------------------------------------------------------- float Actor::angular_damping() const { return ((PxRigidDynamic*)m_actor)->getAngularDamping(); } //----------------------------------------------------------------------------- void Actor::set_angular_damping(float rate) { ((PxRigidDynamic*)m_actor)->setAngularDamping(rate); } //----------------------------------------------------------------------------- Vector3 Actor::linear_velocity() const { PxVec3 vel = ((PxRigidBody*)m_actor)->getLinearVelocity(); Vector3 velocity(vel.x, vel.y, vel.z); return velocity; } //----------------------------------------------------------------------------- void Actor::set_linear_velocity(const Vector3& vel) { PxVec3 velocity(vel.x, vel.y, vel.z); ((PxRigidBody*)m_actor)->setLinearVelocity(velocity); } //----------------------------------------------------------------------------- Vector3 Actor::angular_velocity() const { PxVec3 vel = ((PxRigidBody*)m_actor)->getAngularVelocity(); Vector3 velocity(vel.x, vel.y, vel.z); return velocity; } //----------------------------------------------------------------------------- void Actor::set_angular_velocity(const Vector3& vel) { PxVec3 velocity(vel.x, vel.y, vel.z); ((PxRigidBody*)m_actor)->setAngularVelocity(velocity); } //----------------------------------------------------------------------------- bool Actor::is_sleeping() { return ((PxRigidDynamic*)m_actor)->isSleeping(); } //----------------------------------------------------------------------------- void Actor::wake_up() { ((PxRigidDynamic*)m_actor)->wakeUp(); } //----------------------------------------------------------------------------- void Actor::update_pose() { // Read world pose Matrix4x4 wp = m_scene_graph.world_pose(m_node); Matrix4x4 a = wp; const PxMat44 pose((PxReal*) (wp.to_float_ptr())); const PxTransform world_transform(pose); switch (m_type) { case ActorType::DYNAMIC_KINEMATIC: { static_cast<PxRigidDynamic*>(m_actor)->setKinematicTarget(world_transform); break; } default: break; } } //----------------------------------------------------------------------------- void Actor::update(const Matrix4x4& pose) { if (m_type == ActorType::DYNAMIC_PHYSICAL) { m_scene_graph.set_world_pose(m_node, pose); } } } // namespace crown<commit_msg>Remove unused variable<commit_after>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Actor.h" #include "Vector3.h" #include "Quaternion.h" #include "Matrix4x4.h" #include "Unit.h" #include "Device.h" #include "Physics.h" #include "Log.h" #include "SceneGraph.h" #include "PxPhysicsAPI.h" using physx::PxRigidDynamicFlag; using physx::PxMat44; using physx::PxTransform; using physx::PxActorFlag; using physx::PxVec3; using physx::PxReal; using physx::PxRigidBody; using physx::PxRigidDynamic; using physx::PxPlaneGeometry; using physx::PxSphereGeometry; using physx::PxBoxGeometry; using physx::PxRigidBodyExt; using physx::PxD6Joint; using physx::PxD6JointCreate; using physx::PxD6Axis; using physx::PxD6Motion; namespace crown { //----------------------------------------------------------------------------- Actor::Actor(PxScene* scene, SceneGraph& sg, int32_t node, ActorType::Enum type, const Vector3& pos, const Quaternion& rot) : m_scene(scene) , m_scene_graph(sg) , m_node(node) , m_type(type) { Matrix4x4 m(rot, pos); m.transpose(); PxMat44 pose((PxReal*)(m.to_float_ptr())); switch (type) { case ActorType::STATIC: { m_actor = device()->physx()->createRigidStatic(PxTransform(pose)); break; } case ActorType::DYNAMIC_PHYSICAL: case ActorType::DYNAMIC_KINEMATIC: { m_actor = device()->physx()->createRigidDynamic(PxTransform(pose)); if (type == ActorType::DYNAMIC_KINEMATIC) { static_cast<PxRigidDynamic*>(m_actor)->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true); } break; } default: { CE_FATAL("Oops, unknown actor type"); break; } } m_actor->userData = this; m_mat = device()->physx()->createMaterial(0.5f, 0.5f, 0.5f); create_box(Vector3(0, 0, 0), .5, .5, .5); PxRigidBodyExt::setMassAndUpdateInertia(*static_cast<PxRigidDynamic*>(m_actor), 500.0f); PxD6Joint* joint = PxD6JointCreate(*device()->physx(), m_actor, PxTransform(pose), NULL, PxTransform(pose)); joint->setMotion(PxD6Axis::eX, PxD6Motion::eFREE); joint->setMotion(PxD6Axis::eY, PxD6Motion::eFREE); //joint->setMotion(PxD6Axis::eZ, PxD6Motion::eFREE); //joint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); joint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); m_scene->addActor(*m_actor); } //----------------------------------------------------------------------------- Actor::~Actor() { if (m_actor) { m_scene->removeActor(*m_actor); m_actor->release(); } } //----------------------------------------------------------------------------- void Actor::create_sphere(const Vector3& position, float radius) { m_actor->createShape(PxSphereGeometry(radius), *m_mat); } //----------------------------------------------------------------------------- void Actor::create_box(const Vector3& position, float a, float b, float c) { m_actor->createShape(PxBoxGeometry(a, b, c), *m_mat); } //----------------------------------------------------------------------------- void Actor::create_plane(const Vector3& /*position*/, const Vector3& /*normal*/) { m_actor->createShape(PxPlaneGeometry(), *m_mat); } //----------------------------------------------------------------------------- void Actor::enable_gravity() { m_actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, false); } //----------------------------------------------------------------------------- void Actor::disable_gravity() { m_actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); } //----------------------------------------------------------------------------- bool Actor::is_static() const { return m_type == ActorType::STATIC; } //----------------------------------------------------------------------------- bool Actor::is_dynamic() const { return m_type == ActorType::DYNAMIC_PHYSICAL || m_type == ActorType::DYNAMIC_KINEMATIC; } //----------------------------------------------------------------------------- bool Actor::is_kinematic() const { return m_type == ActorType::DYNAMIC_KINEMATIC; } //----------------------------------------------------------------------------- bool Actor::is_physical() const { return m_type == ActorType::DYNAMIC_PHYSICAL; } //----------------------------------------------------------------------------- float Actor::linear_damping() const { return ((PxRigidDynamic*)m_actor)->getLinearDamping(); } //----------------------------------------------------------------------------- void Actor::set_linear_damping(float rate) { ((PxRigidDynamic*)m_actor)->setLinearDamping(rate); } //----------------------------------------------------------------------------- float Actor::angular_damping() const { return ((PxRigidDynamic*)m_actor)->getAngularDamping(); } //----------------------------------------------------------------------------- void Actor::set_angular_damping(float rate) { ((PxRigidDynamic*)m_actor)->setAngularDamping(rate); } //----------------------------------------------------------------------------- Vector3 Actor::linear_velocity() const { PxVec3 vel = ((PxRigidBody*)m_actor)->getLinearVelocity(); Vector3 velocity(vel.x, vel.y, vel.z); return velocity; } //----------------------------------------------------------------------------- void Actor::set_linear_velocity(const Vector3& vel) { PxVec3 velocity(vel.x, vel.y, vel.z); ((PxRigidBody*)m_actor)->setLinearVelocity(velocity); } //----------------------------------------------------------------------------- Vector3 Actor::angular_velocity() const { PxVec3 vel = ((PxRigidBody*)m_actor)->getAngularVelocity(); Vector3 velocity(vel.x, vel.y, vel.z); return velocity; } //----------------------------------------------------------------------------- void Actor::set_angular_velocity(const Vector3& vel) { PxVec3 velocity(vel.x, vel.y, vel.z); ((PxRigidBody*)m_actor)->setAngularVelocity(velocity); } //----------------------------------------------------------------------------- bool Actor::is_sleeping() { return ((PxRigidDynamic*)m_actor)->isSleeping(); } //----------------------------------------------------------------------------- void Actor::wake_up() { ((PxRigidDynamic*)m_actor)->wakeUp(); } //----------------------------------------------------------------------------- void Actor::update_pose() { // Read world pose Matrix4x4 wp = m_scene_graph.world_pose(m_node); const PxMat44 pose((PxReal*) (wp.to_float_ptr())); const PxTransform world_transform(pose); switch (m_type) { case ActorType::DYNAMIC_KINEMATIC: { static_cast<PxRigidDynamic*>(m_actor)->setKinematicTarget(world_transform); break; } default: break; } } //----------------------------------------------------------------------------- void Actor::update(const Matrix4x4& pose) { if (m_type == ActorType::DYNAMIC_PHYSICAL) { m_scene_graph.set_world_pose(m_node, pose); } } } // namespace crown<|endoftext|>
<commit_before>#include "engine/Engine.hpp" #include <SDL2/SDL.h> using namespace std; using namespace glm; Engine::Engine(int argc, char** argv) : _wnd(nullptr) { for(int i = 0; i < argc; ++i) _args.push_back(string{argv[i]}); } Engine::~Engine() { } int Engine::run(Application* app) { _running = true; _exit_code = 0; SDL_Init(SDL_INIT_VIDEO); SDL_DisplayMode ask_mode; ask_mode.format = SDL_PIXELFORMAT_RGBA8888; ask_mode.w = 1920; ask_mode.h = 1080; ask_mode.refresh_rate = 60; SDL_DisplayMode mode; SDL_GetClosestDisplayMode(0, &ask_mode, &mode); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, SDL_TRUE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); _wnd = SDL_CreateWindow("OpenGL ES 2.0 Rendering Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mode.w, mode.h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN); SDL_SetWindowDisplayMode(_wnd, &mode); SDL_GLContext ctx = SDL_GL_CreateContext(_wnd); SDL_GL_MakeCurrent(_wnd, ctx); gladLoadGLES2Loader((GLADloadproc) &SDL_GL_GetProcAddress); auto fb_size = framebuffer_size(); glViewport(0, 0, fb_size.x, fb_size.y); glClearColor(0.2f, 0.2f, 0.2f, 1.f); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); SDL_GL_SetSwapInterval(1); SDL_GL_SwapWindow(_wnd); app->initialize(); TimePoint last_time{}; Duration accumulator{}; while(_running) { TimePoint new_time = Clock::now(); Duration dT = new_time - last_time; last_time = new_time; accumulator += dT; SDL_Event e; while(SDL_PollEvent(&e)) { if(e.type == SDL_WINDOWEVENT_CLOSE) _running = false; if(e.type == SDL_KEYUP) app->keyboard_event(static_cast<Key>(e.key.keysym.scancode), false); if(e.type == SDL_KEYDOWN) app->keyboard_event(static_cast<Key>(e.key.keysym.scancode), true); if(e.type == SDL_TEXTINPUT) app->keyboard_character_event(e.text.text); if(e.type == SDL_MOUSEMOTION) app->mouse_move_event({e.motion.xrel, e.motion.yrel}); if(e.type == SDL_MOUSEBUTTONUP) app->mouse_button_event({e.button.x, e.button.y}, static_cast<MouseButton>(e.button.button), false); if(e.type == SDL_MOUSEBUTTONDOWN) app->mouse_button_event({e.button.x, e.button.y}, static_cast<MouseButton>(e.button.button), true); if(e.type == SDL_MOUSEWHEEL) app->scroll_event({e.wheel.x, e.wheel.y}); if(e.type == SDL_WINDOWEVENT_RESIZED) app->resize_event(e.window.data1, e.window.data2); } if(accumulator >= app->fixed_time_step()) { app->update(accumulator); accumulator = Duration{}; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); app->frame_start(); app->frame(); app->frame_end(); SDL_GL_SwapWindow(_wnd); } delete app; SDL_GL_DeleteContext(ctx); SDL_DestroyWindow(_wnd); _wnd = nullptr; SDL_Quit(); return _exit_code; } glm::ivec2 Engine::framebuffer_size() const { ivec2 ret; SDL_GL_GetDrawableSize(_wnd, &ret.x, &ret.y); return ret; } glm::ivec2 Engine::window_size() const { ivec2 ret; SDL_GetWindowSize(_wnd, &ret.x, &ret.y); return ret; } <commit_msg>Removed an if statement<commit_after>#include "engine/Engine.hpp" #include <SDL2/SDL.h> using namespace std; using namespace glm; Engine::Engine(int argc, char** argv) : _wnd(nullptr) { for(int i = 0; i < argc; ++i) _args.push_back(string{argv[i]}); } Engine::~Engine() { } int Engine::run(Application* app) { _running = true; _exit_code = 0; SDL_Init(SDL_INIT_VIDEO); SDL_DisplayMode ask_mode; ask_mode.format = SDL_PIXELFORMAT_RGBA8888; ask_mode.w = 1920; ask_mode.h = 1080; ask_mode.refresh_rate = 60; SDL_DisplayMode mode; SDL_GetClosestDisplayMode(0, &ask_mode, &mode); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_EGL, SDL_TRUE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); _wnd = SDL_CreateWindow("OpenGL ES 2.0 Rendering Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, mode.w, mode.h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN); SDL_SetWindowDisplayMode(_wnd, &mode); SDL_GLContext ctx = SDL_GL_CreateContext(_wnd); SDL_GL_MakeCurrent(_wnd, ctx); gladLoadGLES2Loader((GLADloadproc) &SDL_GL_GetProcAddress); auto fb_size = framebuffer_size(); glViewport(0, 0, fb_size.x, fb_size.y); glClearColor(0.2f, 0.2f, 0.2f, 1.f); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); SDL_GL_SetSwapInterval(1); SDL_GL_SwapWindow(_wnd); app->initialize(); TimePoint last_time{}; Duration accumulator{}; while(_running) { TimePoint new_time = Clock::now(); Duration dT = new_time - last_time; last_time = new_time; accumulator += dT; SDL_Event e; while(SDL_PollEvent(&e)) { if(e.type == SDL_WINDOWEVENT_CLOSE) _running = false; if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN) app->keyboard_event(static_cast<Key>(e.key.keysym.scancode), e.type == SDL_KEYDOWN); if(e.type == SDL_TEXTINPUT) app->keyboard_character_event(e.text.text); if(e.type == SDL_MOUSEMOTION) app->mouse_move_event({e.motion.xrel, e.motion.yrel}); if(e.type == SDL_MOUSEBUTTONUP || e.type == SDL_MOUSEBUTTONDOWN) app->mouse_button_event({e.button.x, e.button.y}, static_cast<MouseButton>(e.button.button), e.type == SDL_MOUSEBUTTONDOWN); if(e.type == SDL_MOUSEWHEEL) app->scroll_event({e.wheel.x, e.wheel.y}); if(e.type == SDL_WINDOWEVENT_RESIZED) app->resize_event(e.window.data1, e.window.data2); } if(accumulator >= app->fixed_time_step()) { app->update(accumulator); accumulator = Duration{}; } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); app->frame_start(); app->frame(); app->frame_end(); SDL_GL_SwapWindow(_wnd); } delete app; SDL_GL_DeleteContext(ctx); SDL_DestroyWindow(_wnd); _wnd = nullptr; SDL_Quit(); return _exit_code; } glm::ivec2 Engine::framebuffer_size() const { ivec2 ret; SDL_GL_GetDrawableSize(_wnd, &ret.x, &ret.y); return ret; } glm::ivec2 Engine::window_size() const { ivec2 ret; SDL_GetWindowSize(_wnd, &ret.x, &ret.y); return ret; } <|endoftext|>
<commit_before>//===-- RegisterContextOpenBSD_x86_64.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===---------------------------------------------------------------------===// #include "RegisterContextOpenBSD_x86_64.h" #include "RegisterContextPOSIX_x86.h" #include <vector> using namespace lldb_private; using namespace lldb; // /usr/include/machine/reg.h typedef struct _GPR { uint64_t rdi; uint64_t rsi; uint64_t rdx; uint64_t rcx; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; uint64_t rbp; uint64_t rbx; uint64_t rax; uint64_t rsp; uint64_t rip; uint64_t rflags; uint64_t cs; uint64_t ss; uint64_t ds; uint64_t es; uint64_t fs; uint64_t gs; } GPR; struct DBG { uint64_t dr[16]; /* debug registers */ /* Index 0-3: debug address registers */ /* Index 4-5: reserved */ /* Index 6: debug status */ /* Index 7: debug control */ /* Index 8-15: reserved */ }; struct UserArea { GPR gpr; FPR fpr; DBG dbg; }; #define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(DBG, dr[reg_index])) //--------------------------------------------------------------------------- // Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 // structure. //--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_X86_64_STRUCT #include "RegisterInfos_x86_64.h" #undef DECLARE_REGISTER_INFOS_X86_64_STRUCT static std::vector<lldb_private::RegisterInfo> &GetSharedRegisterInfoVector() { static std::vector<lldb_private::RegisterInfo> register_infos; return register_infos; } static const RegisterInfo * PrivateGetRegisterInfoPtr(const lldb_private::ArchSpec &target_arch) { switch (target_arch.GetMachine()) { case llvm::Triple::x86_64: return g_register_infos_x86_64; default: assert(false && "Unhandled target architecture."); return nullptr; } } static uint32_t PrivateGetRegisterCount(const lldb_private::ArchSpec &target_arch) { switch (target_arch.GetMachine()) { case llvm::Triple::x86_64: return static_cast<uint32_t>(sizeof(g_register_infos_x86_64) / sizeof(g_register_infos_x86_64[0])); default: assert(false && "Unhandled target architecture."); return 0; } } RegisterContextOpenBSD_x86_64::RegisterContextOpenBSD_x86_64( const ArchSpec &target_arch) : lldb_private::RegisterInfoInterface(target_arch), m_register_info_p(PrivateGetRegisterInfoPtr(target_arch)), m_register_count(PrivateGetRegisterCount(target_arch)) {} size_t RegisterContextOpenBSD_x86_64::GetGPRSize() const { return sizeof(GPR); } const RegisterInfo *RegisterContextOpenBSD_x86_64::GetRegisterInfo() const { return m_register_info_p; } uint32_t RegisterContextOpenBSD_x86_64::GetRegisterCount() const { return m_register_count; } <commit_msg>[Process/Utility] Remove dead code. NFCI.<commit_after>//===-- RegisterContextOpenBSD_x86_64.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===---------------------------------------------------------------------===// #include "RegisterContextOpenBSD_x86_64.h" #include "RegisterContextPOSIX_x86.h" #include <vector> using namespace lldb_private; using namespace lldb; // /usr/include/machine/reg.h typedef struct _GPR { uint64_t rdi; uint64_t rsi; uint64_t rdx; uint64_t rcx; uint64_t r8; uint64_t r9; uint64_t r10; uint64_t r11; uint64_t r12; uint64_t r13; uint64_t r14; uint64_t r15; uint64_t rbp; uint64_t rbx; uint64_t rax; uint64_t rsp; uint64_t rip; uint64_t rflags; uint64_t cs; uint64_t ss; uint64_t ds; uint64_t es; uint64_t fs; uint64_t gs; } GPR; struct DBG { uint64_t dr[16]; /* debug registers */ /* Index 0-3: debug address registers */ /* Index 4-5: reserved */ /* Index 6: debug status */ /* Index 7: debug control */ /* Index 8-15: reserved */ }; struct UserArea { GPR gpr; FPR fpr; DBG dbg; }; #define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(DBG, dr[reg_index])) //--------------------------------------------------------------------------- // Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 // structure. //--------------------------------------------------------------------------- #define DECLARE_REGISTER_INFOS_X86_64_STRUCT #include "RegisterInfos_x86_64.h" #undef DECLARE_REGISTER_INFOS_X86_64_STRUCT static const RegisterInfo * PrivateGetRegisterInfoPtr(const lldb_private::ArchSpec &target_arch) { switch (target_arch.GetMachine()) { case llvm::Triple::x86_64: return g_register_infos_x86_64; default: assert(false && "Unhandled target architecture."); return nullptr; } } static uint32_t PrivateGetRegisterCount(const lldb_private::ArchSpec &target_arch) { switch (target_arch.GetMachine()) { case llvm::Triple::x86_64: return static_cast<uint32_t>(sizeof(g_register_infos_x86_64) / sizeof(g_register_infos_x86_64[0])); default: assert(false && "Unhandled target architecture."); return 0; } } RegisterContextOpenBSD_x86_64::RegisterContextOpenBSD_x86_64( const ArchSpec &target_arch) : lldb_private::RegisterInfoInterface(target_arch), m_register_info_p(PrivateGetRegisterInfoPtr(target_arch)), m_register_count(PrivateGetRegisterCount(target_arch)) {} size_t RegisterContextOpenBSD_x86_64::GetGPRSize() const { return sizeof(GPR); } const RegisterInfo *RegisterContextOpenBSD_x86_64::GetRegisterInfo() const { return m_register_info_p; } uint32_t RegisterContextOpenBSD_x86_64::GetRegisterCount() const { return m_register_count; } <|endoftext|>
<commit_before>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <forward_list> #include <functional> #include <memory> #include <mutex> #include <thread> #include <grpc++/generic/async_generic_service.h> #include <grpc++/security/server_credentials.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc++/server_context.h> #include <grpc++/support/config.h> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/host_port.h> #include <grpc/support/log.h> #include "src/proto/grpc/testing/services.grpc.pb.h" #include "test/core/util/test_config.h" #include "test/cpp/qps/server.h" namespace grpc { namespace testing { template <class RequestType, class ResponseType, class ServiceType, class ServerContextType> class AsyncQpsServerTest : public Server { public: AsyncQpsServerTest( const ServerConfig &config, std::function<void(ServerBuilder *, ServiceType *)> register_service, std::function<void(ServiceType *, ServerContextType *, RequestType *, ServerAsyncResponseWriter<ResponseType> *, CompletionQueue *, ServerCompletionQueue *, void *)> request_unary_function, std::function<void(ServiceType *, ServerContextType *, ServerAsyncReaderWriter<ResponseType, RequestType> *, CompletionQueue *, ServerCompletionQueue *, void *)> request_streaming_function, std::function<grpc::Status(const PayloadConfig &, const RequestType *, ResponseType *)> process_rpc) : Server(config) { char *server_address = NULL; gpr_join_host_port(&server_address, "::", port()); ServerBuilder builder; builder.AddListeningPort(server_address, Server::CreateServerCredentials(config)); gpr_free(server_address); register_service(&builder, &async_service_); int num_threads = config.async_server_threads(); if (num_threads <= 0) { // dynamic sizing num_threads = cores(); gpr_log(GPR_INFO, "Sizing async server to %d threads", num_threads); } for (int i = 0; i < num_threads; i++) { srv_cqs_.emplace_back(builder.AddCompletionQueue()); } server_ = builder.BuildAndStart(); using namespace std::placeholders; auto process_rpc_bound = std::bind(process_rpc, config.payload_config(), _1, _2); for (int i = 0; i < 15000; i++) { for (int j = 0; j < num_threads; j++) { if (request_unary_function) { auto request_unary = std::bind(request_unary_function, &async_service_, _1, _2, _3, srv_cqs_[j].get(), srv_cqs_[j].get(), _4); contexts_.emplace_back( new ServerRpcContextUnaryImpl(request_unary, process_rpc_bound)); } if (request_streaming_function) { auto request_streaming = std::bind(request_streaming_function, &async_service_, _1, _2, srv_cqs_[j].get(), srv_cqs_[j].get(), _3); contexts_.emplace_back(new ServerRpcContextStreamingImpl( request_streaming, process_rpc_bound)); } } } for (int i = 0; i < num_threads; i++) { shutdown_state_.emplace_back(new PerThreadShutdownState()); threads_.emplace_back(&AsyncQpsServerTest::ThreadFunc, this, i); } } ~AsyncQpsServerTest() { for (auto ss = shutdown_state_.begin(); ss != shutdown_state_.end(); ++ss) { std::lock_guard<std::mutex> lock((*ss)->mutex); (*ss)->shutdown = true; } // TODO (vpai): Remove this deadline and allow Shutdown to finish properly auto deadline = std::chrono::system_clock::now() + std::chrono::seconds(3); server_->Shutdown(deadline); for (auto cq = srv_cqs_.begin(); cq != srv_cqs_.end(); ++cq) { (*cq)->Shutdown(); } for (auto thr = threads_.begin(); thr != threads_.end(); thr++) { thr->join(); } for (auto cq = srv_cqs_.begin(); cq != srv_cqs_.end(); ++cq) { bool ok; void *got_tag; while ((*cq)->Next(&got_tag, &ok)) ; } } private: void ThreadFunc(int thread_idx) { // Wait until work is available or we are shutting down bool ok; void *got_tag; while (srv_cqs_[thread_idx]->Next(&got_tag, &ok)) { ServerRpcContext *ctx = detag(got_tag); // The tag is a pointer to an RPC context to invoke // Proceed while holding a lock to make sure that // this thread isn't supposed to shut down std::lock_guard<std::mutex> l(shutdown_state_[thread_idx]->mutex); if (shutdown_state_[thread_idx]->shutdown) { return; } const bool still_going = ctx->RunNextState(ok); // if this RPC context is done, refresh it if (!still_going) { ctx->Reset(); } } return; } class ServerRpcContext { public: ServerRpcContext() {} virtual ~ServerRpcContext(){}; virtual bool RunNextState(bool) = 0; // next state, return false if done virtual void Reset() = 0; // start this back at a clean state }; static void *tag(ServerRpcContext *func) { return reinterpret_cast<void *>(func); } static ServerRpcContext *detag(void *tag) { return reinterpret_cast<ServerRpcContext *>(tag); } class ServerRpcContextUnaryImpl GRPC_FINAL : public ServerRpcContext { public: ServerRpcContextUnaryImpl( std::function<void(ServerContextType *, RequestType *, grpc::ServerAsyncResponseWriter<ResponseType> *, void *)> request_method, std::function<grpc::Status(const RequestType *, ResponseType *)> invoke_method) : srv_ctx_(new ServerContextType), next_state_(&ServerRpcContextUnaryImpl::invoker), request_method_(request_method), invoke_method_(invoke_method), response_writer_(srv_ctx_.get()) { request_method_(srv_ctx_.get(), &req_, &response_writer_, AsyncQpsServerTest::tag(this)); } ~ServerRpcContextUnaryImpl() GRPC_OVERRIDE {} bool RunNextState(bool ok) GRPC_OVERRIDE { return (this->*next_state_)(ok); } void Reset() GRPC_OVERRIDE { srv_ctx_.reset(new ServerContextType); req_ = RequestType(); response_writer_ = grpc::ServerAsyncResponseWriter<ResponseType>(srv_ctx_.get()); // Then request the method next_state_ = &ServerRpcContextUnaryImpl::invoker; request_method_(srv_ctx_.get(), &req_, &response_writer_, AsyncQpsServerTest::tag(this)); } private: bool finisher(bool) { return false; } bool invoker(bool ok) { if (!ok) { return false; } ResponseType response; // Call the RPC processing function grpc::Status status = invoke_method_(&req_, &response); // Have the response writer work and invoke on_finish when done next_state_ = &ServerRpcContextUnaryImpl::finisher; response_writer_.Finish(response, status, AsyncQpsServerTest::tag(this)); return true; } std::unique_ptr<ServerContextType> srv_ctx_; RequestType req_; bool (ServerRpcContextUnaryImpl::*next_state_)(bool); std::function<void(ServerContextType *, RequestType *, grpc::ServerAsyncResponseWriter<ResponseType> *, void *)> request_method_; std::function<grpc::Status(const RequestType *, ResponseType *)> invoke_method_; grpc::ServerAsyncResponseWriter<ResponseType> response_writer_; }; class ServerRpcContextStreamingImpl GRPC_FINAL : public ServerRpcContext { public: ServerRpcContextStreamingImpl( std::function<void( ServerContextType *, grpc::ServerAsyncReaderWriter<ResponseType, RequestType> *, void *)> request_method, std::function<grpc::Status(const RequestType *, ResponseType *)> invoke_method) : srv_ctx_(new ServerContextType), next_state_(&ServerRpcContextStreamingImpl::request_done), request_method_(request_method), invoke_method_(invoke_method), stream_(srv_ctx_.get()) { request_method_(srv_ctx_.get(), &stream_, AsyncQpsServerTest::tag(this)); } ~ServerRpcContextStreamingImpl() GRPC_OVERRIDE {} bool RunNextState(bool ok) GRPC_OVERRIDE { return (this->*next_state_)(ok); } void Reset() GRPC_OVERRIDE { srv_ctx_.reset(new ServerContextType); req_ = RequestType(); stream_ = grpc::ServerAsyncReaderWriter<ResponseType, RequestType>( srv_ctx_.get()); // Then request the method next_state_ = &ServerRpcContextStreamingImpl::request_done; request_method_(srv_ctx_.get(), &stream_, AsyncQpsServerTest::tag(this)); } private: bool request_done(bool ok) { if (!ok) { return false; } stream_.Read(&req_, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::read_done; return true; } bool read_done(bool ok) { if (ok) { // invoke the method ResponseType response; // Call the RPC processing function grpc::Status status = invoke_method_(&req_, &response); // initiate the write stream_.Write(response, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::write_done; } else { // client has sent writes done // finish the stream stream_.Finish(Status::OK, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::finish_done; } return true; } bool write_done(bool ok) { // now go back and get another streaming read! if (ok) { stream_.Read(&req_, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::read_done; } else { stream_.Finish(Status::OK, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::finish_done; } return true; } bool finish_done(bool ok) { return false; /* reset the context */ } std::unique_ptr<ServerContextType> srv_ctx_; RequestType req_; bool (ServerRpcContextStreamingImpl::*next_state_)(bool); std::function<void( ServerContextType *, grpc::ServerAsyncReaderWriter<ResponseType, RequestType> *, void *)> request_method_; std::function<grpc::Status(const RequestType *, ResponseType *)> invoke_method_; grpc::ServerAsyncReaderWriter<ResponseType, RequestType> stream_; }; std::vector<std::thread> threads_; std::unique_ptr<grpc::Server> server_; std::vector<std::unique_ptr<grpc::ServerCompletionQueue>> srv_cqs_; ServiceType async_service_; std::vector<std::unique_ptr<ServerRpcContext>> contexts_; struct PerThreadShutdownState { mutable std::mutex mutex; bool shutdown; PerThreadShutdownState() : shutdown(false) {} }; std::vector<std::unique_ptr<PerThreadShutdownState>> shutdown_state_; }; static void RegisterBenchmarkService(ServerBuilder *builder, BenchmarkService::AsyncService *service) { builder->RegisterService(service); } static void RegisterGenericService(ServerBuilder *builder, grpc::AsyncGenericService *service) { builder->RegisterAsyncGenericService(service); } static Status ProcessSimpleRPC(const PayloadConfig &, const SimpleRequest *request, SimpleResponse *response) { if (request->response_size() > 0) { if (!Server::SetPayload(request->response_type(), request->response_size(), response->mutable_payload())) { return Status(grpc::StatusCode::INTERNAL, "Error creating payload."); } } return Status::OK; } static Status ProcessGenericRPC(const PayloadConfig &payload_config, const ByteBuffer *request, ByteBuffer *response) { int resp_size = payload_config.bytebuf_params().resp_size(); std::unique_ptr<char[]> buf(new char[resp_size]); gpr_slice s = gpr_slice_from_copied_buffer(buf.get(), resp_size); Slice slice(s, Slice::STEAL_REF); *response = ByteBuffer(&slice, 1); return Status::OK; } std::unique_ptr<Server> CreateAsyncServer(const ServerConfig &config) { return std::unique_ptr<Server>( new AsyncQpsServerTest<SimpleRequest, SimpleResponse, BenchmarkService::AsyncService, grpc::ServerContext>( config, RegisterBenchmarkService, &BenchmarkService::AsyncService::RequestUnaryCall, &BenchmarkService::AsyncService::RequestStreamingCall, ProcessSimpleRPC)); } std::unique_ptr<Server> CreateAsyncGenericServer(const ServerConfig &config) { return std::unique_ptr<Server>( new AsyncQpsServerTest<ByteBuffer, ByteBuffer, grpc::AsyncGenericService, grpc::GenericServerContext>( config, RegisterGenericService, nullptr, &grpc::AsyncGenericService::RequestCall, ProcessGenericRPC)); } } // namespace testing } // namespace grpc <commit_msg>Fix benchmark shutdown<commit_after>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <forward_list> #include <functional> #include <memory> #include <mutex> #include <thread> #include <grpc++/generic/async_generic_service.h> #include <grpc++/security/server_credentials.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc++/server_context.h> #include <grpc++/support/config.h> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/host_port.h> #include <grpc/support/log.h> #include "src/proto/grpc/testing/services.grpc.pb.h" #include "test/core/util/test_config.h" #include "test/cpp/qps/server.h" namespace grpc { namespace testing { template <class RequestType, class ResponseType, class ServiceType, class ServerContextType> class AsyncQpsServerTest : public Server { public: AsyncQpsServerTest( const ServerConfig &config, std::function<void(ServerBuilder *, ServiceType *)> register_service, std::function<void(ServiceType *, ServerContextType *, RequestType *, ServerAsyncResponseWriter<ResponseType> *, CompletionQueue *, ServerCompletionQueue *, void *)> request_unary_function, std::function<void(ServiceType *, ServerContextType *, ServerAsyncReaderWriter<ResponseType, RequestType> *, CompletionQueue *, ServerCompletionQueue *, void *)> request_streaming_function, std::function<grpc::Status(const PayloadConfig &, const RequestType *, ResponseType *)> process_rpc) : Server(config) { char *server_address = NULL; gpr_join_host_port(&server_address, "::", port()); ServerBuilder builder; builder.AddListeningPort(server_address, Server::CreateServerCredentials(config)); gpr_free(server_address); register_service(&builder, &async_service_); int num_threads = config.async_server_threads(); if (num_threads <= 0) { // dynamic sizing num_threads = cores(); gpr_log(GPR_INFO, "Sizing async server to %d threads", num_threads); } for (int i = 0; i < num_threads; i++) { srv_cqs_.emplace_back(builder.AddCompletionQueue()); } server_ = builder.BuildAndStart(); using namespace std::placeholders; auto process_rpc_bound = std::bind(process_rpc, config.payload_config(), _1, _2); for (int i = 0; i < 15000; i++) { for (int j = 0; j < num_threads; j++) { if (request_unary_function) { auto request_unary = std::bind(request_unary_function, &async_service_, _1, _2, _3, srv_cqs_[j].get(), srv_cqs_[j].get(), _4); contexts_.emplace_back( new ServerRpcContextUnaryImpl(request_unary, process_rpc_bound)); } if (request_streaming_function) { auto request_streaming = std::bind(request_streaming_function, &async_service_, _1, _2, srv_cqs_[j].get(), srv_cqs_[j].get(), _3); contexts_.emplace_back(new ServerRpcContextStreamingImpl( request_streaming, process_rpc_bound)); } } } for (int i = 0; i < num_threads; i++) { shutdown_state_.emplace_back(new PerThreadShutdownState()); threads_.emplace_back(&AsyncQpsServerTest::ThreadFunc, this, i); } } ~AsyncQpsServerTest() { for (auto ss = shutdown_state_.begin(); ss != shutdown_state_.end(); ++ss) { std::lock_guard<std::mutex> lock((*ss)->mutex); (*ss)->shutdown = true; } // TODO (vpai): Remove this deadline and allow Shutdown to finish properly std::thread shutdown_thread([this]() { auto deadline = std::chrono::system_clock::now() + std::chrono::seconds(3); server_->Shutdown(deadline); }); for (auto cq = srv_cqs_.begin(); cq != srv_cqs_.end(); ++cq) { (*cq)->Shutdown(); } for (auto thr = threads_.begin(); thr != threads_.end(); thr++) { thr->join(); } for (auto cq = srv_cqs_.begin(); cq != srv_cqs_.end(); ++cq) { bool ok; void *got_tag; while ((*cq)->Next(&got_tag, &ok)) ; } shutdown_thread.join(); } private: void ThreadFunc(int thread_idx) { // Wait until work is available or we are shutting down bool ok; void *got_tag; while (srv_cqs_[thread_idx]->Next(&got_tag, &ok)) { ServerRpcContext *ctx = detag(got_tag); // The tag is a pointer to an RPC context to invoke // Proceed while holding a lock to make sure that // this thread isn't supposed to shut down std::lock_guard<std::mutex> l(shutdown_state_[thread_idx]->mutex); if (shutdown_state_[thread_idx]->shutdown) { return; } const bool still_going = ctx->RunNextState(ok); // if this RPC context is done, refresh it if (!still_going) { ctx->Reset(); } } return; } class ServerRpcContext { public: ServerRpcContext() {} virtual ~ServerRpcContext(){}; virtual bool RunNextState(bool) = 0; // next state, return false if done virtual void Reset() = 0; // start this back at a clean state }; static void *tag(ServerRpcContext *func) { return reinterpret_cast<void *>(func); } static ServerRpcContext *detag(void *tag) { return reinterpret_cast<ServerRpcContext *>(tag); } class ServerRpcContextUnaryImpl GRPC_FINAL : public ServerRpcContext { public: ServerRpcContextUnaryImpl( std::function<void(ServerContextType *, RequestType *, grpc::ServerAsyncResponseWriter<ResponseType> *, void *)> request_method, std::function<grpc::Status(const RequestType *, ResponseType *)> invoke_method) : srv_ctx_(new ServerContextType), next_state_(&ServerRpcContextUnaryImpl::invoker), request_method_(request_method), invoke_method_(invoke_method), response_writer_(srv_ctx_.get()) { request_method_(srv_ctx_.get(), &req_, &response_writer_, AsyncQpsServerTest::tag(this)); } ~ServerRpcContextUnaryImpl() GRPC_OVERRIDE {} bool RunNextState(bool ok) GRPC_OVERRIDE { return (this->*next_state_)(ok); } void Reset() GRPC_OVERRIDE { srv_ctx_.reset(new ServerContextType); req_ = RequestType(); response_writer_ = grpc::ServerAsyncResponseWriter<ResponseType>(srv_ctx_.get()); // Then request the method next_state_ = &ServerRpcContextUnaryImpl::invoker; request_method_(srv_ctx_.get(), &req_, &response_writer_, AsyncQpsServerTest::tag(this)); } private: bool finisher(bool) { return false; } bool invoker(bool ok) { if (!ok) { return false; } ResponseType response; // Call the RPC processing function grpc::Status status = invoke_method_(&req_, &response); // Have the response writer work and invoke on_finish when done next_state_ = &ServerRpcContextUnaryImpl::finisher; response_writer_.Finish(response, status, AsyncQpsServerTest::tag(this)); return true; } std::unique_ptr<ServerContextType> srv_ctx_; RequestType req_; bool (ServerRpcContextUnaryImpl::*next_state_)(bool); std::function<void(ServerContextType *, RequestType *, grpc::ServerAsyncResponseWriter<ResponseType> *, void *)> request_method_; std::function<grpc::Status(const RequestType *, ResponseType *)> invoke_method_; grpc::ServerAsyncResponseWriter<ResponseType> response_writer_; }; class ServerRpcContextStreamingImpl GRPC_FINAL : public ServerRpcContext { public: ServerRpcContextStreamingImpl( std::function<void( ServerContextType *, grpc::ServerAsyncReaderWriter<ResponseType, RequestType> *, void *)> request_method, std::function<grpc::Status(const RequestType *, ResponseType *)> invoke_method) : srv_ctx_(new ServerContextType), next_state_(&ServerRpcContextStreamingImpl::request_done), request_method_(request_method), invoke_method_(invoke_method), stream_(srv_ctx_.get()) { request_method_(srv_ctx_.get(), &stream_, AsyncQpsServerTest::tag(this)); } ~ServerRpcContextStreamingImpl() GRPC_OVERRIDE {} bool RunNextState(bool ok) GRPC_OVERRIDE { return (this->*next_state_)(ok); } void Reset() GRPC_OVERRIDE { srv_ctx_.reset(new ServerContextType); req_ = RequestType(); stream_ = grpc::ServerAsyncReaderWriter<ResponseType, RequestType>( srv_ctx_.get()); // Then request the method next_state_ = &ServerRpcContextStreamingImpl::request_done; request_method_(srv_ctx_.get(), &stream_, AsyncQpsServerTest::tag(this)); } private: bool request_done(bool ok) { if (!ok) { return false; } stream_.Read(&req_, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::read_done; return true; } bool read_done(bool ok) { if (ok) { // invoke the method ResponseType response; // Call the RPC processing function grpc::Status status = invoke_method_(&req_, &response); // initiate the write stream_.Write(response, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::write_done; } else { // client has sent writes done // finish the stream stream_.Finish(Status::OK, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::finish_done; } return true; } bool write_done(bool ok) { // now go back and get another streaming read! if (ok) { stream_.Read(&req_, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::read_done; } else { stream_.Finish(Status::OK, AsyncQpsServerTest::tag(this)); next_state_ = &ServerRpcContextStreamingImpl::finish_done; } return true; } bool finish_done(bool ok) { return false; /* reset the context */ } std::unique_ptr<ServerContextType> srv_ctx_; RequestType req_; bool (ServerRpcContextStreamingImpl::*next_state_)(bool); std::function<void( ServerContextType *, grpc::ServerAsyncReaderWriter<ResponseType, RequestType> *, void *)> request_method_; std::function<grpc::Status(const RequestType *, ResponseType *)> invoke_method_; grpc::ServerAsyncReaderWriter<ResponseType, RequestType> stream_; }; std::vector<std::thread> threads_; std::unique_ptr<grpc::Server> server_; std::vector<std::unique_ptr<grpc::ServerCompletionQueue>> srv_cqs_; ServiceType async_service_; std::vector<std::unique_ptr<ServerRpcContext>> contexts_; struct PerThreadShutdownState { mutable std::mutex mutex; bool shutdown; PerThreadShutdownState() : shutdown(false) {} }; std::vector<std::unique_ptr<PerThreadShutdownState>> shutdown_state_; }; static void RegisterBenchmarkService(ServerBuilder *builder, BenchmarkService::AsyncService *service) { builder->RegisterService(service); } static void RegisterGenericService(ServerBuilder *builder, grpc::AsyncGenericService *service) { builder->RegisterAsyncGenericService(service); } static Status ProcessSimpleRPC(const PayloadConfig &, const SimpleRequest *request, SimpleResponse *response) { if (request->response_size() > 0) { if (!Server::SetPayload(request->response_type(), request->response_size(), response->mutable_payload())) { return Status(grpc::StatusCode::INTERNAL, "Error creating payload."); } } return Status::OK; } static Status ProcessGenericRPC(const PayloadConfig &payload_config, const ByteBuffer *request, ByteBuffer *response) { int resp_size = payload_config.bytebuf_params().resp_size(); std::unique_ptr<char[]> buf(new char[resp_size]); gpr_slice s = gpr_slice_from_copied_buffer(buf.get(), resp_size); Slice slice(s, Slice::STEAL_REF); *response = ByteBuffer(&slice, 1); return Status::OK; } std::unique_ptr<Server> CreateAsyncServer(const ServerConfig &config) { return std::unique_ptr<Server>( new AsyncQpsServerTest<SimpleRequest, SimpleResponse, BenchmarkService::AsyncService, grpc::ServerContext>( config, RegisterBenchmarkService, &BenchmarkService::AsyncService::RequestUnaryCall, &BenchmarkService::AsyncService::RequestStreamingCall, ProcessSimpleRPC)); } std::unique_ptr<Server> CreateAsyncGenericServer(const ServerConfig &config) { return std::unique_ptr<Server>( new AsyncQpsServerTest<ByteBuffer, ByteBuffer, grpc::AsyncGenericService, grpc::GenericServerContext>( config, RegisterGenericService, nullptr, &grpc::AsyncGenericService::RequestCall, ProcessGenericRPC)); } } // namespace testing } // namespace grpc <|endoftext|>
<commit_before><commit_msg>Fade out rotation gizmo axes when facing head-on<commit_after><|endoftext|>
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved. #include <ctime> #include <boost/lexical_cast.hpp> #include "osquery/database.h" namespace osquery { namespace tables { const int kNumCols = 1; QueryData genTime() { Row r; time_t _time = time(0); struct tm* now = localtime(&_time); r["hour"] = boost::lexical_cast<std::string>(now->tm_hour); r["minutes"] = boost::lexical_cast<std::string>(now->tm_min); r["seconds"] = boost::lexical_cast<std::string>(now->tm_sec); QueryData results; for (int i = 0; i < kNumCols; ++i) { results.push_back(r); } return results; } } } <commit_msg>Use INTEGER macro.<commit_after>// Copyright 2004-present Facebook. All Rights Reserved. #include <ctime> #include "osquery/database.h" namespace osquery { namespace tables { const int kNumCols = 1; QueryData genTime() { Row r; time_t _time = time(0); struct tm* now = localtime(&_time); r["hour"] = INTEGER(now->tm_hour); r["minutes"] = INTEGER(now->tm_min); r["seconds"] = INTEGER(now->tm_sec); QueryData results; for (int i = 0; i < kNumCols; ++i) { results.push_back(r); } return results; } } } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "bochs.h" #define LOG_THIS bx_parallel. #define OUTPUT BX_PAR_THIS output bx_parallel_c bx_parallel; #if BX_USE_PAR_SMF #define this (&bx_parallel) #endif bx_parallel_c::bx_parallel_c(void) { put("PAR"); settype(PARLOG); } bx_parallel_c::~bx_parallel_c(void) { fclose(OUTPUT); } void bx_parallel_c::init(bx_devices_c *d) { BX_DEBUG(("Init $Id$")); BX_PAR_THIS devices = d; /* PARALLEL PORT 1 */ BX_PAR_THIS devices->register_irq(7, "Parallel Port 1"); BX_PAR_THIS devices->register_io_read_handler(this, read_handler, 0x0379, "Parallel Port 1"); BX_PAR_THIS devices->register_io_read_handler(this, read_handler, 0x037A, "Parallel Port 1"); BX_PAR_THIS devices->register_io_write_handler(this, write_handler, 0x0378, "Parallel Port 1"); BX_PAR_THIS devices->register_io_write_handler(this, write_handler, 0x037A, "Parallel Port 1"); BX_PAR_THIS s.STATUS.error = 1; BX_PAR_THIS s.STATUS.slct = 1; BX_PAR_THIS s.STATUS.pe = 0; BX_PAR_THIS s.STATUS.ack = 1; BX_PAR_THIS s.STATUS.busy = 1; BX_PAR_THIS s.CONTROL.strobe = 0; BX_PAR_THIS s.CONTROL.autofeed = 0; BX_PAR_THIS s.CONTROL.init = 1; BX_PAR_THIS s.CONTROL.slct_in = 1; BX_PAR_THIS s.CONTROL.irq = 0; OUTPUT = fopen("parport.out", "w"); } void bx_parallel_c::virtual_printer(void) { fprintf(OUTPUT, "%c", BX_PAR_THIS s.data); if (BX_PAR_THIS s.CONTROL.irq == 1) { BX_PAR_THIS devices->pic->trigger_irq(7); } BX_PAR_THIS s.STATUS.ack = 0; BX_PAR_THIS s.STATUS.busy = 1; } // static IO port read callback handler // redirects to non-static class handler to avoid virtual functions Bit32u bx_parallel_c::read_handler(void *this_ptr, Bit32u address, unsigned io_len) { #if !BX_USE_PAR_SMF bx_parallel_c *class_ptr = (bx_parallel_c *) this_ptr; return( class_ptr->read(address, io_len) ); } Bit32u bx_parallel_c::read(Bit32u address, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_PAR_SMF if (io_len == 1) { switch (address) { case 0x0379: { Bit32u retval; retval = ((BX_PAR_THIS s.STATUS.busy << 7) | (BX_PAR_THIS s.STATUS.ack << 6) | (BX_PAR_THIS s.STATUS.pe << 5) | (BX_PAR_THIS s.STATUS.slct << 4) | (BX_PAR_THIS s.STATUS.error << 3)); BX_PAR_THIS s.STATUS.ack = 1; if (BX_PAR_THIS s.CONTROL.irq == 1) { BX_PAR_THIS devices->pic->untrigger_irq(7); } return retval; } break; case 0x037A: { return ((BX_PAR_THIS s.CONTROL.irq << 4) | (BX_PAR_THIS s.CONTROL.slct_in << 3) | (BX_PAR_THIS s.CONTROL.init << 2) | (BX_PAR_THIS s.CONTROL.autofeed << 1) | (BX_PAR_THIS s.CONTROL.strobe)); } break; } } /* PARALLEL PORT 1 */ return(0); } // static IO port write callback handler // redirects to non-static class handler to avoid virtual functions void bx_parallel_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len) { #if !BX_USE_PAR_SMF bx_parallel_c *class_ptr = (bx_parallel_c *) this_ptr; class_ptr->write(address, value, io_len); } void bx_parallel_c::write(Bit32u address, Bit32u value, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_PAR_SMF if (io_len == 1) { switch (address) { case 0x0378: { BX_PAR_THIS s.data = (Bit8u)value; } break; case 0x037A: { if ((value & 0x01) == 1) { if (BX_PAR_THIS s.CONTROL.strobe == 0) { BX_PAR_THIS s.CONTROL.strobe = 1; virtual_printer(); // data is valid now } } else { if (BX_PAR_THIS s.CONTROL.strobe == 1) { BX_PAR_THIS s.CONTROL.strobe = 0; } } BX_PAR_THIS s.CONTROL.autofeed = ((value & 0x02) == 1); BX_PAR_THIS s.CONTROL.init = ((value & 0x04) == 1); BX_PAR_THIS s.CONTROL.slct_in = ((value & 0x08) == 1); BX_PAR_THIS s.STATUS.slct = BX_PAR_THIS s.CONTROL.slct_in; if ((value & 0x10) == 0x10) { BX_PAR_THIS s.CONTROL.irq = 1; } else { BX_PAR_THIS s.CONTROL.irq = 0; } } break; } } /* PARALLEL PORT 1 */ } <commit_msg>- add comments saying who wrote most of this file - add fflush after every character written to output file<commit_after>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////// // This code was just a few stubs until Volker.Ruppert@t-online.de // fixed it up in November 2001. #include "bochs.h" #define LOG_THIS bx_parallel. #define OUTPUT BX_PAR_THIS output bx_parallel_c bx_parallel; #if BX_USE_PAR_SMF #define this (&bx_parallel) #endif bx_parallel_c::bx_parallel_c(void) { put("PAR"); settype(PARLOG); } bx_parallel_c::~bx_parallel_c(void) { fclose(OUTPUT); } void bx_parallel_c::init(bx_devices_c *d) { BX_DEBUG(("Init $Id$")); BX_PAR_THIS devices = d; /* PARALLEL PORT 1 */ BX_PAR_THIS devices->register_irq(7, "Parallel Port 1"); BX_PAR_THIS devices->register_io_read_handler(this, read_handler, 0x0379, "Parallel Port 1"); BX_PAR_THIS devices->register_io_read_handler(this, read_handler, 0x037A, "Parallel Port 1"); BX_PAR_THIS devices->register_io_write_handler(this, write_handler, 0x0378, "Parallel Port 1"); BX_PAR_THIS devices->register_io_write_handler(this, write_handler, 0x037A, "Parallel Port 1"); BX_PAR_THIS s.STATUS.error = 1; BX_PAR_THIS s.STATUS.slct = 1; BX_PAR_THIS s.STATUS.pe = 0; BX_PAR_THIS s.STATUS.ack = 1; BX_PAR_THIS s.STATUS.busy = 1; BX_PAR_THIS s.CONTROL.strobe = 0; BX_PAR_THIS s.CONTROL.autofeed = 0; BX_PAR_THIS s.CONTROL.init = 1; BX_PAR_THIS s.CONTROL.slct_in = 1; BX_PAR_THIS s.CONTROL.irq = 0; OUTPUT = fopen("parport.out", "w"); } void bx_parallel_c::virtual_printer(void) { fprintf(OUTPUT, "%c", BX_PAR_THIS s.data); fflush (OUTPUT); if (BX_PAR_THIS s.CONTROL.irq == 1) { BX_PAR_THIS devices->pic->trigger_irq(7); } BX_PAR_THIS s.STATUS.ack = 0; BX_PAR_THIS s.STATUS.busy = 1; } // static IO port read callback handler // redirects to non-static class handler to avoid virtual functions Bit32u bx_parallel_c::read_handler(void *this_ptr, Bit32u address, unsigned io_len) { #if !BX_USE_PAR_SMF bx_parallel_c *class_ptr = (bx_parallel_c *) this_ptr; return( class_ptr->read(address, io_len) ); } Bit32u bx_parallel_c::read(Bit32u address, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_PAR_SMF if (io_len == 1) { switch (address) { case 0x0379: { Bit32u retval; retval = ((BX_PAR_THIS s.STATUS.busy << 7) | (BX_PAR_THIS s.STATUS.ack << 6) | (BX_PAR_THIS s.STATUS.pe << 5) | (BX_PAR_THIS s.STATUS.slct << 4) | (BX_PAR_THIS s.STATUS.error << 3)); BX_PAR_THIS s.STATUS.ack = 1; if (BX_PAR_THIS s.CONTROL.irq == 1) { BX_PAR_THIS devices->pic->untrigger_irq(7); } return retval; } break; case 0x037A: { return ((BX_PAR_THIS s.CONTROL.irq << 4) | (BX_PAR_THIS s.CONTROL.slct_in << 3) | (BX_PAR_THIS s.CONTROL.init << 2) | (BX_PAR_THIS s.CONTROL.autofeed << 1) | (BX_PAR_THIS s.CONTROL.strobe)); } break; } } /* PARALLEL PORT 1 */ return(0); } // static IO port write callback handler // redirects to non-static class handler to avoid virtual functions void bx_parallel_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len) { #if !BX_USE_PAR_SMF bx_parallel_c *class_ptr = (bx_parallel_c *) this_ptr; class_ptr->write(address, value, io_len); } void bx_parallel_c::write(Bit32u address, Bit32u value, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_PAR_SMF if (io_len == 1) { switch (address) { case 0x0378: { BX_PAR_THIS s.data = (Bit8u)value; } break; case 0x037A: { if ((value & 0x01) == 1) { if (BX_PAR_THIS s.CONTROL.strobe == 0) { BX_PAR_THIS s.CONTROL.strobe = 1; virtual_printer(); // data is valid now } } else { if (BX_PAR_THIS s.CONTROL.strobe == 1) { BX_PAR_THIS s.CONTROL.strobe = 0; } } BX_PAR_THIS s.CONTROL.autofeed = ((value & 0x02) == 1); BX_PAR_THIS s.CONTROL.init = ((value & 0x04) == 1); BX_PAR_THIS s.CONTROL.slct_in = ((value & 0x08) == 1); BX_PAR_THIS s.STATUS.slct = BX_PAR_THIS s.CONTROL.slct_in; if ((value & 0x10) == 0x10) { BX_PAR_THIS s.CONTROL.irq = 1; } else { BX_PAR_THIS s.CONTROL.irq = 0; } } break; } } /* PARALLEL PORT 1 */ } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tabline.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-01-21 16:51:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #pragma hdrstop #define _SVX_TABLINE_CXX #include "dialogs.hrc" #include "tabline.hrc" #include "dlgname.hrc" #define ITEMID_COLOR_TABLE SID_COLOR_TABLE #define ITEMID_DASH_LIST SID_DASH_LIST #define ITEMID_LINEEND_LIST SID_LINEEND_LIST #include "cuitabline.hxx" #include "dlgname.hxx" #include "dialmgr.hxx" #include "svdmodel.hxx" #include "xtable.hxx" #include "drawitem.hxx" #define DLGWIN this->GetParent()->GetParent() #define BITMAP_WIDTH 32 #define BITMAP_HEIGHT 12 #define XOUT_WIDTH 150 /************************************************************************* |* |* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu |* \************************************************************************/ SvxLineTabDialog::SvxLineTabDialog ( Window* pParent, const SfxItemSet* pAttr, SdrModel* pModel, const SdrObject* pSdrObj, BOOL bHasObj ) : SfxTabDialog ( pParent, SVX_RES( RID_SVXDLG_LINE ), pAttr ), pDrawModel ( pModel ), pObj ( pSdrObj ), bObjSelected ( bHasObj ), pColorTab ( pModel->GetColorTable() ), pDashList ( pModel->GetDashList() ), pLineEndList ( pModel->GetLineEndList() ), pNewDashList ( pModel->GetDashList() ), pNewLineEndList ( pModel->GetLineEndList() ), rOutAttrs ( *pAttr ) { FreeResource(); AddTabPage( RID_SVXPAGE_LINE, SvxLineTabPage::Create, 0); AddTabPage( RID_SVXPAGE_LINE_DEF, SvxLineDefTabPage::Create, 0); AddTabPage( RID_SVXPAGE_LINEEND_DEF, SvxLineEndDefTabPage::Create, 0); nLineEndListState = CT_NONE; nDashListState = CT_NONE; nDlgType = 0; nPageType = 0; // wird hier in erster Linie benutzt, um mit FillItemSet // die richtigen Attribute zu erhalten ( noch Fragen? ) nPosDashLb = 0; nPosLineEndLb = 0; SetCurPageId( RID_SVXPAGE_LINE ); CancelButton& rBtnCancel = GetCancelButton(); rBtnCancel.SetClickHdl( LINK( this, SvxLineTabDialog, CancelHdl ) ); //! rBtnCancel.SetText( SVX_RESSTR( RID_SVXSTR_CLOSE ) ); } // ----------------------------------------------------------------------- SvxLineTabDialog::~SvxLineTabDialog() { } // ----------------------------------------------------------------------- void SvxLineTabDialog::SavePalettes() { if( pNewDashList != pDrawModel->GetDashList() ) { delete pDrawModel->GetDashList(); pDrawModel->SetDashList( pNewDashList ); SfxObjectShell::Current()->PutItem( SvxDashListItem( pNewDashList ) ); pDashList = pDrawModel->GetDashList(); } if( pNewLineEndList != pDrawModel->GetLineEndList() ) { delete pDrawModel->GetLineEndList(); pDrawModel->SetLineEndList( pNewLineEndList ); SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pNewLineEndList ) ); pLineEndList = pDrawModel->GetLineEndList(); } // Speichern der Tabellen, wenn sie geaendert wurden. const String aPath( SvtPathOptions().GetPalettePath() ); if( nDashListState & CT_MODIFIED ) { pDashList->SetPath( aPath ); pDashList->Save(); // ToolBoxControls werden benachrichtigt: SfxObjectShell::Current()->PutItem( SvxDashListItem( pDashList ) ); } if( nLineEndListState & CT_MODIFIED ) { pLineEndList->SetPath( aPath ); pLineEndList->Save(); // ToolBoxControls werden benachrichtigt: SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pLineEndList ) ); } } // ----------------------------------------------------------------------- short SvxLineTabDialog::Ok() { SavePalettes(); // Es wird RET_OK zurueckgeliefert, wenn wenigstens eine // TabPage in FillItemSet() TRUE zurueckliefert. Dieses // geschieht z.Z. standardmaessig. return( SfxTabDialog::Ok() ); } // ----------------------------------------------------------------------- IMPL_LINK_INLINE_START( SvxLineTabDialog, CancelHdl, void *, p ) { SavePalettes(); EndDialog( RET_CANCEL ); return 0; } IMPL_LINK_INLINE_END( SvxLineTabDialog, CancelHdl, void *, p ) // ----------------------------------------------------------------------- void SvxLineTabDialog::PageCreated( USHORT nId, SfxTabPage &rPage ) { switch( nId ) { case RID_SVXPAGE_LINE: ( (SvxLineTabPage&) rPage ).SetColorTable( pColorTab ); ( (SvxLineTabPage&) rPage ).SetDashList( pDashList ); ( (SvxLineTabPage&) rPage ).SetLineEndList( pLineEndList ); ( (SvxLineTabPage&) rPage ).SetDlgType( nDlgType );//CHINA001 ( (SvxLineTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineTabPage&) rPage ).SetPageType( nPageType );//CHINA001 ( (SvxLineTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineTabPage&) rPage ).SetPosDashLb( &nPosDashLb ); ( (SvxLineTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb ); ( (SvxLineTabPage&) rPage ).SetDashChgd( &nDashListState ); ( (SvxLineTabPage&) rPage ).SetLineEndChgd( &nLineEndListState ); ( (SvxLineTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineTabPage&) rPage ).Construct(); // ActivatePage() wird das erste mal nicht gerufen ( (SvxLineTabPage&) rPage ).ActivatePage( rOutAttrs ); break; case RID_SVXPAGE_LINE_DEF: ( (SvxLineDefTabPage&) rPage ).SetDashList( pDashList ); ( (SvxLineDefTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineDefTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineDefTabPage&) rPage ).SetPosDashLb( &nPosDashLb ); ( (SvxLineDefTabPage&) rPage ).SetDashChgd( &nDashListState ); ( (SvxLineDefTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineDefTabPage&) rPage ).Construct(); break; case RID_SVXPAGE_LINEEND_DEF: ( (SvxLineEndDefTabPage&) rPage ).SetLineEndList( pLineEndList ); ( (SvxLineEndDefTabPage&) rPage ).SetPolyObj( pObj ); ( (SvxLineEndDefTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineEndDefTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineEndDefTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb ); ( (SvxLineEndDefTabPage&) rPage ).SetLineEndChgd( &nLineEndListState ); ( (SvxLineEndDefTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineEndDefTabPage&) rPage ).Construct(); break; } } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.430); FILE MERGED 2005/09/05 14:22:03 rt 1.4.430.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabline.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:11:56 $ * * 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 * ************************************************************************/ #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #pragma hdrstop #define _SVX_TABLINE_CXX #include "dialogs.hrc" #include "tabline.hrc" #include "dlgname.hrc" #define ITEMID_COLOR_TABLE SID_COLOR_TABLE #define ITEMID_DASH_LIST SID_DASH_LIST #define ITEMID_LINEEND_LIST SID_LINEEND_LIST #include "cuitabline.hxx" #include "dlgname.hxx" #include "dialmgr.hxx" #include "svdmodel.hxx" #include "xtable.hxx" #include "drawitem.hxx" #define DLGWIN this->GetParent()->GetParent() #define BITMAP_WIDTH 32 #define BITMAP_HEIGHT 12 #define XOUT_WIDTH 150 /************************************************************************* |* |* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu |* \************************************************************************/ SvxLineTabDialog::SvxLineTabDialog ( Window* pParent, const SfxItemSet* pAttr, SdrModel* pModel, const SdrObject* pSdrObj, BOOL bHasObj ) : SfxTabDialog ( pParent, SVX_RES( RID_SVXDLG_LINE ), pAttr ), pDrawModel ( pModel ), pObj ( pSdrObj ), bObjSelected ( bHasObj ), pColorTab ( pModel->GetColorTable() ), pDashList ( pModel->GetDashList() ), pLineEndList ( pModel->GetLineEndList() ), pNewDashList ( pModel->GetDashList() ), pNewLineEndList ( pModel->GetLineEndList() ), rOutAttrs ( *pAttr ) { FreeResource(); AddTabPage( RID_SVXPAGE_LINE, SvxLineTabPage::Create, 0); AddTabPage( RID_SVXPAGE_LINE_DEF, SvxLineDefTabPage::Create, 0); AddTabPage( RID_SVXPAGE_LINEEND_DEF, SvxLineEndDefTabPage::Create, 0); nLineEndListState = CT_NONE; nDashListState = CT_NONE; nDlgType = 0; nPageType = 0; // wird hier in erster Linie benutzt, um mit FillItemSet // die richtigen Attribute zu erhalten ( noch Fragen? ) nPosDashLb = 0; nPosLineEndLb = 0; SetCurPageId( RID_SVXPAGE_LINE ); CancelButton& rBtnCancel = GetCancelButton(); rBtnCancel.SetClickHdl( LINK( this, SvxLineTabDialog, CancelHdl ) ); //! rBtnCancel.SetText( SVX_RESSTR( RID_SVXSTR_CLOSE ) ); } // ----------------------------------------------------------------------- SvxLineTabDialog::~SvxLineTabDialog() { } // ----------------------------------------------------------------------- void SvxLineTabDialog::SavePalettes() { if( pNewDashList != pDrawModel->GetDashList() ) { delete pDrawModel->GetDashList(); pDrawModel->SetDashList( pNewDashList ); SfxObjectShell::Current()->PutItem( SvxDashListItem( pNewDashList ) ); pDashList = pDrawModel->GetDashList(); } if( pNewLineEndList != pDrawModel->GetLineEndList() ) { delete pDrawModel->GetLineEndList(); pDrawModel->SetLineEndList( pNewLineEndList ); SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pNewLineEndList ) ); pLineEndList = pDrawModel->GetLineEndList(); } // Speichern der Tabellen, wenn sie geaendert wurden. const String aPath( SvtPathOptions().GetPalettePath() ); if( nDashListState & CT_MODIFIED ) { pDashList->SetPath( aPath ); pDashList->Save(); // ToolBoxControls werden benachrichtigt: SfxObjectShell::Current()->PutItem( SvxDashListItem( pDashList ) ); } if( nLineEndListState & CT_MODIFIED ) { pLineEndList->SetPath( aPath ); pLineEndList->Save(); // ToolBoxControls werden benachrichtigt: SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pLineEndList ) ); } } // ----------------------------------------------------------------------- short SvxLineTabDialog::Ok() { SavePalettes(); // Es wird RET_OK zurueckgeliefert, wenn wenigstens eine // TabPage in FillItemSet() TRUE zurueckliefert. Dieses // geschieht z.Z. standardmaessig. return( SfxTabDialog::Ok() ); } // ----------------------------------------------------------------------- IMPL_LINK_INLINE_START( SvxLineTabDialog, CancelHdl, void *, p ) { SavePalettes(); EndDialog( RET_CANCEL ); return 0; } IMPL_LINK_INLINE_END( SvxLineTabDialog, CancelHdl, void *, p ) // ----------------------------------------------------------------------- void SvxLineTabDialog::PageCreated( USHORT nId, SfxTabPage &rPage ) { switch( nId ) { case RID_SVXPAGE_LINE: ( (SvxLineTabPage&) rPage ).SetColorTable( pColorTab ); ( (SvxLineTabPage&) rPage ).SetDashList( pDashList ); ( (SvxLineTabPage&) rPage ).SetLineEndList( pLineEndList ); ( (SvxLineTabPage&) rPage ).SetDlgType( nDlgType );//CHINA001 ( (SvxLineTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineTabPage&) rPage ).SetPageType( nPageType );//CHINA001 ( (SvxLineTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineTabPage&) rPage ).SetPosDashLb( &nPosDashLb ); ( (SvxLineTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb ); ( (SvxLineTabPage&) rPage ).SetDashChgd( &nDashListState ); ( (SvxLineTabPage&) rPage ).SetLineEndChgd( &nLineEndListState ); ( (SvxLineTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineTabPage&) rPage ).Construct(); // ActivatePage() wird das erste mal nicht gerufen ( (SvxLineTabPage&) rPage ).ActivatePage( rOutAttrs ); break; case RID_SVXPAGE_LINE_DEF: ( (SvxLineDefTabPage&) rPage ).SetDashList( pDashList ); ( (SvxLineDefTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineDefTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineDefTabPage&) rPage ).SetPosDashLb( &nPosDashLb ); ( (SvxLineDefTabPage&) rPage ).SetDashChgd( &nDashListState ); ( (SvxLineDefTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineDefTabPage&) rPage ).Construct(); break; case RID_SVXPAGE_LINEEND_DEF: ( (SvxLineEndDefTabPage&) rPage ).SetLineEndList( pLineEndList ); ( (SvxLineEndDefTabPage&) rPage ).SetPolyObj( pObj ); ( (SvxLineEndDefTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineEndDefTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineEndDefTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb ); ( (SvxLineEndDefTabPage&) rPage ).SetLineEndChgd( &nLineEndListState ); ( (SvxLineEndDefTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineEndDefTabPage&) rPage ).Construct(); break; } } <|endoftext|>
<commit_before><commit_msg>get rid of last use of UniString in LibreOffice<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <hintids.hxx> #include <doc.hxx> #include <IDocumentUndoRedo.hxx> #include <editsh.hxx> #include <cntfrm.hxx> #include <pam.hxx> #include <swundo.hxx> // fuer die UndoIds #include <edimp.hxx> #include <IMark.hxx> #include <docary.hxx> #include <SwRewriter.hxx> #include <globals.hrc> #include <comcore.hrc> #include <list> void SwEditShell::DeleteSel( SwPaM& rPam, sal_Bool* pUndo ) { // only for selections if( !rPam.HasMark() || *rPam.GetPoint() == *rPam.GetMark()) return; // Is the selection in a table? Then delete only the content of the selected boxes. // Here, there are two cases: // 1. Point and Mark are in one box, delete selection as usual // 2. Point and Mare are in different boxes, search all selected boxes and delete content if( rPam.GetNode()->FindTableNode() && rPam.GetNode()->StartOfSectionNode() != rPam.GetNode(sal_False)->StartOfSectionNode() ) { // group the Undo in the table if( pUndo && !*pUndo ) { GetDoc()->GetIDocumentUndoRedo().StartUndo( UNDO_START, NULL ); *pUndo = sal_True; } SwPaM aDelPam( *rPam.Start() ); const SwPosition* pEndSelPos = rPam.End(); do { aDelPam.SetMark(); SwNode* pNd = aDelPam.GetNode(); const SwNode& rEndNd = *pNd->EndOfSectionNode(); if( pEndSelPos->nNode.GetIndex() <= rEndNd.GetIndex() ) { *aDelPam.GetPoint() = *pEndSelPos; pEndSelPos = 0; // misuse a pointer as a flag } else { // then go to the end of the selection aDelPam.GetPoint()->nNode = rEndNd; aDelPam.Move( fnMoveBackward, fnGoCntnt ); } // skip protected boxes if( !pNd->IsCntntNode() || !pNd->IsInProtectSect() ) { // delete everything GetDoc()->DeleteAndJoin( aDelPam ); SaveTblBoxCntnt( aDelPam.GetPoint() ); } if( !pEndSelPos ) // at the end of a selection break; aDelPam.DeleteMark(); aDelPam.Move( fnMoveForward, fnGoCntnt ); // next box } while( pEndSelPos ); } else { // delete everything GetDoc()->DeleteAndJoin( rPam ); SaveTblBoxCntnt( rPam.GetPoint() ); } // Selection is not needed anymore rPam.DeleteMark(); } long SwEditShell::Delete() { SET_CURR_SHELL( this ); long nRet = 0; if( !HasReadonlySel() ) { StartAllAction(); sal_Bool bUndo = GetCrsr()->GetNext() != GetCrsr(); if( bUndo ) // more than one selection? { SwRewriter aRewriter; aRewriter.AddRule(UndoArg1, SW_RESSTR(STR_MULTISEL)); GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_DELETE, &aRewriter); } FOREACHPAM_START(this) DeleteSel( *PCURCRSR, &bUndo ); FOREACHPAM_END() // If undo container then close here if( bUndo ) { GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_END, 0); } EndAllAction(); nRet = 1; } return nRet; } long SwEditShell::Copy( SwEditShell* pDestShell ) { if( !pDestShell ) pDestShell = this; SET_CURR_SHELL( pDestShell ); // List of insert positions for smart insert of block selections std::list< boost::shared_ptr<SwPosition> > aInsertList; // Fill list of insert positions { SwPosition * pPos = 0; boost::shared_ptr<SwPosition> pInsertPos; sal_uInt16 nMove = 0; FOREACHPAM_START(this) if( !pPos ) { if( pDestShell == this ) { // First cursor represents the target position!! PCURCRSR->DeleteMark(); pPos = (SwPosition*)PCURCRSR->GetPoint(); continue; } else pPos = pDestShell->GetCrsr()->GetPoint(); } if( IsBlockMode() ) { // In block mode different insert positions will be calculated // by simulated cursor movements from the given first insert position if( nMove ) { SwCursor aCrsr( *pPos, 0, false); if( aCrsr.UpDown( sal_False, nMove, 0, 0 ) ) { pInsertPos.reset( new SwPosition( *aCrsr.GetPoint() ) ); aInsertList.push_back( pInsertPos ); } } else pInsertPos.reset( new SwPosition( *pPos ) ); ++nMove; } SwPosition *pTmp = IsBlockMode() ? pInsertPos.get() : pPos; // Check if a selection would be copied into itself if( pDestShell->GetDoc() == GetDoc() && *PCURCRSR->Start() <= *pTmp && *pTmp < *PCURCRSR->End() ) return sal_False; FOREACHPAM_END() } pDestShell->StartAllAction(); SwPosition *pPos = 0; sal_Bool bRet = sal_False; bool bFirstMove = true; SwNodeIndex aSttNdIdx( pDestShell->GetDoc()->GetNodes() ); xub_StrLen nSttCntIdx = 0; // For block selection this list is filled with the insert positions std::list< boost::shared_ptr<SwPosition> >::iterator pNextInsert = aInsertList.begin(); pDestShell->GetDoc()->GetIDocumentUndoRedo().StartUndo( UNDO_START, NULL ); FOREACHPAM_START(this) if( !pPos ) { if( pDestShell == this ) { // First cursor represents the target position!! PCURCRSR->DeleteMark(); pPos = (SwPosition*)PCURCRSR->GetPoint(); continue; } else pPos = pDestShell->GetCrsr()->GetPoint(); } if( !bFirstMove ) { if( pNextInsert != aInsertList.end() ) { pPos = pNextInsert->get(); ++pNextInsert; } else if( IsBlockMode() ) GetDoc()->SplitNode( *pPos, false ); } // Only for a selection (non-text nodes have selection but Point/GetMark are equal) if( !PCURCRSR->HasMark() || *PCURCRSR->GetPoint() == *PCURCRSR->GetMark() ) continue; if( bFirstMove ) { // Store start position of the new area aSttNdIdx = pPos->nNode.GetIndex()-1; nSttCntIdx = pPos->nContent.GetIndex(); bFirstMove = false; } const bool bSuccess( GetDoc()->CopyRange( *PCURCRSR, *pPos, false ) ); if (!bSuccess) continue; SwPaM aInsertPaM(*pPos, SwPosition(aSttNdIdx)); pDestShell->GetDoc()->MakeUniqueNumRules(aInsertPaM); bRet = sal_True; FOREACHPAM_END() // Maybe nothing has been moved? if( !bFirstMove ) { SwPaM* pCrsr = pDestShell->GetCrsr(); pCrsr->SetMark(); pCrsr->GetPoint()->nNode = aSttNdIdx.GetIndex()+1; pCrsr->GetPoint()->nContent.Assign( pCrsr->GetCntntNode(),nSttCntIdx); pCrsr->Exchange(); } else { // If the cursor moved during move process, move also its GetMark pDestShell->GetCrsr()->SetMark(); pDestShell->GetCrsr()->DeleteMark(); } #if OSL_DEBUG_LEVEL > 0 // check if the indices are registered in the correct nodes { SwPaM* pCmp = (SwPaM*)pDestShell->GetCrsr(); // store pointer to cursor do { OSL_ENSURE( pCmp->GetPoint()->nContent.GetIdxReg() == pCmp->GetCntntNode(), "Point in wrong Node" ); OSL_ENSURE( pCmp->GetMark()->nContent.GetIdxReg() == pCmp->GetCntntNode(sal_False), "Mark in wrong Node" ); bool bTst = *pCmp->GetPoint() == *pCmp->GetMark(); (void) bTst; } while( pDestShell->GetCrsr() != ( pCmp = (SwPaM*)pCmp->GetNext() ) ); } #endif // close Undo container here pDestShell->GetDoc()->GetIDocumentUndoRedo().EndUndo( UNDO_END, NULL ); pDestShell->EndAllAction(); pDestShell->SaveTblBoxCntnt( pDestShell->GetCrsr()->GetPoint() ); return (long)bRet; } /** Replace a selected area in a text node with a given string. * * Intended for "search & replace". * * @param bRegExpRplc if <true> replace tabs (\\t) and replace with found string (not \&). * E.g. [Fnd: "zzz", Repl: "xx\t\\t..&..\&"] --> "xx\t<Tab>..zzz..&" */ sal_Bool SwEditShell::Replace( const String& rNewStr, sal_Bool bRegExpRplc ) { SET_CURR_SHELL( this ); sal_Bool bRet = sal_False; if( !HasReadonlySel() ) { StartAllAction(); GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_EMPTY, NULL); FOREACHPAM_START(this) if( PCURCRSR->HasMark() && *PCURCRSR->GetMark() != *PCURCRSR->GetPoint() ) { bRet = GetDoc()->ReplaceRange( *PCURCRSR, rNewStr, bRegExpRplc ) || bRet; SaveTblBoxCntnt( PCURCRSR->GetPoint() ); } FOREACHPAM_END() // close Undo container here GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_EMPTY, NULL); EndAllAction(); } return bRet; } /// special method for JOE's wizards sal_Bool SwEditShell::DelFullPara() { sal_Bool bRet = sal_False; if( !IsTableMode() ) { SwPaM* pCrsr = GetCrsr(); // no multi selection if( pCrsr->GetNext() == pCrsr && !HasReadonlySel() ) { SET_CURR_SHELL( this ); StartAllAction(); bRet = GetDoc()->DelFullPara( *pCrsr ); EndAllAction(); } } return bRet; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Related: #i121925# fixed by reverting change for issue #i119652#<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <hintids.hxx> #include <doc.hxx> #include <IDocumentUndoRedo.hxx> #include <editsh.hxx> #include <cntfrm.hxx> #include <pam.hxx> #include <swundo.hxx> // fuer die UndoIds #include <edimp.hxx> #include <IMark.hxx> #include <docary.hxx> #include <SwRewriter.hxx> #include <globals.hrc> #include <comcore.hrc> #include <list> void SwEditShell::DeleteSel( SwPaM& rPam, sal_Bool* pUndo ) { // only on a selection if ( !rPam.HasMark() || *rPam.GetPoint() == *rPam.GetMark()) return; // Is the selection in a table? Then delete only the content of the selected boxes. // Here, there are two cases: // 1. Point and Mark are in one box, delete selection as usual // 2. Point and Mare are in different boxes, search all selected boxes and delete content if( rPam.GetNode()->FindTableNode() && rPam.GetNode()->StartOfSectionNode() != rPam.GetNode(sal_False)->StartOfSectionNode() ) { // group the Undo in the table if( pUndo && !*pUndo ) { GetDoc()->GetIDocumentUndoRedo().StartUndo( UNDO_START, NULL ); *pUndo = sal_True; } SwPaM aDelPam( *rPam.Start() ); const SwPosition* pEndSelPos = rPam.End(); do { aDelPam.SetMark(); SwNode* pNd = aDelPam.GetNode(); const SwNode& rEndNd = *pNd->EndOfSectionNode(); if( pEndSelPos->nNode.GetIndex() <= rEndNd.GetIndex() ) { *aDelPam.GetPoint() = *pEndSelPos; pEndSelPos = 0; // misuse a pointer as a flag } else { // then go to the end of the selection aDelPam.GetPoint()->nNode = rEndNd; aDelPam.Move( fnMoveBackward, fnGoCntnt ); } // skip protected boxes //For i117395, in some situation, the node would be hidden or invisible, which makes the frame of it unavailable //So verify it before use it. SwCntntFrm* pFrm = NULL; if( !pNd->IsCntntNode() || !pNd->IsInProtectSect() ) { // delete everything GetDoc()->DeleteAndJoin( aDelPam ); SaveTblBoxCntnt( aDelPam.GetPoint() ); } if( !pEndSelPos ) // at the end of a selection break; aDelPam.DeleteMark(); aDelPam.Move( fnMoveForward, fnGoCntnt ); // next box } while( pEndSelPos ); } else { // delete everything GetDoc()->DeleteAndJoin( rPam ); SaveTblBoxCntnt( rPam.GetPoint() ); } // Selection is not needed anymore rPam.DeleteMark(); } long SwEditShell::Delete() { SET_CURR_SHELL( this ); long nRet = 0; if( !HasReadonlySel() ) { StartAllAction(); sal_Bool bUndo = GetCrsr()->GetNext() != GetCrsr(); if( bUndo ) // more than one selection? { SwRewriter aRewriter; aRewriter.AddRule(UndoArg1, SW_RESSTR(STR_MULTISEL)); GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_DELETE, &aRewriter); } FOREACHPAM_START(this) DeleteSel( *PCURCRSR, &bUndo ); FOREACHPAM_END() // If undo container then close here if( bUndo ) { GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_END, 0); } EndAllAction(); nRet = 1; } return nRet; } long SwEditShell::Copy( SwEditShell* pDestShell ) { if( !pDestShell ) pDestShell = this; SET_CURR_SHELL( pDestShell ); // List of insert positions for smart insert of block selections std::list< boost::shared_ptr<SwPosition> > aInsertList; // Fill list of insert positions { SwPosition * pPos = 0; boost::shared_ptr<SwPosition> pInsertPos; sal_uInt16 nMove = 0; FOREACHPAM_START(this) if( !pPos ) { if( pDestShell == this ) { // First cursor represents the target position!! PCURCRSR->DeleteMark(); pPos = (SwPosition*)PCURCRSR->GetPoint(); continue; } else pPos = pDestShell->GetCrsr()->GetPoint(); } if( IsBlockMode() ) { // In block mode different insert positions will be calculated // by simulated cursor movements from the given first insert position if( nMove ) { SwCursor aCrsr( *pPos, 0, false); if( aCrsr.UpDown( sal_False, nMove, 0, 0 ) ) { pInsertPos.reset( new SwPosition( *aCrsr.GetPoint() ) ); aInsertList.push_back( pInsertPos ); } } else pInsertPos.reset( new SwPosition( *pPos ) ); ++nMove; } SwPosition *pTmp = IsBlockMode() ? pInsertPos.get() : pPos; // Check if a selection would be copied into itself if( pDestShell->GetDoc() == GetDoc() && *PCURCRSR->Start() <= *pTmp && *pTmp < *PCURCRSR->End() ) return sal_False; FOREACHPAM_END() } pDestShell->StartAllAction(); SwPosition *pPos = 0; sal_Bool bRet = sal_False; bool bFirstMove = true; SwNodeIndex aSttNdIdx( pDestShell->GetDoc()->GetNodes() ); xub_StrLen nSttCntIdx = 0; // For block selection this list is filled with the insert positions std::list< boost::shared_ptr<SwPosition> >::iterator pNextInsert = aInsertList.begin(); pDestShell->GetDoc()->GetIDocumentUndoRedo().StartUndo( UNDO_START, NULL ); FOREACHPAM_START(this) if( !pPos ) { if( pDestShell == this ) { // First cursor represents the target position!! PCURCRSR->DeleteMark(); pPos = (SwPosition*)PCURCRSR->GetPoint(); continue; } else pPos = pDestShell->GetCrsr()->GetPoint(); } if( !bFirstMove ) { if( pNextInsert != aInsertList.end() ) { pPos = pNextInsert->get(); ++pNextInsert; } else if( IsBlockMode() ) GetDoc()->SplitNode( *pPos, false ); } // Only for a selection (non-text nodes have selection but Point/GetMark are equal) if( !PCURCRSR->HasMark() || *PCURCRSR->GetPoint() == *PCURCRSR->GetMark() ) continue; if( bFirstMove ) { // Store start position of the new area aSttNdIdx = pPos->nNode.GetIndex()-1; nSttCntIdx = pPos->nContent.GetIndex(); bFirstMove = false; } const bool bSuccess( GetDoc()->CopyRange( *PCURCRSR, *pPos, false ) ); if (!bSuccess) continue; SwPaM aInsertPaM(*pPos, SwPosition(aSttNdIdx)); pDestShell->GetDoc()->MakeUniqueNumRules(aInsertPaM); bRet = sal_True; FOREACHPAM_END() // Maybe nothing has been moved? if( !bFirstMove ) { SwPaM* pCrsr = pDestShell->GetCrsr(); pCrsr->SetMark(); pCrsr->GetPoint()->nNode = aSttNdIdx.GetIndex()+1; pCrsr->GetPoint()->nContent.Assign( pCrsr->GetCntntNode(),nSttCntIdx); pCrsr->Exchange(); } else { // If the cursor moved during move process, move also its GetMark pDestShell->GetCrsr()->SetMark(); pDestShell->GetCrsr()->DeleteMark(); } #if OSL_DEBUG_LEVEL > 0 // check if the indices are registered in the correct nodes { SwPaM* pCmp = (SwPaM*)pDestShell->GetCrsr(); // store pointer to cursor do { OSL_ENSURE( pCmp->GetPoint()->nContent.GetIdxReg() == pCmp->GetCntntNode(), "Point in wrong Node" ); OSL_ENSURE( pCmp->GetMark()->nContent.GetIdxReg() == pCmp->GetCntntNode(sal_False), "Mark in wrong Node" ); bool bTst = *pCmp->GetPoint() == *pCmp->GetMark(); (void) bTst; } while( pDestShell->GetCrsr() != ( pCmp = (SwPaM*)pCmp->GetNext() ) ); } #endif // close Undo container here pDestShell->GetDoc()->GetIDocumentUndoRedo().EndUndo( UNDO_END, NULL ); pDestShell->EndAllAction(); pDestShell->SaveTblBoxCntnt( pDestShell->GetCrsr()->GetPoint() ); return (long)bRet; } /** Replace a selected area in a text node with a given string. * * Intended for "search & replace". * * @param bRegExpRplc if <true> replace tabs (\\t) and replace with found string (not \&). * E.g. [Fnd: "zzz", Repl: "xx\t\\t..&..\&"] --> "xx\t<Tab>..zzz..&" */ sal_Bool SwEditShell::Replace( const String& rNewStr, sal_Bool bRegExpRplc ) { SET_CURR_SHELL( this ); sal_Bool bRet = sal_False; if( !HasReadonlySel() ) { StartAllAction(); GetDoc()->GetIDocumentUndoRedo().StartUndo(UNDO_EMPTY, NULL); FOREACHPAM_START(this) if( PCURCRSR->HasMark() && *PCURCRSR->GetMark() != *PCURCRSR->GetPoint() ) { bRet = GetDoc()->ReplaceRange( *PCURCRSR, rNewStr, bRegExpRplc ) || bRet; SaveTblBoxCntnt( PCURCRSR->GetPoint() ); } FOREACHPAM_END() // close Undo container here GetDoc()->GetIDocumentUndoRedo().EndUndo(UNDO_EMPTY, NULL); EndAllAction(); } return bRet; } /// special method for JOE's wizards sal_Bool SwEditShell::DelFullPara() { sal_Bool bRet = sal_False; if( !IsTableMode() ) { SwPaM* pCrsr = GetCrsr(); // no multi selection if( pCrsr->GetNext() == pCrsr && !HasReadonlySel() ) { SET_CURR_SHELL( this ); StartAllAction(); bRet = GetDoc()->DelFullPara( *pCrsr ); EndAllAction(); } } return bRet; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before><commit_msg>Some more conversion to consinstent integer types<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unotools.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: os $ $Date: 2001-04-27 10:58:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _UNOTOOLS_HXX #define _UNOTOOLS_HXX #ifndef _SV_DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _ACTCTRL_HXX //autogen #include <actctrl.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXTCURSOR_HPP_ #include <com/sun/star/text/XTextCursor.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XCONTROL_HPP_ #include <com/sun/star/awt/XControl.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _SV_RESARY_HXX #include <vcl/resary.hxx> #endif #define STAR_REFERENCE(aType) \ ::com::sun::star::uno::Reference< ::com::sun::star::aType > /* -----------------09.06.99 14:36------------------- * * --------------------------------------------------*/ class SwRenameXNamedDlg : public ModalDialog { FixedText aNewNameFT; NoSpaceEdit aNewNameED; GroupBox aNameGB; OKButton aOk; CancelButton aCancel; HelpButton aHelp; String sRemoveWarning; STAR_REFERENCE( container::XNamed ) & xNamed; STAR_REFERENCE( container::XNameAccess ) & xNameAccess; STAR_REFERENCE( container::XNameAccess ) xSecondAccess; STAR_REFERENCE( container::XNameAccess ) xThirdAccess; DECL_LINK(OkHdl, OKButton*); DECL_LINK(ModifyHdl, NoSpaceEdit*); public: SwRenameXNamedDlg( Window* pParent, STAR_REFERENCE( container::XNamed ) & xNamed, STAR_REFERENCE( container::XNameAccess ) & xNameAccess ); void SetForbiddenChars( const String& rSet ) { aNewNameED.SetForbiddenChars( rSet ); } void SetAlternativeAccess( STAR_REFERENCE( container::XNameAccess ) & xSecond, STAR_REFERENCE( container::XNameAccess ) & xThird ) { xSecondAccess = xSecond; xThirdAccess = xThird; } }; /* -----------------------------15.12.99 09:55-------------------------------- ---------------------------------------------------------------------------*/ class SwOneExampleFrame; class SwFrmCtrlWindow : public Window { SwOneExampleFrame* pExampleFrame; public: SwFrmCtrlWindow(Window* pParent, WinBits nBits, SwOneExampleFrame* pFrame); virtual void Command( const CommandEvent& rCEvt ); }; /* -----------------------------15.12.99 12:56-------------------------------- ---------------------------------------------------------------------------*/ class MenuResource : public Resource { ResStringArray aMenuArray; public: MenuResource(const ResId& rResId); ResStringArray& GetMenuArray() {return aMenuArray;} }; /* -----------------27.07.99 15:20------------------- --------------------------------------------------*/ #define EX_SHOW_ONLINE_LAYOUT 0x001 // hard zoom value #define EX_SHOW_BUSINESS_CARDS 0x02 class SwView; class SwOneExampleFrame { STAR_REFERENCE( awt::XControl ) _xControl; STAR_REFERENCE( frame::XModel ) _xModel; STAR_REFERENCE( frame::XController ) _xController; STAR_REFERENCE( text::XTextCursor ) _xCursor; SwFrmCtrlWindow aTopWindow; Window& rWindow; Timer aLoadedTimer; Link aInitializedLink; MenuResource aMenuRes; String sArgumentURL; SwView* pModuleView; sal_uInt32 nStyleFlags; sal_Bool bIsInitialized; sal_Bool bServiceAvailable; static sal_Bool bShowServiceNotAvailableMessage; DECL_LINK( TimeoutHdl, Timer* ); DECL_LINK( PopupHdl, Menu* ); void CreateControl(); void DisposeControl(); public: SwOneExampleFrame(Window& rWin, sal_uInt32 nStyleFlags = EX_SHOW_ONLINE_LAYOUT, const Link* pInitalizedLink = 0, String* pURL = 0); ~SwOneExampleFrame(); STAR_REFERENCE( awt::XControl ) & GetControl() {return _xControl; } STAR_REFERENCE( frame::XModel ) & GetModel() {return _xModel;} STAR_REFERENCE( frame::XController ) & GetController() {return _xController;} STAR_REFERENCE( text::XTextCursor ) & GetTextCursor() {return _xCursor;} void ClearDocument( BOOL bStartTimer = FALSE ); sal_Bool IsInitialized() const {return bIsInitialized;} sal_Bool IsServiceAvailable() const {return bServiceAvailable;} void CreatePopup(const Point& rPt); static void CreateErrorMessage(Window* pParent); }; #endif <commit_msg>defines for UNO namespaces into own headerfile moved<commit_after>/************************************************************************* * * $RCSfile: unotools.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: jp $ $Date: 2001-04-30 15:48:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _UNOTOOLS_HXX #define _UNOTOOLS_HXX #ifndef _SV_DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _ACTCTRL_HXX //autogen #include <actctrl.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXTCURSOR_HPP_ #include <com/sun/star/text/XTextCursor.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XCONTROL_HPP_ #include <com/sun/star/awt/XControl.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif #ifndef _SV_RESARY_HXX #include <vcl/resary.hxx> #endif #ifndef _SWUNODEF_HXX #include <swunodef.hxx> #endif /* -----------------09.06.99 14:36------------------- * * --------------------------------------------------*/ class SwRenameXNamedDlg : public ModalDialog { FixedText aNewNameFT; NoSpaceEdit aNewNameED; GroupBox aNameGB; OKButton aOk; CancelButton aCancel; HelpButton aHelp; String sRemoveWarning; STAR_REFERENCE( container::XNamed ) & xNamed; STAR_REFERENCE( container::XNameAccess ) & xNameAccess; STAR_REFERENCE( container::XNameAccess ) xSecondAccess; STAR_REFERENCE( container::XNameAccess ) xThirdAccess; DECL_LINK(OkHdl, OKButton*); DECL_LINK(ModifyHdl, NoSpaceEdit*); public: SwRenameXNamedDlg( Window* pParent, STAR_REFERENCE( container::XNamed ) & xNamed, STAR_REFERENCE( container::XNameAccess ) & xNameAccess ); void SetForbiddenChars( const String& rSet ) { aNewNameED.SetForbiddenChars( rSet ); } void SetAlternativeAccess( STAR_REFERENCE( container::XNameAccess ) & xSecond, STAR_REFERENCE( container::XNameAccess ) & xThird ) { xSecondAccess = xSecond; xThirdAccess = xThird; } }; /* -----------------------------15.12.99 09:55-------------------------------- ---------------------------------------------------------------------------*/ class SwOneExampleFrame; class SwFrmCtrlWindow : public Window { SwOneExampleFrame* pExampleFrame; public: SwFrmCtrlWindow(Window* pParent, WinBits nBits, SwOneExampleFrame* pFrame); virtual void Command( const CommandEvent& rCEvt ); }; /* -----------------------------15.12.99 12:56-------------------------------- ---------------------------------------------------------------------------*/ class MenuResource : public Resource { ResStringArray aMenuArray; public: MenuResource(const ResId& rResId); ResStringArray& GetMenuArray() {return aMenuArray;} }; /* -----------------27.07.99 15:20------------------- --------------------------------------------------*/ #define EX_SHOW_ONLINE_LAYOUT 0x001 // hard zoom value #define EX_SHOW_BUSINESS_CARDS 0x02 class SwView; class SwOneExampleFrame { STAR_REFERENCE( awt::XControl ) _xControl; STAR_REFERENCE( frame::XModel ) _xModel; STAR_REFERENCE( frame::XController ) _xController; STAR_REFERENCE( text::XTextCursor ) _xCursor; SwFrmCtrlWindow aTopWindow; Window& rWindow; Timer aLoadedTimer; Link aInitializedLink; MenuResource aMenuRes; String sArgumentURL; SwView* pModuleView; sal_uInt32 nStyleFlags; sal_Bool bIsInitialized; sal_Bool bServiceAvailable; static sal_Bool bShowServiceNotAvailableMessage; DECL_LINK( TimeoutHdl, Timer* ); DECL_LINK( PopupHdl, Menu* ); void CreateControl(); void DisposeControl(); public: SwOneExampleFrame(Window& rWin, sal_uInt32 nStyleFlags = EX_SHOW_ONLINE_LAYOUT, const Link* pInitalizedLink = 0, String* pURL = 0); ~SwOneExampleFrame(); STAR_REFERENCE( awt::XControl ) & GetControl() {return _xControl; } STAR_REFERENCE( frame::XModel ) & GetModel() {return _xModel;} STAR_REFERENCE( frame::XController ) & GetController() {return _xController;} STAR_REFERENCE( text::XTextCursor ) & GetTextCursor() {return _xCursor;} void ClearDocument( BOOL bStartTimer = FALSE ); sal_Bool IsInitialized() const {return bIsInitialized;} sal_Bool IsServiceAvailable() const {return bServiceAvailable;} void CreatePopup(const Point& rPt); static void CreateErrorMessage(Window* pParent); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtsh4.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-09-27 12:53:55 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif /* * private Methoden, die den Cursor ueber Suchen bewegen. Das * Aufheben der Selektion muss auf der Ebene darueber erfolgen. */ /* * Der Anfang eines Wortes ist das Folgen eines nicht- * Trennzeichens auf Trennzeichen. Ferner das Folgen von * nicht-Satztrennern auf Satztrenner. Der Absatzanfang ist * ebenfalls Wortanfang. */ BOOL SwWrtShell::_SttWrd() { if ( IsSttPara() ) return 1; /* * temporaeren Cursor ohne Selektion erzeugen */ Push(); ClearMark(); if( !GoStartWord() ) // nicht gefunden --> an den Absatzanfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } /* * Das Ende eines Wortes ist das Folgen von Trennzeichen auf * nicht-Trennzeichen. Unter dem Ende eines Wortes wird * ebenfalls die Folge von Worttrennzeichen auf Interpunktions- * zeichen verstanden. Das Absatzende ist ebenfalls Wortende. */ BOOL SwWrtShell::_EndWrd() { if ( IsEndWrd() ) return 1; // temporaeren Cursor ohne Selektion erzeugen Push(); ClearMark(); if( !GoEndWord() ) // nicht gefunden --> an das Absatz Ende SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } BOOL SwWrtShell::_NxtWrd() { if( IsEndPara() ) // wenn schon am Ende, dann naechsten ??? { if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) // Document - Ende ?? { Pop( FALSE ); return 0L; } return 1; } Push(); ClearMark(); if( !GoNextWord() ) // nicht gefunden --> das AbsatzEnde ist Ende vom Wort SwCrsrShell::MovePara( fnParaCurr, fnParaEnd ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_PrvWrd() { if(IsSttPara()) { // wenn schon am Anfang, dann naechsten ??? if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { // Document - Anfang ?? Pop( FALSE ); return 0; } return 1; } Push(); ClearMark(); if( !GoPrevWord() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_FwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if( !GoNextSentence() && !IsEndPara() ) SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_BwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if(IsSttPara()) { Pop(); return 1; } if( !GoPrevSentence() && !IsSttPara() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_FwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Left(1,CRSR_SKIP_CHARS); BOOL bRet = SwCrsrShell::MovePara(fnParaNext, fnParaStart); ClearMark(); Combine(); return bRet; } BOOL SwWrtShell::_BwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Right(1,CRSR_SKIP_CHARS); if(!IsSttOfPara()) SttPara(); BOOL bRet = SwCrsrShell::MovePara(fnParaPrev, fnParaStart); ClearMark(); Combine(); return bRet; } <commit_msg>INTEGRATION: CWS changefileheader (1.8.242); FILE MERGED 2008/04/01 12:56:07 thb 1.8.242.2: #i85898# Stripping all external header guards 2008/03/31 17:00:15 rt 1.8.242.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: wrtsh4.cxx,v $ * $Revision: 1.9 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <wrtsh.hxx> #include <crsskip.hxx> /* * private Methoden, die den Cursor ueber Suchen bewegen. Das * Aufheben der Selektion muss auf der Ebene darueber erfolgen. */ /* * Der Anfang eines Wortes ist das Folgen eines nicht- * Trennzeichens auf Trennzeichen. Ferner das Folgen von * nicht-Satztrennern auf Satztrenner. Der Absatzanfang ist * ebenfalls Wortanfang. */ BOOL SwWrtShell::_SttWrd() { if ( IsSttPara() ) return 1; /* * temporaeren Cursor ohne Selektion erzeugen */ Push(); ClearMark(); if( !GoStartWord() ) // nicht gefunden --> an den Absatzanfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } /* * Das Ende eines Wortes ist das Folgen von Trennzeichen auf * nicht-Trennzeichen. Unter dem Ende eines Wortes wird * ebenfalls die Folge von Worttrennzeichen auf Interpunktions- * zeichen verstanden. Das Absatzende ist ebenfalls Wortende. */ BOOL SwWrtShell::_EndWrd() { if ( IsEndWrd() ) return 1; // temporaeren Cursor ohne Selektion erzeugen Push(); ClearMark(); if( !GoEndWord() ) // nicht gefunden --> an das Absatz Ende SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } BOOL SwWrtShell::_NxtWrd() { if( IsEndPara() ) // wenn schon am Ende, dann naechsten ??? { if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) // Document - Ende ?? { Pop( FALSE ); return 0L; } return 1; } Push(); ClearMark(); if( !GoNextWord() ) // nicht gefunden --> das AbsatzEnde ist Ende vom Wort SwCrsrShell::MovePara( fnParaCurr, fnParaEnd ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_PrvWrd() { if(IsSttPara()) { // wenn schon am Anfang, dann naechsten ??? if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { // Document - Anfang ?? Pop( FALSE ); return 0; } return 1; } Push(); ClearMark(); if( !GoPrevWord() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_FwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if( !GoNextSentence() && !IsEndPara() ) SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_BwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if(IsSttPara()) { Pop(); return 1; } if( !GoPrevSentence() && !IsSttPara() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_FwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Left(1,CRSR_SKIP_CHARS); BOOL bRet = SwCrsrShell::MovePara(fnParaNext, fnParaStart); ClearMark(); Combine(); return bRet; } BOOL SwWrtShell::_BwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Right(1,CRSR_SKIP_CHARS); if(!IsSttOfPara()) SttPara(); BOOL bRet = SwCrsrShell::MovePara(fnParaPrev, fnParaStart); ClearMark(); Combine(); return bRet; } <|endoftext|>
<commit_before>#include "options.h" namespace nng { options::options() { } option_names::option_names() { } const std::string option_names::raw = NNG_OPT_RAW; const std::string option_names::linger = NNG_OPT_LINGER; const std::string option_names::receive_buffer = NNG_OPT_RECVBUF; const std::string option_names::send_buffer = NNG_OPT_SENDBUF; const std::string option_names::receive_file_descriptor = NNG_OPT_RECVFD; const std::string option_names::send_file_descriptor = NNG_OPT_SENDFD; const std::string option_names::receive_timeout_usec = NNG_OPT_RECVTIMEO; const std::string option_names::send_timeout_usec = NNG_OPT_SENDTIMEO; const std::string option_names::local_address = NNG_OPT_LOCADDR; const std::string option_names::remote_address = NNG_OPT_REMADDR; const std::string option_names::url = NNG_OPT_URL; const std::string option_names::max_ttl = NNG_OPT_MAXTTL; const std::string option_names::protocol = NNG_OPT_PROTOCOL; const std::string option_names::transport = NNG_OPT_TRANSPORT; const std::string option_names::receive_max_size = NNG_OPT_RECVMAXSZ; const std::string option_names::min_reconnect_time_usec = NNG_OPT_RECONNMINT; const std::string option_names::sub_subscribe = NNG_OPT_SUB_SUBSCRIBE; const std::string option_names::surveyor_survey_time_usec = NNG_OPT_SURVEYOR_SURVEYTIME; } <commit_msg>added symbol definition to the source code<commit_after>#include "options.h" namespace nng { options::options() { } option_names::option_names() { } const std::string option_names::raw = NNG_OPT_RAW; const std::string option_names::linger = NNG_OPT_LINGER; const std::string option_names::receive_buffer = NNG_OPT_RECVBUF; const std::string option_names::send_buffer = NNG_OPT_SENDBUF; const std::string option_names::receive_file_descriptor = NNG_OPT_RECVFD; const std::string option_names::send_file_descriptor = NNG_OPT_SENDFD; const std::string option_names::receive_timeout_usec = NNG_OPT_RECVTIMEO; const std::string option_names::send_timeout_usec = NNG_OPT_SENDTIMEO; const std::string option_names::local_address = NNG_OPT_LOCADDR; const std::string option_names::remote_address = NNG_OPT_REMADDR; const std::string option_names::url = NNG_OPT_URL; const std::string option_names::max_ttl = NNG_OPT_MAXTTL; const std::string option_names::protocol = NNG_OPT_PROTOCOL; const std::string option_names::transport = NNG_OPT_TRANSPORT; const std::string option_names::receive_max_size = NNG_OPT_RECVMAXSZ; const std::string option_names::min_reconnect_time_usec = NNG_OPT_RECONNMINT; const std::string option_names::max_reconnect_time_usec = NNG_OPT_RECONNMAXT; const std::string option_names::sub_subscribe = NNG_OPT_SUB_SUBSCRIBE; const std::string option_names::surveyor_survey_time_usec = NNG_OPT_SURVEYOR_SURVEYTIME; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan, Robert Haschke */ #include "query_planners_service_capability.h" #include <moveit/planning_pipeline/planning_pipeline.h> #include <moveit/move_group/capability_names.h> move_group::MoveGroupQueryPlannersService::MoveGroupQueryPlannersService(): MoveGroupCapability("QueryPlannersService") { } void move_group::MoveGroupQueryPlannersService::initialize() { query_service_ = root_node_handle_.advertiseService(QUERY_PLANNERS_SERVICE_NAME, &MoveGroupQueryPlannersService::queryInterface, this); get_service_ = root_node_handle_.advertiseService(GET_PLANNER_PARAMS_SERVICE_NAME, &MoveGroupQueryPlannersService::getParams, this); set_service_ = root_node_handle_.advertiseService(SET_PLANNER_PARAMS_SERVICE_NAME, &MoveGroupQueryPlannersService::setParams, this); } bool move_group::MoveGroupQueryPlannersService::queryInterface(moveit_msgs::QueryPlannerInterfaces::Request &req, moveit_msgs::QueryPlannerInterfaces::Response &res) { const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager(); if (planner_interface) { std::vector<std::string> algs; planner_interface->getPlanningAlgorithms(algs); moveit_msgs::PlannerInterfaceDescription pi_desc; pi_desc.name = planner_interface->getDescription(); planner_interface->getPlanningAlgorithms(pi_desc.planner_ids); res.planner_interfaces.push_back(pi_desc); } return true; } bool move_group::MoveGroupQueryPlannersService::getParams(moveit_msgs::GetPlannerParams::Request &req, moveit_msgs::GetPlannerParams::Response &res) { const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager(); if (planner_interface) { std::map<std::string, std::string> config; const planning_interface::PlannerConfigurationMap& configs = planner_interface->getPlannerConfigurations(); planning_interface::PlannerConfigurationMap::const_iterator it = configs.find(req.planner_config); // fetch default params first config.insert(it->second.config.begin(), it->second.config.end()); if (!req.group.empty()) { // merge in group-specific params it = configs.find(req.group + "[" + req.planner_config + "]"); config.insert(it->second.config.begin(), it->second.config.end()); } for (std::map<std::string, std::string>::const_iterator it = config.begin(), end = config.end(); it != end; ++it) { res.params.keys.push_back(it->first); res.params.values.push_back(it->second); } } return true; } bool move_group::MoveGroupQueryPlannersService::setParams(moveit_msgs::SetPlannerParams::Request &req, moveit_msgs::SetPlannerParams::Response &res) { const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager(); if (req.params.keys.size() != req.params.values.size()) return false; if (planner_interface) { planning_interface::PlannerConfigurationMap configs = planner_interface->getPlannerConfigurations(); std::string config_name = req.group.empty() ? req.planner_config : req.group + "[" + req.planner_config + "]"; planning_interface::PlannerConfigurationSettings &config = configs[config_name]; config.group = req.group; config.name = config_name; if (req.replace) config.config.clear(); for (unsigned int i=0, end=req.params.keys.size(); i < end; ++i) config.config[req.params.keys[i]] = req.params.values[i]; planner_interface->setPlannerConfigurations(configs); } return true; } #include <class_loader/class_loader.h> CLASS_LOADER_REGISTER_CLASS(move_group::MoveGroupQueryPlannersService, move_group::MoveGroupCapability) <commit_msg>added missing validity check<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan, Robert Haschke */ #include "query_planners_service_capability.h" #include <moveit/planning_pipeline/planning_pipeline.h> #include <moveit/move_group/capability_names.h> move_group::MoveGroupQueryPlannersService::MoveGroupQueryPlannersService(): MoveGroupCapability("QueryPlannersService") { } void move_group::MoveGroupQueryPlannersService::initialize() { query_service_ = root_node_handle_.advertiseService(QUERY_PLANNERS_SERVICE_NAME, &MoveGroupQueryPlannersService::queryInterface, this); get_service_ = root_node_handle_.advertiseService(GET_PLANNER_PARAMS_SERVICE_NAME, &MoveGroupQueryPlannersService::getParams, this); set_service_ = root_node_handle_.advertiseService(SET_PLANNER_PARAMS_SERVICE_NAME, &MoveGroupQueryPlannersService::setParams, this); } bool move_group::MoveGroupQueryPlannersService::queryInterface(moveit_msgs::QueryPlannerInterfaces::Request &req, moveit_msgs::QueryPlannerInterfaces::Response &res) { const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager(); if (planner_interface) { std::vector<std::string> algs; planner_interface->getPlanningAlgorithms(algs); moveit_msgs::PlannerInterfaceDescription pi_desc; pi_desc.name = planner_interface->getDescription(); planner_interface->getPlanningAlgorithms(pi_desc.planner_ids); res.planner_interfaces.push_back(pi_desc); } return true; } bool move_group::MoveGroupQueryPlannersService::getParams(moveit_msgs::GetPlannerParams::Request &req, moveit_msgs::GetPlannerParams::Response &res) { const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager(); if (planner_interface) { std::map<std::string, std::string> config; const planning_interface::PlannerConfigurationMap& configs = planner_interface->getPlannerConfigurations(); planning_interface::PlannerConfigurationMap::const_iterator it = configs.find(req.planner_config); // fetch default params first if (it != configs.end()) config.insert(it->second.config.begin(), it->second.config.end()); if (!req.group.empty()) { // merge in group-specific params it = configs.find(req.group + "[" + req.planner_config + "]"); if (it != configs.end()) config.insert(it->second.config.begin(), it->second.config.end()); } for (std::map<std::string, std::string>::const_iterator it = config.begin(), end = config.end(); it != end; ++it) { res.params.keys.push_back(it->first); res.params.values.push_back(it->second); } } return true; } bool move_group::MoveGroupQueryPlannersService::setParams(moveit_msgs::SetPlannerParams::Request &req, moveit_msgs::SetPlannerParams::Response &res) { const planning_interface::PlannerManagerPtr &planner_interface = context_->planning_pipeline_->getPlannerManager(); if (req.params.keys.size() != req.params.values.size()) return false; if (planner_interface) { planning_interface::PlannerConfigurationMap configs = planner_interface->getPlannerConfigurations(); std::string config_name = req.group.empty() ? req.planner_config : req.group + "[" + req.planner_config + "]"; planning_interface::PlannerConfigurationSettings &config = configs[config_name]; config.group = req.group; config.name = config_name; if (req.replace) config.config.clear(); for (unsigned int i=0, end=req.params.keys.size(); i < end; ++i) config.config[req.params.keys[i]] = req.params.values[i]; planner_interface->setPlannerConfigurations(configs); } return true; } #include <class_loader/class_loader.h> CLASS_LOADER_REGISTER_CLASS(move_group::MoveGroupQueryPlannersService, move_group::MoveGroupCapability) <|endoftext|>
<commit_before>#include <chrono> #include <cstdint> #include "envoy/config/endpoint/v3/endpoint_components.pb.h" #include "source/common/common/base64.h" #include "source/common/http/utility.h" #include "source/common/protobuf/protobuf.h" #include "source/extensions/filters/http/stateful_session/stateful_session.h" #include "test/integration/http_integration.h" #include "gtest/gtest.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace StatefulSession { namespace { class StatefulSessionIntegrationTest : public Envoy::HttpIntegrationTest, public testing::Test { public: StatefulSessionIntegrationTest() : HttpIntegrationTest( Http::CodecType::HTTP1, [](int i) { return Network::Utility::parseInternetAddress("127.0.0.1", 50000 + i); }, Network::Address::IpVersion::v4) { // Create 4 different upstream server for stateful session test. setUpstreamCount(4); skipPortUsageValidation(); // Update endpoints of default cluster `cluster_0` to 4 different fake upstreams. config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) { auto* cluster_0 = bootstrap.mutable_static_resources()->mutable_clusters()->Mutable(0); ASSERT(cluster_0->name() == "cluster_0"); auto* endpoint = cluster_0->mutable_load_assignment()->mutable_endpoints()->Mutable(0); const std::string EndpointsYaml = R"EOF( lb_endpoints: - endpoint: address: socket_address: address: 127.0.0.1 port_value: 50000 - endpoint: address: socket_address: address: 127.0.0.1 port_value: 50001 - endpoint: address: socket_address: address: 127.0.0.1 port_value: 50002 - endpoint: address: socket_address: address: 127.0.0.1 port_value: 50003 )EOF"; envoy::config::endpoint::v3::LocalityLbEndpoints new_lb_endpints; TestUtility::loadFromYaml(EndpointsYaml, new_lb_endpints); *endpoint = new_lb_endpints; }); } // Initialize route filter and per route config. void initializeFilterAndRoute(const std::string& filter_yaml, const std::string& per_route_config_yaml) { config_helper_.prependFilter(filter_yaml); // Create virtual host with domain `stateful.session.com` and default route to `cluster_0` auto virtual_host = config_helper_.createVirtualHost("stateful.session.com"); // Update per route config of default route. if (!per_route_config_yaml.empty()) { auto* route = virtual_host.mutable_routes(0); ProtobufWkt::Any per_route_config; TestUtility::loadFromYaml(per_route_config_yaml, per_route_config); route->mutable_typed_per_filter_config()->insert( {"envoy.filters.http.stateful_session", per_route_config}); } config_helper_.addVirtualHost(virtual_host); initialize(); } }; static const std::string STATEFUL_SESSION_FILTER = R"EOF( name: envoy.filters.http.stateful_session typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSession session_state: name: envoy.http.stateful_session.cookie typed_config: "@type": type.googleapis.com/envoy.extensions.http.stateful_session.cookie.v3.CookieBasedSessionState cookie: name: global-session-cookie path: /path ttl: 120s )EOF"; static const std::string DISABLE_STATEFUL_SESSION = R"EOF( "@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSessionPerRoute disabled: true )EOF"; static const std::string OVERRIDE_STATEFUL_SESSION = R"EOF( "@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSessionPerRoute stateful_session: session_state: name: envoy.http.stateful_session.cookie typed_config: "@type": type.googleapis.com/envoy.extensions.http.stateful_session.cookie.v3.CookieBasedSessionState cookie: name: route-session-cookie path: /path ttl: 120s )EOF"; TEST_F(StatefulSessionIntegrationTest, NormalStatefulSession) { initializeFilterAndRoute(STATEFUL_SESSION_FILTER, ""); codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); const std::string address_string = fmt::format("127.0.0.1:{}", upstream_index.value() + 50000); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), 15); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // The selected upstream server address would be selected to the response headers. EXPECT_EQ( Envoy::Http::Utility::makeSetCookieValue("global-session-cookie", encoded_address, "/path", std::chrono::seconds(120), true), response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView()); cleanupUpstreamAndDownstream(); } TEST_F(StatefulSessionIntegrationTest, DownstreamRequestWithStatefulSessionCookie) { initializeFilterAndRoute(STATEFUL_SESSION_FILTER, ""); { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.1:50001", 15))}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); // `127.0.0.1:50001` should be selected and it's upstream index is 1. auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); EXPECT_EQ(upstream_index.value(), 1); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.1:50002", 15))}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); // `127.0.0.1:50002` should be selected and it's upstream index is 2. auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); EXPECT_EQ(upstream_index.value(), 2); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } // Test the case that stateful session cookie with unknown server address. { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.1:50005", 15))}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); const std::string address_string = fmt::format("127.0.0.1:{}", upstream_index.value() + 50000); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), 15); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // The selected upstream server address would be selected to the response headers. EXPECT_EQ( Envoy::Http::Utility::makeSetCookieValue("global-session-cookie", encoded_address, "/path", std::chrono::seconds(120), true), response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView()); cleanupUpstreamAndDownstream(); } } TEST_F(StatefulSessionIntegrationTest, StatefulSessionDisabledByRoute) { initializeFilterAndRoute(STATEFUL_SESSION_FILTER, DISABLE_STATEFUL_SESSION); uint64_t first_index = 0; uint64_t second_index = 0; { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.1:50001", 15))}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); first_index = upstream_index.value(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.1:50001", 15))}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); second_index = upstream_index.value(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } // Choose different upstream servers by default. EXPECT_NE(first_index, second_index); } TEST_F(StatefulSessionIntegrationTest, StatefulSessionOverriddenByRoute) { initializeFilterAndRoute(STATEFUL_SESSION_FILTER, OVERRIDE_STATEFUL_SESSION); { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.1:50001", 15))}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); const std::string address_string = fmt::format("127.0.0.1:{}", upstream_index.value() + 50000); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), 15); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); EXPECT_EQ( Envoy::Http::Utility::makeSetCookieValue("route-session-cookie", encoded_address, "/path", std::chrono::seconds(120), true), response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView()); cleanupUpstreamAndDownstream(); } { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("route-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.1:50002", 15))}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); // Stateful session is overridden and `127.0.0.1:50002` should be selected. auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); EXPECT_EQ(upstream_index.value(), 2); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } } } // namespace } // namespace StatefulSession } // namespace HttpFilters } // namespace Extensions } // namespace Envoy <commit_msg>fix stateful session test flakes (#19560)<commit_after>#include <chrono> #include <cstdint> #include "envoy/config/endpoint/v3/endpoint_components.pb.h" #include "source/common/common/base64.h" #include "source/common/http/utility.h" #include "source/common/protobuf/protobuf.h" #include "source/extensions/filters/http/stateful_session/stateful_session.h" #include "test/integration/http_integration.h" #include "gtest/gtest.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace StatefulSession { namespace { class StatefulSessionIntegrationTest : public Envoy::HttpIntegrationTest, public testing::Test { public: StatefulSessionIntegrationTest() : HttpIntegrationTest(Http::CodecType::HTTP1, Network::Address::IpVersion::v4) { // Create 4 different upstream server for stateful session test. setUpstreamCount(4); // Update endpoints of default cluster `cluster_0` to 4 different fake upstreams. config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) { auto* cluster_0 = bootstrap.mutable_static_resources()->mutable_clusters()->Mutable(0); ASSERT(cluster_0->name() == "cluster_0"); auto* endpoint = cluster_0->mutable_load_assignment()->mutable_endpoints()->Mutable(0); const std::string EndpointsYaml = R"EOF( lb_endpoints: - endpoint: address: socket_address: address: 127.0.0.1 port_value: 0 - endpoint: address: socket_address: address: 127.0.0.1 port_value: 0 - endpoint: address: socket_address: address: 127.0.0.1 port_value: 0 - endpoint: address: socket_address: address: 127.0.0.1 port_value: 0 )EOF"; envoy::config::endpoint::v3::LocalityLbEndpoints new_lb_endpints; TestUtility::loadFromYaml(EndpointsYaml, new_lb_endpints); *endpoint = new_lb_endpints; }); } // Initialize route filter and per route config. void initializeFilterAndRoute(const std::string& filter_yaml, const std::string& per_route_config_yaml) { config_helper_.prependFilter(filter_yaml); // Create virtual host with domain `stateful.session.com` and default route to `cluster_0` auto virtual_host = config_helper_.createVirtualHost("stateful.session.com"); // Update per route config of default route. if (!per_route_config_yaml.empty()) { auto* route = virtual_host.mutable_routes(0); ProtobufWkt::Any per_route_config; TestUtility::loadFromYaml(per_route_config_yaml, per_route_config); route->mutable_typed_per_filter_config()->insert( {"envoy.filters.http.stateful_session", per_route_config}); } config_helper_.addVirtualHost(virtual_host); initialize(); } }; static const std::string STATEFUL_SESSION_FILTER = R"EOF( name: envoy.filters.http.stateful_session typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSession session_state: name: envoy.http.stateful_session.cookie typed_config: "@type": type.googleapis.com/envoy.extensions.http.stateful_session.cookie.v3.CookieBasedSessionState cookie: name: global-session-cookie path: /path ttl: 120s )EOF"; static const std::string DISABLE_STATEFUL_SESSION = R"EOF( "@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSessionPerRoute disabled: true )EOF"; static const std::string OVERRIDE_STATEFUL_SESSION = R"EOF( "@type": type.googleapis.com/envoy.extensions.filters.http.stateful_session.v3.StatefulSessionPerRoute stateful_session: session_state: name: envoy.http.stateful_session.cookie typed_config: "@type": type.googleapis.com/envoy.extensions.http.stateful_session.cookie.v3.CookieBasedSessionState cookie: name: route-session-cookie path: /path ttl: 120s )EOF"; TEST_F(StatefulSessionIntegrationTest, NormalStatefulSession) { initializeFilterAndRoute(STATEFUL_SESSION_FILTER, ""); codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{{":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); envoy::config::endpoint::v3::LbEndpoint endpoint; setUpstreamAddress(upstream_index.value(), endpoint); const std::string address_string = fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value()); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), address_string.size()); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // The selected upstream server address would be selected to the response headers. EXPECT_EQ( Envoy::Http::Utility::makeSetCookieValue("global-session-cookie", encoded_address, "/path", std::chrono::seconds(120), true), response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView()); cleanupUpstreamAndDownstream(); } TEST_F(StatefulSessionIntegrationTest, DownstreamRequestWithStatefulSessionCookie) { initializeFilterAndRoute(STATEFUL_SESSION_FILTER, ""); { envoy::config::endpoint::v3::LbEndpoint endpoint; setUpstreamAddress(1, endpoint); const std::string address_string = fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value()); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), address_string.size()); codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); // The upstream with index 1 should be selected. auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); EXPECT_EQ(upstream_index.value(), 1); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } { envoy::config::endpoint::v3::LbEndpoint endpoint; setUpstreamAddress(2, endpoint); const std::string address_string = fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value()); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), address_string.size()); codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); // The upstream with index 2 should be selected. auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); EXPECT_EQ(upstream_index.value(), 2); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } // Test the case that stateful session cookie with unknown server address. { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", Envoy::Base64::encode("127.0.0.7:50000", 15))}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); envoy::config::endpoint::v3::LbEndpoint endpoint; setUpstreamAddress(upstream_index.value(), endpoint); const std::string address_string = fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value()); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), address_string.size()); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // The selected upstream server address would be selected to the response headers. EXPECT_EQ( Envoy::Http::Utility::makeSetCookieValue("global-session-cookie", encoded_address, "/path", std::chrono::seconds(120), true), response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView()); cleanupUpstreamAndDownstream(); } } TEST_F(StatefulSessionIntegrationTest, StatefulSessionDisabledByRoute) { initializeFilterAndRoute(STATEFUL_SESSION_FILTER, DISABLE_STATEFUL_SESSION); uint64_t first_index = 0; uint64_t second_index = 0; envoy::config::endpoint::v3::LbEndpoint endpoint; setUpstreamAddress(1, endpoint); const std::string address_string = fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value()); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), address_string.size()); { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); first_index = upstream_index.value(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } { codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); second_index = upstream_index.value(); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } // Choose different upstream servers by default. EXPECT_NE(first_index, second_index); } TEST_F(StatefulSessionIntegrationTest, StatefulSessionOverriddenByRoute) { initializeFilterAndRoute(STATEFUL_SESSION_FILTER, OVERRIDE_STATEFUL_SESSION); { envoy::config::endpoint::v3::LbEndpoint endpoint; setUpstreamAddress(1, endpoint); const std::string address_string = fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value()); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), address_string.size()); codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("global-session-cookie=\"{}\"", encoded_address)}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); ASSERT(upstream_index.has_value()); envoy::config::endpoint::v3::LbEndpoint route_endpoint; setUpstreamAddress(upstream_index.value(), route_endpoint); const std::string route_address_string = fmt::format( "127.0.0.1:{}", route_endpoint.endpoint().address().socket_address().port_value()); const std::string route_encoded_address = Envoy::Base64::encode(route_address_string.data(), route_address_string.size()); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); EXPECT_EQ( Envoy::Http::Utility::makeSetCookieValue("route-session-cookie", route_encoded_address, "/path", std::chrono::seconds(120), true), response->headers().get(Http::LowerCaseString("set-cookie"))[0]->value().getStringView()); cleanupUpstreamAndDownstream(); } { envoy::config::endpoint::v3::LbEndpoint endpoint; setUpstreamAddress(2, endpoint); const std::string address_string = fmt::format("127.0.0.1:{}", endpoint.endpoint().address().socket_address().port_value()); const std::string encoded_address = Envoy::Base64::encode(address_string.data(), address_string.size()); codec_client_ = makeHttpConnection(lookupPort("http")); Http::TestRequestHeaderMapImpl request_headers{ {":method", "GET"}, {":path", "/test"}, {":scheme", "http"}, {":authority", "stateful.session.com"}, {"cookie", fmt::format("route-session-cookie=\"{}\"", encoded_address)}}; auto response = codec_client_->makeRequestWithBody(request_headers, 0); // Stateful session is overridden and the upstream with index 2 should be selected.. auto upstream_index = waitForNextUpstreamRequest({0, 1, 2, 3}); EXPECT_EQ(upstream_index.value(), 2); upstream_request_->encodeHeaders(default_response_headers_, true); ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(upstream_request_->complete()); EXPECT_TRUE(response->complete()); // No response header to be added. EXPECT_TRUE(response->headers().get(Http::LowerCaseString("set-cookie")).empty()); cleanupUpstreamAndDownstream(); } } } // namespace } // namespace StatefulSession } // namespace HttpFilters } // namespace Extensions } // namespace Envoy <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ComponentDefinition.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: vg $ $Date: 2007-01-15 14:31:06 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBA_COREDATAACESS_COMPONENTDEFINITION_HXX #include "ComponentDefinition.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition() { static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration; } //........................................................................ namespace dbaccess { //........................................................................ DBG_NAME(OComponentDefinition_Impl) OComponentDefinition_Impl::OComponentDefinition_Impl() { DBG_CTOR(OComponentDefinition_Impl,NULL); } // ----------------------------------------------------------------------------- OComponentDefinition_Impl::~OComponentDefinition_Impl() { DBG_DTOR(OComponentDefinition_Impl,NULL); } //========================================================================== //= OComponentDefinition //========================================================================== //-------------------------------------------------------------------------- DBG_NAME(OComponentDefinition) //-------------------------------------------------------------------------- void OComponentDefinition::registerProperties() { OComponentDefinition_Impl& rDefinition( getDefinition() ); ODataSettings::registerPropertiesFor( &rDefinition ); registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED, &rDefinition.m_aProps.aTitle, ::getCppuType(&rDefinition.m_aProps.aTitle)); if ( m_bTable ) { registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND, &rDefinition.m_sSchemaName, ::getCppuType(&rDefinition.m_sSchemaName)); registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND, &rDefinition.m_sCatalogName, ::getCppuType(&rDefinition.m_sCatalogName)); } } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB ,const Reference< XInterface >& _xParentContainer ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_xParentContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); } //-------------------------------------------------------------------------- OComponentDefinition::~OComponentDefinition() { DBG_DTOR(OComponentDefinition, NULL); } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer ,const ::rtl::OUString& _rElementName ,const Reference< XMultiServiceFactory >& _xORB ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_rxContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); m_pImpl->m_aProps.aTitle = _rElementName; DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !"); } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition); IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE); IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE) //-------------------------------------------------------------------------- ::rtl::OUString OComponentDefinition::getImplementationName_Static( ) throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition")); } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(2); aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION; aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content")); return aServices; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------------ Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl))); } // ----------------------------------------------------------------------------- void SAL_CALL OComponentDefinition::disposing() { OContentHelper::disposing(); if ( m_pColumns.get() ) m_pColumns->disposing(); } // ----------------------------------------------------------------------------- IPropertyArrayHelper& OComponentDefinition::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new OPropertyArrayHelper(aProps); } //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( ) throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed); if ( !m_pColumns.get() ) { ::std::vector< ::rtl::OUString> aNames; const OComponentDefinition_Impl& rDefinition( getDefinition() ); aNames.reserve( rDefinition.size() ); OComponentDefinition_Impl::const_iterator aIter = rDefinition.begin(); OComponentDefinition_Impl::const_iterator aEnd = rDefinition.end(); for ( ; aIter != aEnd; ++aIter ) aNames.push_back( aIter->first ); m_pColumns.reset( new OColumns( *this, m_aMutex, sal_True, aNames, this, NULL, sal_True, sal_False, sal_False ) ); m_pColumns->setParent( *this ); } return m_pColumns.get(); } // ----------------------------------------------------------------------------- OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const { const OComponentDefinition_Impl& rDefinition( getDefinition() ); OComponentDefinition_Impl::const_iterator aFind = rDefinition.find( _rName ); if ( aFind != rDefinition.end() ) return new OTableColumnWrapper( aFind->second, aFind->second, sal_True ); return new OTableColumn( _rName ); } // ----------------------------------------------------------------------------- Reference< ::com::sun::star::beans::XPropertySet > OComponentDefinition::createColumnDescriptor() { return new OTableColumnDescriptor(); } // ----------------------------------------------------------------------------- void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) { ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName) { getDefinition().erase( _sName ); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnAppended( const Reference< XPropertySet >& _rxSourceDescriptor ) { ::rtl::OUString sName; _rxSourceDescriptor->getPropertyValue( PROPERTY_NAME ) >>= sName; Reference<XPropertySet> xColDesc = new OTableColumnDescriptor(); ::comphelper::copyProperties( _rxSourceDescriptor, xColDesc ); getDefinition().insert( sName, xColDesc ); // formerly, here was a setParent at the xColDesc. The parent used was an adapter (ChildHelper_Impl) // which held another XChild weak, and forwarded all getParent requests to this other XChild. // m_pColumns was used for this. This was nonsense, since m_pColumns dies when our instance dies, // but xColDesc will live longer than this. So effectively, the setParent call was pretty useless. // // The intention for this parenting was that the column descriptor is able to find the data source, // by traveling up the parent hierachy until there's an XDataSource. This didn't work (which // for instance causes #i65023#). We need another way to properly ensure this. notifyDataSourceModified(); } //........................................................................ } // namespace dbaccess //........................................................................ <commit_msg>INTEGRATION: CWS dba24a (1.12.56); FILE MERGED 2007/08/02 10:49:09 oj 1.12.56.1: #i65023# modify dswhen column width changed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ComponentDefinition.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: hr $ $Date: 2007-09-26 14:39:27 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBA_COREDATAACESS_COMPONENTDEFINITION_HXX #include "ComponentDefinition.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif #include <cppuhelper/implbase1.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition() { static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration; } //........................................................................ namespace dbaccess { //........................................................................ /// helper class for column property change events which holds the OComponentDefinition weak typedef ::cppu::WeakImplHelper1 < XPropertyChangeListener > TColumnPropertyListener_BASE; class OColumnPropertyListener : public TColumnPropertyListener_BASE { OComponentDefinition* m_pComponent; OColumnPropertyListener(const OColumnPropertyListener&); void operator =(const OColumnPropertyListener&); protected: virtual ~OColumnPropertyListener(){} public: OColumnPropertyListener(OComponentDefinition* _pComponent) : m_pComponent(_pComponent){} // XPropertyChangeListener virtual void SAL_CALL propertyChange( const PropertyChangeEvent& /*_rEvent*/ ) throw (RuntimeException) { m_pComponent->notifyDataSourceModified(); } // XEventListener virtual void SAL_CALL disposing( const EventObject& /*_rSource*/ ) throw (RuntimeException) { } }; DBG_NAME(OComponentDefinition_Impl) OComponentDefinition_Impl::OComponentDefinition_Impl() { DBG_CTOR(OComponentDefinition_Impl,NULL); } // ----------------------------------------------------------------------------- OComponentDefinition_Impl::~OComponentDefinition_Impl() { DBG_DTOR(OComponentDefinition_Impl,NULL); } //========================================================================== //= OComponentDefinition //========================================================================== //-------------------------------------------------------------------------- DBG_NAME(OComponentDefinition) //-------------------------------------------------------------------------- void OComponentDefinition::registerProperties() { m_xColumnPropertyListener = new OColumnPropertyListener(this); OComponentDefinition_Impl& rDefinition( getDefinition() ); ODataSettings::registerPropertiesFor( &rDefinition ); registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED, &rDefinition.m_aProps.aTitle, ::getCppuType(&rDefinition.m_aProps.aTitle)); if ( m_bTable ) { registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND, &rDefinition.m_sSchemaName, ::getCppuType(&rDefinition.m_sSchemaName)); registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND, &rDefinition.m_sCatalogName, ::getCppuType(&rDefinition.m_sCatalogName)); } } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB ,const Reference< XInterface >& _xParentContainer ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_xParentContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); } //-------------------------------------------------------------------------- OComponentDefinition::~OComponentDefinition() { DBG_DTOR(OComponentDefinition, NULL); } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer ,const ::rtl::OUString& _rElementName ,const Reference< XMultiServiceFactory >& _xORB ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_rxContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); m_pImpl->m_aProps.aTitle = _rElementName; DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !"); } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition); IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE); IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE) //-------------------------------------------------------------------------- ::rtl::OUString OComponentDefinition::getImplementationName_Static( ) throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition")); } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(2); aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION; aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content")); return aServices; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------------ Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl))); } // ----------------------------------------------------------------------------- void SAL_CALL OComponentDefinition::disposing() { OContentHelper::disposing(); m_xColumnPropertyListener.clear(); if ( m_pColumns.get() ) m_pColumns->disposing(); } // ----------------------------------------------------------------------------- IPropertyArrayHelper& OComponentDefinition::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new OPropertyArrayHelper(aProps); } //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( ) throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed); if ( !m_pColumns.get() ) { ::std::vector< ::rtl::OUString> aNames; const OComponentDefinition_Impl& rDefinition( getDefinition() ); aNames.reserve( rDefinition.size() ); OComponentDefinition_Impl::const_iterator aIter = rDefinition.begin(); OComponentDefinition_Impl::const_iterator aEnd = rDefinition.end(); for ( ; aIter != aEnd; ++aIter ) aNames.push_back( aIter->first ); m_pColumns.reset( new OColumns( *this, m_aMutex, sal_True, aNames, this, NULL, sal_True, sal_False, sal_False ) ); m_pColumns->setParent( *this ); } return m_pColumns.get(); } // ----------------------------------------------------------------------------- OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const { const OComponentDefinition_Impl& rDefinition( getDefinition() ); OComponentDefinition_Impl::const_iterator aFind = rDefinition.find( _rName ); if ( aFind != rDefinition.end() ) { aFind->second->addPropertyChangeListener(::rtl::OUString(),m_xColumnPropertyListener); return new OTableColumnWrapper( aFind->second, aFind->second, sal_True ); } return new OTableColumn( _rName ); } // ----------------------------------------------------------------------------- Reference< XPropertySet > OComponentDefinition::createColumnDescriptor() { return new OTableColumnDescriptor(); } // ----------------------------------------------------------------------------- void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) { ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName) { getDefinition().erase( _sName ); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnAppended( const Reference< XPropertySet >& _rxSourceDescriptor ) { ::rtl::OUString sName; _rxSourceDescriptor->getPropertyValue( PROPERTY_NAME ) >>= sName; Reference<XPropertySet> xColDesc = new OTableColumnDescriptor(); ::comphelper::copyProperties( _rxSourceDescriptor, xColDesc ); getDefinition().insert( sName, xColDesc ); // formerly, here was a setParent at the xColDesc. The parent used was an adapter (ChildHelper_Impl) // which held another XChild weak, and forwarded all getParent requests to this other XChild. // m_pColumns was used for this. This was nonsense, since m_pColumns dies when our instance dies, // but xColDesc will live longer than this. So effectively, the setParent call was pretty useless. // // The intention for this parenting was that the column descriptor is able to find the data source, // by traveling up the parent hierachy until there's an XDataSource. This didn't work (which // for instance causes #i65023#). We need another way to properly ensure this. notifyDataSourceModified(); } //........................................................................ } // namespace dbaccess //........................................................................ <|endoftext|>
<commit_before>#include <netinet/ip6.h> #include <arpa/inet.h> #include "PacketPayload.h" #include "PcapDumper.h" #include "TransportLayerProcessorFactory.h" #include "IPv6Processor.h" void IPv6Processor::process(const u_char *header, const struct pcap_pkthdr *pkthdr, const u_char *packet, const vector<NetData> &tcpNetData, const vector<NetData> &udpNetData, const vector<NetData> &tcp6NetData, const vector<NetData> &udp6NetData) { const struct ip6_hdr* ip6Header = reinterpret_cast<const struct ip6_hdr*>(header); char srcIp6Buffer[INET6_ADDRSTRLEN]; char dstIp6Buffer[INET6_ADDRSTRLEN]; string srcIp6 = inet_ntop(AF_INET6, &ip6Header->ip6_src, srcIp6Buffer, INET6_ADDRSTRLEN); string dstIp6 = inet_ntop(AF_INET6, &ip6Header->ip6_dst, dstIp6Buffer, INET6_ADDRSTRLEN); auto protocol = ip6Header->ip6_ctlun.ip6_un1.ip6_un1_nxt; auto processor = TransportLayerProcessorFactory().getProcessor(protocol); if (processor != nullptr) { auto srcPort = processor->getSourcePort(header + sizeof(struct ip6_hdr)); auto dstPort = processor->getDestinationPort(header + sizeof(struct ip6_hdr)); vector<NetData> ip6NetDataTemp; if (protocol == IPPROTO_TCP) { ip6NetDataTemp = move(tcp6NetData); } else if (protocol == IPPROTO_UDP) { ip6NetDataTemp = move(udp6NetData); } for (auto data: ip6NetDataTemp) { struct in6_addr localIp6Addr; char localIp6Buffer[INET6_ADDRSTRLEN]; sscanf(data.localIp.c_str(), "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx", &localIp6Addr.s6_addr[3], &localIp6Addr.s6_addr[2], &localIp6Addr.s6_addr[1], &localIp6Addr.s6_addr[0], &localIp6Addr.s6_addr[7], &localIp6Addr.s6_addr[6], &localIp6Addr.s6_addr[5], &localIp6Addr.s6_addr[4], &localIp6Addr.s6_addr[11], &localIp6Addr.s6_addr[10], &localIp6Addr.s6_addr[9], &localIp6Addr.s6_addr[8], &localIp6Addr.s6_addr[15], &localIp6Addr.s6_addr[14], &localIp6Addr.s6_addr[13], &localIp6Addr.s6_addr[12]); string localIp6 = inet_ntop(AF_INET6, &localIp6Addr, localIp6Buffer, INET6_ADDRSTRLEN); uint32_t localPort = static_cast<uint32_t >(stoul(data.localPort, nullptr, 16)); if (srcIp6 == localIp6 && srcPort == localPort) { PacketPayload::getInstance().addUploadedBytes(pkthdr->caplen); PcapDumper::getInstance().writePcapToFile(pkthdr, packet); break; } if (dstIp6 == localIp6 && dstPort == localPort) { PacketPayload::getInstance().addDownloadedBytes(pkthdr->caplen); PcapDumper::getInstance().writePcapToFile(pkthdr, packet); break; } } } } <commit_msg>Include ip header to ipv6 processor<commit_after>#include <netinet/ip.h> #include <netinet/ip6.h> #include <arpa/inet.h> #include "PacketPayload.h" #include "PcapDumper.h" #include "TransportLayerProcessorFactory.h" #include "IPv6Processor.h" void IPv6Processor::process(const u_char *header, const struct pcap_pkthdr *pkthdr, const u_char *packet, const vector<NetData> &tcpNetData, const vector<NetData> &udpNetData, const vector<NetData> &tcp6NetData, const vector<NetData> &udp6NetData) { const struct ip6_hdr* ip6Header = reinterpret_cast<const struct ip6_hdr*>(header); char srcIp6Buffer[INET6_ADDRSTRLEN]; char dstIp6Buffer[INET6_ADDRSTRLEN]; string srcIp6 = inet_ntop(AF_INET6, &ip6Header->ip6_src, srcIp6Buffer, INET6_ADDRSTRLEN); string dstIp6 = inet_ntop(AF_INET6, &ip6Header->ip6_dst, dstIp6Buffer, INET6_ADDRSTRLEN); auto protocol = ip6Header->ip6_ctlun.ip6_un1.ip6_un1_nxt; auto processor = TransportLayerProcessorFactory().getProcessor(protocol); if (processor != nullptr) { auto srcPort = processor->getSourcePort(header + sizeof(struct ip6_hdr)); auto dstPort = processor->getDestinationPort(header + sizeof(struct ip6_hdr)); vector<NetData> ip6NetDataTemp; if (protocol == IPPROTO_TCP) { ip6NetDataTemp = move(tcp6NetData); } else if (protocol == IPPROTO_UDP) { ip6NetDataTemp = move(udp6NetData); } for (auto data: ip6NetDataTemp) { struct in6_addr localIp6Addr; char localIp6Buffer[INET6_ADDRSTRLEN]; sscanf(data.localIp.c_str(), "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx", &localIp6Addr.s6_addr[3], &localIp6Addr.s6_addr[2], &localIp6Addr.s6_addr[1], &localIp6Addr.s6_addr[0], &localIp6Addr.s6_addr[7], &localIp6Addr.s6_addr[6], &localIp6Addr.s6_addr[5], &localIp6Addr.s6_addr[4], &localIp6Addr.s6_addr[11], &localIp6Addr.s6_addr[10], &localIp6Addr.s6_addr[9], &localIp6Addr.s6_addr[8], &localIp6Addr.s6_addr[15], &localIp6Addr.s6_addr[14], &localIp6Addr.s6_addr[13], &localIp6Addr.s6_addr[12]); string localIp6 = inet_ntop(AF_INET6, &localIp6Addr, localIp6Buffer, INET6_ADDRSTRLEN); uint32_t localPort = static_cast<uint32_t >(stoul(data.localPort, nullptr, 16)); if (srcIp6 == localIp6 && srcPort == localPort) { PacketPayload::getInstance().addUploadedBytes(pkthdr->caplen); PcapDumper::getInstance().writePcapToFile(pkthdr, packet); break; } if (dstIp6 == localIp6 && dstPort == localPort) { PacketPayload::getInstance().addDownloadedBytes(pkthdr->caplen); PcapDumper::getInstance().writePcapToFile(pkthdr, packet); break; } } } } <|endoftext|>
<commit_before>//http://www.spoj.com/problems/EDIST/ //longes common subsequence <commit_msg>Adding<commit_after>//http://www.spoj.com/problems/EDIST/ //longes common subsequence #include <stdio.h> using namespace std; int lcs(int a,int b){ } int main(int argc, char const *argv[]) { return 0; }<|endoftext|>
<commit_before>#include "generateur/ParseCmdLine.hh" #include <string> using namespace std; variables_map ParseCmdLine::parse(int argc_p, char** argv_p){ options_description desc_l("Options autorisees"); desc_l.add_options() ("help", "genere ce message") ("strategy,s", value<string>(), "Specifie la strategy de generation a adopter"); variables_map result_l; store(parse_command_line(argc_p, argv_p, desc_l), result_l); notify(result_l); if ( result_l.count("help") ){ cout << desc_l << endl; } return result_l; } <commit_msg>Ajout d'une gestion des erreurs autours de la lecture de la ligne de cmd<commit_after>#include "generateur/ParseCmdLine.hh" #include <string> using namespace std; variables_map ParseCmdLine::parse(int argc_p, char** argv_p){ variables_map result_l; options_description desc_l("Options autorisees"); desc_l.add_options() ("help", "genere ce message") ("strategy,s", value<string>(), "Specifie la strategy de generation a adopter"); try { store(parse_command_line(argc_p, argv_p, desc_l), result_l); notify(result_l); if ( result_l.count("help") ){ cout << desc_l << endl; } }catch(exception& err_l) { cerr << "Erreur de lecture de la ligne de commande : " << err_l.what() << endl; cerr << desc_l << endl; } return result_l; } <|endoftext|>
<commit_before>#pragma once #include <string> #include <list> typedef std::pair<std::string, std::string> keilo_instance; typedef std::list<keilo_instance> keilo_record; typedef struct { SOCKET sock; SOCKADDR_IN addr; } client;<commit_msg>winsock<commit_after>#pragma once #include <string> #include <list> #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") typedef std::pair<std::string, std::string> keilo_instance; typedef std::list<keilo_instance> keilo_record; typedef struct { SOCKET sock; SOCKADDR_IN addr; } client;<|endoftext|>
<commit_before>using namespace std; string encrypt (string plaintext, string key) { return "TODO"; } <commit_msg>Removed unused namespace import.<commit_after>string encrypt (string plaintext, string key) { return "TODO"; } <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "peer/peer_controller.h" #include "base/logging.h" #include "base/task_runner.h" #include "peer/client_authenticator.h" #include "proto/router.pb.h" namespace peer { namespace { const std::chrono::seconds kReconnectTimeout{ 15 }; } // namespace PeerController::PeerController(std::shared_ptr<base::TaskRunner> task_runner) : task_runner_(task_runner), reconnect_timer_(task_runner) { // TODO } PeerController::~PeerController() { // TODO } void PeerController::start(const RouterInfo& router_info, Delegate* delegate) { router_info_ = router_info; delegate_ = delegate; if (!delegate_) { LOG(LS_ERROR) << "Invalid parameters"; return; } LOG(LS_INFO) << "Starting peer controller for router: " << router_info_.address << ":" << router_info_.port; connectToRouter(); } void PeerController::connectTo(peer::PeerId peer_id) { // TODO } void PeerController::onConnected() { LOG(LS_INFO) << "Connection to the router is established"; static const std::chrono::seconds kKeepAliveTime{ 30 }; static const std::chrono::seconds kKeepAliveInterval{ 3 }; channel_->setKeepAlive(true, kKeepAliveTime, kKeepAliveInterval); channel_->setNoDelay(true); authenticator_ = std::make_unique<peer::ClientAuthenticator>(task_runner_); authenticator_->setIdentify(proto::IDENTIFY_ANONYMOUS); authenticator_->setPeerPublicKey(router_info_.public_key); authenticator_->setSessionType(proto::ROUTER_SESSION_ANONIMOUS_PEER); authenticator_->start(std::move(channel_), [this](peer::ClientAuthenticator::ErrorCode error_code) { if (error_code == peer::ClientAuthenticator::ErrorCode::SUCCESS) { // The authenticator takes the listener on itself, we return the receipt of // notifications. channel_ = authenticator_->takeChannel(); channel_->setListener(this); LOG(LS_INFO) << "Router connected. Receiving peer ID..."; delegate_->onRouterConnected(); proto::PeerToRouter message; proto::PeerIdRequest* peer_id_request = message.mutable_peer_id_request(); if (router_info_.peer_key.empty()) { peer_id_request->set_type(proto::PeerIdRequest::NEW_ID); } else { peer_id_request->set_type(proto::PeerIdRequest::EXISTING_ID); peer_id_request->set_key(base::toStdString(router_info_.peer_key)); } // Now the session will receive incoming messages. channel_->resume(); // Send peer ID request. channel_->send(base::serialize(message)); } else { LOG(LS_WARNING) << "Authentication failed: " << ClientAuthenticator::errorToString(error_code); delayedConnectToRouter(); } // Authenticator is no longer needed. task_runner_->deleteSoon(std::move(authenticator_)); }); } void PeerController::onDisconnected(base::NetworkChannel::ErrorCode error_code) { LOG(LS_INFO) << "Connection to the router is lost (" << base::NetworkChannel::errorToString(error_code) << ")"; delegate_->onPeerIdAssigned(kInvalidPeerId, base::ByteArray()); delegate_->onRouterDisconnected(error_code); peer_id_ = kInvalidPeerId; delayedConnectToRouter(); } void PeerController::onMessageReceived(const base::ByteArray& buffer) { proto::RouterToPeer message; if (!base::parse(buffer, &message)) { LOG(LS_ERROR) << "Invalid message from router"; return; } if (message.has_peer_id_response()) { if (peer_id_ != kInvalidPeerId) { LOG(LS_ERROR) << "Peer ID already assigned"; return; } const proto::PeerIdResponse& peer_id_response = message.peer_id_response(); if (peer_id_response.peer_id() == kInvalidPeerId) { LOG(LS_ERROR) << "Invalid peer ID received"; return; } LOG(LS_INFO) << "Peer ID received: " << peer_id_response.peer_id(); router_info_.peer_key = base::fromStdString(peer_id_response.key()); peer_id_ = peer_id_response.peer_id(); delegate_->onPeerIdAssigned(peer_id_, router_info_.peer_key); } else { if (peer_id_ == kInvalidPeerId) { LOG(LS_ERROR) << "Request could not be processed (peer ID not received yet)"; return; } if (message.has_connection_request()) { LOG(LS_INFO) << "CONNECTION REQUEST"; } else if (message.has_connection_response()) { LOG(LS_INFO) << "CONNECTION RESPONSE"; } else if (message.has_connection_offer()) { LOG(LS_INFO) << "CONNECTION OFFER"; } else { LOG(LS_WARNING) << "Unhandled message from router"; } } } void PeerController::onMessageWritten(size_t /* pending */) { // Nothing } void PeerController::connectToRouter() { LOG(LS_INFO) << "Connecting to router..."; channel_ = std::make_unique<base::NetworkChannel>(); channel_->setListener(this); channel_->connect(router_info_.address, router_info_.port); } void PeerController::delayedConnectToRouter() { LOG(LS_INFO) << "Reconnect after " << kReconnectTimeout.count() << " seconds"; reconnect_timer_.start(kReconnectTimeout, std::bind(&PeerController::connectToRouter, this)); } } // namespace peer <commit_msg>Overwrite only not empty key.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "peer/peer_controller.h" #include "base/logging.h" #include "base/task_runner.h" #include "peer/client_authenticator.h" #include "proto/router.pb.h" namespace peer { namespace { const std::chrono::seconds kReconnectTimeout{ 15 }; } // namespace PeerController::PeerController(std::shared_ptr<base::TaskRunner> task_runner) : task_runner_(task_runner), reconnect_timer_(task_runner) { // TODO } PeerController::~PeerController() { // TODO } void PeerController::start(const RouterInfo& router_info, Delegate* delegate) { router_info_ = router_info; delegate_ = delegate; if (!delegate_) { LOG(LS_ERROR) << "Invalid parameters"; return; } LOG(LS_INFO) << "Starting peer controller for router: " << router_info_.address << ":" << router_info_.port; connectToRouter(); } void PeerController::connectTo(peer::PeerId peer_id) { // TODO } void PeerController::onConnected() { LOG(LS_INFO) << "Connection to the router is established"; static const std::chrono::seconds kKeepAliveTime{ 30 }; static const std::chrono::seconds kKeepAliveInterval{ 3 }; channel_->setKeepAlive(true, kKeepAliveTime, kKeepAliveInterval); channel_->setNoDelay(true); authenticator_ = std::make_unique<peer::ClientAuthenticator>(task_runner_); authenticator_->setIdentify(proto::IDENTIFY_ANONYMOUS); authenticator_->setPeerPublicKey(router_info_.public_key); authenticator_->setSessionType(proto::ROUTER_SESSION_ANONIMOUS_PEER); authenticator_->start(std::move(channel_), [this](peer::ClientAuthenticator::ErrorCode error_code) { if (error_code == peer::ClientAuthenticator::ErrorCode::SUCCESS) { // The authenticator takes the listener on itself, we return the receipt of // notifications. channel_ = authenticator_->takeChannel(); channel_->setListener(this); LOG(LS_INFO) << "Router connected. Receiving peer ID..."; delegate_->onRouterConnected(); proto::PeerToRouter message; proto::PeerIdRequest* peer_id_request = message.mutable_peer_id_request(); if (router_info_.peer_key.empty()) { peer_id_request->set_type(proto::PeerIdRequest::NEW_ID); } else { peer_id_request->set_type(proto::PeerIdRequest::EXISTING_ID); peer_id_request->set_key(base::toStdString(router_info_.peer_key)); } // Now the session will receive incoming messages. channel_->resume(); // Send peer ID request. channel_->send(base::serialize(message)); } else { LOG(LS_WARNING) << "Authentication failed: " << ClientAuthenticator::errorToString(error_code); delayedConnectToRouter(); } // Authenticator is no longer needed. task_runner_->deleteSoon(std::move(authenticator_)); }); } void PeerController::onDisconnected(base::NetworkChannel::ErrorCode error_code) { LOG(LS_INFO) << "Connection to the router is lost (" << base::NetworkChannel::errorToString(error_code) << ")"; delegate_->onPeerIdAssigned(kInvalidPeerId, base::ByteArray()); delegate_->onRouterDisconnected(error_code); peer_id_ = kInvalidPeerId; delayedConnectToRouter(); } void PeerController::onMessageReceived(const base::ByteArray& buffer) { proto::RouterToPeer message; if (!base::parse(buffer, &message)) { LOG(LS_ERROR) << "Invalid message from router"; return; } if (message.has_peer_id_response()) { if (peer_id_ != kInvalidPeerId) { LOG(LS_ERROR) << "Peer ID already assigned"; return; } const proto::PeerIdResponse& peer_id_response = message.peer_id_response(); if (peer_id_response.peer_id() == kInvalidPeerId) { LOG(LS_ERROR) << "Invalid peer ID received"; return; } LOG(LS_INFO) << "Peer ID received: " << peer_id_response.peer_id(); base::ByteArray peer_key = base::fromStdString(peer_id_response.key()); if (!peer_key.empty()) router_info_.peer_key = base::fromStdString(peer_id_response.key()); peer_id_ = peer_id_response.peer_id(); delegate_->onPeerIdAssigned(peer_id_, router_info_.peer_key); } else { if (peer_id_ == kInvalidPeerId) { LOG(LS_ERROR) << "Request could not be processed (peer ID not received yet)"; return; } if (message.has_connection_request()) { LOG(LS_INFO) << "CONNECTION REQUEST"; } else if (message.has_connection_response()) { LOG(LS_INFO) << "CONNECTION RESPONSE"; } else if (message.has_connection_offer()) { LOG(LS_INFO) << "CONNECTION OFFER"; } else { LOG(LS_WARNING) << "Unhandled message from router"; } } } void PeerController::onMessageWritten(size_t /* pending */) { // Nothing } void PeerController::connectToRouter() { LOG(LS_INFO) << "Connecting to router..."; channel_ = std::make_unique<base::NetworkChannel>(); channel_->setListener(this); channel_->connect(router_info_.address, router_info_.port); } void PeerController::delayedConnectToRouter() { LOG(LS_INFO) << "Reconnect after " << kReconnectTimeout.count() << " seconds"; reconnect_timer_.start(kReconnectTimeout, std::bind(&PeerController::connectToRouter, this)); } } // namespace peer <|endoftext|>
<commit_before>/** * \file * \brief Scheduler class implementation * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-01-24 */ #include "distortos/scheduler/Scheduler.hpp" #include "distortos/SoftwareTimer.hpp" #include "distortos/scheduler/MainThreadControlBlock.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" #include "distortos/architecture/InterruptUnmaskingLock.hpp" #include <cerrno> namespace distortos { namespace scheduler { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Forces unconditional context switch. * * Temporarily disables any interrupt masking and requests unconditional context switch. */ void forceContextSwitch() { architecture::requestContextSwitch(); architecture::InterruptUnmaskingLock interruptUnmaskingLock; } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ Scheduler::Scheduler() : currentThreadControlBlock_{}, mutexControlBlockListAllocatorPool_{}, threadControlBlockListAllocatorPool_{}, threadControlBlockListAllocator_{threadControlBlockListAllocatorPool_}, runnableList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Runnable}, suspendedList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Suspended}, softwareTimerControlBlockSupervisor_{}, contextSwitchCount_{}, tickCount_{} { } void Scheduler::add(ThreadControlBlock& threadControlBlock) { architecture::InterruptMaskingLock interruptMaskingLock; addInternal(threadControlBlock); maybeRequestContextSwitch(); } void Scheduler::block(ThreadControlBlockList& container) { block(container, currentThreadControlBlock_); } int Scheduler::block(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator) { { architecture::InterruptMaskingLock interruptMaskingLock; const auto ret = blockInternal(container, iterator); if (ret != 0) return ret; if (iterator != currentThreadControlBlock_) // blocked thread is not current thread - no forced switch required return 0; } forceContextSwitch(); return 0; } int Scheduler::blockUntil(ThreadControlBlockList& container, const TickClock::time_point timePoint) { architecture::InterruptMaskingLock interruptMaskingLock; const auto iterator = currentThreadControlBlock_; // This lambda unblocks the thread only if it wasn't already unblocked - this is necessary because double unblock // should be avoided (it could mess the order of threads of the same priority). In that case it also sets // UnblockReason::Timeout. auto softwareTimer = makeSoftwareTimer([this, iterator]() { if (iterator->get().getList() != &runnableList_) unblockInternal(iterator, ThreadControlBlock::UnblockReason::Timeout); }); softwareTimer.start(timePoint); block(container); const auto unblockReason = currentThreadControlBlock_->get().getUnblockReason(); return unblockReason == ThreadControlBlock::UnblockReason::UnblockRequest ? 0 : ETIMEDOUT; } uint64_t Scheduler::getContextSwitchCount() const { architecture::InterruptMaskingLock interruptMaskingLock; return contextSwitchCount_; } uint64_t Scheduler::getTickCount() const { architecture::InterruptMaskingLock interruptMaskingLock; return tickCount_; } void Scheduler::initialize(MainThreadControlBlock& mainThreadControlBlock) { addInternal(mainThreadControlBlock); currentThreadControlBlock_ = runnableList_.begin(); } void Scheduler::maybeRequestContextSwitch() const { if (isContextSwitchRequired() == true) architecture::requestContextSwitch(); } int Scheduler::remove() { { architecture::InterruptMaskingLock interruptMaskingLock; ThreadControlBlockList terminatedList {threadControlBlockListAllocator_, ThreadControlBlock::State::Terminated}; const auto ret = blockInternal(terminatedList, currentThreadControlBlock_); if (ret != 0) return ret; terminatedList.begin()->get().terminationHook(); } forceContextSwitch(); return 0; } int Scheduler::resume(const ThreadControlBlockListIterator iterator) { architecture::InterruptMaskingLock interruptMaskingLock; if (iterator->get().getList() != &suspendedList_) return EINVAL; unblock(iterator); return 0; } void Scheduler::suspend() { suspend(currentThreadControlBlock_); } int Scheduler::suspend(const ThreadControlBlockListIterator iterator) { return block(suspendedList_, iterator); } void* Scheduler::switchContext(void* const stackPointer) { architecture::InterruptMaskingLock interruptMaskingLock; ++contextSwitchCount_; getCurrentThreadControlBlock().getStack().setStackPointer(stackPointer); currentThreadControlBlock_ = runnableList_.begin(); return getCurrentThreadControlBlock().getStack().getStackPointer(); } bool Scheduler::tickInterruptHandler() { architecture::InterruptMaskingLock interruptMaskingLock; ++tickCount_; getCurrentThreadControlBlock().getRoundRobinQuantum().decrement(); // if the object is on the "runnable" list, it uses SchedulingPolicy::RoundRobin and it used its round-robin // quantum, then do the "rotation": move current thread to the end of same-priority group to implement round-robin // scheduling if (getCurrentThreadControlBlock().getList() == &runnableList_ && getCurrentThreadControlBlock().getSchedulingPolicy() == SchedulingPolicy::RoundRobin && getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true) { getCurrentThreadControlBlock().getRoundRobinQuantum().reset(); runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); } softwareTimerControlBlockSupervisor_.tickInterruptHandler(TickClock::time_point{TickClock::duration{tickCount_}}); return isContextSwitchRequired(); } void Scheduler::unblock(const ThreadControlBlockListIterator iterator) { architecture::InterruptMaskingLock interruptMaskingLock; unblockInternal(iterator); maybeRequestContextSwitch(); } void Scheduler::yield() { architecture::InterruptMaskingLock interruptMaskingLock; runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); maybeRequestContextSwitch(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void Scheduler::addInternal(ThreadControlBlock& threadControlBlock) { threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink()); runnableList_.sortedEmplace(threadControlBlock); } int Scheduler::blockInternal(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator) { if (iterator->get().getList() != &runnableList_) return EINVAL; container.sortedSplice(runnableList_, iterator); return 0; } bool Scheduler::isContextSwitchRequired() const { if (getCurrentThreadControlBlock().getList() != &runnableList_) return true; if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available? return true; return false; } void Scheduler::unblockInternal(const ThreadControlBlockListIterator iterator, const ThreadControlBlock::UnblockReason unblockReason) { runnableList_.sortedSplice(*iterator->get().getList(), iterator); iterator->get().getRoundRobinQuantum().reset(); iterator->get().setUnblockReason(unblockReason); } } // namespace scheduler } // namespace distortos <commit_msg>Scheduler::unblockInternal(): call ThreadControlBlock::unblockHook() instead of calling RoundRobinQuantum::reset() and ThreadControlBlock::setUnblockReason()<commit_after>/** * \file * \brief Scheduler class implementation * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-02-01 */ #include "distortos/scheduler/Scheduler.hpp" #include "distortos/SoftwareTimer.hpp" #include "distortos/scheduler/MainThreadControlBlock.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" #include "distortos/architecture/InterruptUnmaskingLock.hpp" #include <cerrno> namespace distortos { namespace scheduler { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Forces unconditional context switch. * * Temporarily disables any interrupt masking and requests unconditional context switch. */ void forceContextSwitch() { architecture::requestContextSwitch(); architecture::InterruptUnmaskingLock interruptUnmaskingLock; } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ Scheduler::Scheduler() : currentThreadControlBlock_{}, mutexControlBlockListAllocatorPool_{}, threadControlBlockListAllocatorPool_{}, threadControlBlockListAllocator_{threadControlBlockListAllocatorPool_}, runnableList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Runnable}, suspendedList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Suspended}, softwareTimerControlBlockSupervisor_{}, contextSwitchCount_{}, tickCount_{} { } void Scheduler::add(ThreadControlBlock& threadControlBlock) { architecture::InterruptMaskingLock interruptMaskingLock; addInternal(threadControlBlock); maybeRequestContextSwitch(); } void Scheduler::block(ThreadControlBlockList& container) { block(container, currentThreadControlBlock_); } int Scheduler::block(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator) { { architecture::InterruptMaskingLock interruptMaskingLock; const auto ret = blockInternal(container, iterator); if (ret != 0) return ret; if (iterator != currentThreadControlBlock_) // blocked thread is not current thread - no forced switch required return 0; } forceContextSwitch(); return 0; } int Scheduler::blockUntil(ThreadControlBlockList& container, const TickClock::time_point timePoint) { architecture::InterruptMaskingLock interruptMaskingLock; const auto iterator = currentThreadControlBlock_; // This lambda unblocks the thread only if it wasn't already unblocked - this is necessary because double unblock // should be avoided (it could mess the order of threads of the same priority). In that case it also sets // UnblockReason::Timeout. auto softwareTimer = makeSoftwareTimer([this, iterator]() { if (iterator->get().getList() != &runnableList_) unblockInternal(iterator, ThreadControlBlock::UnblockReason::Timeout); }); softwareTimer.start(timePoint); block(container); const auto unblockReason = currentThreadControlBlock_->get().getUnblockReason(); return unblockReason == ThreadControlBlock::UnblockReason::UnblockRequest ? 0 : ETIMEDOUT; } uint64_t Scheduler::getContextSwitchCount() const { architecture::InterruptMaskingLock interruptMaskingLock; return contextSwitchCount_; } uint64_t Scheduler::getTickCount() const { architecture::InterruptMaskingLock interruptMaskingLock; return tickCount_; } void Scheduler::initialize(MainThreadControlBlock& mainThreadControlBlock) { addInternal(mainThreadControlBlock); currentThreadControlBlock_ = runnableList_.begin(); } void Scheduler::maybeRequestContextSwitch() const { if (isContextSwitchRequired() == true) architecture::requestContextSwitch(); } int Scheduler::remove() { { architecture::InterruptMaskingLock interruptMaskingLock; ThreadControlBlockList terminatedList {threadControlBlockListAllocator_, ThreadControlBlock::State::Terminated}; const auto ret = blockInternal(terminatedList, currentThreadControlBlock_); if (ret != 0) return ret; terminatedList.begin()->get().terminationHook(); } forceContextSwitch(); return 0; } int Scheduler::resume(const ThreadControlBlockListIterator iterator) { architecture::InterruptMaskingLock interruptMaskingLock; if (iterator->get().getList() != &suspendedList_) return EINVAL; unblock(iterator); return 0; } void Scheduler::suspend() { suspend(currentThreadControlBlock_); } int Scheduler::suspend(const ThreadControlBlockListIterator iterator) { return block(suspendedList_, iterator); } void* Scheduler::switchContext(void* const stackPointer) { architecture::InterruptMaskingLock interruptMaskingLock; ++contextSwitchCount_; getCurrentThreadControlBlock().getStack().setStackPointer(stackPointer); currentThreadControlBlock_ = runnableList_.begin(); return getCurrentThreadControlBlock().getStack().getStackPointer(); } bool Scheduler::tickInterruptHandler() { architecture::InterruptMaskingLock interruptMaskingLock; ++tickCount_; getCurrentThreadControlBlock().getRoundRobinQuantum().decrement(); // if the object is on the "runnable" list, it uses SchedulingPolicy::RoundRobin and it used its round-robin // quantum, then do the "rotation": move current thread to the end of same-priority group to implement round-robin // scheduling if (getCurrentThreadControlBlock().getList() == &runnableList_ && getCurrentThreadControlBlock().getSchedulingPolicy() == SchedulingPolicy::RoundRobin && getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true) { getCurrentThreadControlBlock().getRoundRobinQuantum().reset(); runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); } softwareTimerControlBlockSupervisor_.tickInterruptHandler(TickClock::time_point{TickClock::duration{tickCount_}}); return isContextSwitchRequired(); } void Scheduler::unblock(const ThreadControlBlockListIterator iterator) { architecture::InterruptMaskingLock interruptMaskingLock; unblockInternal(iterator); maybeRequestContextSwitch(); } void Scheduler::yield() { architecture::InterruptMaskingLock interruptMaskingLock; runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); maybeRequestContextSwitch(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void Scheduler::addInternal(ThreadControlBlock& threadControlBlock) { threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink()); runnableList_.sortedEmplace(threadControlBlock); } int Scheduler::blockInternal(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator) { if (iterator->get().getList() != &runnableList_) return EINVAL; container.sortedSplice(runnableList_, iterator); return 0; } bool Scheduler::isContextSwitchRequired() const { if (getCurrentThreadControlBlock().getList() != &runnableList_) return true; if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available? return true; return false; } void Scheduler::unblockInternal(const ThreadControlBlockListIterator iterator, const ThreadControlBlock::UnblockReason unblockReason) { runnableList_.sortedSplice(*iterator->get().getList(), iterator); iterator->get().unblockHook(unblockReason); } } // namespace scheduler } // namespace distortos <|endoftext|>
<commit_before>// // NSolver::setup_system.cpp // // Created by Lei Qiao on 15/8/9. // A work based on deal.II tutorial step-33. // #include <NSolver/solver/NSolver.h> namespace NSFEMSolver { using namespace dealii; // @sect4{NSolver::setup_system} // // The following (easy) function is called each time the mesh is // changed. All it does is to resize the Trilinos matrix according to a // sparsity pattern that we generate as in all the previous tutorial // programs. template <int dim> void NSolver<dim>::setup_system() { dof_handler.clear(); dof_handler.distribute_dofs (fe); locally_owned_dofs.clear(); locally_owned_dofs = dof_handler.locally_owned_dofs(); locally_relevant_dofs.clear(); DoFTools::extract_locally_relevant_dofs (dof_handler, locally_relevant_dofs); if (parameters->output_sparsity_pattern) { ++n_sparsity_pattern_out; TrilinosWrappers::SparsityPattern sparsity_pattern (locally_owned_dofs, mpi_communicator); DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern, /*const ConstraintMatrix constraints = */ ConstraintMatrix(), /*const bool keep_constrained_dofs = */ true, Utilities::MPI::this_mpi_process (mpi_communicator)); sparsity_pattern.compress(); const std::string file_name = "sparsity_pattern." + Utilities::int_to_string (n_sparsity_pattern_out,4) + ".origin"; std::ofstream out (file_name.c_str()); sparsity_pattern.print_gnuplot (out); } switch (parameters->renumber_dofs) { case Parameters::AllParameters<dim>::None : { break; } case Parameters::AllParameters<dim>::RCM : { DoFRenumbering::Cuthill_McKee (dof_handler, /* reversed_numbering = */ true); break; } case Parameters::AllParameters<dim>::RCM_WithStartPoint : { std::vector<types::global_dof_index> dof_indices (fe.dofs_per_cell); Point<dim> target_point; for (unsigned int id=0; id<dim; ++id) { target_point[id] = parameters->renumber_start_point[id]; } typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(), endc = dof_handler.end(); unsigned int cell_index (0); for (; cell!=endc; ++cell, ++cell_index) if (cell->is_locally_owned()) { if (target_point.distance (cell->center()) < 0.01) { cell->get_dof_indices (dof_indices); break; } } DoFRenumbering::Cuthill_McKee (dof_handler, /* reversed_numbering = */ true, /* use_constraints = */ false , /* starting_indices */ dof_indices); break; } default: { Assert (false, ExcNotImplemented()); break; } } TrilinosWrappers::SparsityPattern sparsity_pattern (locally_owned_dofs, mpi_communicator); DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern, /*const ConstraintMatrix constraints = */ ConstraintMatrix(), /*const bool keep_constrained_dofs = */ true, Utilities::MPI::this_mpi_process (mpi_communicator)); sparsity_pattern.compress(); if (parameters->output_sparsity_pattern && parameters->renumber_dofs != Parameters::AllParameters<dim>::None) { const std::string file_name = "sparsity_pattern." + Utilities::int_to_string (n_sparsity_pattern_out,4) + ".renumbered"; std::ofstream out (file_name.c_str()); sparsity_pattern.print_gnuplot (out); } system_matrix.reinit (sparsity_pattern); // Initialize vectors locally_owned_solution.reinit (locally_owned_dofs, mpi_communicator); current_solution.reinit (locally_relevant_dofs, mpi_communicator); // const bool fast = true means leave its content untouched. old_solution.reinit (current_solution, /*const bool fast = */ true); old_old_solution.reinit (current_solution, true); predictor.reinit (locally_owned_solution, true); right_hand_side.reinit (locally_owned_solution, true); newton_update.reinit (locally_owned_solution, true); residual_for_output.reinit (current_solution, true); entropy_viscosity.reinit (triangulation.n_active_cells()); cellSize_viscosity.reinit (triangulation.n_active_cells()); refinement_indicators.reinit (triangulation.n_active_cells()); } #include "NSolver.inst" } <commit_msg>Renumbering DoFs immediately after distribute_dofs, then do other following things<commit_after>// // NSolver::setup_system.cpp // // Created by Lei Qiao on 15/8/9. // A work based on deal.II tutorial step-33. // #include <NSolver/solver/NSolver.h> namespace NSFEMSolver { using namespace dealii; // @sect4{NSolver::setup_system} // // The following (easy) function is called each time the mesh is // changed. All it does is to resize the Trilinos matrix according to a // sparsity pattern that we generate as in all the previous tutorial // programs. template <int dim> void NSolver<dim>::setup_system() { dof_handler.clear(); dof_handler.distribute_dofs (fe); if (parameters->output_sparsity_pattern) { ++n_sparsity_pattern_out; TrilinosWrappers::SparsityPattern sparsity_pattern (locally_owned_dofs, mpi_communicator); DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern, /*const ConstraintMatrix constraints = */ ConstraintMatrix(), /*const bool keep_constrained_dofs = */ true, Utilities::MPI::this_mpi_process (mpi_communicator)); sparsity_pattern.compress(); const std::string file_name = "sparsity_pattern." + Utilities::int_to_string (n_sparsity_pattern_out,4) + ".origin"; std::ofstream out (file_name.c_str()); sparsity_pattern.print_gnuplot (out); } switch (parameters->renumber_dofs) { case Parameters::AllParameters<dim>::None : { break; } case Parameters::AllParameters<dim>::RCM : { DoFRenumbering::Cuthill_McKee (dof_handler, /* reversed_numbering = */ true); break; } case Parameters::AllParameters<dim>::RCM_WithStartPoint : { std::vector<types::global_dof_index> dof_indices (fe.dofs_per_cell); Point<dim> target_point; for (unsigned int id=0; id<dim; ++id) { target_point[id] = parameters->renumber_start_point[id]; } typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(), endc = dof_handler.end(); unsigned int cell_index (0); for (; cell!=endc; ++cell, ++cell_index) if (cell->is_locally_owned()) { if (target_point.distance (cell->center()) < 0.01) { cell->get_dof_indices (dof_indices); break; } } DoFRenumbering::Cuthill_McKee (dof_handler, /* reversed_numbering = */ true, /* use_constraints = */ false , /* starting_indices */ dof_indices); break; } default: { Assert (false, ExcNotImplemented()); break; } } locally_owned_dofs.clear(); locally_owned_dofs = dof_handler.locally_owned_dofs(); locally_relevant_dofs.clear(); DoFTools::extract_locally_relevant_dofs (dof_handler, locally_relevant_dofs); TrilinosWrappers::SparsityPattern sparsity_pattern (locally_owned_dofs, mpi_communicator); DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern, /*const ConstraintMatrix constraints = */ ConstraintMatrix(), /*const bool keep_constrained_dofs = */ true, Utilities::MPI::this_mpi_process (mpi_communicator)); sparsity_pattern.compress(); if (parameters->output_sparsity_pattern && parameters->renumber_dofs != Parameters::AllParameters<dim>::None) { const std::string file_name = "sparsity_pattern." + Utilities::int_to_string (n_sparsity_pattern_out,4) + ".renumbered"; std::ofstream out (file_name.c_str()); sparsity_pattern.print_gnuplot (out); } system_matrix.reinit (sparsity_pattern); // Initialize vectors locally_owned_solution.reinit (locally_owned_dofs, mpi_communicator); current_solution.reinit (locally_relevant_dofs, mpi_communicator); // const bool fast = true means leave its content untouched. old_solution.reinit (current_solution, /*const bool fast = */ true); old_old_solution.reinit (current_solution, true); predictor.reinit (locally_owned_solution, true); right_hand_side.reinit (locally_owned_solution, true); newton_update.reinit (locally_owned_solution, true); residual_for_output.reinit (current_solution, true); entropy_viscosity.reinit (triangulation.n_active_cells()); cellSize_viscosity.reinit (triangulation.n_active_cells()); refinement_indicators.reinit (triangulation.n_active_cells()); } #include "NSolver.inst" } <|endoftext|>
<commit_before>#include "gui/qrworkspace.h" #include <QtCore/qmap.h> #include <QtCore/qdebug.h> #include <QtWidgets/qwidget.h> #include <QtWidgets/qscrollarea.h> #include <QtWidgets/qtabbar.h> #include "gui/qrworkspacewidget.h" NS_CHAOS_BASE_BEGIN class QrWorkspacePrivate{ QR_DECLARE_PUBLIC(QrWorkspace) public: static QrWorkspace* qInstance; int lastIndex = -1; QMap<QrWorkspaceWidget*, QScrollArea*> existedTabWidgets; public: QrWorkspacePrivate(QrWorkspace *q); public: static QrWorkspacePrivate* dInstance(); QrWorkspaceWidget* getWorkspaceWidget(int index); }; QrWorkspace* QrWorkspacePrivate::qInstance = nullptr; QrWorkspacePrivate::QrWorkspacePrivate(QrWorkspace *q) : q_ptr(q) { qInstance = q; } QrWorkspacePrivate *QrWorkspacePrivate::dInstance(){ Q_ASSERT(nullptr != QrWorkspacePrivate::qInstance); return QrWorkspacePrivate::qInstance->d_func(); } QrWorkspaceWidget *QrWorkspacePrivate::getWorkspaceWidget(int index) { Q_Q(QrWorkspace); return qobject_cast<QrWorkspaceWidget*>( qobject_cast<QScrollArea*>(q->widget(index))->widget()); } NS_CHAOS_BASE_END USING_NS_CHAOS_BASE; QrWorkspace::QrWorkspace(QWidget *parent) :QTabWidget(parent), d_ptr(new QrWorkspacePrivate(this)) { tabBar()->setObjectName("workspace_tabbar"); setTabsClosable(true); connect(this, &QrWorkspace::tabCloseRequested, [this](int index){ Q_D(QrWorkspace); QrWorkspaceWidget *workspaceWidget = d->getWorkspaceWidget(index); if(! workspaceWidget->closeRequested()) { qDebug() << "workspace widget reject to close."; return; } d->existedTabWidgets.remove(workspaceWidget); removeTab(index); }); connect(this, &QrWorkspace::currentChanged, [this](int index){ Q_D(QrWorkspace); QrWorkspaceWidget *workspaceWidget = d->getWorkspaceWidget(index); workspaceWidget->switchFrom(d->lastIndex); d->lastIndex = index; }); } int QrWorkspace::appendTab(QrWorkspaceWidget *widget, QString label, bool autoExpanding /*= true*/) { if (nullptr == widget) { qWarning() << "widget append to tag is null."; return -1; } auto q = QrWorkspacePrivate::qInstance; Q_ASSERT(nullptr != q); auto d = QrWorkspacePrivate::dInstance(); if (d->existedTabWidgets.contains(widget)) { qInfo() << label << " widget is exist. show previous widget."; auto preIndex = q->indexOf(d->existedTabWidgets[widget]); q->setTabText(preIndex, label); q->setCurrentIndex(preIndex); d->lastIndex = preIndex; return preIndex; } if(autoExpanding) { widget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding); } auto wrapWidget = new QScrollArea(); wrapWidget->setWidget (widget); wrapWidget->setWidgetResizable(true); d->existedTabWidgets[widget] = wrapWidget; auto tabIndex = q->addTab(wrapWidget, label); q->setCurrentIndex(tabIndex); d->lastIndex = tabIndex; return tabIndex; } <commit_msg>fix crash bug<commit_after>#include "gui/qrworkspace.h" #include <QtCore/qmap.h> #include <QtCore/qdebug.h> #include <QtWidgets/qwidget.h> #include <QtWidgets/qscrollarea.h> #include <QtWidgets/qtabbar.h> #include "gui/qrworkspacewidget.h" NS_CHAOS_BASE_BEGIN class QrWorkspacePrivate{ QR_DECLARE_PUBLIC(QrWorkspace) public: static QrWorkspace* qInstance; int lastIndex = -1; QMap<QrWorkspaceWidget*, QScrollArea*> existedTabWidgets; public: QrWorkspacePrivate(QrWorkspace *q); public: static QrWorkspacePrivate* dInstance(); QrWorkspaceWidget* getWorkspaceWidget(int index); }; QrWorkspace* QrWorkspacePrivate::qInstance = nullptr; QrWorkspacePrivate::QrWorkspacePrivate(QrWorkspace *q) : q_ptr(q) { qInstance = q; } QrWorkspacePrivate *QrWorkspacePrivate::dInstance(){ Q_ASSERT(nullptr != QrWorkspacePrivate::qInstance); return QrWorkspacePrivate::qInstance->d_func(); } QrWorkspaceWidget *QrWorkspacePrivate::getWorkspaceWidget(int index) { Q_Q(QrWorkspace); QScrollArea* wrapWidget = qobject_cast<QScrollArea*>(q->widget(index)); if(nullptr == wrapWidget) { qDebug() << "wrap widget is nullptr"; return nullptr; } return qobject_cast<QrWorkspaceWidget*>(wrapWidget->widget()); } NS_CHAOS_BASE_END USING_NS_CHAOS_BASE; QrWorkspace::QrWorkspace(QWidget *parent) :QTabWidget(parent), d_ptr(new QrWorkspacePrivate(this)) { tabBar()->setObjectName("workspace_tabbar"); setTabsClosable(true); connect(this, &QrWorkspace::tabCloseRequested, [this](int index){ Q_D(QrWorkspace); QrWorkspaceWidget *workspaceWidget = d->getWorkspaceWidget(index); if(nullptr == workspaceWidget) { qDebug() << "workspace widget is nullptr."; return; } if(! workspaceWidget->closeRequested()) { qDebug() << "workspace widget reject to close."; return; } d->existedTabWidgets.remove(workspaceWidget); removeTab(index); }); connect(this, &QrWorkspace::currentChanged, [this](int index){ Q_D(QrWorkspace); QrWorkspaceWidget *workspaceWidget = d->getWorkspaceWidget(index); if(nullptr != workspaceWidget) { workspaceWidget->switchFrom(d->lastIndex); } else { qDebug() << "workspace widget is nullptr."; } d->lastIndex = index; }); } int QrWorkspace::appendTab(QrWorkspaceWidget *widget, QString label, bool autoExpanding /*= true*/) { if (nullptr == widget) { qWarning() << "widget append to tag is null."; return -1; } auto q = QrWorkspacePrivate::qInstance; Q_ASSERT(nullptr != q); auto d = QrWorkspacePrivate::dInstance(); if (d->existedTabWidgets.contains(widget)) { qInfo() << label << " widget is exist. show previous widget."; auto preIndex = q->indexOf(d->existedTabWidgets[widget]); q->setTabText(preIndex, label); q->setCurrentIndex(preIndex); d->lastIndex = preIndex; return preIndex; } if(autoExpanding) { widget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding); } auto wrapWidget = new QScrollArea(q); wrapWidget->setWidget (widget); wrapWidget->setWidgetResizable(true); d->existedTabWidgets[widget] = wrapWidget; auto tabIndex = q->addTab(wrapWidget, label); q->setCurrentIndex(tabIndex); d->lastIndex = tabIndex; return tabIndex; } <|endoftext|>
<commit_before>#ifndef RBX_STATE_HPP #define RBX_STATE_HPP namespace rubinius { class VM; class VMJIT; class ManagedThread; class VMThreadState; class SharedState; class State { VM* vm_; VMJIT* vm_jit_; SharedState& shared_; public: State(VM* vm) : vm_(vm) , vm_jit_(&vm->vm_jit_) , shared_(vm->shared) {} VM* vm() { return vm_; } ManagedThread* thread() { return static_cast<ManagedThread*>(vm_); } Object* raise_exception(Exception* exc) { vm_->thread_state()->raise_exception(exc); return 0; } void set_vm(VM* vm) { vm_ = vm; } void set_call_frame(CallFrame* cf) { vm_->set_call_frame(cf); } Globals& globals() { return shared_.globals; } Symbol* symbol(const char* str) { return vm_->symbol(str); } Symbol* symbol(std::string str) { return vm_->symbol(str); } Symbol* symbol(String* str) { return vm_->symbol(str); } uint32_t hash_seed() { return shared_.hash_seed; } template <class T> T* new_object(Class *cls) { return static_cast<T*>(vm_->new_object_typed(cls, sizeof(T), T::type)); } template <class T> T* new_object_dirty(Class *cls) { return static_cast<T*>(vm_->new_object_typed_dirty(cls, sizeof(T), T::type)); } VMThreadState* thread_state() { return vm_->thread_state(); } ObjectMemory* memory() { return shared_.memory(); } SharedState& shared() { return shared_; } bool detect_stack_condition(void* end) { return vm_->detect_stack_condition(end); } bool check_local_interrupts() { return vm_jit_->check_local_interrupts_; } bool check_async(CallFrame* call_frame) { state->set_call_frame(state); if(vm_->check_local_interrupts()) { return process_async(call_frame); } return true; } void raise_stack_error(CallFrame* call_frame); bool check_stack(CallFrame* call_frame, void* end) { // @TODO assumes stack growth direction if(unlikely(vm_->detect_stack_condition(end))) { raise_stack_error(call_frame); return false; } return true; } bool process_async(CallFrame* call_frame); void check_exception(CallFrame* call_frame); bool check_interrupts(GCToken gct, CallFrame* call_frame, void* end); gc::Slab& local_slab() { return vm_->local_slab(); } bool stop_the_world() WARN_UNUSED { return shared_.stop_the_world(vm_); }; void restart_world() { shared_.restart_world(vm_); } void gc_independent(GCToken gct) { shared_.gc_independent(vm_); } void gc_dependent() { shared_.gc_dependent(vm_); } void checkpoint(GCToken gct, CallFrame* call_frame) { vm_->set_call_frame(call_frame); gc_checkpoint(gct, call_frame); shared_.checkpoint(vm_); } void gc_checkpoint(GCToken gct, CallFrame* frame) { if(unlikely(shared_.check_gc_p())) { vm_->collect_maybe(gct, frame); } } void lock(GCToken gct) { gc_independent(gct); vm_->lock(vm_); gc_dependent(); } void unlock() { vm_->unlock(vm_); } Object* park(GCToken gct, CallFrame* call_frame); Object* park_timed(GCToken gct, CallFrame* call_frame, struct timespec* ts); }; } #endif <commit_msg>Properly fix the call_frame setting<commit_after>#ifndef RBX_STATE_HPP #define RBX_STATE_HPP namespace rubinius { class VM; class VMJIT; class ManagedThread; class VMThreadState; class SharedState; class State { VM* vm_; VMJIT* vm_jit_; SharedState& shared_; public: State(VM* vm) : vm_(vm) , vm_jit_(&vm->vm_jit_) , shared_(vm->shared) {} VM* vm() { return vm_; } ManagedThread* thread() { return static_cast<ManagedThread*>(vm_); } Object* raise_exception(Exception* exc) { vm_->thread_state()->raise_exception(exc); return 0; } void set_vm(VM* vm) { vm_ = vm; } void set_call_frame(CallFrame* cf) { vm_->set_call_frame(cf); } Globals& globals() { return shared_.globals; } Symbol* symbol(const char* str) { return vm_->symbol(str); } Symbol* symbol(std::string str) { return vm_->symbol(str); } Symbol* symbol(String* str) { return vm_->symbol(str); } uint32_t hash_seed() { return shared_.hash_seed; } template <class T> T* new_object(Class *cls) { return static_cast<T*>(vm_->new_object_typed(cls, sizeof(T), T::type)); } template <class T> T* new_object_dirty(Class *cls) { return static_cast<T*>(vm_->new_object_typed_dirty(cls, sizeof(T), T::type)); } VMThreadState* thread_state() { return vm_->thread_state(); } ObjectMemory* memory() { return shared_.memory(); } SharedState& shared() { return shared_; } bool detect_stack_condition(void* end) { return vm_->detect_stack_condition(end); } bool check_local_interrupts() { return vm_jit_->check_local_interrupts_; } bool check_async(CallFrame* call_frame) { set_call_frame(call_frame); if(vm_->check_local_interrupts()) { return process_async(call_frame); } return true; } void raise_stack_error(CallFrame* call_frame); bool check_stack(CallFrame* call_frame, void* end) { // @TODO assumes stack growth direction if(unlikely(vm_->detect_stack_condition(end))) { raise_stack_error(call_frame); return false; } return true; } bool process_async(CallFrame* call_frame); void check_exception(CallFrame* call_frame); bool check_interrupts(GCToken gct, CallFrame* call_frame, void* end); gc::Slab& local_slab() { return vm_->local_slab(); } bool stop_the_world() WARN_UNUSED { return shared_.stop_the_world(vm_); }; void restart_world() { shared_.restart_world(vm_); } void gc_independent(GCToken gct) { shared_.gc_independent(vm_); } void gc_dependent() { shared_.gc_dependent(vm_); } void checkpoint(GCToken gct, CallFrame* call_frame) { vm_->set_call_frame(call_frame); gc_checkpoint(gct, call_frame); shared_.checkpoint(vm_); } void gc_checkpoint(GCToken gct, CallFrame* frame) { if(unlikely(shared_.check_gc_p())) { vm_->collect_maybe(gct, frame); } } void lock(GCToken gct) { gc_independent(gct); vm_->lock(vm_); gc_dependent(); } void unlock() { vm_->unlock(vm_); } Object* park(GCToken gct, CallFrame* call_frame); Object* park_timed(GCToken gct, CallFrame* call_frame, struct timespec* ts); }; } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: event.cc,v 1.3 2001/12/29 23:59:06 steve Exp $" #endif # include "event.h" # include "compile.h" # include "vthread.h" # include "schedule.h" # include <string.h> # include <assert.h> # include <stdlib.h> #ifdef HAVE_MALLOC_H # include <malloc.h> #endif event_functor_s::event_functor_s(edge_t e) : edge(e), threads(0) {} event_functor_s::~event_functor_s() {} /* * Receive a value into an event functor, whether an edge or event/or. * Detect edges, if any, then schedule awakened threads. */ void event_functor_s::set(vvp_ipoint_t ptr, bool, unsigned val, unsigned) { old_ival = ival; put(ptr, val); /* Only go through the effort if there is someone interested in the results... */ if (threads || out) { bool edge_p = true; /* If there is an edge detect lookup table, then use the out input and new input to detect whether this is the requested edge. If there is no edge table, then any set is a match. */ if (edge) { unsigned pp = ipoint_port(ptr); unsigned oval = (old_ival >> 2*pp) & 3; unsigned nval = (ival >> 2*pp) & 3; unsigned val = (oval << 2) | nval; edge_p = ((edge>>val) & 1) != 0; } /* If we detect an edge, then schedule any threads that are attached to this event, then propagate the positive detect to the output. Note that only other events (notably event/or functors) can be connected to event outputs. */ if (edge_p) { vthread_t tmp = threads; threads = 0; vthread_schedule_list(tmp); if (out) { functor_set(out, 0, St0, true); } // only one output? Why not propagate? //schedule_assign(out, 0, 0); } } } /* ** Create an event functor ** edge: compile_event(label, type, argc, argv) ** or: compile_event(label, NULL, argc, argv) ** name: compile_event(label, name, NULL, NULL) */ void compile_event(char*label, char*type, unsigned argc, struct symb_s*argv) { event_functor_s::edge_t edge = vvp_edge_none; if (argc && type) { if (strcmp(type,"posedge") == 0) edge = vvp_edge_posedge; else if (strcmp(type,"negedge") == 0) edge = vvp_edge_negedge; else if (strcmp(type,"edge") == 0) edge = vvp_edge_anyedge; assert(argc <= 4 || edge == vvp_edge_none); } if (!argc && type) { // "type" is the name of the named event } free(type); functor_t obj = new event_functor_s(edge); vvp_ipoint_t fdx = functor_allocate(1); functor_define(fdx, obj); define_functor_symbol(label, fdx); free(label); /* Run through the arguments looking for the functors that are connected to my input ports. For each source functor that I find, connect the output of that functor to the indexed input by inserting myself (complete with the port number in the vvp_ipoint_t) into the list that the source heads. If the source functor is not declared yet, then don't do the link yet. Save the reference to be resolved later. */ if (edge != vvp_edge_none) inputs_connect(fdx, argc, argv); else // Are we sure that we have those .event/or // drivers exclusively? for (unsigned i=0; i<argc; i++) { inputs_connect(fdx, 1, argv+i); } free(argv); } /* * $Log: event.cc,v $ * Revision 1.3 2001/12/29 23:59:06 steve * push events through event/or lists. * * Revision 1.2 2001/11/16 04:22:27 steve * include stdlib.h for portability. * * Revision 1.1 2001/11/06 03:07:22 steve * Code rearrange. (Stephan Boettcher) * */ <commit_msg> Spelling in comment.<commit_after>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: event.cc,v 1.4 2002/01/24 04:17:46 steve Exp $" #endif # include "event.h" # include "compile.h" # include "vthread.h" # include "schedule.h" # include <string.h> # include <assert.h> # include <stdlib.h> #ifdef HAVE_MALLOC_H # include <malloc.h> #endif event_functor_s::event_functor_s(edge_t e) : edge(e), threads(0) {} event_functor_s::~event_functor_s() {} /* * Receive a value into an event functor, whether an edge or event/or. * Detect edges, if any, then schedule awakened threads. */ void event_functor_s::set(vvp_ipoint_t ptr, bool, unsigned val, unsigned) { old_ival = ival; put(ptr, val); /* Only go through the effort if there is someone interested in the results... */ if (threads || out) { bool edge_p = true; /* If there is an edge detect lookup table, then use the old input and new input to detect whether this is the requested edge. If there is no edge table, then any set is a match. */ if (edge) { unsigned pp = ipoint_port(ptr); unsigned oval = (old_ival >> 2*pp) & 3; unsigned nval = (ival >> 2*pp) & 3; unsigned val = (oval << 2) | nval; edge_p = ((edge>>val) & 1) != 0; } /* If we detect an edge, then schedule any threads that are attached to this event, then propagate the positive detect to the output. Note that only other events (notably event/or functors) can be connected to event outputs. */ if (edge_p) { vthread_t tmp = threads; threads = 0; vthread_schedule_list(tmp); if (out) { functor_set(out, 0, St0, true); } // only one output? Why not propagate? //schedule_assign(out, 0, 0); } } } /* ** Create an event functor ** edge: compile_event(label, type, argc, argv) ** or: compile_event(label, NULL, argc, argv) ** name: compile_event(label, name, NULL, NULL) */ void compile_event(char*label, char*type, unsigned argc, struct symb_s*argv) { event_functor_s::edge_t edge = vvp_edge_none; if (argc && type) { if (strcmp(type,"posedge") == 0) edge = vvp_edge_posedge; else if (strcmp(type,"negedge") == 0) edge = vvp_edge_negedge; else if (strcmp(type,"edge") == 0) edge = vvp_edge_anyedge; assert(argc <= 4 || edge == vvp_edge_none); } if (!argc && type) { // "type" is the name of the named event } free(type); functor_t obj = new event_functor_s(edge); vvp_ipoint_t fdx = functor_allocate(1); functor_define(fdx, obj); define_functor_symbol(label, fdx); free(label); /* Run through the arguments looking for the functors that are connected to my input ports. For each source functor that I find, connect the output of that functor to the indexed input by inserting myself (complete with the port number in the vvp_ipoint_t) into the list that the source heads. If the source functor is not declared yet, then don't do the link yet. Save the reference to be resolved later. */ if (edge != vvp_edge_none) inputs_connect(fdx, argc, argv); else // Are we sure that we have those .event/or // drivers exclusively? for (unsigned i=0; i<argc; i++) { inputs_connect(fdx, 1, argv+i); } free(argv); } /* * $Log: event.cc,v $ * Revision 1.4 2002/01/24 04:17:46 steve * Spelling in comment. * * Revision 1.3 2001/12/29 23:59:06 steve * push events through event/or lists. * * Revision 1.2 2001/11/16 04:22:27 steve * include stdlib.h for portability. * * Revision 1.1 2001/11/06 03:07:22 steve * Code rearrange. (Stephan Boettcher) * */ <|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 "chrome/browser/ui/gtk/tab_contents/chrome_web_contents_view_delegate_gtk.h" #include <map> #include "base/lazy_instance.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/tab_contents/web_drag_bookmark_handler_gtk.h" #include "chrome/browser/ui/gtk/constrained_window_gtk.h" #include "chrome/browser/ui/gtk/tab_contents/render_view_context_menu_gtk.h" #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "ui/base/gtk/focus_store_gtk.h" #include "ui/base/gtk/gtk_floating_container.h" static base::LazyInstance<std::map< content::WebContents*, ChromeWebContentsViewDelegateGtk*> > g_instances = LAZY_INSTANCE_INITIALIZER; ChromeWebContentsViewDelegateGtk* ChromeWebContentsViewDelegateGtk::GetFor( content::WebContents* web_contents) { if (!g_instances.Get().count(web_contents)) return 0; return g_instances.Get()[web_contents]; } ChromeWebContentsViewDelegateGtk::ChromeWebContentsViewDelegateGtk( content::WebContents* web_contents) : floating_(gtk_floating_container_new()), constrained_window_(NULL), web_contents_(web_contents), expanded_container_(NULL), focus_store_(NULL) { gtk_widget_set_name(floating_.get(), "chrome-tab-contents-view"); g_signal_connect(floating_.get(), "set-floating-position", G_CALLBACK(OnSetFloatingPositionThunk), this); DCHECK_EQ(g_instances.Get().count(web_contents), 0u); g_instances.Get()[web_contents] = this; } ChromeWebContentsViewDelegateGtk::~ChromeWebContentsViewDelegateGtk() { floating_.Destroy(); DCHECK_EQ(g_instances.Get().count(web_contents_), 1u); g_instances.Get().erase(web_contents_); } void ChromeWebContentsViewDelegateGtk::AttachConstrainedWindow( ConstrainedWindowGtk* constrained_window) { DCHECK(constrained_window_ == NULL); constrained_window_ = constrained_window; gtk_floating_container_add_floating(GTK_FLOATING_CONTAINER(floating_.get()), constrained_window->widget()); } void ChromeWebContentsViewDelegateGtk::RemoveConstrainedWindow( ConstrainedWindowGtk* constrained_window) { DCHECK(constrained_window == constrained_window_); constrained_window_ = NULL; gtk_container_remove(GTK_CONTAINER(floating_.get()), constrained_window->widget()); } void ChromeWebContentsViewDelegateGtk::Initialize( GtkWidget* expanded_container, ui::FocusStoreGtk* focus_store) { expanded_container_ = expanded_container; focus_store_ = focus_store; // We install a chrome specific handler to intercept bookmark drags for the // bookmark manager/extension API. bookmark_handler_gtk_.reset(new WebDragBookmarkHandlerGtk); gtk_container_add(GTK_CONTAINER(floating_.get()), expanded_container); gtk_widget_show(floating_.get()); } gfx::NativeView ChromeWebContentsViewDelegateGtk::GetNativeView() const { return floating_.get(); } void ChromeWebContentsViewDelegateGtk::Focus() { if (!constrained_window_) { GtkWidget* widget = web_contents_->GetView()->GetContentNativeView(); if (widget) gtk_widget_grab_focus(widget); } } gboolean ChromeWebContentsViewDelegateGtk::OnNativeViewFocusEvent( GtkWidget* widget, GtkDirectionType type, gboolean* return_value) { // If we are showing a constrained window, don't allow the native view to take // focus. if (constrained_window_) { // If we return false, it will revert to the default handler, which will // take focus. We don't want that. But if we return true, the event will // stop being propagated, leaving focus wherever it is currently. That is // also bad. So we return false to let the default handler run, but take // focus first so as to trick it into thinking the view was already focused // and allowing the event to propagate. gtk_widget_grab_focus(widget); *return_value = FALSE; return TRUE; } // Let the default WebContentsViewGtk::OnFocus() behaviour run. return FALSE; } void ChromeWebContentsViewDelegateGtk::ShowContextMenu( const content::ContextMenuParams& params, content::ContextMenuSourceType type) { // Find out the RenderWidgetHostView that corresponds to the render widget on // which this context menu is showed, so that we can retrieve the last mouse // down event on the render widget and use it as the timestamp of the // activation event to show the context menu. content::RenderWidgetHostView* view = NULL; if (params.custom_context.render_widget_id != content::CustomContextMenuContext::kCurrentRenderWidget) { content::RenderWidgetHost* host = web_contents_->GetRenderProcessHost()->GetRenderWidgetHostByID( params.custom_context.render_widget_id); if (!host) { NOTREACHED(); return; } view = host->GetView(); } else { view = web_contents_->GetRenderWidgetHostView(); } context_menu_.reset( new RenderViewContextMenuGtk(web_contents_, params, view)); context_menu_->Init(); gfx::Rect bounds; web_contents_->GetView()->GetContainerBounds(&bounds); gfx::Point point = bounds.origin(); point.Offset(params.x, params.y); context_menu_->Popup(point); } content::WebDragDestDelegate* ChromeWebContentsViewDelegateGtk::GetDragDestDelegate() { return bookmark_handler_gtk_.get(); } void ChromeWebContentsViewDelegateGtk::OnSetFloatingPosition( GtkWidget* floating_container, GtkAllocation* allocation) { if (!constrained_window_) return; // Place each ConstrainedWindow in the center of the view. GtkWidget* widget = constrained_window_->widget(); DCHECK(gtk_widget_get_parent(widget) == floating_.get()); GtkRequisition requisition; gtk_widget_size_request(widget, &requisition); GValue value = { 0, }; g_value_init(&value, G_TYPE_INT); int child_x = std::max((allocation->width - requisition.width) / 2, 0); g_value_set_int(&value, child_x); gtk_container_child_set_property(GTK_CONTAINER(floating_container), widget, "x", &value); int child_y = std::max((allocation->height - requisition.height) / 2, 0); g_value_set_int(&value, child_y); gtk_container_child_set_property(GTK_CONTAINER(floating_container), widget, "y", &value); g_value_unset(&value); } namespace chrome { content::WebContentsViewDelegate* CreateWebContentsViewDelegate( content::WebContents* web_contents) { return new ChromeWebContentsViewDelegateGtk(web_contents); } } // namespace chrome <commit_msg>Clean up ChromeWebContentsViewDelegateGtk.<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 "chrome/browser/ui/gtk/tab_contents/chrome_web_contents_view_delegate_gtk.h" #include <map> #include "base/lazy_instance.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/tab_contents/web_drag_bookmark_handler_gtk.h" #include "chrome/browser/ui/gtk/constrained_window_gtk.h" #include "chrome/browser/ui/gtk/tab_contents/render_view_context_menu_gtk.h" #include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "ui/base/gtk/focus_store_gtk.h" #include "ui/base/gtk/gtk_floating_container.h" namespace { const char kViewDelegateUserDataKey[] = "ChromeWebContentsViewDelegateGtk"; class ViewDelegateUserData : public base::SupportsUserData::Data { public: explicit ViewDelegateUserData(ChromeWebContentsViewDelegateGtk* view_delegate) : view_delegate_(view_delegate) {} virtual ~ViewDelegateUserData() {} ChromeWebContentsViewDelegateGtk* view_delegate() { return view_delegate_; } private: ChromeWebContentsViewDelegateGtk* view_delegate_; // unowned }; } // namespace ChromeWebContentsViewDelegateGtk* ChromeWebContentsViewDelegateGtk::GetFor( content::WebContents* web_contents) { ViewDelegateUserData* user_data = static_cast<ViewDelegateUserData*>( web_contents->GetUserData(&kViewDelegateUserDataKey)); return user_data ? user_data->view_delegate() : NULL; } ChromeWebContentsViewDelegateGtk::ChromeWebContentsViewDelegateGtk( content::WebContents* web_contents) : floating_(gtk_floating_container_new()), constrained_window_(NULL), web_contents_(web_contents), expanded_container_(NULL), focus_store_(NULL) { gtk_widget_set_name(floating_.get(), "chrome-tab-contents-view"); g_signal_connect(floating_.get(), "set-floating-position", G_CALLBACK(OnSetFloatingPositionThunk), this); // Stash this in the WebContents. web_contents->SetUserData(&kViewDelegateUserDataKey, new ViewDelegateUserData(this)); } ChromeWebContentsViewDelegateGtk::~ChromeWebContentsViewDelegateGtk() { floating_.Destroy(); } void ChromeWebContentsViewDelegateGtk::AttachConstrainedWindow( ConstrainedWindowGtk* constrained_window) { DCHECK(constrained_window_ == NULL); constrained_window_ = constrained_window; gtk_floating_container_add_floating(GTK_FLOATING_CONTAINER(floating_.get()), constrained_window->widget()); } void ChromeWebContentsViewDelegateGtk::RemoveConstrainedWindow( ConstrainedWindowGtk* constrained_window) { DCHECK(constrained_window == constrained_window_); constrained_window_ = NULL; gtk_container_remove(GTK_CONTAINER(floating_.get()), constrained_window->widget()); } void ChromeWebContentsViewDelegateGtk::Initialize( GtkWidget* expanded_container, ui::FocusStoreGtk* focus_store) { expanded_container_ = expanded_container; focus_store_ = focus_store; // We install a chrome specific handler to intercept bookmark drags for the // bookmark manager/extension API. bookmark_handler_gtk_.reset(new WebDragBookmarkHandlerGtk); gtk_container_add(GTK_CONTAINER(floating_.get()), expanded_container); gtk_widget_show(floating_.get()); } gfx::NativeView ChromeWebContentsViewDelegateGtk::GetNativeView() const { return floating_.get(); } void ChromeWebContentsViewDelegateGtk::Focus() { if (!constrained_window_) { GtkWidget* widget = web_contents_->GetView()->GetContentNativeView(); if (widget) gtk_widget_grab_focus(widget); } } gboolean ChromeWebContentsViewDelegateGtk::OnNativeViewFocusEvent( GtkWidget* widget, GtkDirectionType type, gboolean* return_value) { // If we are showing a constrained window, don't allow the native view to take // focus. if (constrained_window_) { // If we return false, it will revert to the default handler, which will // take focus. We don't want that. But if we return true, the event will // stop being propagated, leaving focus wherever it is currently. That is // also bad. So we return false to let the default handler run, but take // focus first so as to trick it into thinking the view was already focused // and allowing the event to propagate. gtk_widget_grab_focus(widget); *return_value = FALSE; return TRUE; } // Let the default WebContentsViewGtk::OnFocus() behaviour run. return FALSE; } void ChromeWebContentsViewDelegateGtk::ShowContextMenu( const content::ContextMenuParams& params, content::ContextMenuSourceType type) { // Find out the RenderWidgetHostView that corresponds to the render widget on // which this context menu is showed, so that we can retrieve the last mouse // down event on the render widget and use it as the timestamp of the // activation event to show the context menu. content::RenderWidgetHostView* view = NULL; if (params.custom_context.render_widget_id != content::CustomContextMenuContext::kCurrentRenderWidget) { content::RenderWidgetHost* host = web_contents_->GetRenderProcessHost()->GetRenderWidgetHostByID( params.custom_context.render_widget_id); if (!host) { NOTREACHED(); return; } view = host->GetView(); } else { view = web_contents_->GetRenderWidgetHostView(); } context_menu_.reset( new RenderViewContextMenuGtk(web_contents_, params, view)); context_menu_->Init(); gfx::Rect bounds; web_contents_->GetView()->GetContainerBounds(&bounds); gfx::Point point = bounds.origin(); point.Offset(params.x, params.y); context_menu_->Popup(point); } content::WebDragDestDelegate* ChromeWebContentsViewDelegateGtk::GetDragDestDelegate() { return bookmark_handler_gtk_.get(); } void ChromeWebContentsViewDelegateGtk::OnSetFloatingPosition( GtkWidget* floating_container, GtkAllocation* allocation) { if (!constrained_window_) return; // Place each ConstrainedWindow in the center of the view. GtkWidget* widget = constrained_window_->widget(); DCHECK(gtk_widget_get_parent(widget) == floating_.get()); GtkRequisition requisition; gtk_widget_size_request(widget, &requisition); GValue value = { 0, }; g_value_init(&value, G_TYPE_INT); int child_x = std::max((allocation->width - requisition.width) / 2, 0); g_value_set_int(&value, child_x); gtk_container_child_set_property(GTK_CONTAINER(floating_container), widget, "x", &value); int child_y = std::max((allocation->height - requisition.height) / 2, 0); g_value_set_int(&value, child_y); gtk_container_child_set_property(GTK_CONTAINER(floating_container), widget, "y", &value); g_value_unset(&value); } namespace chrome { content::WebContentsViewDelegate* CreateWebContentsViewDelegate( content::WebContents* web_contents) { return new ChromeWebContentsViewDelegateGtk(web_contents); } } // namespace chrome <|endoftext|>
<commit_before>// bdls_osutil.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bdls_osutil.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdls_osutil_cpp, "$Id$ $CSID$") #include <bdls_processutil.h> #include <bsl_cstring.h> #include <bsl_sstream.h> #include <bslmf_assert.h> #include <bsls_platform.h> #ifdef BSLS_PLATFORM_OS_WINDOWS # include <bsl_limits.h> # include "windows.h" # include "VersionHelpers.h" #else # include <unistd.h> # include <sys/utsname.h> #endif namespace BloombergLP { // -------------------- // struct bdls::OsUtil // -------------------- // CLASS METHODS #ifdef BSLS_PLATFORM_OS_WINDOWS namespace bdls { int OsUtil::getOsInfo(bsl::string *osName, bsl::string *osVersion, bsl::string *osPatch) { BSLS_ASSERT(osName); BSLS_ASSERT(osVersion); BSLS_ASSERT(osPatch); *osName = "Windows"; // On Windows, 'WORD' means a 16-bit unsigned int. WORD major = 0; WORD minor = 0; WORD servicePackMajor = 0; const WORD maxWord = bsl::numeric_limits<WORD>::max(); while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) { if (major >= maxWord) { return -1; // RETURN } ++major; } --major; while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) { if (minor >= maxWord) { return -1; // RETURN } ++minor; } --minor; while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) { if (servicePackMajor >= maxWord) { return -1; // RETURN } ++servicePackMajor; } --servicePackMajor; // Os version bsl::ostringstream version; version << major << '.' << minor; *osVersion = version.str(); version.str(""); // Service pack number if (servicePackMajor) { version << "Service Pack " << servicePackMajor << ".0"; } *osPatch = version.str(); return 0; } } // close package namespace #elif defined(BSLS_PLATFORM_OS_UNIX) namespace bdls { int OsUtil::getOsInfo(bsl::string *osName, bsl::string *osVersion, bsl::string *osPatch) { BSLS_ASSERT(osName); BSLS_ASSERT(osVersion); BSLS_ASSERT(osPatch); struct utsname unameInfo; if (-1 == uname(&unameInfo)) { return -1; // RETURN } *osName = unameInfo.sysname; *osVersion = unameInfo.release; *osPatch = unameInfo.version; return 0; } } // close package namespace #else BSLMF_ASSERT("Unsupported operating system", false); #endif } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>bdls_osutil: #idef 2 imps, for pre & post Vista compiles<commit_after>// bdls_osutil.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bdls_osutil.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdls_osutil_cpp, "$Id$ $CSID$") #include <bdls_processutil.h> #include <bslmf_assert.h> #include <bsls_platform.h> #include <bsl_cstring.h> #include <bsl_sstream.h> #ifdef BSLS_PLATFORM_OS_WINDOWS # undef u_VISTA_OR_LATER # if 6 <= BSLS_PLATFORM_OS_VER_MAJOR # define u_VISTA_OR_LATER 1 # endif # include <windows.h> # ifdef u_VISTA_OR_LATER # include <bsl_limits.h> # include "VersionHelpers.h" # else # include <process.h> # endif #else # include <unistd.h> # include <sys/utsname.h> #endif namespace BloombergLP { // -------------------- // struct bdls::OsUtil // -------------------- // CLASS METHODS #ifdef BSLS_PLATFORM_OS_WINDOWS namespace bdls { int OsUtil::getOsInfo(bsl::string *osName, bsl::string *osVersion, bsl::string *osPatch) { BSLS_ASSERT(osName); BSLS_ASSERT(osVersion); BSLS_ASSERT(osPatch); *osName = "Windows"; #ifdef u_VISTA_OR_LATER // On Windows, 'WORD' means a 16-bit unsigned int. WORD major = 0; WORD minor = 0; WORD servicePackMajor = 0; const WORD maxWord = bsl::numeric_limits<WORD>::max(); while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) { if (major >= maxWord) { return -1; // RETURN } ++major; } --major; while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) { if (minor >= maxWord) { return -1; // RETURN } ++minor; } --minor; while (IsWindowsVersionOrGreater(major, minor, servicePackMajor)) { if (servicePackMajor >= maxWord) { return -1; // RETURN } ++servicePackMajor; } --servicePackMajor; // Os version bsl::ostringstream version; version << major << '.' << minor; *osVersion = version.str(); version.str(""); // Service pack number if (servicePackMajor) { // Note that we are incapable of detecting any 'servicePackMinor' // version other than 0. But it seems rational that if Microsoft had // any plans for non-zero 'servicePackMinor' version at or after // Vista, they would have made 'IsWindowsVersionOrGreater' take 4 args // instead of 3. version << "Service Pack " << servicePackMajor << ".0"; } *osPatch = version.str(); #else OSVERSIONINFOEX osvi; bsl::memset(&osvi, 0, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!GetVersionEx((OSVERSIONINFO *)&osvi)) { return -1; } // Os version bsl::ostringstream version; version << osvi.dwMajorVersion << '.' << osvi.dwMinorVersion; *osVersion = version.str(); version.clear(); version.str(""); // Service pack number if (osvi.wServicePackMajor) { version << "Service Pack " << osvi.wServicePackMajor << '.' << osvi.wServicePackMinor; } *osPatch = version.str(); #endif return 0; } } // close package namespace #elif defined(BSLS_PLATFORM_OS_UNIX) namespace bdls { int OsUtil::getOsInfo(bsl::string *osName, bsl::string *osVersion, bsl::string *osPatch) { BSLS_ASSERT(osName); BSLS_ASSERT(osVersion); BSLS_ASSERT(osPatch); struct utsname unameInfo; if (-1 == uname(&unameInfo)) { return -1; // RETURN } *osName = unameInfo.sysname; *osVersion = unameInfo.release; *osPatch = unameInfo.version; return 0; } } // close package namespace #else BSLMF_ASSERT("Unsupported operating system", false); #endif } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>#include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> int main (int argc, char** argv) { // Load input file into a PointCloud<T> with an appropriate type pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ()); sensor_msgs::PointCloud2 cloud_blob; // Load bun0.pcd -- should be available with the PCL archive in test pcl::io::loadPCDFile ("bun0.pcd", cloud_blob); pcl::fromROSMsg (cloud_blob, *cloud); // Create a KD-Tree pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); tree->setInputCloud (cloud); // Output has the same type as the input one, it will be only smoothed pcl::PointCloud<pcl::PointXYZ> mls_points; // Init object (second point type is for the normals, even if unused) pcl::MovingLeastSquares<pcl::PointXYZ, pcl::Normal> mls; // Optionally, a pointer to a cloud can be provided, to be set by MLS pcl::PointCloud<pcl::Normal>::Ptr mls_normals (new pcl::PointCloud<pcl::Normal> ()); mls.setOutputNormals (mls_normals); // Set parameters mls.setInputCloud (cloud); mls.setPolynomialFit (true); mls.setSearchMethod (tree); mls.setSearchRadius (0.03); // Reconstruct mls.reconstruct (mls_points); // Concatenate fields for saving pcl::PointCloud<pcl::PointNormal> mls_cloud; pcl::concatenateFields (mls_points, *mls_normals, mls_cloud); // Save output pcl::io::savePCDFile ("bun0-mls.pcd", mls_cloud); } <commit_msg>* fixed issue #441 where the resampling tutorial was setting the input twice: once in the tutorial code, and once inside the @MovingLeastSquares@ class (thanks Peter!)<commit_after>#include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> int main (int argc, char** argv) { // Load input file into a PointCloud<T> with an appropriate type pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ()); sensor_msgs::PointCloud2 cloud_blob; // Load bun0.pcd -- should be available with the PCL archive in test pcl::io::loadPCDFile ("bun0.pcd", cloud_blob); pcl::fromROSMsg (cloud_blob, *cloud); // Create a KD-Tree pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); // Output has the same type as the input one, it will be only smoothed pcl::PointCloud<pcl::PointXYZ> mls_points; // Init object (second point type is for the normals, even if unused) pcl::MovingLeastSquares<pcl::PointXYZ, pcl::Normal> mls; // Optionally, a pointer to a cloud can be provided, to be set by MLS pcl::PointCloud<pcl::Normal>::Ptr mls_normals (new pcl::PointCloud<pcl::Normal> ()); mls.setOutputNormals (mls_normals); // Set parameters mls.setInputCloud (cloud); mls.setPolynomialFit (true); mls.setSearchMethod (tree); mls.setSearchRadius (0.03); // Reconstruct mls.reconstruct (mls_points); // Concatenate fields for saving pcl::PointCloud<pcl::PointNormal> mls_cloud; pcl::concatenateFields (mls_points, *mls_normals, mls_cloud); // Save output pcl::io::savePCDFile ("bun0-mls.pcd", mls_cloud); } <|endoftext|>
<commit_before>#define _CRT_SECURE_NO_WARNINGS #include"../main/IOfunction.h" #include"../main/memoryfunction.h" #include<unordered_map> #include<queue> #include<string> #include<iostream> using namespace std; struct product{ int pid; double sim; product(int _id, double _sim) { pid = _id; sim = _sim; } }; struct compare{ bool operator()(product &a, product &b) { return a.sim > b.sim; } }; class ProductSim{ unordered_map<string, int> labels; priority_queue<product, vector<product>, compare> Q; int K = 20; vector<string> nodelabels; DIR *dir = NULL; struct dirent *ent; vector<string> filenames; int productnum; public: ProductSim(int num){ productnum = num; nodelabels.resize(num); } ~ProductSim() { filenames.clear(); if (ent != NULL) { free(ent); ent = NULL; } } void readNodeLabel(string filename) { ifstream infile(filename); if (infile.is_open() == false) { cout << "could not open the filename" << endl; exit(4); } int idx; string s; string strLine; while (!infile.eof()) { getline(infile, strLine); std::size_t found = strLine.find_last_of("\t"); s = str.substr(0,found); idx = stoi(str.substr(found + 1)); labels[s] = idx; nodelabels[idx] = s; } infile.close(); } void listfileinDir(string dirname) { if ((dir = opendir(dirname.c_str())) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir(dir)) != NULL) { if (ent->d_name[0] != '.'){ filenames.push_back(dirname+"/"+ent->d_name); } } closedir(dir); } else { /* could not open directory */ perror("could not open directory"); exit(EXIT_FAILURE); } } void computesim(string productname) { if (this->labels.find(productname) == labels.end()) { cout << "the product does not exit in our data" << endl; exit(4); } else { int idx = labels[productname]; SparseMatrix Z; Z.Initmemory(productnum); Z.setcolumnnum(20); FILE *rfile = NULL; for (int t = 0; t < filenames.size(); t++) { rfile = fopen(filenames[t].c_str(), "r"); if (rfile == NULL) { cout << "could not open file to read" << endl; exit(4); } Readcommunity(Z, productnum, rfile); for (int j = 0; j < productnum; j++) { if (j != idx) { double sim = Z.Rowdotproduct2(idx, j); product a(j, sim); if (Q.size() < K) { Q.push(a); } else if (sim >= Q.top().sim) { Q.pop(); Q.push(a); } } } //output the similar products; while (!Q.empty()) { product o = Q.top(); cout << t << "\t" << nodelabels[o.pid] << "\t" << o.sim << endl; Q.pop(); } //release the memory of Z; Z.clear(); } Z.deletemem(); } } }; int main (int argc, char *argv[]) { if (argc < 1) { cout << "Usage " << argv[0]; cout << "[#product] [embedding-file-name] [node-label-file-name] [product-name]" << endl; exit(4); } int v = atoi(argv[1]); ProductSim a(v); string dirname(argv[2]); string labelname(argv[3]); string productname(argv[4]); Initmemory(); InitIOmemory(); filebuffer = new char[BYTE_TO_READ]; a.listfileinDir(dirname); a.readNodeLabel(labelname); a.computesim(productname); releaseIOmemory(); releaseblockmemory(); return 0; } <commit_msg>rename<commit_after>#define _CRT_SECURE_NO_WARNINGS #include"../main/IOfunction.h" #include"../main/memoryfunction.h" #include<unordered_map> #include<queue> #include<string> #include<iostream> using namespace std; struct product{ int pid; double sim; product(int _id, double _sim) { pid = _id; sim = _sim; } }; struct compare{ bool operator()(product &a, product &b) { return a.sim > b.sim; } }; class ProductSim{ unordered_map<string, int> labels; priority_queue<product, vector<product>, compare> Q; int K = 20; vector<string> nodelabels; DIR *dir = NULL; struct dirent *ent; vector<string> filenames; int productnum; public: ProductSim(int num){ productnum = num; nodelabels.resize(num); } ~ProductSim() { filenames.clear(); if (ent != NULL) { free(ent); ent = NULL; } } void readNodeLabel(string filename) { ifstream infile(filename); if (infile.is_open() == false) { cout << "could not open the filename" << endl; exit(4); } int idx; string s; string strLine; while (!infile.eof()) { getline(infile, strLine); std::size_t found = strLine.find_last_of("\t"); s = strLine.substr(0,found); idx = stoi(strLine.substr(found + 1)); labels[s] = idx; nodelabels[idx] = s; } infile.close(); } void listfileinDir(string dirname) { if ((dir = opendir(dirname.c_str())) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir(dir)) != NULL) { if (ent->d_name[0] != '.'){ filenames.push_back(dirname+"/"+ent->d_name); } } closedir(dir); } else { /* could not open directory */ perror("could not open directory"); exit(EXIT_FAILURE); } } void computesim(string productname) { if (this->labels.find(productname) == labels.end()) { cout << "the product does not exit in our data" << endl; exit(4); } else { int idx = labels[productname]; SparseMatrix Z; Z.Initmemory(productnum); Z.setcolumnnum(20); FILE *rfile = NULL; for (int t = 0; t < filenames.size(); t++) { rfile = fopen(filenames[t].c_str(), "r"); if (rfile == NULL) { cout << "could not open file to read" << endl; exit(4); } Readcommunity(Z, productnum, rfile); for (int j = 0; j < productnum; j++) { if (j != idx) { double sim = Z.Rowdotproduct2(idx, j); product a(j, sim); if (Q.size() < K) { Q.push(a); } else if (sim >= Q.top().sim) { Q.pop(); Q.push(a); } } } //output the similar products; while (!Q.empty()) { product o = Q.top(); cout << t << "\t" << nodelabels[o.pid] << "\t" << o.sim << endl; Q.pop(); } //release the memory of Z; Z.clear(); } Z.deletemem(); } } }; int main (int argc, char *argv[]) { if (argc < 1) { cout << "Usage " << argv[0]; cout << "[#product] [embedding-file-name] [node-label-file-name] [product-name]" << endl; exit(4); } int v = atoi(argv[1]); ProductSim a(v); string dirname(argv[2]); string labelname(argv[3]); string productname(argv[4]); Initmemory(); InitIOmemory(); filebuffer = new char[BYTE_TO_READ]; a.listfileinDir(dirname); a.readNodeLabel(labelname); a.computesim(productname); releaseIOmemory(); releaseblockmemory(); return 0; } <|endoftext|>
<commit_before><commit_msg>various improvements in signals<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin 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/pch.hpp" #include <libtorrent/kademlia/closest_nodes.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include "libtorrent/assert.hpp" namespace libtorrent { namespace dht { using asio::ip::udp; closest_nodes_observer::~closest_nodes_observer() { if (m_algorithm) m_algorithm->failed(m_self, true); } void closest_nodes_observer::reply(msg const& in) { if (!m_algorithm) { TORRENT_ASSERT(false); return; } if (!in.nodes.empty()) { for (msg::nodes_t::const_iterator i = in.nodes.begin() , end(in.nodes.end()); i != end; ++i) { m_algorithm->traverse(i->id, i->addr); } } m_algorithm->finished(m_self); m_algorithm = 0; } void closest_nodes_observer::timeout() { if (!m_algorithm) return; m_algorithm->failed(m_self); m_algorithm = 0; } closest_nodes::closest_nodes( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) : traversal_algorithm( target , branch_factor , max_results , table , rpc , table.begin() , table.end() ) , m_done_callback(callback) { boost::intrusive_ptr<closest_nodes> self(this); add_requests(); } void closest_nodes::invoke(node_id const& id, udp::endpoint addr) { TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer)); observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target)); #ifndef NDEBUG o->m_in_constructor = false; #endif m_rpc.invoke(messages::find_node, addr, o); } void closest_nodes::done() { std::vector<node_entry> results; int num_results = m_max_results; for (std::vector<result>::iterator i = m_results.begin() , end(m_results.end()); i != end && num_results >= 0; ++i) { if (i->flags & result::no_id) continue; if ((i->flags & result::queried) == 0) continue; results.push_back(node_entry(i->id, i->addr)); --num_results; } m_done_callback(results); } void closest_nodes::initiate( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) { new closest_nodes(target, branch_factor, max_results, table, rpc, callback); } } } // namespace libtorrent::dht <commit_msg>minor dht fix<commit_after>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin 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/pch.hpp" #include <libtorrent/kademlia/closest_nodes.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include "libtorrent/assert.hpp" namespace libtorrent { namespace dht { using asio::ip::udp; closest_nodes_observer::~closest_nodes_observer() { if (m_algorithm) m_algorithm->failed(m_self, true); } void closest_nodes_observer::reply(msg const& in) { if (!m_algorithm) { TORRENT_ASSERT(false); return; } if (!in.nodes.empty()) { for (msg::nodes_t::const_iterator i = in.nodes.begin() , end(in.nodes.end()); i != end; ++i) { m_algorithm->traverse(i->id, i->addr); } } m_algorithm->finished(m_self); m_algorithm = 0; } void closest_nodes_observer::timeout() { if (!m_algorithm) return; m_algorithm->failed(m_self); m_algorithm = 0; } closest_nodes::closest_nodes( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) : traversal_algorithm( target , branch_factor , max_results , table , rpc , table.begin() , table.end() ) , m_done_callback(callback) { boost::intrusive_ptr<closest_nodes> self(this); add_requests(); } void closest_nodes::invoke(node_id const& id, udp::endpoint addr) { TORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer)); observer_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target)); #ifndef NDEBUG o->m_in_constructor = false; #endif m_rpc.invoke(messages::find_node, addr, o); } void closest_nodes::done() { std::vector<node_entry> results; int num_results = m_max_results; for (std::vector<result>::iterator i = m_results.begin() , end(m_results.end()); i != end && num_results > 0; ++i) { if (i->flags & result::no_id) continue; if ((i->flags & result::queried) == 0) continue; results.push_back(node_entry(i->id, i->addr)); --num_results; } m_done_callback(results); } void closest_nodes::initiate( node_id target , int branch_factor , int max_results , routing_table& table , rpc_manager& rpc , done_callback const& callback ) { new closest_nodes(target, branch_factor, max_results, table, rpc, callback); } } } // namespace libtorrent::dht <|endoftext|>