text
stringlengths
54
60.6k
<commit_before>// Copyright 2015 Google Inc. All Rights Reserved. // Author: Sebastian Schaffert <[email protected]> #include "SourcesToolService.h" #include <booster/log.h> #include <cppcms/service.h> #include <cppcms/http_response.h> #include <cppcms/http_request.h> #include <cppcms/url_dispatcher.h> #include <cppcms/url_mapper.h> #include <fstream> #include "SerializerTSV.h" #include "SerializerJSON.h" #include "Persistence.h" #include "Membuf.h" #include "Version.h" #define TIMING(message, begin, end) \ BOOSTER_NOTICE("sourcestool") \ << request().remote_addr() << ": " \ << (message) << " time: " \ << 1000 * (static_cast<double>(end - begin) / CLOCKS_PER_SEC) \ << "ms" << std::endl; // initialise static counters for status reports time_t SourcesToolService::startupTime = std::time(NULL); int64_t SourcesToolService::reqGetEntityCount = 0; int64_t SourcesToolService::reqGetRandomCount = 0; int64_t SourcesToolService::reqGetStatementCount = 0; int64_t SourcesToolService::reqUpdateStatementCount = 0; int64_t SourcesToolService::reqStatusCount = 0; // format a time_t using ISO8601 GMT time inline std::string formatGMT(time_t* time) { char result[128]; std::strftime(result, 128, "%Y-%m-%dT%H:%M:%SZ", gmtime(time)); return std::string(result); } // represent memory statistics (used for status) struct memstat { double rss, shared_mem, private_mem; }; // read memory statistics from /proc (used for status) inline memstat getMemStat() { int tSize = 0, resident = 0, share = 0; std::ifstream buffer("/proc/self/statm"); buffer >> tSize >> resident >> share; buffer.close(); struct memstat result; long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages result.rss = resident * page_size_kb; result.shared_mem = share * page_size_kb; result.private_mem = result.rss - result.shared_mem; return result; } // initialise service mappings from URLs to methods SourcesToolService::SourcesToolService(cppcms::service &srv) : cppcms::application(srv), backend(settings()["database"]) { dispatcher().assign("/entities/(Q\\d+)", &SourcesToolService::getEntityByQID, this, 1); mapper().assign("entity_by_qid", "/entities/{1}"); // map request to random entity selector dispatcher().assign("/entities/any", &SourcesToolService::getRandomEntity, this); mapper().assign("entity_by_topic_user", "/entities/any"); // map GET and POST requests to /entities/<QID> to the respective handlers // we use a helper function to distinguish both cases, since cppcms // currently does not really support REST dispatcher().assign("/statements/(\\d+)", &SourcesToolService::handleGetPostStatement, this, 1); mapper().assign("stmt_by_id", "/statements/{1}"); dispatcher().assign("/statements/any", &SourcesToolService::getRandomStatements, this); mapper().assign("stmt_by_random", "/statements/any"); dispatcher().assign("/import", &SourcesToolService::importStatements, this); mapper().assign("import", "/import"); dispatcher().assign("/delete", &SourcesToolService::deleteStatements, this); mapper().assign("delete", "/delete"); dispatcher().assign("/datasets/all", &SourcesToolService::getAllDatasets, this); mapper().assign("datasets_all", "/datasets/all"); dispatcher().assign("/status", &SourcesToolService::getStatus, this); mapper().assign("status", "/status"); dispatcher().assign("/dashboard/activitylog", &SourcesToolService::getActivityLog, this); mapper().assign("activitylog", "/dashboard/activitylog"); } void SourcesToolService::handleGetPostStatement(std::string stid) { if (request().request_method() == "POST") { approveStatement(std::stoll(stid)); } else { getStatement(std::stoll(stid)); } } void SourcesToolService::getEntityByQID(std::string qid) { clock_t begin = std::clock(); std::vector<Statement> statements = backend.getStatementsByQID(cache(), qid, true, request().get("dataset")); addCORSHeaders(); addVersionHeaders(); if (statements.size() > 0) { serializeStatements(statements); } else { response().status(404, "no statements found for entity "+qid); } reqGetEntityCount++; clock_t end = std::clock(); TIMING("GET /entities/" + qid, begin, end); } void SourcesToolService::getRandomEntity() { clock_t begin = std::clock(); addCORSHeaders(); addVersionHeaders(); try { std::vector<Statement> statements = backend.getStatementsByRandomQID(cache(), true, request().get("dataset")); serializeStatements(statements); } catch(PersistenceException const &e) { response().status(404, "no random unapproved entity found"); } reqGetRandomCount++; clock_t end = std::clock(); TIMING("GET /entities/any", begin, end); } void SourcesToolService::approveStatement(int64_t stid) { clock_t begin = std::clock(); ApprovalState state; addCORSHeaders(); addVersionHeaders(); // return 403 forbidden when there is no user given or the username is too // long for the database if (request().get("user") == "" || request().get("user").length() > 64) { response().status(403, "Forbidden: invalid or missing user"); return; } // check if statement exists and update it with new state try { backend.updateStatement(cache(), stid, stateFromString(request().get("state")), request().get("user")); } catch(PersistenceException const &e) { response().status(404, "Statement not found"); } catch(InvalidApprovalState const &e) { response().status(400, "Bad Request: invalid or missing state parameter"); } reqUpdateStatementCount++; clock_t end = std::clock(); TIMING("POST /statements/" + std::to_string(stid), begin, end); } void SourcesToolService::getStatement(int64_t stid) { clock_t begin = std::clock(); addCORSHeaders(); addVersionHeaders(); // query for statement, wrap it in a vector and return it try { std::vector<Statement> statements = { backend.getStatementByID(cache(), stid) }; serializeStatements(statements); } catch(PersistenceException const &e) { std::cerr << "error: " << e.what() << std::endl; response().status(404, "Statement not found"); } reqGetStatementCount++; clock_t end = std::clock(); TIMING("GET /statements/" + std::to_string(stid), begin, end); } void SourcesToolService::getRandomStatements() { clock_t begin = std::clock(); int count = 10; if (request().get("count") != "") { count = std::stoi(request().get("count")); } addCORSHeaders(); addVersionHeaders(); serializeStatements(backend.getRandomStatements(cache(), count, true)); clock_t end = std::clock(); TIMING("GET /statements/any", begin, end); } void SourcesToolService::getStatus() { clock_t begin = std::clock(); addCORSHeaders(); addVersionHeaders(); cppcms::json::value result; Status status = backend.getStatus(cache()); result["statements"]["total"] = status.getStatements(); result["statements"]["approved"] = status.getApproved(); result["statements"]["unapproved"] = status.getUnapproved(); result["statements"]["blacklisted"] = status.getBlacklisted(); result["statements"]["duplicate"] = status.getDuplicate(); result["statements"]["wrong"] = status.getWrong(); cppcms::json::array topusers; for (auto entry : status.getTopUsers()) { cppcms::json::value v; v["name"] = entry.first; v["activities"] = entry.second; topusers.push_back(v); } result["topusers"] = topusers; // system information result["system"]["startup"] = formatGMT(&SourcesToolService::startupTime); result["system"]["version"] = std::string(GIT_SHA1); result["system"]["cache_hits"] = backend.getCacheHits(); result["system"]["cache_misses"] = backend.getCacheMisses(); struct memstat meminfo = getMemStat(); result["system"]["shared_mem"] = meminfo.shared_mem; result["system"]["private_mem"] = meminfo.private_mem; result["system"]["rss"] = meminfo.rss; // request statistics result["requests"]["getentity"] = reqGetEntityCount; result["requests"]["getrandom"] = reqGetRandomCount; result["requests"]["getstatement"] = reqGetStatementCount; result["requests"]["updatestatement"] = reqUpdateStatementCount; result["requests"]["getstatus"] = reqStatusCount; response().content_type("application/json"); result.save(response().out(), cppcms::json::readable); reqStatusCount++; clock_t end = std::clock(); TIMING("GET /status", begin, end); } void SourcesToolService::serializeStatements(const std::vector<Statement> &statements) { if(request().http_accept() == "text/vnd.wikidata+tsv" || request().http_accept() == "text/tsv") { response().content_type("text/vnd.wikidata+tsv"); Serializer::writeTSV(statements.cbegin(), statements.cend(), &response().out()); } else if(request().http_accept() == "application/vnd.wikidata+json") { response().content_type("application/vnd.wikidata+json"); Serializer::writeWikidataJSON(statements.cbegin(), statements.cend(), &response().out()); } else { response().content_type("application/vnd.wikidata.envelope+json"); Serializer::writeEnvelopeJSON(statements.cbegin(), statements.cend(), &response().out()); } } void SourcesToolService::importStatements() { addVersionHeaders(); if (request().request_method() == "POST") { clock_t begin = std::clock(); // check if token matches if (request().get("token") != settings()["token"].str()) { response().status(401, "Invalid authorization token"); return; } if (request().get("dataset") == "") { response().status(400, "Missing argument: dataset"); return; } // check if content is gzipped bool gzip = false; if (request().get("gzip") == "true") { gzip = true; } bool dedup = true; if (request().get("deduplicate") == "false") { dedup = false; } // wrap raw post data into a memory stream Membuf body(request().raw_post_data()); std::istream in(&body); // import statements int64_t count = backend.importStatements( cache(), in, request().get("dataset"), gzip, dedup); clock_t end = std::clock(); cppcms::json::value result; result["count"] = count; result["time"] = 1000 * (static_cast<double>(end - begin) / CLOCKS_PER_SEC); response().content_type("application/json"); result.save(response().out(), cppcms::json::readable); TIMING("POST /import", begin, end); } else { response().status(405, "Method not allowed"); response().set_header("Allow", "POST"); } } void SourcesToolService::getAllDatasets() { addCORSHeaders(); addVersionHeaders(); std::vector<std::string> datasets = backend.getDatasets(cache()); cppcms::json::value result; for(std::string id : datasets) { result[id]["id"] = id; } response().content_type("application/json"); result.save(response().out(), cppcms::json::readable); } void SourcesToolService::deleteStatements() { addVersionHeaders(); if (request().request_method() == "POST") { // check if token matches if (request().get("token") != settings()["token"].str()) { response().status(401, "Invalid authorization token"); return; } clock_t begin = std::clock(); // check if statement exists and update it with new state try { backend.deleteStatements(cache(), stateFromString(request().get("state"))); } catch(PersistenceException const &e) { response().status(404, "Could not delete statements"); } catch(InvalidApprovalState const &e) { response().status(400, "Bad Request: invalid or missing state parameter"); } clock_t end = std::clock(); TIMING("POST /delete", begin, end); } else { response().status(405, "Method not allowed"); response().set_header("Allow", "POST"); } } void SourcesToolService::addCORSHeaders() { response().set_header("Access-Control-Allow-Origin", "*"); } void SourcesToolService::addVersionHeaders() { response().set_header("X-Powered-By", std::string("Wikidata Sources Tool/") + GIT_SHA1); } void SourcesToolService::getActivityLog() { clock_t begin = std::clock(); addCORSHeaders(); addVersionHeaders(); cppcms::json::value result; Dashboard::ActivityLog activities = backend.getActivityLog(cache()); std::vector<std::string> users(activities.getUsers().begin(), activities.getUsers().end()); result["users"] = users; for(int i=0; i< activities.getActivities().size(); i++) { Dashboard::ActivityEntry entry = activities.getActivities()[i]; if (entry.date != "") { result["approved"][i][0] = entry.date; for (int j = 0; j < users.size(); j++) { if (entry.approved.find(users[j]) != entry.approved.end()) { result["approved"][i][j + 1] = entry.approved[users[j]]; } else { result["approved"][i][j + 1] = 0; } } result["rejected"][i][0] = entry.date; for (int j = 0; j < users.size(); j++) { if (entry.rejected.find(users[j]) != entry.rejected.end()) { result["rejected"][i][j + 1] = entry.rejected[users[j]]; } else { result["rejected"][i][j + 1] = 0; } } } } response().content_type("application/json"); result.save(response().out(), cppcms::json::readable); reqStatusCount++; clock_t end = std::clock(); TIMING("GET /dashboard/activitylog", begin, end); } <commit_msg>Adds dataset to the import response<commit_after>// Copyright 2015 Google Inc. All Rights Reserved. // Author: Sebastian Schaffert <[email protected]> #include "SourcesToolService.h" #include <booster/log.h> #include <cppcms/service.h> #include <cppcms/http_response.h> #include <cppcms/http_request.h> #include <cppcms/url_dispatcher.h> #include <cppcms/url_mapper.h> #include <fstream> #include "SerializerTSV.h" #include "SerializerJSON.h" #include "Persistence.h" #include "Membuf.h" #include "Version.h" #define TIMING(message, begin, end) \ BOOSTER_NOTICE("sourcestool") \ << request().remote_addr() << ": " \ << (message) << " time: " \ << 1000 * (static_cast<double>(end - begin) / CLOCKS_PER_SEC) \ << "ms" << std::endl; // initialise static counters for status reports time_t SourcesToolService::startupTime = std::time(NULL); int64_t SourcesToolService::reqGetEntityCount = 0; int64_t SourcesToolService::reqGetRandomCount = 0; int64_t SourcesToolService::reqGetStatementCount = 0; int64_t SourcesToolService::reqUpdateStatementCount = 0; int64_t SourcesToolService::reqStatusCount = 0; // format a time_t using ISO8601 GMT time inline std::string formatGMT(time_t* time) { char result[128]; std::strftime(result, 128, "%Y-%m-%dT%H:%M:%SZ", gmtime(time)); return std::string(result); } // represent memory statistics (used for status) struct memstat { double rss, shared_mem, private_mem; }; // read memory statistics from /proc (used for status) inline memstat getMemStat() { int tSize = 0, resident = 0, share = 0; std::ifstream buffer("/proc/self/statm"); buffer >> tSize >> resident >> share; buffer.close(); struct memstat result; long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages result.rss = resident * page_size_kb; result.shared_mem = share * page_size_kb; result.private_mem = result.rss - result.shared_mem; return result; } // initialise service mappings from URLs to methods SourcesToolService::SourcesToolService(cppcms::service &srv) : cppcms::application(srv), backend(settings()["database"]) { dispatcher().assign("/entities/(Q\\d+)", &SourcesToolService::getEntityByQID, this, 1); mapper().assign("entity_by_qid", "/entities/{1}"); // map request to random entity selector dispatcher().assign("/entities/any", &SourcesToolService::getRandomEntity, this); mapper().assign("entity_by_topic_user", "/entities/any"); // map GET and POST requests to /entities/<QID> to the respective handlers // we use a helper function to distinguish both cases, since cppcms // currently does not really support REST dispatcher().assign("/statements/(\\d+)", &SourcesToolService::handleGetPostStatement, this, 1); mapper().assign("stmt_by_id", "/statements/{1}"); dispatcher().assign("/statements/any", &SourcesToolService::getRandomStatements, this); mapper().assign("stmt_by_random", "/statements/any"); dispatcher().assign("/import", &SourcesToolService::importStatements, this); mapper().assign("import", "/import"); dispatcher().assign("/delete", &SourcesToolService::deleteStatements, this); mapper().assign("delete", "/delete"); dispatcher().assign("/datasets/all", &SourcesToolService::getAllDatasets, this); mapper().assign("datasets_all", "/datasets/all"); dispatcher().assign("/status", &SourcesToolService::getStatus, this); mapper().assign("status", "/status"); dispatcher().assign("/dashboard/activitylog", &SourcesToolService::getActivityLog, this); mapper().assign("activitylog", "/dashboard/activitylog"); } void SourcesToolService::handleGetPostStatement(std::string stid) { if (request().request_method() == "POST") { approveStatement(std::stoll(stid)); } else { getStatement(std::stoll(stid)); } } void SourcesToolService::getEntityByQID(std::string qid) { clock_t begin = std::clock(); std::vector<Statement> statements = backend.getStatementsByQID(cache(), qid, true, request().get("dataset")); addCORSHeaders(); addVersionHeaders(); if (statements.size() > 0) { serializeStatements(statements); } else { response().status(404, "no statements found for entity "+qid); } reqGetEntityCount++; clock_t end = std::clock(); TIMING("GET /entities/" + qid, begin, end); } void SourcesToolService::getRandomEntity() { clock_t begin = std::clock(); addCORSHeaders(); addVersionHeaders(); try { std::vector<Statement> statements = backend.getStatementsByRandomQID(cache(), true, request().get("dataset")); serializeStatements(statements); } catch(PersistenceException const &e) { response().status(404, "no random unapproved entity found"); } reqGetRandomCount++; clock_t end = std::clock(); TIMING("GET /entities/any", begin, end); } void SourcesToolService::approveStatement(int64_t stid) { clock_t begin = std::clock(); ApprovalState state; addCORSHeaders(); addVersionHeaders(); // return 403 forbidden when there is no user given or the username is too // long for the database if (request().get("user") == "" || request().get("user").length() > 64) { response().status(403, "Forbidden: invalid or missing user"); return; } // check if statement exists and update it with new state try { backend.updateStatement(cache(), stid, stateFromString(request().get("state")), request().get("user")); } catch(PersistenceException const &e) { response().status(404, "Statement not found"); } catch(InvalidApprovalState const &e) { response().status(400, "Bad Request: invalid or missing state parameter"); } reqUpdateStatementCount++; clock_t end = std::clock(); TIMING("POST /statements/" + std::to_string(stid), begin, end); } void SourcesToolService::getStatement(int64_t stid) { clock_t begin = std::clock(); addCORSHeaders(); addVersionHeaders(); // query for statement, wrap it in a vector and return it try { std::vector<Statement> statements = { backend.getStatementByID(cache(), stid) }; serializeStatements(statements); } catch(PersistenceException const &e) { std::cerr << "error: " << e.what() << std::endl; response().status(404, "Statement not found"); } reqGetStatementCount++; clock_t end = std::clock(); TIMING("GET /statements/" + std::to_string(stid), begin, end); } void SourcesToolService::getRandomStatements() { clock_t begin = std::clock(); int count = 10; if (request().get("count") != "") { count = std::stoi(request().get("count")); } addCORSHeaders(); addVersionHeaders(); serializeStatements(backend.getRandomStatements(cache(), count, true)); clock_t end = std::clock(); TIMING("GET /statements/any", begin, end); } void SourcesToolService::getStatus() { clock_t begin = std::clock(); addCORSHeaders(); addVersionHeaders(); cppcms::json::value result; Status status = backend.getStatus(cache()); result["statements"]["total"] = status.getStatements(); result["statements"]["approved"] = status.getApproved(); result["statements"]["unapproved"] = status.getUnapproved(); result["statements"]["blacklisted"] = status.getBlacklisted(); result["statements"]["duplicate"] = status.getDuplicate(); result["statements"]["wrong"] = status.getWrong(); cppcms::json::array topusers; for (auto entry : status.getTopUsers()) { cppcms::json::value v; v["name"] = entry.first; v["activities"] = entry.second; topusers.push_back(v); } result["topusers"] = topusers; // system information result["system"]["startup"] = formatGMT(&SourcesToolService::startupTime); result["system"]["version"] = std::string(GIT_SHA1); result["system"]["cache_hits"] = backend.getCacheHits(); result["system"]["cache_misses"] = backend.getCacheMisses(); struct memstat meminfo = getMemStat(); result["system"]["shared_mem"] = meminfo.shared_mem; result["system"]["private_mem"] = meminfo.private_mem; result["system"]["rss"] = meminfo.rss; // request statistics result["requests"]["getentity"] = reqGetEntityCount; result["requests"]["getrandom"] = reqGetRandomCount; result["requests"]["getstatement"] = reqGetStatementCount; result["requests"]["updatestatement"] = reqUpdateStatementCount; result["requests"]["getstatus"] = reqStatusCount; response().content_type("application/json"); result.save(response().out(), cppcms::json::readable); reqStatusCount++; clock_t end = std::clock(); TIMING("GET /status", begin, end); } void SourcesToolService::serializeStatements(const std::vector<Statement> &statements) { if(request().http_accept() == "text/vnd.wikidata+tsv" || request().http_accept() == "text/tsv") { response().content_type("text/vnd.wikidata+tsv"); Serializer::writeTSV(statements.cbegin(), statements.cend(), &response().out()); } else if(request().http_accept() == "application/vnd.wikidata+json") { response().content_type("application/vnd.wikidata+json"); Serializer::writeWikidataJSON(statements.cbegin(), statements.cend(), &response().out()); } else { response().content_type("application/vnd.wikidata.envelope+json"); Serializer::writeEnvelopeJSON(statements.cbegin(), statements.cend(), &response().out()); } } void SourcesToolService::importStatements() { addVersionHeaders(); if (request().request_method() == "POST") { clock_t begin = std::clock(); // check if token matches if (request().get("token") != settings()["token"].str()) { response().status(401, "Invalid authorization token"); return; } std::string dataset = request().get("dataset"); if (dataset == "") { response().status(400, "Missing argument: dataset"); return; } // check if content is gzipped bool gzip = false; if (request().get("gzip") == "true") { gzip = true; } bool dedup = true; if (request().get("deduplicate") == "false") { dedup = false; } // wrap raw post data into a memory stream Membuf body(request().raw_post_data()); std::istream in(&body); // import statements int64_t count = backend.importStatements( cache(), in, dataset, gzip, dedup); clock_t end = std::clock(); cppcms::json::value result; result["count"] = count; result["time"] = 1000 * (static_cast<double>(end - begin) / CLOCKS_PER_SEC); result["dataset"] = dataset; response().content_type("application/json"); result.save(response().out(), cppcms::json::readable); TIMING("POST /import", begin, end); } else { response().status(405, "Method not allowed"); response().set_header("Allow", "POST"); } } void SourcesToolService::getAllDatasets() { addCORSHeaders(); addVersionHeaders(); std::vector<std::string> datasets = backend.getDatasets(cache()); cppcms::json::value result; for(std::string id : datasets) { result[id]["id"] = id; } response().content_type("application/json"); result.save(response().out(), cppcms::json::readable); } void SourcesToolService::deleteStatements() { addVersionHeaders(); if (request().request_method() == "POST") { // check if token matches if (request().get("token") != settings()["token"].str()) { response().status(401, "Invalid authorization token"); return; } clock_t begin = std::clock(); // check if statement exists and update it with new state try { backend.deleteStatements(cache(), stateFromString(request().get("state"))); } catch(PersistenceException const &e) { response().status(404, "Could not delete statements"); } catch(InvalidApprovalState const &e) { response().status(400, "Bad Request: invalid or missing state parameter"); } clock_t end = std::clock(); TIMING("POST /delete", begin, end); } else { response().status(405, "Method not allowed"); response().set_header("Allow", "POST"); } } void SourcesToolService::addCORSHeaders() { response().set_header("Access-Control-Allow-Origin", "*"); } void SourcesToolService::addVersionHeaders() { response().set_header("X-Powered-By", std::string("Wikidata Sources Tool/") + GIT_SHA1); } void SourcesToolService::getActivityLog() { clock_t begin = std::clock(); addCORSHeaders(); addVersionHeaders(); cppcms::json::value result; Dashboard::ActivityLog activities = backend.getActivityLog(cache()); std::vector<std::string> users(activities.getUsers().begin(), activities.getUsers().end()); result["users"] = users; for(int i=0; i< activities.getActivities().size(); i++) { Dashboard::ActivityEntry entry = activities.getActivities()[i]; if (entry.date != "") { result["approved"][i][0] = entry.date; for (int j = 0; j < users.size(); j++) { if (entry.approved.find(users[j]) != entry.approved.end()) { result["approved"][i][j + 1] = entry.approved[users[j]]; } else { result["approved"][i][j + 1] = 0; } } result["rejected"][i][0] = entry.date; for (int j = 0; j < users.size(); j++) { if (entry.rejected.find(users[j]) != entry.rejected.end()) { result["rejected"][i][j + 1] = entry.rejected[users[j]]; } else { result["rejected"][i][j + 1] = 0; } } } } response().content_type("application/json"); result.save(response().out(), cppcms::json::readable); reqStatusCount++; clock_t end = std::clock(); TIMING("GET /dashboard/activitylog", begin, end); } <|endoftext|>
<commit_before> #include "config.h" #include "ambdec.h" #include <cstring> #include <cctype> #include <limits> #include <string> #include <fstream> #include <sstream> #include "compat.h" namespace { int readline(std::istream &f, std::string &output) { while(f.good() && f.peek() == '\n') f.ignore(); std::getline(f, output); return !output.empty(); } bool read_clipped_line(std::istream &f, std::string &buffer) { while(readline(f, buffer)) { std::size_t pos{0}; while(pos < buffer.length() && std::isspace(buffer[pos])) pos++; buffer.erase(0, pos); std::size_t cmtpos{buffer.find_first_of('#')}; if(cmtpos < buffer.length()) buffer.resize(cmtpos); while(!buffer.empty() && std::isspace(buffer.back())) buffer.pop_back(); if(!buffer.empty()) return true; } return false; } std::string read_word(std::istream &f) { std::string ret; f >> ret; return ret; } bool is_at_end(const std::string &buffer, std::size_t endpos) { while(endpos < buffer.length() && std::isspace(buffer[endpos])) ++endpos; if(endpos < buffer.length()) return false; return true; } bool load_ambdec_speakers(AmbDecConf *conf, std::istream &f, std::string &buffer) { ALsizei cur = 0; while(cur < conf->NumSpeakers) { std::istringstream istr{buffer}; std::string cmd = read_word(istr); if(cmd.empty()) { if(!read_clipped_line(f, buffer)) { ERR("Unexpected end of file\n"); return false; } istr = std::istringstream{buffer}; cmd = read_word(istr); } if(cmd == "add_spkr") { istr >> conf->Speakers[cur].Name; if(istr.fail()) WARN("Name not specified for speaker %u\n", cur+1); istr >> conf->Speakers[cur].Distance; if(istr.fail()) WARN("Distance not specified for speaker %u\n", cur+1); istr >> conf->Speakers[cur].Azimuth; if(istr.fail()) WARN("Azimuth not specified for speaker %u\n", cur+1); istr >> conf->Speakers[cur].Elevation; if(istr.fail()) WARN("Elevation not specified for speaker %u\n", cur+1); istr >> conf->Speakers[cur].Connection; if(istr.fail()) TRACE("Connection not specified for speaker %u\n", cur+1); cur++; } else { ERR("Unexpected speakers command: %s\n", cmd.c_str()); return false; } istr.clear(); std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return false; } buffer.clear(); } return true; } bool load_ambdec_matrix(ALfloat *gains, ALfloat (*matrix)[MAX_AMBI_COEFFS], ALsizei maxrow, std::istream &f, std::string &buffer) { bool gotgains = false; ALsizei cur = 0; while(cur < maxrow) { std::istringstream istr{buffer}; std::string cmd; istr >> cmd; if(cmd.empty()) { if(!read_clipped_line(f, buffer)) { ERR("Unexpected end of file\n"); return false; } istr = std::istringstream{buffer}; istr >> cmd; } if(cmd == "order_gain") { ALuint curgain = 0; float value; while(istr.good()) { istr >> value; if(istr.fail()) break; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk on gain %u: %s\n", curgain+1, buffer.c_str()+istr.tellg()); return false; } if(curgain < MAX_AMBI_ORDER+1) gains[curgain++] = value; } while(curgain < MAX_AMBI_ORDER+1) gains[curgain++] = 0.0f; gotgains = true; } else if(cmd == "add_row") { ALuint curidx = 0; float value; while(istr.good()) { istr >> value; if(istr.fail()) break; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk on matrix element %ux%u: %s\n", cur, curidx, buffer.c_str()+istr.tellg()); return false; } if(curidx < MAX_AMBI_COEFFS) matrix[cur][curidx++] = value; } while(curidx < MAX_AMBI_COEFFS) matrix[cur][curidx++] = 0.0f; cur++; } else { ERR("Unexpected matrix command: %s\n", cmd.c_str()); return false; } istr.clear(); std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return false; } buffer.clear(); } if(!gotgains) { ERR("Matrix order_gain not specified\n"); return false; } return true; } } // namespace int AmbDecConf::load(const char *fname) { al::ifstream f{fname}; if(!f.is_open()) { ERR("Failed to open: %s\n", fname); return 0; } std::string buffer; while(read_clipped_line(f, buffer)) { std::istringstream istr{buffer}; std::string command; istr >> command; if(command.empty()) { ERR("Malformed line: %s\n", buffer.c_str()); return 0; } if(command == "/description") istr >> Description; else if(command == "/version") { istr >> Version; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after version: %s\n", buffer.c_str()+istr.tellg()); return 0; } if(Version != 3) { ERR("Unsupported version: %u\n", Version); return 0; } } else if(command == "/dec/chan_mask") { istr >> std::hex >> ChanMask >> std::dec; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after mask: %s\n", buffer.c_str()+istr.tellg()); return 0; } } else if(command == "/dec/freq_bands") { istr >> FreqBands; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after freq_bands: %s\n", buffer.c_str()+istr.tellg()); return 0; } if(FreqBands != 1 && FreqBands != 2) { ERR("Invalid freq_bands value: %u\n", FreqBands); return 0; } } else if(command == "/dec/speakers") { istr >> NumSpeakers; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after speakers: %s\n", buffer.c_str()+istr.tellg()); return 0; } if(NumSpeakers > MAX_OUTPUT_CHANNELS) { ERR("Unsupported speaker count: %u\n", NumSpeakers); return 0; } } else if(command == "/dec/coeff_scale") { std::string scale = read_word(istr); if(scale == "n3d") CoeffScale = AmbDecScale::N3D; else if(scale == "sn3d") CoeffScale = AmbDecScale::SN3D; else if(scale == "fuma") CoeffScale = AmbDecScale::FuMa; else { ERR("Unsupported coeff scale: %s\n", scale.c_str()); return 0; } } else if(command == "/opt/xover_freq") { istr >> XOverFreq; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after xover_freq: %s\n", buffer.c_str()+istr.tellg()); return 0; } } else if(command == "/opt/xover_ratio") { istr >> XOverRatio; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after xover_ratio: %s\n", buffer.c_str()+istr.tellg()); return 0; } } else if(command == "/opt/input_scale" || command == "/opt/nfeff_comp" || command == "/opt/delay_comp" || command == "/opt/level_comp") { /* Unused */ read_word(istr); } else if(command == "/speakers/{") { std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return 0; } buffer.clear(); if(!load_ambdec_speakers(this, f, buffer)) return 0; if(!read_clipped_line(f, buffer)) { ERR("Unexpected end of file\n"); return 0; } istr = std::istringstream{buffer}; std::string endmark = read_word(istr); if(endmark != "/}") { ERR("Expected /} after speaker definitions, got %s\n", endmark.c_str()); return 0; } } else if(command == "/lfmatrix/{" || command == "/hfmatrix/{" || command == "/matrix/{") { std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return 0; } buffer.clear(); if(FreqBands == 1) { if(command != "/matrix/{") { ERR("Unexpected \"%s\" type for a single-band decoder\n", command.c_str()); return 0; } if(!load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer)) return 0; } else { if(command == "/lfmatrix/{") { if(!load_ambdec_matrix(LFOrderGain, LFMatrix, NumSpeakers, f, buffer)) return 0; } else if(command == "/hfmatrix/{") { if(!load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer)) return 0; } else { ERR("Unexpected \"%s\" type for a dual-band decoder\n", command.c_str()); return 0; } } if(!read_clipped_line(f, buffer)) { ERR("Unexpected end of file\n"); return 0; } istr = std::istringstream{buffer}; std::string endmark = read_word(istr); if(endmark != "/}") { ERR("Expected /} after matrix definitions, got %s\n", endmark.c_str()); return 0; } } else if(command == "/end") { std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on end: %s\n", buffer.c_str()+endpos); return 0; } return 1; } else { ERR("Unexpected command: %s\n", command.c_str()); return 0; } istr.clear(); std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return 0; } buffer.clear(); } ERR("Unexpected end of file\n"); return 0; } <commit_msg>Avoid moving istringstreams<commit_after> #include "config.h" #include "ambdec.h" #include <cstring> #include <cctype> #include <limits> #include <string> #include <fstream> #include <sstream> #include "compat.h" namespace { int readline(std::istream &f, std::string &output) { while(f.good() && f.peek() == '\n') f.ignore(); std::getline(f, output); return !output.empty(); } bool read_clipped_line(std::istream &f, std::string &buffer) { while(readline(f, buffer)) { std::size_t pos{0}; while(pos < buffer.length() && std::isspace(buffer[pos])) pos++; buffer.erase(0, pos); std::size_t cmtpos{buffer.find_first_of('#')}; if(cmtpos < buffer.length()) buffer.resize(cmtpos); while(!buffer.empty() && std::isspace(buffer.back())) buffer.pop_back(); if(!buffer.empty()) return true; } return false; } std::string read_word(std::istream &f) { std::string ret; f >> ret; return ret; } bool is_at_end(const std::string &buffer, std::size_t endpos) { while(endpos < buffer.length() && std::isspace(buffer[endpos])) ++endpos; if(endpos < buffer.length()) return false; return true; } bool load_ambdec_speakers(AmbDecConf *conf, std::istream &f, std::string &buffer) { ALsizei cur = 0; while(cur < conf->NumSpeakers) { std::istringstream istr{buffer}; std::string cmd{read_word(istr)}; if(cmd.empty()) { if(!read_clipped_line(f, buffer)) { ERR("Unexpected end of file\n"); return false; } continue; } if(cmd == "add_spkr") { istr >> conf->Speakers[cur].Name; if(istr.fail()) WARN("Name not specified for speaker %u\n", cur+1); istr >> conf->Speakers[cur].Distance; if(istr.fail()) WARN("Distance not specified for speaker %u\n", cur+1); istr >> conf->Speakers[cur].Azimuth; if(istr.fail()) WARN("Azimuth not specified for speaker %u\n", cur+1); istr >> conf->Speakers[cur].Elevation; if(istr.fail()) WARN("Elevation not specified for speaker %u\n", cur+1); istr >> conf->Speakers[cur].Connection; if(istr.fail()) TRACE("Connection not specified for speaker %u\n", cur+1); cur++; } else { ERR("Unexpected speakers command: %s\n", cmd.c_str()); return false; } istr.clear(); std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return false; } buffer.clear(); } return true; } bool load_ambdec_matrix(ALfloat *gains, ALfloat (*matrix)[MAX_AMBI_COEFFS], ALsizei maxrow, std::istream &f, std::string &buffer) { bool gotgains = false; ALsizei cur = 0; while(cur < maxrow) { std::istringstream istr{buffer}; std::string cmd{read_word(istr)}; if(cmd.empty()) { if(!read_clipped_line(f, buffer)) { ERR("Unexpected end of file\n"); return false; } continue; } if(cmd == "order_gain") { ALuint curgain = 0; float value; while(istr.good()) { istr >> value; if(istr.fail()) break; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk on gain %u: %s\n", curgain+1, buffer.c_str()+istr.tellg()); return false; } if(curgain < MAX_AMBI_ORDER+1) gains[curgain++] = value; } while(curgain < MAX_AMBI_ORDER+1) gains[curgain++] = 0.0f; gotgains = true; } else if(cmd == "add_row") { ALuint curidx = 0; float value; while(istr.good()) { istr >> value; if(istr.fail()) break; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk on matrix element %ux%u: %s\n", cur, curidx, buffer.c_str()+istr.tellg()); return false; } if(curidx < MAX_AMBI_COEFFS) matrix[cur][curidx++] = value; } while(curidx < MAX_AMBI_COEFFS) matrix[cur][curidx++] = 0.0f; cur++; } else { ERR("Unexpected matrix command: %s\n", cmd.c_str()); return false; } istr.clear(); std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return false; } buffer.clear(); } if(!gotgains) { ERR("Matrix order_gain not specified\n"); return false; } return true; } } // namespace int AmbDecConf::load(const char *fname) { al::ifstream f{fname}; if(!f.is_open()) { ERR("Failed to open: %s\n", fname); return 0; } std::string buffer; while(read_clipped_line(f, buffer)) { std::istringstream istr{buffer}; std::string command{read_word(istr)}; if(command.empty()) { ERR("Malformed line: %s\n", buffer.c_str()); return 0; } if(command == "/description") istr >> Description; else if(command == "/version") { istr >> Version; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after version: %s\n", buffer.c_str()+istr.tellg()); return 0; } if(Version != 3) { ERR("Unsupported version: %u\n", Version); return 0; } } else if(command == "/dec/chan_mask") { istr >> std::hex >> ChanMask >> std::dec; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after mask: %s\n", buffer.c_str()+istr.tellg()); return 0; } } else if(command == "/dec/freq_bands") { istr >> FreqBands; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after freq_bands: %s\n", buffer.c_str()+istr.tellg()); return 0; } if(FreqBands != 1 && FreqBands != 2) { ERR("Invalid freq_bands value: %u\n", FreqBands); return 0; } } else if(command == "/dec/speakers") { istr >> NumSpeakers; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after speakers: %s\n", buffer.c_str()+istr.tellg()); return 0; } if(NumSpeakers > MAX_OUTPUT_CHANNELS) { ERR("Unsupported speaker count: %u\n", NumSpeakers); return 0; } } else if(command == "/dec/coeff_scale") { std::string scale = read_word(istr); if(scale == "n3d") CoeffScale = AmbDecScale::N3D; else if(scale == "sn3d") CoeffScale = AmbDecScale::SN3D; else if(scale == "fuma") CoeffScale = AmbDecScale::FuMa; else { ERR("Unsupported coeff scale: %s\n", scale.c_str()); return 0; } } else if(command == "/opt/xover_freq") { istr >> XOverFreq; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after xover_freq: %s\n", buffer.c_str()+istr.tellg()); return 0; } } else if(command == "/opt/xover_ratio") { istr >> XOverRatio; if(!istr.eof() && !std::isspace(istr.peek())) { ERR("Extra junk after xover_ratio: %s\n", buffer.c_str()+istr.tellg()); return 0; } } else if(command == "/opt/input_scale" || command == "/opt/nfeff_comp" || command == "/opt/delay_comp" || command == "/opt/level_comp") { /* Unused */ read_word(istr); } else if(command == "/speakers/{") { std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return 0; } buffer.clear(); if(!load_ambdec_speakers(this, f, buffer)) return 0; if(!read_clipped_line(f, buffer)) { ERR("Unexpected end of file\n"); return 0; } std::istringstream istr2{buffer}; std::string endmark{read_word(istr2)}; if(endmark != "/}") { ERR("Expected /} after speaker definitions, got %s\n", endmark.c_str()); return 0; } istr.swap(istr2); } else if(command == "/lfmatrix/{" || command == "/hfmatrix/{" || command == "/matrix/{") { std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return 0; } buffer.clear(); if(FreqBands == 1) { if(command != "/matrix/{") { ERR("Unexpected \"%s\" type for a single-band decoder\n", command.c_str()); return 0; } if(!load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer)) return 0; } else { if(command == "/lfmatrix/{") { if(!load_ambdec_matrix(LFOrderGain, LFMatrix, NumSpeakers, f, buffer)) return 0; } else if(command == "/hfmatrix/{") { if(!load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer)) return 0; } else { ERR("Unexpected \"%s\" type for a dual-band decoder\n", command.c_str()); return 0; } } if(!read_clipped_line(f, buffer)) { ERR("Unexpected end of file\n"); return 0; } std::istringstream istr2{buffer}; std::string endmark{read_word(istr2)}; if(endmark != "/}") { ERR("Expected /} after matrix definitions, got %s\n", endmark.c_str()); return 0; } istr.swap(istr2); } else if(command == "/end") { std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on end: %s\n", buffer.c_str()+endpos); return 0; } return 1; } else { ERR("Unexpected command: %s\n", command.c_str()); return 0; } istr.clear(); std::streamsize endpos{istr.tellg()}; if(!is_at_end(buffer, endpos)) { ERR("Unexpected junk on line: %s\n", buffer.c_str()+endpos); return 0; } buffer.clear(); } ERR("Unexpected end of file\n"); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/account_screen.h" #include "chrome/browser/chromeos/login/eula_view.h" #include "chrome/browser/chromeos/login/language_switch_menu.h" #include "chrome/browser/chromeos/login/login_screen.h" #include "chrome/browser/chromeos/login/mock_update_screen.h" #include "chrome/browser/chromeos/login/network_screen.h" #include "chrome/browser/chromeos/login/network_selection_view.h" #include "chrome/browser/chromeos/login/user_image_screen.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/test/ui_test_utils.h" #include "grit/generated_resources.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "unicode/locid.h" #include "views/accelerator.h" namespace { template <class T> class MockOutShowHide : public T { public: template <class P> MockOutShowHide(P p) : T(p) {} template <class P1, class P2> MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {} MOCK_METHOD0(Show, void()); MOCK_METHOD0(Hide, void()); }; template <class T> struct CreateMockWizardScreenHelper { static MockOutShowHide<T>* Create(WizardController* wizard); }; template <class T> MockOutShowHide<T>* CreateMockWizardScreenHelper<T>::Create(WizardController* wizard) { return new MockOutShowHide<T>(wizard); } template <> MockOutShowHide<chromeos::NetworkScreen>* CreateMockWizardScreenHelper<chromeos::NetworkScreen>::Create( WizardController* wizard) { return new MockOutShowHide<chromeos::NetworkScreen>(wizard); } #define MOCK(mock_var, screen_name, mocked_class) \ mock_var = CreateMockWizardScreenHelper<mocked_class>::Create(controller()); \ controller()->screen_name.reset(mock_var); \ EXPECT_CALL(*mock_var, Show()).Times(0); \ EXPECT_CALL(*mock_var, Hide()).Times(0); } // namespace class WizardControllerTest : public chromeos::WizardInProcessBrowserTest { protected: WizardControllerTest() : chromeos::WizardInProcessBrowserTest( WizardController::kTestNoScreenName) {} virtual ~WizardControllerTest() {} private: DISALLOW_COPY_AND_ASSIGN(WizardControllerTest); }; IN_PROC_BROWSER_TEST_F(WizardControllerTest, SwitchLanguage) { WizardController* const wizard = controller(); ASSERT_TRUE(wizard != NULL); wizard->ShowFirstScreen(WizardController::kNetworkScreenName); views::View* current_screen = wizard->contents(); ASSERT_TRUE(current_screen != NULL); // Checking the default locale. Provided that the profile is cleared in SetUp. EXPECT_EQ("en-US", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("en", icu::Locale::getDefault().getLanguage()); EXPECT_FALSE(base::i18n::IsRTL()); const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); chromeos::LanguageSwitchMenu::SwitchLanguage("fr"); EXPECT_EQ("fr", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("fr", icu::Locale::getDefault().getLanguage()); EXPECT_FALSE(base::i18n::IsRTL()); const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); EXPECT_NE(en_str, fr_str); chromeos::LanguageSwitchMenu::SwitchLanguage("ar"); EXPECT_EQ("ar", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("ar", icu::Locale::getDefault().getLanguage()); EXPECT_TRUE(base::i18n::IsRTL()); const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); EXPECT_NE(fr_str, ar_str); } class WizardControllerFlowTest : public WizardControllerTest { protected: WizardControllerFlowTest() {} // Overriden from InProcessBrowserTest: virtual Browser* CreateBrowser(Profile* profile) { Browser* ret = WizardControllerTest::CreateBrowser(profile); // Make sure that OOBE is run as an "official" build. WizardController::default_controller()->is_official_build_ = true; // Set up the mocks for all screens. MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen); MOCK(mock_login_screen_, login_screen_, chromeos::LoginScreen); MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen); MOCK(mock_update_screen_, update_screen_, MockUpdateScreen); MOCK(mock_eula_screen_, eula_screen_, chromeos::EulaScreen); // Switch to the initial screen. EXPECT_EQ(NULL, controller()->current_screen()); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); controller()->ShowFirstScreen(WizardController::kNetworkScreenName); return ret; } MockOutShowHide<chromeos::AccountScreen>* mock_account_screen_; MockOutShowHide<chromeos::LoginScreen>* mock_login_screen_; MockOutShowHide<chromeos::NetworkScreen>* mock_network_screen_; MockOutShowHide<MockUpdateScreen>* mock_update_screen_; MockOutShowHide<chromeos::EulaScreen>* mock_eula_screen_; private: DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest); }; IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); EXPECT_CALL(*mock_eula_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen()); EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::EULA_ACCEPTED); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_CALL(*mock_eula_screen_, Show()).Times(0); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); EXPECT_CALL(*mock_login_screen_, Hide()).Times(1); EXPECT_CALL(*mock_account_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT); EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen()); EXPECT_CALL(*mock_account_screen_, Hide()).Times(1); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_CALL(*mock_login_screen_, Hide()).Times(0); // last transition controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(0); EXPECT_CALL(*mock_eula_screen_, Show()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(0); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen()); EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::EULA_ACCEPTED); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_CALL(*mock_eula_screen_, Show()).Times(0); EXPECT_CALL(*mock_eula_screen_, Hide()).Times(0); // last transition EXPECT_CALL(*mock_login_screen_, Show()).Times(1); controller()->OnExit( chromeos::ScreenObserver::UPDATE_ERROR_UPDATING); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowEulaDeclined) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(0); EXPECT_CALL(*mock_eula_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen()); EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(0); // last transition controller()->OnExit(chromeos::ScreenObserver::EULA_BACK); EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } #if defined(OFFICIAL_BUILD) // This test is supposed to fail on official test. #define MAYBE_Accelerators DISABLED_Accelerators #else #define MAYBE_Accelerators Accelerators #endif IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, MAYBE_Accelerators) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); views::FocusManager* focus_manager = controller()->contents()->GetFocusManager(); views::Accelerator accel_account_screen(app::VKEY_A, false, true, true); views::Accelerator accel_login_screen(app::VKEY_L, false, true, true); views::Accelerator accel_network_screen(app::VKEY_N, false, true, true); views::Accelerator accel_update_screen(app::VKEY_U, false, true, true); views::Accelerator accel_image_screen(app::VKEY_I, false, true, true); views::Accelerator accel_eula_screen(app::VKEY_E, false, true, true); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); EXPECT_CALL(*mock_account_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_account_screen)); EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_account_screen_, Hide()).Times(1); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_login_screen)); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_login_screen_, Hide()).Times(1); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_network_screen)); EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_update_screen)); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_image_screen)); EXPECT_EQ(controller()->GetUserImageScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_eula_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_eula_screen)); EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen()); } COMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 18, add_tests_for_new_control_flow_you_just_introduced); <commit_msg>Mark failing unittest to FAILS.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/login/account_screen.h" #include "chrome/browser/chromeos/login/eula_view.h" #include "chrome/browser/chromeos/login/language_switch_menu.h" #include "chrome/browser/chromeos/login/login_screen.h" #include "chrome/browser/chromeos/login/mock_update_screen.h" #include "chrome/browser/chromeos/login/network_screen.h" #include "chrome/browser/chromeos/login/network_selection_view.h" #include "chrome/browser/chromeos/login/user_image_screen.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/test/ui_test_utils.h" #include "grit/generated_resources.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "unicode/locid.h" #include "views/accelerator.h" namespace { template <class T> class MockOutShowHide : public T { public: template <class P> MockOutShowHide(P p) : T(p) {} template <class P1, class P2> MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {} MOCK_METHOD0(Show, void()); MOCK_METHOD0(Hide, void()); }; template <class T> struct CreateMockWizardScreenHelper { static MockOutShowHide<T>* Create(WizardController* wizard); }; template <class T> MockOutShowHide<T>* CreateMockWizardScreenHelper<T>::Create(WizardController* wizard) { return new MockOutShowHide<T>(wizard); } template <> MockOutShowHide<chromeos::NetworkScreen>* CreateMockWizardScreenHelper<chromeos::NetworkScreen>::Create( WizardController* wizard) { return new MockOutShowHide<chromeos::NetworkScreen>(wizard); } #define MOCK(mock_var, screen_name, mocked_class) \ mock_var = CreateMockWizardScreenHelper<mocked_class>::Create(controller()); \ controller()->screen_name.reset(mock_var); \ EXPECT_CALL(*mock_var, Show()).Times(0); \ EXPECT_CALL(*mock_var, Hide()).Times(0); } // namespace class WizardControllerTest : public chromeos::WizardInProcessBrowserTest { protected: WizardControllerTest() : chromeos::WizardInProcessBrowserTest( WizardController::kTestNoScreenName) {} virtual ~WizardControllerTest() {} private: DISALLOW_COPY_AND_ASSIGN(WizardControllerTest); }; // TODO(zelidrag): Need to revisit this once translation for fr and ar is // complete. See http://crosbug.com/8974 IN_PROC_BROWSER_TEST_F(WizardControllerTest, FAILS_SwitchLanguage) { WizardController* const wizard = controller(); ASSERT_TRUE(wizard != NULL); wizard->ShowFirstScreen(WizardController::kNetworkScreenName); views::View* current_screen = wizard->contents(); ASSERT_TRUE(current_screen != NULL); // Checking the default locale. Provided that the profile is cleared in SetUp. EXPECT_EQ("en-US", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("en", icu::Locale::getDefault().getLanguage()); EXPECT_FALSE(base::i18n::IsRTL()); const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); chromeos::LanguageSwitchMenu::SwitchLanguage("fr"); EXPECT_EQ("fr", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("fr", icu::Locale::getDefault().getLanguage()); EXPECT_FALSE(base::i18n::IsRTL()); const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); EXPECT_NE(en_str, fr_str); chromeos::LanguageSwitchMenu::SwitchLanguage("ar"); EXPECT_EQ("ar", g_browser_process->GetApplicationLocale()); EXPECT_STREQ("ar", icu::Locale::getDefault().getLanguage()); EXPECT_TRUE(base::i18n::IsRTL()); const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE); EXPECT_NE(fr_str, ar_str); } class WizardControllerFlowTest : public WizardControllerTest { protected: WizardControllerFlowTest() {} // Overriden from InProcessBrowserTest: virtual Browser* CreateBrowser(Profile* profile) { Browser* ret = WizardControllerTest::CreateBrowser(profile); // Make sure that OOBE is run as an "official" build. WizardController::default_controller()->is_official_build_ = true; // Set up the mocks for all screens. MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen); MOCK(mock_login_screen_, login_screen_, chromeos::LoginScreen); MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen); MOCK(mock_update_screen_, update_screen_, MockUpdateScreen); MOCK(mock_eula_screen_, eula_screen_, chromeos::EulaScreen); // Switch to the initial screen. EXPECT_EQ(NULL, controller()->current_screen()); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); controller()->ShowFirstScreen(WizardController::kNetworkScreenName); return ret; } MockOutShowHide<chromeos::AccountScreen>* mock_account_screen_; MockOutShowHide<chromeos::LoginScreen>* mock_login_screen_; MockOutShowHide<chromeos::NetworkScreen>* mock_network_screen_; MockOutShowHide<MockUpdateScreen>* mock_update_screen_; MockOutShowHide<chromeos::EulaScreen>* mock_eula_screen_; private: DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest); }; IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); EXPECT_CALL(*mock_eula_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen()); EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::EULA_ACCEPTED); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_CALL(*mock_eula_screen_, Show()).Times(0); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); EXPECT_CALL(*mock_login_screen_, Hide()).Times(1); EXPECT_CALL(*mock_account_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT); EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen()); EXPECT_CALL(*mock_account_screen_, Hide()).Times(1); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_CALL(*mock_login_screen_, Hide()).Times(0); // last transition controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(0); EXPECT_CALL(*mock_eula_screen_, Show()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(0); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen()); EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); controller()->OnExit(chromeos::ScreenObserver::EULA_ACCEPTED); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_CALL(*mock_eula_screen_, Show()).Times(0); EXPECT_CALL(*mock_eula_screen_, Hide()).Times(0); // last transition EXPECT_CALL(*mock_login_screen_, Show()).Times(1); controller()->OnExit( chromeos::ScreenObserver::UPDATE_ERROR_UPDATING); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowEulaDeclined) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(0); EXPECT_CALL(*mock_eula_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED); EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen()); EXPECT_CALL(*mock_eula_screen_, Hide()).Times(1); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(0); // last transition controller()->OnExit(chromeos::ScreenObserver::EULA_BACK); EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); } IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); } #if defined(OFFICIAL_BUILD) // This test is supposed to fail on official test. #define MAYBE_Accelerators DISABLED_Accelerators #else #define MAYBE_Accelerators Accelerators #endif IN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, MAYBE_Accelerators) { EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); views::FocusManager* focus_manager = controller()->contents()->GetFocusManager(); views::Accelerator accel_account_screen(app::VKEY_A, false, true, true); views::Accelerator accel_login_screen(app::VKEY_L, false, true, true); views::Accelerator accel_network_screen(app::VKEY_N, false, true, true); views::Accelerator accel_update_screen(app::VKEY_U, false, true, true); views::Accelerator accel_image_screen(app::VKEY_I, false, true, true); views::Accelerator accel_eula_screen(app::VKEY_E, false, true, true); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); EXPECT_CALL(*mock_account_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_account_screen)); EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_account_screen_, Hide()).Times(1); EXPECT_CALL(*mock_login_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_login_screen)); EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_login_screen_, Hide()).Times(1); EXPECT_CALL(*mock_network_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_network_screen)); EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_network_screen_, Hide()).Times(1); EXPECT_CALL(*mock_update_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_update_screen)); EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_update_screen_, Hide()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_image_screen)); EXPECT_EQ(controller()->GetUserImageScreen(), controller()->current_screen()); focus_manager = controller()->contents()->GetFocusManager(); EXPECT_CALL(*mock_eula_screen_, Show()).Times(1); EXPECT_TRUE(focus_manager->ProcessAccelerator(accel_eula_screen)); EXPECT_EQ(controller()->GetEulaScreen(), controller()->current_screen()); } COMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 18, add_tests_for_new_control_flow_you_just_introduced); <|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 "base/process_util.h" #include "base/sys_string_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/omnibox/location_bar.h" #include "chrome/browser/ui/omnibox/omnibox_view.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "extensions/common/constants.h" #include "googleurl/src/gurl.h" using content::NavigationEntry; class ExtensionURLRewriteBrowserTest : public ExtensionBrowserTest { public: virtual void SetUp() OVERRIDE { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ExtensionBrowserTest::SetUp(); } protected: std::string GetLocationBarText() const { return UTF16ToUTF8( browser()->window()->GetLocationBar()->GetLocationEntry()->GetText()); } GURL GetLocationBarTextAsURL() const { return GURL(GetLocationBarText()); } content::NavigationController* GetNavigationController() const { return &browser()->tab_strip_model()->GetActiveWebContents()-> GetController(); } NavigationEntry* GetNavigationEntry() const { return GetNavigationController()->GetActiveEntry(); } base::FilePath GetTestExtensionPath(const char* extension_name) const { return test_data_dir_.AppendASCII("browsertest/url_rewrite/"). AppendASCII(extension_name); } // Navigates to |url| and tests that the location bar and the |virtual_url| // correspond to |url|, while the real URL of the navigation entry uses the // chrome-extension:// scheme. void TestExtensionURLOverride(const GURL& url) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ(url, GetLocationBarTextAsURL()); EXPECT_EQ(url, GetNavigationEntry()->GetVirtualURL()); EXPECT_TRUE( GetNavigationEntry()->GetURL().SchemeIs(extensions::kExtensionScheme)); } // Navigates to |url| and tests that the location bar is empty while the // |virtual_url| is the same as |url|. void TestURLNotShown(const GURL& url) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ("", GetLocationBarText()); EXPECT_EQ(url, GetNavigationEntry()->GetVirtualURL()); } }; IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, NewTabPageURL) { // Navigate to chrome://newtab and check that the location bar text is blank. GURL url(chrome::kChromeUINewTabURL); TestURLNotShown(url); // Check that the actual URL corresponds to chrome://newtab. EXPECT_EQ(url, GetNavigationEntry()->GetURL()); } IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, NewTabPageURLOverride) { // Load an extension to override the NTP and check that the location bar text // is blank after navigating to chrome://newtab. LoadExtension(GetTestExtensionPath("newtab")); TestURLNotShown(GURL(chrome::kChromeUINewTabURL)); // Check that the internal URL uses the chrome-extension:// scheme. EXPECT_TRUE(GetNavigationEntry()->GetURL().SchemeIs( extensions::kExtensionScheme)); } // TODO(linux_aura) http://crbug.com/163931 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA) #define MAYBE_BookmarksURL DISABLED_BookmarksURL #else #define MAYBE_BookmarksURL BookmarksURL #endif IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, MAYBE_BookmarksURL) { // Navigate to chrome://bookmarks and check that the location bar URL is // what was entered and the internal URL uses the chrome-extension:// scheme. TestExtensionURLOverride(GURL(chrome::kChromeUIBookmarksURL)); } #if defined(FILE_MANAGER_EXTENSION) IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, FileManagerURL) { // Navigate to chrome://files and check that the location bar URL is // what was entered and the internal URL uses the chrome-extension:// scheme. TestExtensionURLOverride(GURL(chrome::kChromeUIFileManagerURL)); } #endif IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURLWithRef) { // Navigate to chrome://bookmarks/#1 and check that the location bar URL is // what was entered and the internal URL uses the chrome-extension:// scheme. GURL url_with_ref(chrome::kChromeUIBookmarksURL + std::string("#1")); TestExtensionURLOverride(url_with_ref); } // Disabled for flakiness: crbug.com/176332 IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, DISABLED_BookmarksURLOverride) { // Load an extension that overrides chrome://bookmarks. LoadExtension(GetTestExtensionPath("bookmarks")); // Navigate to chrome://bookmarks and check that the location bar URL is what // was entered and the internal URL uses the chrome-extension:// scheme. TestExtensionURLOverride(GURL(chrome::kChromeUIBookmarksURL)); } <commit_msg>Attempt to fix flakyness of ExtensionURLRewriteBrowserTest.BookmarksURL.<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 "base/process_util.h" #include "base/sys_string_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/omnibox/location_bar.h" #include "chrome/browser/ui/omnibox/omnibox_view.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "extensions/common/constants.h" #include "googleurl/src/gurl.h" using content::NavigationEntry; class ExtensionURLRewriteBrowserTest : public ExtensionBrowserTest { public: virtual void SetUp() OVERRIDE { extensions::ComponentLoader::EnableBackgroundExtensionsForTesting(); ExtensionBrowserTest::SetUp(); } protected: std::string GetLocationBarText() const { return UTF16ToUTF8( browser()->window()->GetLocationBar()->GetLocationEntry()->GetText()); } GURL GetLocationBarTextAsURL() const { return GURL(GetLocationBarText()); } content::NavigationController* GetNavigationController() const { return &browser()->tab_strip_model()->GetActiveWebContents()-> GetController(); } NavigationEntry* GetNavigationEntry() const { return GetNavigationController()->GetActiveEntry(); } base::FilePath GetTestExtensionPath(const char* extension_name) const { return test_data_dir_.AppendASCII("browsertest/url_rewrite/"). AppendASCII(extension_name); } // Navigates to |url| and tests that the location bar and the |virtual_url| // correspond to |url|, while the real URL of the navigation entry uses the // chrome-extension:// scheme. void TestExtensionURLOverride(const GURL& url) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ(url, GetLocationBarTextAsURL()); EXPECT_EQ(url, GetNavigationEntry()->GetVirtualURL()); EXPECT_TRUE( GetNavigationEntry()->GetURL().SchemeIs(extensions::kExtensionScheme)); } // Navigates to |url| and tests that the location bar is empty while the // |virtual_url| is the same as |url|. void TestURLNotShown(const GURL& url) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ("", GetLocationBarText()); EXPECT_EQ(url, GetNavigationEntry()->GetVirtualURL()); } }; IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, NewTabPageURL) { // Navigate to chrome://newtab and check that the location bar text is blank. GURL url(chrome::kChromeUINewTabURL); TestURLNotShown(url); // Check that the actual URL corresponds to chrome://newtab. EXPECT_EQ(url, GetNavigationEntry()->GetURL()); } IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, NewTabPageURLOverride) { // Load an extension to override the NTP and check that the location bar text // is blank after navigating to chrome://newtab. ASSERT_TRUE(LoadExtension(GetTestExtensionPath("newtab"))); TestURLNotShown(GURL(chrome::kChromeUINewTabURL)); // Check that the internal URL uses the chrome-extension:// scheme. EXPECT_TRUE(GetNavigationEntry()->GetURL().SchemeIs( extensions::kExtensionScheme)); } // TODO(linux_aura) http://crbug.com/163931 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA) #define MAYBE_BookmarksURL DISABLED_BookmarksURL #else #define MAYBE_BookmarksURL BookmarksURL #endif IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, MAYBE_BookmarksURL) { // Navigate to chrome://bookmarks and check that the location bar URL is // what was entered and the internal URL uses the chrome-extension:// scheme. const GURL bookmarks_url(chrome::kChromeUIBookmarksURL); ui_test_utils::NavigateToURL(browser(), bookmarks_url); // The default chrome://bookmarks implementation will append /#1 to the URL // once loaded. Use |GetWithEmptyPath()| to avoid flakyness. EXPECT_EQ(bookmarks_url, GetLocationBarTextAsURL().GetWithEmptyPath()); NavigationEntry* navigation = GetNavigationEntry(); EXPECT_EQ(bookmarks_url, navigation->GetVirtualURL().GetWithEmptyPath()); EXPECT_TRUE(navigation->GetURL().SchemeIs(extensions::kExtensionScheme)); } #if defined(FILE_MANAGER_EXTENSION) IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, FileManagerURL) { // Navigate to chrome://files and check that the location bar URL is // what was entered and the internal URL uses the chrome-extension:// scheme. TestExtensionURLOverride(GURL(chrome::kChromeUIFileManagerURL)); } #endif IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURLWithRef) { // Navigate to chrome://bookmarks/#1 and check that the location bar URL is // what was entered and the internal URL uses the chrome-extension:// scheme. GURL url_with_ref(chrome::kChromeUIBookmarksURL + std::string("#1")); TestExtensionURLOverride(url_with_ref); } IN_PROC_BROWSER_TEST_F(ExtensionURLRewriteBrowserTest, BookmarksURLOverride) { // Load an extension that overrides chrome://bookmarks. ASSERT_TRUE(LoadExtension(GetTestExtensionPath("bookmarks"))); // Navigate to chrome://bookmarks and check that the location bar URL is what // was entered and the internal URL uses the chrome-extension:// scheme. TestExtensionURLOverride(GURL(chrome::kChromeUIBookmarksURL)); } <|endoftext|>
<commit_before>#include <boost/any.hpp> #include <iostream> #include <vector> #include <string> int main(int argc, char** argv) { std::vector<boost::any> some_values; some_values.push_back(10); const char* c_str = "Hello there!"; some_values.push_back(c_str); some_values.push_back(std::string("Wow!")); std::string& s = boost::any_cast<std::string&>(some_values.back()); s += " That is great!\n"; std::cout << s; return 0; }<commit_msg>'Any' example updated.<commit_after>#include <boost/any.hpp> #include <iostream> #include <vector> #include <string> #include <cassert> int main(int argc, char** argv) { { boost::any any_value = 10; std::cout << boost::any_cast<int>(any_value) << std::endl; int *pointer = boost::any_cast<int>(&any_value); std::cout << *pointer << std::endl; any_value = 2.34; std::cout << boost::any_cast<double>(any_value) << std::endl; any_value = false; std::cout << std::boolalpha << boost::any_cast<bool>(any_value) << std::endl; } { boost::any any_value = 10; assert(any_value.type() == typeid(int)); boost::any empty_value; assert(empty_value.empty()); } return 0; }<|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_TRI_INVERSE_HPP #define STAN_MATH_OPENCL_TRI_INVERSE_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/matrix_cl.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/kernels/diag_inv.hpp> #include <stan/math/opencl/kernels/inv_lower_tri_multiply.hpp> #include <stan/math/opencl/kernels/neg_rect_lower_tri_multiply.hpp> #include <stan/math/opencl/err.hpp> #include <stan/math/opencl/identity.hpp> #include <stan/math/opencl/sub_block.hpp> #include <stan/math/opencl/zeros.hpp> #include <stan/math/opencl/kernel_generator.hpp> #include <stan/math/prim/meta.hpp> #include <cmath> #include <string> #include <vector> namespace stan { namespace math { /** \ingroup opencl * Computes the inverse of a triangular matrix * * For a full guide to how this works and fits into Cholesky decompositions, * see the reference report * <a href="https://github.com/SteveBronder/stancon2018/blob/master/report.pdf"> * here</a> and kernel doc * <a href="https://github.com/stan-dev/math/wiki/GPU-Kernels">here</a>. * * @param A matrix on the OpenCL device * @return the inverse of A * * @throw <code>std::invalid_argument</code> if the matrix * is not square */ template <matrix_cl_view matrix_view = matrix_cl_view::Entire, typename T, typename = require_floating_point_t<T>> inline matrix_cl<T> tri_inverse(const matrix_cl<T>& A) { // if the triangular view is not specified use the triangularity of // the input matrix matrix_cl_view tri_view = matrix_view; if (matrix_view == matrix_cl_view::Entire || matrix_view == matrix_cl_view::Diagonal) { tri_view = A.view(); } check_triangular("tri_inverse (OpenCL)", "A", A); check_square("tri_inverse (OpenCL)", "A", A); int thread_block_2D_dim = 32; int max_1D_thread_block_size = opencl_context.max_thread_block_size(); // we split the input matrix to 32 blocks int thread_block_size_1D = (((A.rows() / 32) + thread_block_2D_dim - 1) / thread_block_2D_dim) * thread_block_2D_dim; if (max_1D_thread_block_size < thread_block_size_1D) { thread_block_size_1D = max_1D_thread_block_size; } int max_2D_thread_block_dim = std::sqrt(max_1D_thread_block_size); if (max_2D_thread_block_dim < thread_block_2D_dim) { thread_block_2D_dim = max_2D_thread_block_dim; } // for small size split in max 2 parts if (thread_block_size_1D < 64) { thread_block_size_1D = 32; } if (A.rows() < thread_block_size_1D) { thread_block_size_1D = A.rows(); } // pad the input matrix int A_rows_padded = ((A.rows() + thread_block_size_1D - 1) / thread_block_size_1D) * thread_block_size_1D; matrix_cl<T> temp(A_rows_padded, A_rows_padded); matrix_cl<T> inv_padded(A_rows_padded, A_rows_padded); matrix_cl<T> inv_mat(A); matrix_cl<T> zero_mat(A_rows_padded - A.rows(), A_rows_padded); zero_mat.template zeros<stan::math::matrix_cl_view::Entire>(); inv_padded.template zeros<stan::math::matrix_cl_view::Entire>(); if (tri_view == matrix_cl_view::Upper) { inv_mat = transpose(inv_mat); } int work_per_thread = opencl_kernels::inv_lower_tri_multiply.make_functor.get_opts().at( "WORK_PER_THREAD"); // the number of blocks in the first step // each block is inverted with using the regular forward substitution int parts = inv_padded.rows() / thread_block_size_1D; inv_padded.sub_block(inv_mat, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows()); try { // create a batch of identity matrices to be used in the first step opencl_kernels::batch_identity( cl::NDRange(parts, thread_block_size_1D, thread_block_size_1D), temp, thread_block_size_1D, temp.size()); // spawn parts thread blocks, each responsible for one block opencl_kernels::diag_inv(cl::NDRange(parts * thread_block_size_1D), cl::NDRange(thread_block_size_1D), inv_padded, temp, inv_padded.rows()); } catch (cl::Error& e) { check_opencl_error("inverse step1", e); } // set the padded part of the matrix and the upper triangular to zeros inv_padded.sub_block(zero_mat, 0, 0, inv_mat.rows(), 0, zero_mat.rows(), zero_mat.cols()); inv_padded.template zeros_strict_tri<stan::math::matrix_cl_view::Upper>(); if (parts == 1) { inv_mat.sub_block(inv_padded, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows()); if (tri_view == matrix_cl_view::Upper) { inv_mat = transpose(inv_mat); } return inv_mat; } using std::ceil; parts = ceil(parts / 2.0); auto result_matrix_dim = thread_block_size_1D; auto thread_block_work2d_dim = thread_block_2D_dim / work_per_thread; auto ndrange_2d = cl::NDRange(thread_block_2D_dim, thread_block_work2d_dim, 1); while (parts > 0) { int result_matrix_dim_x = result_matrix_dim; // when calculating the last submatrix // we can reduce the size to the actual size (not the next power of 2) if (parts == 1 && (inv_padded.rows() - result_matrix_dim * 2) < 0) { result_matrix_dim_x = inv_padded.rows() - result_matrix_dim; } auto result_work_dim = result_matrix_dim / work_per_thread; auto result_ndrange = cl::NDRange(result_matrix_dim_x, result_work_dim, parts); opencl_kernels::inv_lower_tri_multiply(result_ndrange, ndrange_2d, inv_padded, temp, inv_padded.rows(), result_matrix_dim); opencl_kernels::neg_rect_lower_tri_multiply( result_ndrange, ndrange_2d, inv_padded, temp, inv_padded.rows(), result_matrix_dim); // if this is the last submatrix, end if (parts == 1) { parts = 0; } else { parts = ceil(parts / 2.0); } result_matrix_dim *= 2; // set the padded part and upper diagonal to zeros inv_padded.sub_block(zero_mat, 0, 0, inv_mat.rows(), 0, zero_mat.rows(), zero_mat.cols()); inv_padded.template zeros_strict_tri<stan::math::matrix_cl_view::Upper>(); } // un-pad and return inv_mat.sub_block(inv_padded, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows()); if (tri_view == matrix_cl_view::Upper) { inv_mat = transpose(inv_mat); } inv_mat.view(tri_view); return inv_mat; } } // namespace math } // namespace stan #endif #endif <commit_msg>fixed aliasing in tri_inverse<commit_after>#ifndef STAN_MATH_OPENCL_TRI_INVERSE_HPP #define STAN_MATH_OPENCL_TRI_INVERSE_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/matrix_cl.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/kernels/diag_inv.hpp> #include <stan/math/opencl/kernels/inv_lower_tri_multiply.hpp> #include <stan/math/opencl/kernels/neg_rect_lower_tri_multiply.hpp> #include <stan/math/opencl/err.hpp> #include <stan/math/opencl/identity.hpp> #include <stan/math/opencl/sub_block.hpp> #include <stan/math/opencl/zeros.hpp> #include <stan/math/opencl/kernel_generator.hpp> #include <stan/math/prim/meta.hpp> #include <cmath> #include <string> #include <vector> namespace stan { namespace math { /** \ingroup opencl * Computes the inverse of a triangular matrix * * For a full guide to how this works and fits into Cholesky decompositions, * see the reference report * <a href="https://github.com/SteveBronder/stancon2018/blob/master/report.pdf"> * here</a> and kernel doc * <a href="https://github.com/stan-dev/math/wiki/GPU-Kernels">here</a>. * * @param A matrix on the OpenCL device * @return the inverse of A * * @throw <code>std::invalid_argument</code> if the matrix * is not square */ template <matrix_cl_view matrix_view = matrix_cl_view::Entire, typename T, typename = require_floating_point_t<T>> inline matrix_cl<T> tri_inverse(const matrix_cl<T>& A) { // if the triangular view is not specified use the triangularity of // the input matrix matrix_cl_view tri_view = matrix_view; if (matrix_view == matrix_cl_view::Entire || matrix_view == matrix_cl_view::Diagonal) { tri_view = A.view(); } check_triangular("tri_inverse (OpenCL)", "A", A); check_square("tri_inverse (OpenCL)", "A", A); int thread_block_2D_dim = 32; int max_1D_thread_block_size = opencl_context.max_thread_block_size(); // we split the input matrix to 32 blocks int thread_block_size_1D = (((A.rows() / 32) + thread_block_2D_dim - 1) / thread_block_2D_dim) * thread_block_2D_dim; if (max_1D_thread_block_size < thread_block_size_1D) { thread_block_size_1D = max_1D_thread_block_size; } int max_2D_thread_block_dim = std::sqrt(max_1D_thread_block_size); if (max_2D_thread_block_dim < thread_block_2D_dim) { thread_block_2D_dim = max_2D_thread_block_dim; } // for small size split in max 2 parts if (thread_block_size_1D < 64) { thread_block_size_1D = 32; } if (A.rows() < thread_block_size_1D) { thread_block_size_1D = A.rows(); } // pad the input matrix int A_rows_padded = ((A.rows() + thread_block_size_1D - 1) / thread_block_size_1D) * thread_block_size_1D; matrix_cl<T> temp(A_rows_padded, A_rows_padded); matrix_cl<T> inv_padded(A_rows_padded, A_rows_padded); matrix_cl<T> inv_mat(A); matrix_cl<T> zero_mat(A_rows_padded - A.rows(), A_rows_padded); zero_mat.template zeros<stan::math::matrix_cl_view::Entire>(); inv_padded.template zeros<stan::math::matrix_cl_view::Entire>(); if (tri_view == matrix_cl_view::Upper) { inv_mat = transpose(inv_mat).eval(); } int work_per_thread = opencl_kernels::inv_lower_tri_multiply.make_functor.get_opts().at( "WORK_PER_THREAD"); // the number of blocks in the first step // each block is inverted with using the regular forward substitution int parts = inv_padded.rows() / thread_block_size_1D; inv_padded.sub_block(inv_mat, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows()); try { // create a batch of identity matrices to be used in the first step opencl_kernels::batch_identity( cl::NDRange(parts, thread_block_size_1D, thread_block_size_1D), temp, thread_block_size_1D, temp.size()); // spawn parts thread blocks, each responsible for one block opencl_kernels::diag_inv(cl::NDRange(parts * thread_block_size_1D), cl::NDRange(thread_block_size_1D), inv_padded, temp, inv_padded.rows()); } catch (cl::Error& e) { check_opencl_error("inverse step1", e); } // set the padded part of the matrix and the upper triangular to zeros inv_padded.sub_block(zero_mat, 0, 0, inv_mat.rows(), 0, zero_mat.rows(), zero_mat.cols()); inv_padded.template zeros_strict_tri<stan::math::matrix_cl_view::Upper>(); if (parts == 1) { inv_mat.sub_block(inv_padded, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows()); if (tri_view == matrix_cl_view::Upper) { inv_mat = transpose(inv_mat).eval(); } return inv_mat; } using std::ceil; parts = ceil(parts / 2.0); auto result_matrix_dim = thread_block_size_1D; auto thread_block_work2d_dim = thread_block_2D_dim / work_per_thread; auto ndrange_2d = cl::NDRange(thread_block_2D_dim, thread_block_work2d_dim, 1); while (parts > 0) { int result_matrix_dim_x = result_matrix_dim; // when calculating the last submatrix // we can reduce the size to the actual size (not the next power of 2) if (parts == 1 && (inv_padded.rows() - result_matrix_dim * 2) < 0) { result_matrix_dim_x = inv_padded.rows() - result_matrix_dim; } auto result_work_dim = result_matrix_dim / work_per_thread; auto result_ndrange = cl::NDRange(result_matrix_dim_x, result_work_dim, parts); opencl_kernels::inv_lower_tri_multiply(result_ndrange, ndrange_2d, inv_padded, temp, inv_padded.rows(), result_matrix_dim); opencl_kernels::neg_rect_lower_tri_multiply( result_ndrange, ndrange_2d, inv_padded, temp, inv_padded.rows(), result_matrix_dim); // if this is the last submatrix, end if (parts == 1) { parts = 0; } else { parts = ceil(parts / 2.0); } result_matrix_dim *= 2; // set the padded part and upper diagonal to zeros inv_padded.sub_block(zero_mat, 0, 0, inv_mat.rows(), 0, zero_mat.rows(), zero_mat.cols()); inv_padded.template zeros_strict_tri<stan::math::matrix_cl_view::Upper>(); } // un-pad and return inv_mat.sub_block(inv_padded, 0, 0, 0, 0, inv_mat.rows(), inv_mat.rows()); if (tri_view == matrix_cl_view::Upper) { inv_mat = transpose(inv_mat).eval(); } inv_mat.view(tri_view); return inv_mat; } } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>#include "MainFrame.h" #include <algorithm> #include <wx/log.h> #include <wx/mstream.h> #include <wx/button.h> #include "ImageViewPanel.h" #include "ZipEntry.h" #include "FileEntry.h" enum MainFrameIds { ID_DIRECTORY_TREE = 1, ID_IMAGE_BUTTON }; MainFrame::MainFrame() : wxFrame(NULL, wxID_ANY, "ZipPicView") { auto statusBar = CreateStatusBar(); SetStatusText("Welcome to ZipPicView!"); auto outerSizer = new wxBoxSizer(wxVERTICAL); auto toolSizer = new wxBoxSizer(wxHORIZONTAL); onTopChk = new wxCheckBox(this, wxID_ANY, "On Top"); onTopChk->Bind(wxEVT_CHECKBOX, &MainFrame::OnOnTopChecked, this); notebook = new wxNotebook(this, wxID_ANY); currentFileCtrl = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); dirBrowseBtn = new wxButton(this, wxID_ANY, "Directory..."); dirBrowseBtn->Bind(wxEVT_BUTTON, &MainFrame::OnDirBrowsePressed, this); zipBrowseBtn = new wxButton(this, wxID_ANY, "Zip..."); zipBrowseBtn->Bind(wxEVT_BUTTON, &MainFrame::OnZipBrowsePressed, this); toolSizer->Add(currentFileCtrl, 1, wxEXPAND | wxALL); toolSizer->Add(dirBrowseBtn, 0, wxEXPAND | wxALL); toolSizer->Add(zipBrowseBtn, 0, wxEXPAND | wxALL); toolSizer->Add(onTopChk, 0, wxEXPAND | wxALL); outerSizer->Add(toolSizer, 0, wxEXPAND | wxALL, 5); outerSizer->Add(notebook, 1, wxEXPAND | wxALL, 5); splitter = new wxSplitterWindow(notebook, wxID_ANY); dirTree = new wxTreeCtrl(splitter, ID_DIRECTORY_TREE, wxDefaultPosition, wxDefaultSize, wxTR_SINGLE | wxTR_NO_LINES | wxTR_FULL_ROW_HIGHLIGHT); dirTree->Bind(wxEVT_TREE_SEL_CHANGED, &MainFrame::OnTreeSelectionChanged, this, ID_DIRECTORY_TREE); dirTree->Bind(wxEVT_TREE_ITEM_COLLAPSING, [=](wxTreeEvent &event) { event.Veto(); }, ID_DIRECTORY_TREE); dirTree->SetMinSize({250, 250}); auto rightWindow = new wxScrolledWindow(splitter, wxID_ANY); auto grid = new wxGridSizer(5); rightWindow->SetSizer(grid); rightWindow->SetScrollRate(10, 10); rightWindow->SetMinSize({250, 250}); rightWindow->Bind(wxEVT_SIZE, &MainFrame::OnGridPanelSize, this); splitter->SplitVertically(dirTree, rightWindow, 250); notebook->AddPage(splitter, "Browse"); SetMinSize({640, 480}); SetSizer(outerSizer); } void MainFrame::BuildDirectoryTree() { auto root = dirTree->AddRoot(entry->Name(), -1, -1, new EntryItemData(entry)); AddTreeItemsFromEntry(root, entry); } void MainFrame::AddTreeItemsFromEntry(const wxTreeItemId &itemId, Entry *entry) { for (auto childEntry : *entry) { if (!childEntry->IsDirectory()) return; auto child = dirTree->AppendItem(itemId, childEntry->Name(), -1, -1, new EntryItemData(childEntry)); AddTreeItemsFromEntry(child, childEntry); } } void MainFrame::OnTreeSelectionChanged(wxTreeEvent &event) { wxProgressDialog progressDlg("Loading", "Please Wait"); auto treeItemId = event.GetItem(); auto rootId = dirTree->GetRootItem(); auto currentFileEntry = dynamic_cast<EntryItemData *>(dirTree->GetItemData(treeItemId))->Get(); progressDlg.Pulse(); auto gridPanel = dynamic_cast<wxScrolledWindow *>(splitter->GetWindow2()); gridPanel->Show(false); auto grid = gridPanel->GetSizer(); grid->Clear(true); for (auto childEntry : *currentFileEntry) { if (childEntry->IsDirectory()) return; auto name = childEntry->Name(); if (!(name.EndsWith(".jpg") || name.EndsWith(".jpeg") || name.EndsWith(".png") || name.EndsWith(".gif"))) return; auto image = childEntry->LoadImage(); auto button = new wxButton(gridPanel, wxID_ANY); button->Bind(wxEVT_BUTTON, &MainFrame::OnImageButtonClick, this); int longerSide = image.GetWidth() > image.GetHeight() ? image.GetWidth() : image.GetHeight(); int width = 200 * image.GetWidth() / longerSide; int height = 200 * image.GetHeight() / longerSide; auto thumbnailImage = image.Scale(width, height, wxIMAGE_QUALITY_HIGH); button->SetBitmap(thumbnailImage, wxBOTTOM); button->SetClientObject(new EntryItemData(childEntry)); button->SetMinSize({250, 250}); auto btnSizer = new wxBoxSizer(wxVERTICAL); btnSizer->Add(button, 0, wxEXPAND); btnSizer->Add(new wxStaticText(gridPanel, wxID_ANY, childEntry->Name())); grid->Add(btnSizer, 0, wxALL | wxEXPAND, 5); progressDlg.Pulse(); } grid->FitInside(gridPanel); gridPanel->Show(true); gridPanel->Scroll(0, 0); progressDlg.Update(100); } void MainFrame::OnImageButtonClick(wxCommandEvent &event) { auto button = dynamic_cast<wxButton *>(event.GetEventObject()); auto clientData = dynamic_cast<wxStringClientData *>(button->GetClientObject()); auto page = notebook->GetPageCount(); auto childEntry = dynamic_cast<EntryItemData *>(button->GetClientObject())->Get(); auto bitmapCtl = new ImageViewPanel(notebook, childEntry->LoadImage()); notebook->AddPage(bitmapCtl, childEntry->Name()); notebook->SetSelection(page); } void MainFrame::OnGridPanelSize(wxSizeEvent &event) { auto grid = dynamic_cast<wxGridSizer *>(splitter->GetWindow2()->GetSizer()); auto size = event.GetSize(); int col = (size.GetWidth() / 250); grid->SetCols(col > 0 ? col : 1); grid->FitInside(splitter->GetWindow2()); } void MainFrame::OnOnTopChecked(wxCommandEvent &event) { auto style = GetWindowStyle(); if (onTopChk->IsChecked()) { style += wxSTAY_ON_TOP; } else { style -= wxSTAY_ON_TOP; } SetWindowStyle(style); } void MainFrame::OnDirBrowsePressed(wxCommandEvent &event) { wxDirDialog dlg(NULL, "Choose directory", "", wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (dlg.ShowModal() == wxID_CANCEL) return; auto oldEntry = entry; auto path = dlg.GetPath() + wxFileName::GetPathSeparator(); wxFileName filename(path); auto entry = FileEntry::Create(filename); SetEntry(entry); currentFileCtrl->SetLabelText(filename.GetFullPath()); } void MainFrame::OnZipBrowsePressed(wxCommandEvent &event) { wxFileDialog dialog(this, _("Open ZIP file"), "", "", "ZIP files (*.zip)|*.zip", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (dialog.ShowModal() == wxID_CANCEL) return; auto path = dialog.GetPath(); wxFileName filename(path); int error; auto zipFile = zip_open(path, ZIP_RDONLY, &error); if (zipFile == nullptr) { throw error; } auto entry = ZipEntry::Create(zipFile); SetEntry(entry); currentFileCtrl->SetLabelText(filename.GetFullPath()); } void MainFrame::SetEntry(Entry *entry) { auto oldEntry = MainFrame::entry; MainFrame::entry = entry; dirTree->UnselectAll(); dirTree->DeleteAllItems(); BuildDirectoryTree(); dirTree->SelectItem(dirTree->GetRootItem()); dirTree->ExpandAll(); if (oldEntry) { delete oldEntry; } } <commit_msg>Unicode filename handling (almost) properly.<commit_after>#include "MainFrame.h" #include <algorithm> #include <wx/log.h> #include <wx/mstream.h> #include <wx/button.h> #include "ImageViewPanel.h" #include "ZipEntry.h" #include "FileEntry.h" enum MainFrameIds { ID_DIRECTORY_TREE = 1, ID_IMAGE_BUTTON }; MainFrame::MainFrame() : wxFrame(NULL, wxID_ANY, "ZipPicView") { auto statusBar = CreateStatusBar(); SetStatusText("Welcome to ZipPicView!"); auto outerSizer = new wxBoxSizer(wxVERTICAL); auto toolSizer = new wxBoxSizer(wxHORIZONTAL); onTopChk = new wxCheckBox(this, wxID_ANY, "On Top"); onTopChk->Bind(wxEVT_CHECKBOX, &MainFrame::OnOnTopChecked, this); notebook = new wxNotebook(this, wxID_ANY); currentFileCtrl = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); dirBrowseBtn = new wxButton(this, wxID_ANY, "Directory..."); dirBrowseBtn->Bind(wxEVT_BUTTON, &MainFrame::OnDirBrowsePressed, this); zipBrowseBtn = new wxButton(this, wxID_ANY, "Zip..."); zipBrowseBtn->Bind(wxEVT_BUTTON, &MainFrame::OnZipBrowsePressed, this); toolSizer->Add(currentFileCtrl, 1, wxEXPAND | wxALL); toolSizer->Add(dirBrowseBtn, 0, wxEXPAND | wxALL); toolSizer->Add(zipBrowseBtn, 0, wxEXPAND | wxALL); toolSizer->Add(onTopChk, 0, wxEXPAND | wxALL); outerSizer->Add(toolSizer, 0, wxEXPAND | wxALL, 5); outerSizer->Add(notebook, 1, wxEXPAND | wxALL, 5); splitter = new wxSplitterWindow(notebook, wxID_ANY); dirTree = new wxTreeCtrl(splitter, ID_DIRECTORY_TREE, wxDefaultPosition, wxDefaultSize, wxTR_SINGLE | wxTR_NO_LINES | wxTR_FULL_ROW_HIGHLIGHT); dirTree->Bind(wxEVT_TREE_SEL_CHANGED, &MainFrame::OnTreeSelectionChanged, this, ID_DIRECTORY_TREE); dirTree->Bind(wxEVT_TREE_ITEM_COLLAPSING, [=](wxTreeEvent &event) { event.Veto(); }, ID_DIRECTORY_TREE); dirTree->SetMinSize({250, 250}); auto rightWindow = new wxScrolledWindow(splitter, wxID_ANY); auto grid = new wxGridSizer(5); rightWindow->SetSizer(grid); rightWindow->SetScrollRate(10, 10); rightWindow->SetMinSize({250, 250}); rightWindow->Bind(wxEVT_SIZE, &MainFrame::OnGridPanelSize, this); splitter->SplitVertically(dirTree, rightWindow, 250); notebook->AddPage(splitter, "Browse"); SetMinSize({640, 480}); SetSizer(outerSizer); } void MainFrame::BuildDirectoryTree() { auto root = dirTree->AddRoot(entry->Name(), -1, -1, new EntryItemData(entry)); AddTreeItemsFromEntry(root, entry); } void MainFrame::AddTreeItemsFromEntry(const wxTreeItemId &itemId, Entry *entry) { for (auto childEntry : *entry) { if (!childEntry->IsDirectory()) return; auto child = dirTree->AppendItem(itemId, childEntry->Name(), -1, -1, new EntryItemData(childEntry)); AddTreeItemsFromEntry(child, childEntry); } } void MainFrame::OnTreeSelectionChanged(wxTreeEvent &event) { wxProgressDialog progressDlg("Loading", "Please Wait"); auto treeItemId = event.GetItem(); auto rootId = dirTree->GetRootItem(); auto currentFileEntry = dynamic_cast<EntryItemData *>(dirTree->GetItemData(treeItemId))->Get(); progressDlg.Pulse(); auto gridPanel = dynamic_cast<wxScrolledWindow *>(splitter->GetWindow2()); gridPanel->Show(false); auto grid = gridPanel->GetSizer(); grid->Clear(true); for (auto childEntry : *currentFileEntry) { if (childEntry->IsDirectory()) return; auto name = childEntry->Name(); if (!(name.EndsWith(".jpg") || name.EndsWith(".jpeg") || name.EndsWith(".png") || name.EndsWith(".gif"))) return; auto image = childEntry->LoadImage(); auto button = new wxButton(gridPanel, wxID_ANY); button->Bind(wxEVT_BUTTON, &MainFrame::OnImageButtonClick, this); int longerSide = image.GetWidth() > image.GetHeight() ? image.GetWidth() : image.GetHeight(); int width = 200 * image.GetWidth() / longerSide; int height = 200 * image.GetHeight() / longerSide; auto thumbnailImage = image.Scale(width, height, wxIMAGE_QUALITY_HIGH); button->SetBitmap(thumbnailImage, wxBOTTOM); button->SetClientObject(new EntryItemData(childEntry)); button->SetMinSize({250, 250}); auto btnSizer = new wxBoxSizer(wxVERTICAL); btnSizer->Add(button, 0, wxEXPAND); btnSizer->Add(new wxStaticText(gridPanel, wxID_ANY, childEntry->Name())); grid->Add(btnSizer, 0, wxALL | wxEXPAND, 5); progressDlg.Pulse(); } grid->FitInside(gridPanel); gridPanel->Show(true); gridPanel->Scroll(0, 0); progressDlg.Update(100); } void MainFrame::OnImageButtonClick(wxCommandEvent &event) { auto button = dynamic_cast<wxButton *>(event.GetEventObject()); auto clientData = dynamic_cast<wxStringClientData *>(button->GetClientObject()); auto page = notebook->GetPageCount(); auto childEntry = dynamic_cast<EntryItemData *>(button->GetClientObject())->Get(); auto bitmapCtl = new ImageViewPanel(notebook, childEntry->LoadImage()); notebook->AddPage(bitmapCtl, childEntry->Name()); notebook->SetSelection(page); } void MainFrame::OnGridPanelSize(wxSizeEvent &event) { auto grid = dynamic_cast<wxGridSizer *>(splitter->GetWindow2()->GetSizer()); auto size = event.GetSize(); int col = (size.GetWidth() / 250); grid->SetCols(col > 0 ? col : 1); grid->FitInside(splitter->GetWindow2()); } void MainFrame::OnOnTopChecked(wxCommandEvent &event) { auto style = GetWindowStyle(); if (onTopChk->IsChecked()) { style += wxSTAY_ON_TOP; } else { style -= wxSTAY_ON_TOP; } SetWindowStyle(style); } void MainFrame::OnDirBrowsePressed(wxCommandEvent &event) { wxDirDialog dlg(NULL, "Choose directory", "", wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (dlg.ShowModal() == wxID_CANCEL) return; auto oldEntry = entry; auto path = dlg.GetPath() + wxFileName::GetPathSeparator(); wxFileName filename(path); auto entry = FileEntry::Create(filename); SetEntry(entry); currentFileCtrl->SetLabelText(filename.GetFullPath()); } void MainFrame::OnZipBrowsePressed(wxCommandEvent &event) { wxFileDialog dialog(this, _("Open ZIP file"), "", "", "ZIP files (*.zip)|*.zip", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (dialog.ShowModal() == wxID_CANCEL) return; auto path = dialog.GetPath(); wxFileName filename(path); wxFile file(path); int error; auto zipFile = zip_fdopen(file.fd(), ZIP_RDONLY, &error); // auto zipFile = zip_open(path.ToUTF8(), ZIP_RDONLY, &error); if (zipFile == nullptr) { throw error; } auto entry = ZipEntry::Create(zipFile); SetEntry(entry); currentFileCtrl->SetLabelText(filename.GetFullPath()); } void MainFrame::SetEntry(Entry *entry) { auto oldEntry = MainFrame::entry; MainFrame::entry = entry; dirTree->UnselectAll(); dirTree->DeleteAllItems(); BuildDirectoryTree(); dirTree->SelectItem(dirTree->GetRootItem()); dirTree->ExpandAll(); if (oldEntry) { delete oldEntry; } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2005-2017 by the FIFE team * * http://www.fifengine.net * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes // 3rd party library includes #include <SDL.h> // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "util/structures/rect.h" #include "util/time/timemanager.h" #include "util/log/logger.h" #include "video/imagemanager.h" #include "animation.h" #include "image.h" #include "renderbackend.h" #include "cursor.h" namespace FIFE { /** Logger to use for this source file. * @relates Logger */ static Logger _log(LM_CURSOR); Cursor::Cursor(RenderBackend* renderbackend): m_cursor_id(NC_ARROW), m_cursor_type(CURSOR_NATIVE), m_drag_type(CURSOR_NONE), m_native_cursor(NULL), m_renderbackend(renderbackend), m_animtime(0), m_drag_animtime(0), m_drag_offset_x(0), m_drag_offset_y(0), m_mx(0), m_my(0), m_timemanager(TimeManager::instance()), m_invalidated(false), m_native_image_cursor_enabled(false) { assert(m_timemanager); set(m_cursor_id); } void Cursor::set(uint32_t cursor_id) { m_cursor_type = CURSOR_NATIVE; if (!SDL_ShowCursor(1)) { SDL_PumpEvents(); } setNativeCursor(cursor_id); m_cursor_image.reset(); m_cursor_animation.reset(); } void Cursor::set(ImagePtr image) { assert(image != 0); m_cursor_image = image; m_cursor_type = CURSOR_IMAGE; if (m_native_image_cursor_enabled) { setNativeImageCursor(image); if (!SDL_ShowCursor(1)) { SDL_PumpEvents(); } } else if (SDL_ShowCursor(0)) { SDL_PumpEvents(); } m_cursor_id = NC_ARROW; m_cursor_animation.reset(); } void Cursor::set(AnimationPtr anim) { assert(anim != 0); m_cursor_animation = anim; m_cursor_type = CURSOR_ANIMATION; if (m_native_image_cursor_enabled) { setNativeImageCursor(anim->getFrameByTimestamp(0)); if (!SDL_ShowCursor(1)) { SDL_PumpEvents(); } } else if (SDL_ShowCursor(0)) { SDL_PumpEvents(); } m_animtime = m_timemanager->getTime(); m_cursor_id = NC_ARROW; m_cursor_image.reset(); } void Cursor::setDrag(ImagePtr image, int32_t drag_offset_x, int32_t drag_offset_y) { assert(image != 0); m_cursor_drag_image = image; m_drag_type = CURSOR_IMAGE; m_drag_offset_x = drag_offset_x; m_drag_offset_y = drag_offset_y; m_cursor_drag_animation.reset(); } void Cursor::setDrag(AnimationPtr anim, int32_t drag_offset_x, int32_t drag_offset_y) { assert(anim != 0); m_cursor_drag_animation = anim; m_drag_type = CURSOR_ANIMATION; m_drag_offset_x = drag_offset_x; m_drag_offset_y = drag_offset_y; m_drag_animtime = m_timemanager->getTime(); m_cursor_drag_image.reset(); } void Cursor::resetDrag() { m_drag_type = CURSOR_NONE; m_drag_animtime = 0; m_drag_offset_x = 0; m_drag_offset_y = 0; m_cursor_drag_animation.reset(); m_cursor_drag_image.reset(); } void Cursor::setPosition(uint32_t x, uint32_t y) { m_mx = x; m_my = y; SDL_WarpMouseInWindow(RenderBackend::instance()->getWindow(), m_mx, m_my); } void Cursor::getPosition(int32_t* x, int32_t* y) { *x = m_mx; *y = m_my; } void Cursor::invalidate() { if (m_native_cursor != NULL) { SDL_FreeCursor(m_native_cursor); m_native_cursor = NULL; m_native_cursor_image.reset(); m_invalidated = true; } } void Cursor::draw() { if (m_invalidated) { if (m_cursor_type == CURSOR_NATIVE ) { set(m_cursor_id); } else if (m_native_image_cursor_enabled) { if (m_cursor_type == CURSOR_IMAGE ) { set(m_cursor_image); } else if (m_cursor_type == CURSOR_ANIMATION ) { set(m_cursor_animation); } } m_invalidated = false; } SDL_GetMouseState(&m_mx, &m_my); if ((m_cursor_type == CURSOR_NATIVE) && (m_drag_type == CURSOR_NONE)) { return; } // render possible drag image ImagePtr img; if (m_drag_type == CURSOR_IMAGE) { img = m_cursor_drag_image; } else if (m_drag_type == CURSOR_ANIMATION) { int32_t animtime = (m_timemanager->getTime() - m_drag_animtime) % m_cursor_drag_animation->getDuration(); img = m_cursor_drag_animation->getFrameByTimestamp(animtime); } if (img != 0) { Rect area(m_mx + m_drag_offset_x + img->getXShift(), m_my + m_drag_offset_y + img->getYShift(), img->getWidth(), img->getHeight()); m_renderbackend->pushClipArea(area, false); img->render(area); m_renderbackend->renderVertexArrays(); m_renderbackend->popClipArea(); } ImagePtr img2; // render possible cursor image if (m_cursor_type == CURSOR_IMAGE) { img2 = m_cursor_image; } else if (m_cursor_type == CURSOR_ANIMATION) { int32_t animtime = (m_timemanager->getTime() - m_animtime) % m_cursor_animation->getDuration(); img2 = m_cursor_animation->getFrameByTimestamp(animtime); } if (img2 != 0) { if (m_native_image_cursor_enabled) { setNativeImageCursor(img2); } else { Rect area(m_mx + img2->getXShift(), m_my + img2->getYShift(), img2->getWidth(), img2->getHeight()); m_renderbackend->pushClipArea(area, false); img2->render(area); m_renderbackend->renderVertexArrays(); m_renderbackend->popClipArea(); } } } uint32_t Cursor::getNativeId(uint32_t cursor_id) { switch (cursor_id) { case NC_ARROW: return SDL_SYSTEM_CURSOR_ARROW; case NC_IBEAM: return SDL_SYSTEM_CURSOR_IBEAM; case NC_WAIT: return SDL_SYSTEM_CURSOR_WAIT; case NC_CROSS: return SDL_SYSTEM_CURSOR_CROSSHAIR; case NC_WAITARROW: return SDL_SYSTEM_CURSOR_WAITARROW; case NC_RESIZENWSE: return SDL_SYSTEM_CURSOR_SIZENWSE; case NC_RESIZENESW: return SDL_SYSTEM_CURSOR_SIZENESW; case NC_RESIZEWE: return SDL_SYSTEM_CURSOR_SIZEWE; case NC_RESIZENS: return SDL_SYSTEM_CURSOR_SIZENS; case NC_RESIZEALL: return SDL_SYSTEM_CURSOR_SIZEALL; case NC_NO: return SDL_SYSTEM_CURSOR_NO; case NC_HAND: return SDL_SYSTEM_CURSOR_HAND; } return cursor_id; } void Cursor::setNativeCursor(uint32_t cursor_id) { cursor_id = getNativeId(cursor_id); SDL_Cursor* cursor = SDL_CreateSystemCursor(static_cast<SDL_SystemCursor>(cursor_id)); if (!cursor) { FL_WARN(_log, "No cursor matching cursor_id was found."); return; } SDL_SetCursor(cursor); if (m_native_cursor != NULL) { SDL_FreeCursor(m_native_cursor); } m_native_cursor = cursor; } void Cursor::setNativeImageCursor(ImagePtr image) { if (image == m_native_cursor_image) { return; } ImagePtr temp_image = image; if (image->isSharedImage()) { temp_image = ImageManager::instance()->create(); temp_image->copySubimage(0, 0, image); } SDL_Cursor* cursor = SDL_CreateColorCursor(temp_image->getSurface(), -image->getXShift(), -image->getYShift()); if (cursor == NULL) { FL_WARN(_log, LMsg("SDL_CreateColorCursor: \"") << SDL_GetError(); if (image->isSharedImage()) { ImageManager::instance()->remove(temp_image); } return; } SDL_SetCursor(cursor); m_native_cursor_image = image; if (image->isSharedImage()) { ImageManager::instance()->remove(temp_image); } if (m_native_cursor != NULL) { SDL_FreeCursor(m_native_cursor); } m_native_cursor = cursor; } void Cursor::setNativeImageCursorEnabled(bool native_image_cursor_enabled) { if (m_native_image_cursor_enabled != native_image_cursor_enabled) { m_native_image_cursor_enabled = native_image_cursor_enabled; if (m_cursor_type == CURSOR_IMAGE ) { set(m_cursor_image); } else if (m_cursor_type == CURSOR_ANIMATION ) { set(m_cursor_animation); } } } bool Cursor::isNativeImageCursorEnabled() const { return m_native_image_cursor_enabled; } } <commit_msg>Fall back to software cursor if SDL_CreateColorCursor() fails<commit_after>/*************************************************************************** * Copyright (C) 2005-2017 by the FIFE team * * http://www.fifengine.net * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes // 3rd party library includes #include <SDL.h> // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "util/structures/rect.h" #include "util/time/timemanager.h" #include "util/log/logger.h" #include "video/imagemanager.h" #include "animation.h" #include "image.h" #include "renderbackend.h" #include "cursor.h" namespace FIFE { /** Logger to use for this source file. * @relates Logger */ static Logger _log(LM_CURSOR); Cursor::Cursor(RenderBackend* renderbackend): m_cursor_id(NC_ARROW), m_cursor_type(CURSOR_NATIVE), m_drag_type(CURSOR_NONE), m_native_cursor(NULL), m_renderbackend(renderbackend), m_animtime(0), m_drag_animtime(0), m_drag_offset_x(0), m_drag_offset_y(0), m_mx(0), m_my(0), m_timemanager(TimeManager::instance()), m_invalidated(false), m_native_image_cursor_enabled(false) { assert(m_timemanager); set(m_cursor_id); } void Cursor::set(uint32_t cursor_id) { m_cursor_type = CURSOR_NATIVE; if (!SDL_ShowCursor(1)) { SDL_PumpEvents(); } setNativeCursor(cursor_id); m_cursor_image.reset(); m_cursor_animation.reset(); } void Cursor::set(ImagePtr image) { assert(image != 0); m_cursor_image = image; m_cursor_type = CURSOR_IMAGE; if (m_native_image_cursor_enabled) { setNativeImageCursor(image); if (!SDL_ShowCursor(1)) { SDL_PumpEvents(); } } else if (SDL_ShowCursor(0)) { SDL_PumpEvents(); } m_cursor_id = NC_ARROW; m_cursor_animation.reset(); } void Cursor::set(AnimationPtr anim) { assert(anim != 0); m_cursor_animation = anim; m_cursor_type = CURSOR_ANIMATION; if (m_native_image_cursor_enabled) { setNativeImageCursor(anim->getFrameByTimestamp(0)); if (!SDL_ShowCursor(1)) { SDL_PumpEvents(); } } else if (SDL_ShowCursor(0)) { SDL_PumpEvents(); } m_animtime = m_timemanager->getTime(); m_cursor_id = NC_ARROW; m_cursor_image.reset(); } void Cursor::setDrag(ImagePtr image, int32_t drag_offset_x, int32_t drag_offset_y) { assert(image != 0); m_cursor_drag_image = image; m_drag_type = CURSOR_IMAGE; m_drag_offset_x = drag_offset_x; m_drag_offset_y = drag_offset_y; m_cursor_drag_animation.reset(); } void Cursor::setDrag(AnimationPtr anim, int32_t drag_offset_x, int32_t drag_offset_y) { assert(anim != 0); m_cursor_drag_animation = anim; m_drag_type = CURSOR_ANIMATION; m_drag_offset_x = drag_offset_x; m_drag_offset_y = drag_offset_y; m_drag_animtime = m_timemanager->getTime(); m_cursor_drag_image.reset(); } void Cursor::resetDrag() { m_drag_type = CURSOR_NONE; m_drag_animtime = 0; m_drag_offset_x = 0; m_drag_offset_y = 0; m_cursor_drag_animation.reset(); m_cursor_drag_image.reset(); } void Cursor::setPosition(uint32_t x, uint32_t y) { m_mx = x; m_my = y; SDL_WarpMouseInWindow(RenderBackend::instance()->getWindow(), m_mx, m_my); } void Cursor::getPosition(int32_t* x, int32_t* y) { *x = m_mx; *y = m_my; } void Cursor::invalidate() { if (m_native_cursor != NULL) { SDL_FreeCursor(m_native_cursor); m_native_cursor = NULL; m_native_cursor_image.reset(); m_invalidated = true; } } void Cursor::draw() { if (m_invalidated) { if (m_cursor_type == CURSOR_NATIVE ) { set(m_cursor_id); } else if (m_native_image_cursor_enabled) { if (m_cursor_type == CURSOR_IMAGE ) { set(m_cursor_image); } else if (m_cursor_type == CURSOR_ANIMATION ) { set(m_cursor_animation); } } m_invalidated = false; } SDL_GetMouseState(&m_mx, &m_my); if ((m_cursor_type == CURSOR_NATIVE) && (m_drag_type == CURSOR_NONE)) { return; } // render possible drag image ImagePtr img; if (m_drag_type == CURSOR_IMAGE) { img = m_cursor_drag_image; } else if (m_drag_type == CURSOR_ANIMATION) { int32_t animtime = (m_timemanager->getTime() - m_drag_animtime) % m_cursor_drag_animation->getDuration(); img = m_cursor_drag_animation->getFrameByTimestamp(animtime); } if (img != 0) { Rect area(m_mx + m_drag_offset_x + img->getXShift(), m_my + m_drag_offset_y + img->getYShift(), img->getWidth(), img->getHeight()); m_renderbackend->pushClipArea(area, false); img->render(area); m_renderbackend->renderVertexArrays(); m_renderbackend->popClipArea(); } ImagePtr img2; // render possible cursor image if (m_cursor_type == CURSOR_IMAGE) { img2 = m_cursor_image; } else if (m_cursor_type == CURSOR_ANIMATION) { int32_t animtime = (m_timemanager->getTime() - m_animtime) % m_cursor_animation->getDuration(); img2 = m_cursor_animation->getFrameByTimestamp(animtime); } if (img2 != 0) { if (m_native_image_cursor_enabled) { setNativeImageCursor(img2); } else { Rect area(m_mx + img2->getXShift(), m_my + img2->getYShift(), img2->getWidth(), img2->getHeight()); m_renderbackend->pushClipArea(area, false); img2->render(area); m_renderbackend->renderVertexArrays(); m_renderbackend->popClipArea(); } } } uint32_t Cursor::getNativeId(uint32_t cursor_id) { switch (cursor_id) { case NC_ARROW: return SDL_SYSTEM_CURSOR_ARROW; case NC_IBEAM: return SDL_SYSTEM_CURSOR_IBEAM; case NC_WAIT: return SDL_SYSTEM_CURSOR_WAIT; case NC_CROSS: return SDL_SYSTEM_CURSOR_CROSSHAIR; case NC_WAITARROW: return SDL_SYSTEM_CURSOR_WAITARROW; case NC_RESIZENWSE: return SDL_SYSTEM_CURSOR_SIZENWSE; case NC_RESIZENESW: return SDL_SYSTEM_CURSOR_SIZENESW; case NC_RESIZEWE: return SDL_SYSTEM_CURSOR_SIZEWE; case NC_RESIZENS: return SDL_SYSTEM_CURSOR_SIZENS; case NC_RESIZEALL: return SDL_SYSTEM_CURSOR_SIZEALL; case NC_NO: return SDL_SYSTEM_CURSOR_NO; case NC_HAND: return SDL_SYSTEM_CURSOR_HAND; } return cursor_id; } void Cursor::setNativeCursor(uint32_t cursor_id) { cursor_id = getNativeId(cursor_id); SDL_Cursor* cursor = SDL_CreateSystemCursor(static_cast<SDL_SystemCursor>(cursor_id)); if (!cursor) { FL_WARN(_log, "No cursor matching cursor_id was found."); return; } SDL_SetCursor(cursor); if (m_native_cursor != NULL) { SDL_FreeCursor(m_native_cursor); } m_native_cursor = cursor; } void Cursor::setNativeImageCursor(ImagePtr image) { if (image == m_native_cursor_image) { return; } ImagePtr temp_image = image; if (image->isSharedImage()) { temp_image = ImageManager::instance()->create(); temp_image->copySubimage(0, 0, image); } SDL_Cursor* cursor = SDL_CreateColorCursor(temp_image->getSurface(), -image->getXShift(), -image->getYShift()); if (cursor == NULL) { FL_WARN(_log, LMsg("SDL_CreateColorCursor: \"") << SDL_GetError() << "\". Falling back to software cursor."); if (image->isSharedImage()) { ImageManager::instance()->remove(temp_image); } setNativeImageCursorEnabled(false); return; } SDL_SetCursor(cursor); m_native_cursor_image = image; if (image->isSharedImage()) { ImageManager::instance()->remove(temp_image); } if (m_native_cursor != NULL) { SDL_FreeCursor(m_native_cursor); } m_native_cursor = cursor; } void Cursor::setNativeImageCursorEnabled(bool native_image_cursor_enabled) { if (m_native_image_cursor_enabled != native_image_cursor_enabled) { m_native_image_cursor_enabled = native_image_cursor_enabled; if (m_cursor_type == CURSOR_IMAGE ) { set(m_cursor_image); } else if (m_cursor_type == CURSOR_ANIMATION ) { set(m_cursor_animation); } } } bool Cursor::isNativeImageCursorEnabled() const { return m_native_image_cursor_enabled; } } <|endoftext|>
<commit_before>//===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===// // // This class contains all of the shared state and information that is used by // the BugPoint tool to track down errors in optimizations. This class is the // main driver class that invokes all sub-functionality. // //===----------------------------------------------------------------------===// #include "BugDriver.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Assembly/Parser.h" #include "llvm/Bytecode/Reader.h" #include "llvm/Transforms/Utils/Linker.h" #include "Support/CommandLine.h" #include "Support/FileUtilities.h" #include <memory> // Anonymous namespace to define command line options for debugging. // namespace { // Output - The user can specify a file containing the expected output of the // program. If this filename is set, it is used as the reference diff source, // otherwise the raw input run through an interpreter is used as the reference // source. // cl::opt<std::string> OutputFile("output", cl::desc("Specify a reference program output " "(for miscompilation detection)")); enum DebugType { DebugCompile, DebugCodegen }; cl::opt<DebugType> DebugMode("mode", cl::desc("Debug mode for bugpoint:"), cl::Prefix, cl::values(clEnumValN(DebugCompile, "compile", " Compilation"), clEnumValN(DebugCodegen, "codegen", " Code generation"), 0), cl::init(DebugCompile)); } /// getPassesString - Turn a list of passes into a string which indicates the /// command line options that must be passed to add the passes. /// std::string getPassesString(const std::vector<const PassInfo*> &Passes) { std::string Result; for (unsigned i = 0, e = Passes.size(); i != e; ++i) { if (i) Result += " "; Result += "-"; Result += Passes[i]->getPassArgument(); } return Result; } // DeleteFunctionBody - "Remove" the function by deleting all of its basic // blocks, making it external. // void DeleteFunctionBody(Function *F) { // delete the body of the function... F->deleteBody(); assert(F->isExternal() && "This didn't make the function external!"); } BugDriver::BugDriver(const char *toolname) : ToolName(toolname), ReferenceOutputFile(OutputFile), Program(0), Interpreter(0), cbe(0), gcc(0) {} /// ParseInputFile - Given a bytecode or assembly input filename, parse and /// return it, or return null if not possible. /// Module *BugDriver::ParseInputFile(const std::string &InputFilename) const { Module *Result = 0; try { Result = ParseBytecodeFile(InputFilename); if (!Result && !(Result = ParseAssemblyFile(InputFilename))){ std::cerr << ToolName << ": could not read input file '" << InputFilename << "'!\n"; } } catch (const ParseException &E) { std::cerr << ToolName << ": " << E.getMessage() << "\n"; Result = 0; } return Result; } // This method takes the specified list of LLVM input files, attempts to load // them, either as assembly or bytecode, then link them together. It returns // true on failure (if, for example, an input bytecode file could not be // parsed), and false on success. // bool BugDriver::addSources(const std::vector<std::string> &Filenames) { assert(Program == 0 && "Cannot call addSources multiple times!"); assert(!Filenames.empty() && "Must specify at least on input filename!"); // Load the first input file... Program = ParseInputFile(Filenames[0]); if (Program == 0) return true; std::cout << "Read input file : '" << Filenames[0] << "'\n"; for (unsigned i = 1, e = Filenames.size(); i != e; ++i) { std::auto_ptr<Module> M(ParseInputFile(Filenames[i])); if (M.get() == 0) return true; std::cout << "Linking in input file: '" << Filenames[i] << "'\n"; std::string ErrorMessage; if (LinkModules(Program, M.get(), &ErrorMessage)) { std::cerr << ToolName << ": error linking in '" << Filenames[i] << "': " << ErrorMessage << "\n"; return true; } } std::cout << "*** All input ok\n"; // All input files read successfully! return false; } /// run - The top level method that is invoked after all of the instance /// variables are set up from command line arguments. /// bool BugDriver::run() { // The first thing that we must do is determine what the problem is. Does the // optimization series crash the compiler, or does it produce illegal code? We // make the top-level decision by trying to run all of the passes on the the // input program, which should generate a bytecode file. If it does generate // a bytecode file, then we know the compiler didn't crash, so try to diagnose // a miscompilation. // std::cout << "Running selected passes on program to test for crash: "; if (runPasses(PassesToRun)) return debugCrash(); std::cout << "Checking for a miscompilation...\n"; // Set up the execution environment, selecting a method to run LLVM bytecode. if (initializeExecutionEnvironment()) return true; // Run the raw input to see where we are coming from. If a reference output // was specified, make sure that the raw output matches it. If not, it's a // problem in the front-end or the code generator. // bool CreatedOutput = false; if (ReferenceOutputFile.empty()) { std::cout << "Generating reference output from raw program..."; if (DebugCodegen) { ReferenceOutputFile = executeProgramWithCBE("bugpoint.reference.out"); } else { ReferenceOutputFile = executeProgram("bugpoint.reference.out"); } CreatedOutput = true; std::cout << "Reference output is: " << ReferenceOutputFile << "\n"; } bool Result; switch (DebugMode) { default: assert(0 && "Bad value for DebugMode!"); case DebugCompile: std::cout << "\n*** Debugging miscompilation!\n"; Result = debugMiscompilation(); break; case DebugCodegen: std::cout << "Debugging code generator problem!\n"; Result = debugCodeGenerator(); } if (CreatedOutput) removeFile(ReferenceOutputFile); return Result; } void BugDriver::PrintFunctionList(const std::vector<Function*> &Funcs) { for (unsigned i = 0, e = Funcs.size(); i != e; ++i) { if (i) std::cout << ", "; std::cout << Funcs[i]->getName(); } } <commit_msg>Unbreak code generator debug mode<commit_after>//===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===// // // This class contains all of the shared state and information that is used by // the BugPoint tool to track down errors in optimizations. This class is the // main driver class that invokes all sub-functionality. // //===----------------------------------------------------------------------===// #include "BugDriver.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Assembly/Parser.h" #include "llvm/Bytecode/Reader.h" #include "llvm/Transforms/Utils/Linker.h" #include "Support/CommandLine.h" #include "Support/FileUtilities.h" #include <memory> // Anonymous namespace to define command line options for debugging. // namespace { // Output - The user can specify a file containing the expected output of the // program. If this filename is set, it is used as the reference diff source, // otherwise the raw input run through an interpreter is used as the reference // source. // cl::opt<std::string> OutputFile("output", cl::desc("Specify a reference program output " "(for miscompilation detection)")); enum DebugType { DebugCompile, DebugCodegen }; cl::opt<DebugType> DebugMode("mode", cl::desc("Debug mode for bugpoint:"), cl::Prefix, cl::values(clEnumValN(DebugCompile, "compile", " Compilation"), clEnumValN(DebugCodegen, "codegen", " Code generation"), 0), cl::init(DebugCompile)); } /// getPassesString - Turn a list of passes into a string which indicates the /// command line options that must be passed to add the passes. /// std::string getPassesString(const std::vector<const PassInfo*> &Passes) { std::string Result; for (unsigned i = 0, e = Passes.size(); i != e; ++i) { if (i) Result += " "; Result += "-"; Result += Passes[i]->getPassArgument(); } return Result; } // DeleteFunctionBody - "Remove" the function by deleting all of its basic // blocks, making it external. // void DeleteFunctionBody(Function *F) { // delete the body of the function... F->deleteBody(); assert(F->isExternal() && "This didn't make the function external!"); } BugDriver::BugDriver(const char *toolname) : ToolName(toolname), ReferenceOutputFile(OutputFile), Program(0), Interpreter(0), cbe(0), gcc(0) {} /// ParseInputFile - Given a bytecode or assembly input filename, parse and /// return it, or return null if not possible. /// Module *BugDriver::ParseInputFile(const std::string &InputFilename) const { Module *Result = 0; try { Result = ParseBytecodeFile(InputFilename); if (!Result && !(Result = ParseAssemblyFile(InputFilename))){ std::cerr << ToolName << ": could not read input file '" << InputFilename << "'!\n"; } } catch (const ParseException &E) { std::cerr << ToolName << ": " << E.getMessage() << "\n"; Result = 0; } return Result; } // This method takes the specified list of LLVM input files, attempts to load // them, either as assembly or bytecode, then link them together. It returns // true on failure (if, for example, an input bytecode file could not be // parsed), and false on success. // bool BugDriver::addSources(const std::vector<std::string> &Filenames) { assert(Program == 0 && "Cannot call addSources multiple times!"); assert(!Filenames.empty() && "Must specify at least on input filename!"); // Load the first input file... Program = ParseInputFile(Filenames[0]); if (Program == 0) return true; std::cout << "Read input file : '" << Filenames[0] << "'\n"; for (unsigned i = 1, e = Filenames.size(); i != e; ++i) { std::auto_ptr<Module> M(ParseInputFile(Filenames[i])); if (M.get() == 0) return true; std::cout << "Linking in input file: '" << Filenames[i] << "'\n"; std::string ErrorMessage; if (LinkModules(Program, M.get(), &ErrorMessage)) { std::cerr << ToolName << ": error linking in '" << Filenames[i] << "': " << ErrorMessage << "\n"; return true; } } std::cout << "*** All input ok\n"; // All input files read successfully! return false; } /// run - The top level method that is invoked after all of the instance /// variables are set up from command line arguments. /// bool BugDriver::run() { // The first thing that we must do is determine what the problem is. Does the // optimization series crash the compiler, or does it produce illegal code? We // make the top-level decision by trying to run all of the passes on the the // input program, which should generate a bytecode file. If it does generate // a bytecode file, then we know the compiler didn't crash, so try to diagnose // a miscompilation. // if (!PassesToRun.empty()) { std::cout << "Running selected passes on program to test for crash: "; if (runPasses(PassesToRun)) return debugCrash(); } std::cout << "Checking for a miscompilation...\n"; // Set up the execution environment, selecting a method to run LLVM bytecode. if (initializeExecutionEnvironment()) return true; // Run the raw input to see where we are coming from. If a reference output // was specified, make sure that the raw output matches it. If not, it's a // problem in the front-end or the code generator. // bool CreatedOutput = false; if (ReferenceOutputFile.empty()) { std::cout << "Generating reference output from raw program..."; if (DebugCodegen) { ReferenceOutputFile = executeProgramWithCBE("bugpoint.reference.out"); } else { ReferenceOutputFile = executeProgram("bugpoint.reference.out"); } CreatedOutput = true; std::cout << "Reference output is: " << ReferenceOutputFile << "\n"; } bool Result; switch (DebugMode) { default: assert(0 && "Bad value for DebugMode!"); case DebugCompile: std::cout << "\n*** Debugging miscompilation!\n"; Result = debugMiscompilation(); break; case DebugCodegen: std::cout << "Debugging code generator problem!\n"; Result = debugCodeGenerator(); } if (CreatedOutput) removeFile(ReferenceOutputFile); return Result; } void BugDriver::PrintFunctionList(const std::vector<Function*> &Funcs) { for (unsigned i = 0, e = Funcs.size(); i != e; ++i) { if (i) std::cout << ", "; std::cout << Funcs[i]->getName(); } } <|endoftext|>
<commit_before>// // Logarithm.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Logarithm.h" using namespace std; #include <string> //constructor for int base with an int operand Logarithm::Logarithm(int base, int operand){ if (operand == 0){ throw runtime_error("Logarithms of 0 are undefined."); } if (operand < 0) { throw runtime_error("Logarithms of negative numbers are undefined."); } this->type = "logarithm"; this->base = base; this->operand = operand; this->eOperand = new Integer(operand); this->eBase = new Integer(base); } //constructor for expression base and or expression operand Logarithm::Logarithm(Expression* eBase, Expression* eOperand){ this->type = "logarithm"; this->eBase = eBase; this->eOperand = eOperand; } //get-set methods below int Logarithm::getBase(){ return base; } int Logarithm::getOperand(){ return operand; } Expression* Logarithm::getEBase(){ return eBase; } Expression* Logarithm::getEOperand(){ return eOperand; } void Logarithm::setBase(Expression* x){ this->eBase = x; } void Logarithm::setOperand(Expression* x){ this->eOperand = x; } Logarithm::~Logarithm(){ delete this; } Expression* Logarithm::simplifyOperand(){ Expression* e = this->eOperand; e->exp = e->toString(); string operand1 = e->exp; cout<<operand1; char asterick = '*'; char slash = '/'; vector<int> position; vector<char> symbols; int length = operand1.length(); for(int i = 0; i < length; i++) { if(operand1.at(i)== (asterick) || operand1.at(i)== slash){ position.push_back(i); position.push_back(operand1.at(i)); cout<<i<<endl; } } string number = ""; vector<Expression* > logs; for(int j =0; j<=position.size();j++){ int positionofop = position.at(j); string number = operand1.substr(j,positionofop-2); Solver* s = new Solver(); Expression* e = s->bindToExpressionType(number); Logarithm* simpleLog = (Logarithm*)e; simpleLog->simplify(); logs.push_back(e); } Expression* endlog = new Integer(0); endlog->type = "multiple"; stringstream endlogexp; for(int k = 0; k<logs.size(); k++){ endlogexp<<*logs.at(k); if(k+1 < logs.size()&& symbols.at(k == asterick)){ endlogexp<< " " << "+" << " "; } if(k+1 < logs.size()&& symbols.at(k == slash)){ endlogexp<< " " << "-" << " "; } } endlog->exp = endlogexp.str(); return endlog; } Expression* Logarithm::simplify(){ if(eOperand->type == "euler") { if(eBase->type == "euler"){ Integer* answer = new Integer(1); return answer; } else{ Logarithm* answer = new Logarithm(eBase, eOperand); return answer; } } if(eOperand->type == "pi") { if(eBase->type == "pi"){ Integer* answer = new Integer(1); return answer; } else{ Logarithm* answer = new Logarithm(eBase, eOperand); return answer; } } if(eOperand->type == "integer"){ vector<int> primefactors = primeFactorization(operand);//Create a vector of all the prime factors of the operand size_t size1 = primefactors.size();//gets the size of this vector vector<Expression *> seperatedLogs(size1);//creates another vector of type expression to save all of the separated Logs has the same size of the number of prime factors for(int i = 0 ; i < size1; i++){ seperatedLogs.at(i) = new Logarithm(this->eBase, new Integer(primefactors.at(i)));//assigns values to each seperatedlog with the same base and operands of the prime factorization } for(int j= 0; j <size1; j++){ if (seperatedLogs.at(j)->type == "logarithm") {//checks to see if the value at seperated log is a log type Logarithm* a = (Logarithm *)seperatedLogs.at(j); Logarithm* log = new Logarithm(a->getEBase(),a->getEOperand()); if(log->eBase->type == log->eOperand->type && log->eBase->type == "integer"){ //makes sure the ebase and eoperand are of the same type Integer* b = (Integer *)(log->eBase); Integer* c = (Integer *)(log->eOperand); if (b->getValue() == c->getValue()){// checks to see if the ebase and the eOperand are the same Integer* inte= new Integer(1);//returns one if they are the same seperatedLogs.at(j) = inte;//assigns 1 to the value of seperated log at j } } } } Expression * answer;//creates a new variable called answer if(size1 >= 2){// if the size is two or higher answer = seperatedLogs.at(0)->add(seperatedLogs.at(1));// add the first two together } else{//if the size is just 1 answer = seperatedLogs.at(0);//the answer is the first one } for(int k = 2; k<size1; k++){ answer = answer->add(seperatedLogs.at(k));//keeps adding elements of seperated log to answer } Integer* size2 = new Integer((int)size1); Integer* answerint = (Integer *)answer; if(answerint->getValue()==size2->getValue()) { return answer; } else if(size1 == 1){ return this; } else { Expression* e = new Integer(answerint->getValue()); e->type = "multiple"; stringstream s; for(int l = 0; l<size1; l++){ s<<*seperatedLogs.at(l); if(l+1 < size1){ s<< " " << "+" << " "; } } e->exp = s.str(); //cout<<e->exp; return e; } } throw runtime_error("invalid entry"); return this; } //creates vector of prime factors of n to be used in the simplify method vector<int> Logarithm::primeFactorization(int n) { int k = 0; vector<int> factors; while (n%2 == 0) { factors.push_back(2); n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { while (n%i == 0) { factors.push_back(i); k++; n = n/i; } } if (n > 2) { factors.push_back(n); } return factors; } Expression* Logarithm::add(Expression* a){ return this; } Expression* Logarithm::subtract(Expression* a){ Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) { if (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){ Expression* answer = new Integer(0); return answer; } } return c; } Expression* Logarithm::multiply(Expression* a){ Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) { if (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){ Exponential* answer = new Exponential(this, new Rational(2,1)); return answer; } } return c; } Expression* Logarithm::divide(Expression* a){//this set up is "this" divided by a so if this = log11 and a = log3 it would be log11/log3 Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->getEBase() == b->getEBase()) { Expression* numeratorOperand = c->getEOperand(); Expression* denominatorOperand = b->getEOperand(); Logarithm* answer = new Logarithm(denominatorOperand, numeratorOperand); return answer; } return c; } ostream& Logarithm::print(std::ostream& output) const{ output << "Log_" << *eBase << ":" << *eOperand<< endl; return output; } string Logarithm::toString(){ stringstream ss; ss << "Log_" << *this->eBase << ":" << *this->eOperand; return ss.str(); }; <commit_msg>stuff<commit_after>// // Logarithm.cpp // Calculator // // Created by Gavin Scheele on 3/27/14. // Copyright (c) 2014 Gavin Scheele. All rights reserved. // #include "Logarithm.h" using namespace std; #include <string> //constructor for int base with an int operand Logarithm::Logarithm(int base, int operand){ if (operand == 0){ throw runtime_error("Logarithms of 0 are undefined."); } if (operand < 0) { throw runtime_error("Logarithms of negative numbers are undefined."); } this->type = "logarithm"; this->base = base; this->operand = operand; this->eOperand = new Integer(operand); this->eBase = new Integer(base); } //constructor for expression base and or expression operand Logarithm::Logarithm(Expression* eBase, Expression* eOperand){ this->type = "logarithm"; this->eBase = eBase; this->eOperand = eOperand; } //get-set methods below int Logarithm::getBase(){ return base; } int Logarithm::getOperand(){ return operand; } Expression* Logarithm::getEBase(){ return eBase; } Expression* Logarithm::getEOperand(){ return eOperand; } void Logarithm::setBase(Expression* x){ this->eBase = x; } void Logarithm::setOperand(Expression* x){ this->eOperand = x; } Logarithm::~Logarithm(){ delete this; } Expression* Logarithm::simplifyOperand(){ Expression* e = this->eOperand; e->exp = e->toString(); string operand1 = e->exp; cout<<operand1; char asterick = '*'; char slash = '/'; vector<int> position; vector<char> symbols; int length = operand1.length(); for(int i = 0; i < length; i++) { if(operand1.at(i)== (asterick) || operand1.at(i)== slash){ position.push_back(i); position.push_back(operand1.at(i)); cout<<i<<endl; } } string number = ""; vector<Expression* > logs; for(int j =0; j<=position.size();j++){ int positionofop = position.at(j); string number = operand1.substr(j,positionofop-2); Solver* s = new Solver(); Expression* e = s->bindToExpressionType(number); Logarithm* simpleLog = (Logarithm*)e; simpleLog->simplify(); logs.push_back(e); } Expression* endlog = new Integer(0); endlog->type = "multiple"; stringstream endlogexp; for(int k = 0; k<logs.size(); k++){ endlogexp<<*logs.at(k); if(k+1 < logs.size()&& symbols.at(k == asterick)){ endlogexp<< " " << "+" << " "; } if(k+1 < logs.size()&& symbols.at(k == slash)){ endlogexp<< " " << "-" << " "; } } endlog->exp = endlogexp.str(); return endlog; } Expression* Logarithm::simplify(){ if(eOperand->type == "euler") { if(eBase->type == "euler"){ Integer* answer = new Integer(1); return answer; } else{ Logarithm* answer = new Logarithm(eBase, eOperand); return answer; } } if(eOperand->type == "pi") { if(eBase->type == "pi"){ Integer* answer = new Integer(1); return answer; } else{ Logarithm* answer = new Logarithm(eBase, eOperand); return answer; } } if(eOperand->type == "integer"){ vector<int> primefactors = primeFactorization(operand);//Create a vector of all the prime factors of the operand size_t size1 = primefactors.size();//gets the size of this vector vector<Expression *> seperatedLogs(size1);//creates another vector of type expression to save all of the separated Logs has the same size of the number of prime factors for(int i = 0 ; i < size1; i++){ seperatedLogs.at(i) = new Logarithm(this->eBase, new Integer(primefactors.at(i)));//assigns values to each seperatedlog with the same base and operands of the prime factorization } for(int j= 0; j <size1; j++){ if (seperatedLogs.at(j)->type == "logarithm") {//checks to see if the value at seperated log is a log type Logarithm* a = (Logarithm *)seperatedLogs.at(j); Logarithm* log = new Logarithm(a->getEBase(),a->getEOperand()); if(log->eBase->type == log->eOperand->type && log->eBase->type == "integer"){ //makes sure the ebase and eoperand are of the same type Integer* b = (Integer *)(log->eBase); Integer* c = (Integer *)(log->eOperand); if (b->getValue() == c->getValue()){// checks to see if the ebase and the eOperand are the same Integer* inte= new Integer(1);//returns one if they are the same seperatedLogs.at(j) = inte;//assigns 1 to the value of seperated log at j } } } } Expression * answer;//creates a new variable called answer if(size1 >= 2){// if the size is two or higher answer = seperatedLogs.at(0)->add(seperatedLogs.at(1));// add the first two together } else{//if the size is just 1 answer = seperatedLogs.at(0);//the answer is the first one } for(int k = 2; k<size1; k++){ answer = answer->add(seperatedLogs.at(k));//keeps adding elements of seperated log to answer } Integer* size2 = new Integer((int)size1); Integer* answerint = (Integer *)answer; if(answerint->getValue()==size2->getValue()) { return answer; } else if(size1 == 1){ return this; } else { Expression* e = new Integer(answerint->getValue()); e->type = "multiple"; stringstream s; for(int l = 0; l<size1; l++){ s<<*seperatedLogs.at(l); if(l+1 < size1){ s<< " " << "+" << " "; } } e->exp = s.str(); cout<<e->exp; return e; } } throw runtime_error("invalid entry"); return this; } //creates vector of prime factors of n to be used in the simplify method vector<int> Logarithm::primeFactorization(int n) { int k = 0; vector<int> factors; while (n%2 == 0) { factors.push_back(2); n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { while (n%i == 0) { factors.push_back(i); k++; n = n/i; } } if (n > 2) { factors.push_back(n); } return factors; } Expression* Logarithm::add(Expression* a){ return this; } Expression* Logarithm::subtract(Expression* a){ Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) { if (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){ Expression* answer = new Integer(0); return answer; } } return c; } Expression* Logarithm::multiply(Expression* a){ Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->eOperand->type == b->eOperand->type) { if (c->getEBase() == b->getEBase() && c->getEOperand() == b->getEOperand()){ Exponential* answer = new Exponential(this, new Rational(2,1)); return answer; } } return c; } Expression* Logarithm::divide(Expression* a){//this set up is "this" divided by a so if this = log11 and a = log3 it would be log11/log3 Logarithm* c = this; Logarithm* b = (Logarithm *) a; if(c->eBase->type == b->eBase->type && c->getEBase() == b->getEBase()) { Expression* numeratorOperand = c->getEOperand(); Expression* denominatorOperand = b->getEOperand(); Logarithm* answer = new Logarithm(denominatorOperand, numeratorOperand); return answer; } return c; } ostream& Logarithm::print(std::ostream& output) const{ output << "Log_" << *eBase << ":" << *eOperand<< endl; return output; } string Logarithm::toString(){ stringstream ss; ss << "Log_" << *this->eBase << ":" << *this->eOperand; return ss.str(); }; <|endoftext|>
<commit_before>// Copyright 2014 BVLC and contributors. #include <glog/logging.h> #include <leveldb/db.h> #include <stdint.h> #include <algorithm> #include <string> #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" using caffe::Datum; using caffe::BlobProto; using std::max; int main(int argc, char** argv) { ::google::InitGoogleLogging(argv[0]); if (argc != 3) { LOG(ERROR) << "Usage: compute_image_mean input_leveldb output_file"; return 1; } leveldb::DB* db; leveldb::Options options; options.create_if_missing = false; LOG(INFO) << "Opening leveldb " << argv[1]; leveldb::Status status = leveldb::DB::Open( options, argv[1], &db); CHECK(status.ok()) << "Failed to open leveldb " << argv[1]; leveldb::ReadOptions read_options; read_options.fill_cache = false; leveldb::Iterator* it = db->NewIterator(read_options); it->SeekToFirst(); Datum datum; BlobProto sum_blob; int count = 0; datum.ParseFromString(it->value().ToString()); sum_blob.set_num(1); sum_blob.set_channels(datum.channels()); sum_blob.set_height(datum.height()); sum_blob.set_width(datum.width()); const int data_size = datum.channels() * datum.height() * datum.width(); int size_in_datum = std::max<int>(datum.data().size(), datum.float_data_size()); for (int i = 0; i < size_in_datum; ++i) { sum_blob.add_data(0.); } LOG(INFO) << "Starting Iteration"; for (it->SeekToFirst(); it->Valid(); it->Next()) { // just a dummy operation datum.ParseFromString(it->value().ToString()); const string& data = datum.data(); size_in_datum = std::max<int>(datum.data().size(), datum.float_data_size()); CHECK_EQ(size_in_datum, data_size) << "Incorrect data field size " << size_in_datum; if (data.size() != 0) { for (int i = 0; i < size_in_datum; ++i) { sum_blob.set_data(i, sum_blob.data(i) + (uint8_t)data[i]); } } else { for (int i = 0; i < size_in_datum; ++i) { sum_blob.set_data(i, sum_blob.data(i) + static_cast<float>(datum.float_data(i))); } } ++count; if (count % 10000 == 0) { LOG(ERROR) << "Processed " << count << " files."; } } if (count % 10000 != 0) { LOG(ERROR) << "Processed " << count << " files."; } for (int i = 0; i < sum_blob.data_size(); ++i) { sum_blob.set_data(i, sum_blob.data(i) / count); } // Write to disk LOG(INFO) << "Write to " << argv[2]; WriteProtoToBinaryFile(sum_blob, argv[2]); delete db; return 0; } <commit_msg>add lmdb support for compute_image_mean<commit_after>// Copyright 2014 BVLC and contributors. #include <glog/logging.h> #include <leveldb/db.h> #include <lmdb.h> #include <stdint.h> #include <algorithm> #include <string> #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" using caffe::Datum; using caffe::BlobProto; using std::max; int main(int argc, char** argv) { ::google::InitGoogleLogging(argv[0]); if (argc < 3 || argc > 4) { LOG(ERROR) << "Usage: compute_image_mean input_leveldb output_file" << " db_backend[leveldb or lmdb]"; return 1; } string db_backend = "leveldb"; if (argc == 4) { db_backend = string(argv[3]); } // leveldb leveldb::DB* db; leveldb::Options options; options.create_if_missing = false; leveldb::Iterator* it; // lmdb MDB_env* mdb_env; MDB_dbi mdb_dbi; MDB_val mdb_key, mdb_value; MDB_txn* mdb_txn; MDB_cursor* mdb_cursor; // Open db if (db_backend == "leveldb") { // leveldb LOG(INFO) << "Opening leveldb " << argv[1]; leveldb::Status status = leveldb::DB::Open( options, argv[1], &db); CHECK(status.ok()) << "Failed to open leveldb " << argv[1]; leveldb::ReadOptions read_options; read_options.fill_cache = false; it = db->NewIterator(read_options); it->SeekToFirst(); } else if (db_backend == "lmdb") { // lmdb LOG(INFO) << "Opening lmdb " << argv[1]; CHECK_EQ(mdb_env_create(&mdb_env), MDB_SUCCESS) << "mdb_env_create failed"; CHECK_EQ(mdb_env_set_mapsize(mdb_env, 1099511627776), MDB_SUCCESS); // 1TB CHECK_EQ(mdb_env_open(mdb_env, argv[1], MDB_RDONLY, 0664), MDB_SUCCESS) << "mdb_env_open failed"; CHECK_EQ(mdb_txn_begin(mdb_env, NULL, MDB_RDONLY, &mdb_txn), MDB_SUCCESS) << "mdb_txn_begin failed"; CHECK_EQ(mdb_open(mdb_txn, NULL, 0, &mdb_dbi), MDB_SUCCESS) << "mdb_open failed"; CHECK_EQ(mdb_cursor_open(mdb_txn, mdb_dbi, &mdb_cursor), MDB_SUCCESS) << "mdb_cursor_open failed"; CHECK_EQ(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_FIRST), MDB_SUCCESS); } else { LOG(FATAL) << "Unknown db backend " << db_backend; } Datum datum; BlobProto sum_blob; int count = 0; // load first datum if (db_backend == "leveldb") { datum.ParseFromString(it->value().ToString()); } else if (db_backend == "lmdb") { datum.ParseFromArray(mdb_value.mv_data, mdb_value.mv_size); } else { LOG(FATAL) << "Unknown db backend " << db_backend; } sum_blob.set_num(1); sum_blob.set_channels(datum.channels()); sum_blob.set_height(datum.height()); sum_blob.set_width(datum.width()); const int data_size = datum.channels() * datum.height() * datum.width(); int size_in_datum = std::max<int>(datum.data().size(), datum.float_data_size()); for (int i = 0; i < size_in_datum; ++i) { sum_blob.add_data(0.); } LOG(INFO) << "Starting Iteration"; if (db_backend == "leveldb") { // leveldb for (it->SeekToFirst(); it->Valid(); it->Next()) { // just a dummy operation datum.ParseFromString(it->value().ToString()); const string& data = datum.data(); size_in_datum = std::max<int>(datum.data().size(), datum.float_data_size()); CHECK_EQ(size_in_datum, data_size) << "Incorrect data field size " << size_in_datum; if (data.size() != 0) { for (int i = 0; i < size_in_datum; ++i) { sum_blob.set_data(i, sum_blob.data(i) + (uint8_t)data[i]); } } else { for (int i = 0; i < size_in_datum; ++i) { sum_blob.set_data(i, sum_blob.data(i) + static_cast<float>(datum.float_data(i))); } } ++count; if (count % 10000 == 0) { LOG(ERROR) << "Processed " << count << " files."; } } } else if (db_backend == "lmdb") { // lmdb CHECK_EQ(mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_FIRST), MDB_SUCCESS); do { // just a dummy operation datum.ParseFromArray(mdb_value.mv_data, mdb_value.mv_size); const string& data = datum.data(); size_in_datum = std::max<int>(datum.data().size(), datum.float_data_size()); CHECK_EQ(size_in_datum, data_size) << "Incorrect data field size " << size_in_datum; if (data.size() != 0) { for (int i = 0; i < size_in_datum; ++i) { sum_blob.set_data(i, sum_blob.data(i) + (uint8_t)data[i]); } } else { for (int i = 0; i < size_in_datum; ++i) { sum_blob.set_data(i, sum_blob.data(i) + static_cast<float>(datum.float_data(i))); } } ++count; if (count % 10000 == 0) { LOG(ERROR) << "Processed " << count << " files."; } } while (mdb_cursor_get(mdb_cursor, &mdb_key, &mdb_value, MDB_NEXT) == MDB_SUCCESS); } else { LOG(FATAL) << "Unknown db backend " << db_backend; } if (count % 10000 != 0) { LOG(ERROR) << "Processed " << count << " files."; } for (int i = 0; i < sum_blob.data_size(); ++i) { sum_blob.set_data(i, sum_blob.data(i) / count); } // Write to disk LOG(INFO) << "Write to " << argv[2]; WriteProtoToBinaryFile(sum_blob, argv[2]); // Clean up if (db_backend == "leveldb") { delete db; } else if (db_backend == "lmdb") { mdb_cursor_close(mdb_cursor); mdb_close(mdb_env, mdb_dbi); mdb_txn_abort(mdb_txn); mdb_env_close(mdb_env); } else { LOG(FATAL) << "Unknown db backend " << db_backend; } return 0; } <|endoftext|>
<commit_before>/* * Copyright © 2011 Stéphane Raimbault <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This library implements the Modbus protocol. * http://libmodbus.org/ */ #include <inttypes.h> #include "WProgram.h" #include "Modbusino.h" #define _MODBUS_RTU_SLAVE 0 #define _MODBUS_RTU_FUNCTION 1 #define _MODBUS_RTU_PRESET_REQ_LENGTH 6 #define _MODBUS_RTU_PRESET_RSP_LENGTH 2 #define _MODBUS_RTU_CHECKSUM_LENGTH 2 #define _MODBUSINO_RTU_MAX_ADU_LENGTH 128 /* Supported function codes */ #define _FC_READ_HOLDING_REGISTERS 0x03 #define _FC_WRITE_MULTIPLE_REGISTERS 0x10 enum { _STEP_FUNCTION = 0x01, _STEP_META, _STEP_DATA }; static uint16_t crc16(uint8_t *req, uint8_t req_length) { uint8_t j; uint16_t crc; crc = 0xFFFF; while (req_length--) { crc = crc ^ *req++; for (j=0; j < 8; j++) { if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; else crc = crc >> 1; } } return (crc << 8 | crc >> 8); } ModbusinoSlave::ModbusinoSlave(uint8_t slave) { _slave = slave; } void ModbusinoSlave::setup(long baud) { Serial.begin(baud); } static int check_integrity(uint8_t *msg, uint8_t msg_length) { uint16_t crc_calculated; uint16_t crc_received; if (msg_length < 2) return -1; crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { return -1; } } static int build_response_basis(uint8_t slave, uint8_t function, uint8_t* rsp) { rsp[0] = slave; rsp[1] = function; return _MODBUS_RTU_PRESET_RSP_LENGTH; } static void send_msg(uint8_t *msg, uint8_t msg_length) { uint16_t crc = crc16(msg, msg_length); msg[msg_length++] = crc >> 8; msg[msg_length++] = crc & 0x00FF; Serial.write(msg, msg_length); } static uint8_t response_exception(uint8_t slave, uint8_t function, uint8_t exception_code, uint8_t *rsp) { uint8_t rsp_length; rsp_length = build_response_basis(slave, function + 0x80, rsp); /* Positive exception code */ rsp[rsp_length++] = exception_code; return rsp_length; } static void flush(void) { /* Wait a moment to receive the remaining garbage */ while (Serial.available()) { Serial.flush(); delay(3); } } static int receive(uint8_t *req, uint8_t _slave) { uint8_t i; uint8_t length_to_read; uint8_t req_index; uint8_t step; uint8_t function; /* We need to analyse the message step by step. At the first step, we want * to reach the function code because all packets contain this * information. */ step = _STEP_FUNCTION; length_to_read = _MODBUS_RTU_FUNCTION + 1; req_index = 0; while (length_to_read != 0) { /* The timeout is defined to ~10 ms between each bytes. Precision is not that important so I rather to avoid millis() to apply the KISS principle (millis overflows after 50 days, etc) */ if (!Serial.available()) { i = 0; while (!Serial.available()) { delay(1); if (++i == 10) { /* Too late, bye */ return -1; } } } req[req_index] = Serial.read(); /* Moves the pointer to receive other data */ req_index++; /* Computes remaining bytes */ length_to_read--; if (length_to_read == 0) { switch (step) { case _STEP_FUNCTION: /* Function code position */ function = req[_MODBUS_RTU_FUNCTION]; if (function == _FC_READ_HOLDING_REGISTERS) { length_to_read = 4; } else if (function == _FC_WRITE_MULTIPLE_REGISTERS) { length_to_read = 5; } else { /* Wait a moment to receive the remaining garbage */ flush(); if (_slave == req[_MODBUS_RTU_SLAVE]) { /* It's for me so send an exception (reuse req) */ uint8_t rsp_length = response_exception( _slave, function, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, req); send_msg(req, rsp_length); return - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION; } return -1; } step = _STEP_META; break; case _STEP_META: length_to_read = _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_WRITE_MULTIPLE_REGISTERS) length_to_read += req[_MODBUS_RTU_FUNCTION + 5]; if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) { flush(); if (_slave == req[_MODBUS_RTU_SLAVE]) { /* It's for me so send an exception (reuse req) */ uint8_t rsp_length = response_exception( _slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, req); send_msg(req, rsp_length); return - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION; } return -1; } step = _STEP_DATA; break; default: break; } } } return check_integrity(req, req_index); } static void reply(uint16_t *tab_reg, uint8_t nb_reg, uint8_t *req, uint8_t req_length, uint8_t _slave) { uint8_t slave = req[_MODBUS_RTU_SLAVE]; uint8_t function = req[_MODBUS_RTU_FUNCTION]; uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) + req[_MODBUS_RTU_FUNCTION + 2]; uint16_t nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) + req[_MODBUS_RTU_FUNCTION + 4]; uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH]; uint8_t rsp_length = 0; if (slave != _slave) { return; } if (address + nb > nb_reg) { rsp_length = response_exception( slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp); } req_length -= _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_READ_HOLDING_REGISTERS) { uint8_t i; rsp_length = build_response_basis(slave, function, rsp); rsp[rsp_length++] = nb << 1; for (i = address; i < address + nb; i++) { rsp[rsp_length++] = tab_reg[i] >> 8; rsp[rsp_length++] = tab_reg[i] & 0xFF; } } else { int i, j; for (i = address, j = 6; i < address + nb; i++, j += 2) { /* 6 and 7 = first value */ tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) + req[_MODBUS_RTU_FUNCTION + j + 1]; } rsp_length = build_response_basis(slave, function, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } send_msg(rsp, rsp_length); } int ModbusinoSlave::loop(uint16_t* tab_reg, uint8_t nb_reg) { int rc; uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH]; if (Serial.available()) { rc = receive(req, _slave); if (rc > 0) { reply(tab_reg, nb_reg, req, rc, _slave); } } /* Returns a positive value if successful, 0 if a slave filtering has occured, -1 if an undefined error has occured, -2 for MODBUS_EXCEPTION_ILLEGAL_FUNCTION etc */ return rc; } <commit_msg>Avoid getting stuck on a line saturated by garbage<commit_after>/* * Copyright © 2011 Stéphane Raimbault <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * This library implements the Modbus protocol. * http://libmodbus.org/ */ #include <inttypes.h> #include "WProgram.h" #include "Modbusino.h" #define _MODBUS_RTU_SLAVE 0 #define _MODBUS_RTU_FUNCTION 1 #define _MODBUS_RTU_PRESET_REQ_LENGTH 6 #define _MODBUS_RTU_PRESET_RSP_LENGTH 2 #define _MODBUS_RTU_CHECKSUM_LENGTH 2 #define _MODBUSINO_RTU_MAX_ADU_LENGTH 128 /* Supported function codes */ #define _FC_READ_HOLDING_REGISTERS 0x03 #define _FC_WRITE_MULTIPLE_REGISTERS 0x10 enum { _STEP_FUNCTION = 0x01, _STEP_META, _STEP_DATA }; static uint16_t crc16(uint8_t *req, uint8_t req_length) { uint8_t j; uint16_t crc; crc = 0xFFFF; while (req_length--) { crc = crc ^ *req++; for (j=0; j < 8; j++) { if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001; else crc = crc >> 1; } } return (crc << 8 | crc >> 8); } ModbusinoSlave::ModbusinoSlave(uint8_t slave) { _slave = slave; } void ModbusinoSlave::setup(long baud) { Serial.begin(baud); } static int check_integrity(uint8_t *msg, uint8_t msg_length) { uint16_t crc_calculated; uint16_t crc_received; if (msg_length < 2) return -1; crc_calculated = crc16(msg, msg_length - 2); crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; /* Check CRC of msg */ if (crc_calculated == crc_received) { return msg_length; } else { return -1; } } static int build_response_basis(uint8_t slave, uint8_t function, uint8_t* rsp) { rsp[0] = slave; rsp[1] = function; return _MODBUS_RTU_PRESET_RSP_LENGTH; } static void send_msg(uint8_t *msg, uint8_t msg_length) { uint16_t crc = crc16(msg, msg_length); msg[msg_length++] = crc >> 8; msg[msg_length++] = crc & 0x00FF; Serial.write(msg, msg_length); } static uint8_t response_exception(uint8_t slave, uint8_t function, uint8_t exception_code, uint8_t *rsp) { uint8_t rsp_length; rsp_length = build_response_basis(slave, function + 0x80, rsp); /* Positive exception code */ rsp[rsp_length++] = exception_code; return rsp_length; } static void flush(void) { uint8_t i = 0; /* Wait a moment to receive the remaining garbage but avoid getting stuck * because the line is saturated */ while (Serial.available() && i++ < 10) { Serial.flush(); delay(3); } } static int receive(uint8_t *req, uint8_t _slave) { uint8_t i; uint8_t length_to_read; uint8_t req_index; uint8_t step; uint8_t function; /* We need to analyse the message step by step. At the first step, we want * to reach the function code because all packets contain this * information. */ step = _STEP_FUNCTION; length_to_read = _MODBUS_RTU_FUNCTION + 1; req_index = 0; while (length_to_read != 0) { /* The timeout is defined to ~10 ms between each bytes. Precision is not that important so I rather to avoid millis() to apply the KISS principle (millis overflows after 50 days, etc) */ if (!Serial.available()) { i = 0; while (!Serial.available()) { delay(1); if (++i == 10) { /* Too late, bye */ return -1; } } } req[req_index] = Serial.read(); /* Moves the pointer to receive other data */ req_index++; /* Computes remaining bytes */ length_to_read--; if (length_to_read == 0) { switch (step) { case _STEP_FUNCTION: /* Function code position */ function = req[_MODBUS_RTU_FUNCTION]; if (function == _FC_READ_HOLDING_REGISTERS) { length_to_read = 4; } else if (function == _FC_WRITE_MULTIPLE_REGISTERS) { length_to_read = 5; } else { /* Wait a moment to receive the remaining garbage */ flush(); if (_slave == req[_MODBUS_RTU_SLAVE]) { /* It's for me so send an exception (reuse req) */ uint8_t rsp_length = response_exception( _slave, function, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, req); send_msg(req, rsp_length); return - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION; } return -1; } step = _STEP_META; break; case _STEP_META: length_to_read = _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_WRITE_MULTIPLE_REGISTERS) length_to_read += req[_MODBUS_RTU_FUNCTION + 5]; if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) { flush(); if (_slave == req[_MODBUS_RTU_SLAVE]) { /* It's for me so send an exception (reuse req) */ uint8_t rsp_length = response_exception( _slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, req); send_msg(req, rsp_length); return - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION; } return -1; } step = _STEP_DATA; break; default: break; } } } return check_integrity(req, req_index); } static void reply(uint16_t *tab_reg, uint8_t nb_reg, uint8_t *req, uint8_t req_length, uint8_t _slave) { uint8_t slave = req[_MODBUS_RTU_SLAVE]; uint8_t function = req[_MODBUS_RTU_FUNCTION]; uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) + req[_MODBUS_RTU_FUNCTION + 2]; uint16_t nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) + req[_MODBUS_RTU_FUNCTION + 4]; uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH]; uint8_t rsp_length = 0; if (slave != _slave) { return; } if (address + nb > nb_reg) { rsp_length = response_exception( slave, function, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp); } req_length -= _MODBUS_RTU_CHECKSUM_LENGTH; if (function == _FC_READ_HOLDING_REGISTERS) { uint8_t i; rsp_length = build_response_basis(slave, function, rsp); rsp[rsp_length++] = nb << 1; for (i = address; i < address + nb; i++) { rsp[rsp_length++] = tab_reg[i] >> 8; rsp[rsp_length++] = tab_reg[i] & 0xFF; } } else { int i, j; for (i = address, j = 6; i < address + nb; i++, j += 2) { /* 6 and 7 = first value */ tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) + req[_MODBUS_RTU_FUNCTION + j + 1]; } rsp_length = build_response_basis(slave, function, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } send_msg(rsp, rsp_length); } int ModbusinoSlave::loop(uint16_t* tab_reg, uint8_t nb_reg) { int rc; uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH]; if (Serial.available()) { rc = receive(req, _slave); if (rc > 0) { reply(tab_reg, nb_reg, req, rc, _slave); } } /* Returns a positive value if successful, 0 if a slave filtering has occured, -1 if an undefined error has occured, -2 for MODBUS_EXCEPTION_ILLEGAL_FUNCTION etc */ return rc; } <|endoftext|>
<commit_before>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2017 Victor DENIS ([email protected]) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include "AutoFill.hpp" #include <QWebEngineScript> #include <QWebEngineScriptCollection> #include <QSettings> #include <QSqlDatabase> #include <QSqlQuery> #include <QMessageBox> #include "Password/PasswordManager.hpp" #include "Web/WebPage.hpp" #include "Web/WebView.hpp" #include "Utils/SqlDatabase.hpp" #include "Application.hpp" #include "AutoFillNotification.hpp" namespace Sn { AutoFill::AutoFill(QObject* parent) : QObject(parent), m_manager(new PasswordManager(this)), m_isStoring(false) { loadSettings(); QString source = QLatin1String("(function() {" "function findUsername(inputs) {" " for (var i = 0; i < inputs.length; ++i)" " if (inputs[i].type == 'text' && inputs[i].value.length && inputs[i].name.indexOf('user') != -1)" " return inputs[i].value;" " for (var i = 0; i < inputs.length; ++i)" " if (inputs[i].type == 'text' && inputs[i].value.length && inputs[i].name.indexOf('name') != -1)" " return inputs[i].value;" " for (var i = 0; i < inputs.length; ++i)" " if (inputs[i].type == 'text' && inputs[i].value.length)" " return inputs[i].value;" " for (var i = 0; i < inputs.length; ++i)" " if (inputs[i].type == 'email' && inputs[i].value.length)" " return inputs[i].value;" " return '';" "}" "" "function registerForm(form) {" " form.addEventListener('submit', function() {" " var form = this;" " var data = '';" " var password = '';" " var inputs = form.getElementsByTagName('input');" " for (var i = 0; i < inputs.length; ++i) {" " var input = inputs[i];" " var type = input.type.toLowerCase();" " if (type != 'text' && type != 'password' && type != 'email')" " continue;" " if (!password && type == 'password')" " password = input.value;" " data += encodeURIComponent(input.name);" " data += '=';" " data += encodeURIComponent(input.value);" " data += '&';" " }" " if (!password)" " return;" " data = data.substring(0, data.length - 1);" " var url = window.location.href;" " var username = findUsername(inputs);" " external.autoFill.formSubmitted(url, username, password, data);" " }, true);" "}" "" "if (!document.documentElement) return;" "" "for (var i = 0; i < document.forms.length; ++i)" " registerForm(document.forms[i]);" "" "var observer = new MutationObserver(function(mutations) {" " for (var i = 0; i < mutations.length; ++i)" " for (var j = 0; j < mutations[i].addedNodes.length; ++j)" " if (mutations[i].addedNodes[j].tagName == 'form')" " registerForm(mutations[i].addedNodes[j]);" "});" "observer.observe(document.documentElement, { childList: true });" "" "})()"); QWebEngineScript script{}; script.setName(QStringLiteral("_sielo_autofill")); script.setInjectionPoint(QWebEngineScript::DocumentReady); script.setWorldId(QWebEngineScript::MainWorld); script.setRunsOnSubFrames(true); script.setSourceCode(source); Application::instance()->webProfile()->scripts()->insert(script); } void AutoFill::loadSettings() { QSettings settings{}; m_isStoring = settings.value("Settings/savePasswordsOnSites", true).toBool(); } bool AutoFill::isStored(const QUrl& url) { if (!isStoringEnabled(url)) return false; return !m_manager->getEntries(url).isEmpty(); } bool AutoFill::isStoringEnabled(const QUrl& url) { if (!m_isStoring) return false; QString server{url.host()}; QSqlQuery query{}; query.prepare("SELECT count(id) FROM autofill_exceptions WHERE server=?"); query.addBindValue(server); query.exec(); if (!query.next()) return false; return query.value(0).toInt() <= 0; } void AutoFill::blockStoringForUrl(const QUrl& url) { QString server{url.host()}; if (server.isEmpty()) server = url.toString(); QSqlQuery query{}; query.prepare("INSERT INTO autofill_exceptions (sever) VALUES (?)"); query.addBindValue(server); SqlDatabase::instance()->execAsync(query); } QVector<PasswordEntry> AutoFill::getFormData(const QUrl& url) { return m_manager->getEntries(url); } QVector<PasswordEntry> AutoFill::getAllFormData() { return m_manager->getAllEntries(); } void AutoFill::updateLastUsed(PasswordEntry& data) { m_manager->updateLastUsed(data); } void AutoFill::addEntry(const QUrl& url, const QString& name, const QString& password) { PasswordEntry entry{}; entry.host = PasswordManager::createHost(url); entry.username = name; entry.password = password; m_manager->addEntry(entry); } void AutoFill::addEntry(const QUrl& url, const PageFormData& formData) { PasswordEntry entry{}; entry.host = PasswordManager::createHost(url); entry.username = formData.username; entry.password = formData.password; entry.data = formData.postData; m_manager->addEntry(entry); } void AutoFill::updateEntry(const QUrl& url, const QString& name, const QString& password) { PasswordEntry entry{}; entry.host = PasswordManager::createHost(url); entry.username = name; entry.password = password; m_manager->updateEntry(entry); } bool AutoFill::updateEntry(const PasswordEntry& entry) { return m_manager->updateEntry(entry); } void AutoFill::removeEntry(const PasswordEntry& entry) { m_manager->removeEntry(entry); } void AutoFill::removeAllEntries() { m_manager->removeAllEntries(); } void AutoFill::saveForm(WebPage* page, const QUrl& frameUrl, const PageFormData& formData) { if (Application::instance()->privateBrowsing() || !page) return; if (!isStoringEnabled(frameUrl)) return; PasswordEntry updateData{}; if (isStored(frameUrl)) { const QVector<PasswordEntry>& list = getFormData(frameUrl); foreach (const PasswordEntry& data, list) { if (data.username == formData.username) { updateData = data; updateLastUsed(updateData); if (data.password == formData.password) { updateData.password.clear(); return; } updateData.username = formData.username; updateData.password = formData.password; updateData.data = formData.postData; break; } } } AutoFillNotification* notification{new AutoFillNotification(frameUrl, formData, updateData)}; page->view()->addNotification(notification); } QVector<PasswordEntry> AutoFill::completePage(WebPage* page, const QUrl& frameUrl) { QVector<PasswordEntry> list; if (!page || !isStored(frameUrl)) return list; list = getFormData(frameUrl); if (!list.isEmpty()) { QString source = QLatin1String("(function() {" "var data = '%1'.split('&');" "var inputs = document.getElementsByTagName('input');" "" "for (var i = 0; i < data.length; ++i) {" " var pair = data[i].split('=');" " if (pair.length != 2)" " continue;" " var key = decodeURIComponent(pair[0]);" " var val = decodeURIComponent(pair[1]);" " for (var j = 0; j < inputs.length; ++j) {" " var input = inputs[j];" " var type = input.type.toLowerCase();" " if (type != 'text' && type != 'password' && type != 'email')" " continue;" " if (input.name == key)" " input.value = val;" " }" "}" "" "})()"); const PasswordEntry entry = list[0]; QString data{entry.data}; data.replace(QLatin1String("'"), QLatin1String("\\'")); page->runJavaScript(source.arg(data), QWebEngineScript::ApplicationWorld); } return list; } QByteArray AutoFill::exportPasswords() { //TODO: do QMessageBox::critical(nullptr, tr("No"), tr("You can't export password yet")); return QByteArray(); } bool AutoFill::importPasswords(const QByteArray& data) { //TODO: do QMessageBox::critical(nullptr, tr("No"), tr("You can't import password yet")); return false; } } <commit_msg>[Fix] mistakes in AutoFill class<commit_after>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2017 Victor DENIS ([email protected]) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include "AutoFill.hpp" #include <QWebEngineScript> #include <QWebEngineScriptCollection> #include <QSettings> #include <QSqlDatabase> #include <QSqlQuery> #include <QMessageBox> #include "Password/PasswordManager.hpp" #include "Web/WebPage.hpp" #include "Web/WebView.hpp" #include "Utils/SqlDatabase.hpp" #include "Application.hpp" #include "AutoFillNotification.hpp" namespace Sn { AutoFill::AutoFill(QObject* parent) : QObject(parent), m_manager(new PasswordManager(this)), m_isStoring(false) { loadSettings(); QString source = QLatin1String("(function() {" "function findUsername(inputs) {" " for (var i = 0; i < inputs.length; ++i)" " if (inputs[i].type == 'text' && inputs[i].value.length && inputs[i].name.indexOf('user') != -1)" " return inputs[i].value;" " for (var i = 0; i < inputs.length; ++i)" " if (inputs[i].type == 'text' && inputs[i].value.length && inputs[i].name.indexOf('name') != -1)" " return inputs[i].value;" " for (var i = 0; i < inputs.length; ++i)" " if (inputs[i].type == 'text' && inputs[i].value.length)" " return inputs[i].value;" " for (var i = 0; i < inputs.length; ++i)" " if (inputs[i].type == 'email' && inputs[i].value.length)" " return inputs[i].value;" " return '';" "}" "" "function registerForm(form) {" " form.addEventListener('submit', function() {" " var form = this;" " var data = '';" " var password = '';" " var inputs = form.getElementsByTagName('input');" " for (var i = 0; i < inputs.length; ++i) {" " var input = inputs[i];" " var type = input.type.toLowerCase();" " if (type != 'text' && type != 'password' && type != 'email')" " continue;" " if (!password && type == 'password')" " password = input.value;" " data += encodeURIComponent(input.name);" " data += '=';" " data += encodeURIComponent(input.value);" " data += '&';" " }" " if (!password)" " return;" " data = data.substring(0, data.length - 1);" " var url = window.location.href;" " var username = findUsername(inputs);" " external.autoFill.formSubmitted(url, username, password, data);" " }, true);" "}" "" "if (!document.documentElement) return;" "" "for (var i = 0; i < document.forms.length; ++i)" " registerForm(document.forms[i]);" "" "var observer = new MutationObserver(function(mutations) {" " for (var i = 0; i < mutations.length; ++i)" " for (var j = 0; j < mutations[i].addedNodes.length; ++j)" " if (mutations[i].addedNodes[j].tagName == 'form')" " registerForm(mutations[i].addedNodes[j]);" "});" "observer.observe(document.documentElement, { childList: true });" "" "})()"); QWebEngineScript script{}; script.setName(QStringLiteral("_sielo_autofill")); script.setInjectionPoint(QWebEngineScript::DocumentReady); script.setWorldId(QWebEngineScript::MainWorld); script.setRunsOnSubFrames(true); script.setSourceCode(source); Application::instance()->webProfile()->scripts()->insert(script); } void AutoFill::loadSettings() { QSettings settings{}; m_isStoring = settings.value("Settings/savePasswordsOnSites", true).toBool(); } bool AutoFill::isStored(const QUrl& url) { if (!isStoringEnabled(url)) return false; return !m_manager->getEntries(url).isEmpty(); } bool AutoFill::isStoringEnabled(const QUrl& url) { if (!m_isStoring) return false; QString server{url.host()}; if (server.isEmpty()) server = url.toString(); QSqlQuery query{}; query.prepare("SELECT count(id) FROM autofill_exceptions WHERE server=?"); query.addBindValue(server); query.exec(); if (!query.next()) return false; return query.value(0).toInt() <= 0; } void AutoFill::blockStoringForUrl(const QUrl& url) { QString server{url.host()}; if (server.isEmpty()) server = url.toString(); QSqlQuery query{}; query.prepare("INSERT INTO autofill_exceptions (server) VALUES (?)"); query.addBindValue(server); SqlDatabase::instance()->execAsync(query); } QVector<PasswordEntry> AutoFill::getFormData(const QUrl& url) { return m_manager->getEntries(url); } QVector<PasswordEntry> AutoFill::getAllFormData() { return m_manager->getAllEntries(); } void AutoFill::updateLastUsed(PasswordEntry& data) { m_manager->updateLastUsed(data); } void AutoFill::addEntry(const QUrl& url, const QString& name, const QString& password) { PasswordEntry entry{}; entry.host = PasswordManager::createHost(url); entry.username = name; entry.password = password; m_manager->addEntry(entry); } void AutoFill::addEntry(const QUrl& url, const PageFormData& formData) { PasswordEntry entry{}; entry.host = PasswordManager::createHost(url); entry.username = formData.username; entry.password = formData.password; entry.data = formData.postData; m_manager->addEntry(entry); } void AutoFill::updateEntry(const QUrl& url, const QString& name, const QString& password) { PasswordEntry entry{}; entry.host = PasswordManager::createHost(url); entry.username = name; entry.password = password; m_manager->updateEntry(entry); } bool AutoFill::updateEntry(const PasswordEntry& entry) { return m_manager->updateEntry(entry); } void AutoFill::removeEntry(const PasswordEntry& entry) { m_manager->removeEntry(entry); } void AutoFill::removeAllEntries() { m_manager->removeAllEntries(); } void AutoFill::saveForm(WebPage* page, const QUrl& frameUrl, const PageFormData& formData) { if (Application::instance()->privateBrowsing() || !page) return; if (!isStoringEnabled(frameUrl)) return; PasswordEntry updateData{}; if (isStored(frameUrl)) { const QVector<PasswordEntry>& list = getFormData(frameUrl); foreach (const PasswordEntry& data, list) { if (data.username == formData.username) { updateData = data; updateLastUsed(updateData); if (data.password == formData.password) { updateData.password.clear(); return; } updateData.username = formData.username; updateData.password = formData.password; updateData.data = formData.postData; break; } } } AutoFillNotification* notification{new AutoFillNotification(frameUrl, formData, updateData)}; page->view()->addNotification(notification); } QVector<PasswordEntry> AutoFill::completePage(WebPage* page, const QUrl& frameUrl) { QVector<PasswordEntry> list; if (!page || !isStored(frameUrl)) return list; list = getFormData(frameUrl); if (!list.isEmpty()) { QString source = QLatin1String("(function() {" "var data = '%1'.split('&');" "var inputs = document.getElementsByTagName('input');" "" "for (var i = 0; i < data.length; ++i) {" " var pair = data[i].split('=');" " if (pair.length != 2)" " continue;" " var key = decodeURIComponent(pair[0]);" " var val = decodeURIComponent(pair[1]);" " for (var j = 0; j < inputs.length; ++j) {" " var input = inputs[j];" " var type = input.type.toLowerCase();" " if (type != 'text' && type != 'password' && type != 'email')" " continue;" " if (input.name == key)" " input.value = val;" " }" "}" "" "})()"); const PasswordEntry entry = list[0]; QString data{entry.data}; data.replace(QLatin1String("'"), QLatin1String("\\'")); page->runJavaScript(source.arg(data), QWebEngineScript::ApplicationWorld); } return list; } QByteArray AutoFill::exportPasswords() { //TODO: do QMessageBox::critical(nullptr, tr("No"), tr("You can't export password yet")); return QByteArray(); } bool AutoFill::importPasswords(const QByteArray& data) { //TODO: do QMessageBox::critical(nullptr, tr("No"), tr("You can't import password yet")); return false; } } <|endoftext|>
<commit_before>#include <bitset> #include <iostream> #include <cassert> #include <vector> #include <stack> #include <map> #include <queue> #include <algorithm> #include <unordered_map> #include <algorithm> using namespace std; /* GF(2n), to be productized void print(int i) { // bitset<8> x(i); // cout << x << " "; cout << i << " "; } int shift(int i) { i = i << 1; if ((i & (1 << 3)) != 0) { // 76543210 // 00001011 i = i ^ 0xb; } return i; } int add(int i, int j) { return i ^ j; } int multiply(int i, int j) { int result = 0; int mask = 1; for (int bit = 0; bit < 3; bit++) { if ((mask & j) != 0) { int temp = i; for (int times = 0; times < bit; times++) { temp = shift(temp); } result = add(result, temp); } mask = mask << 1; } return result; } int main() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { cout << multiply(i, j) << " "; } cout << endl; } return 0; } */ const int n = 64; const int a = 125; // TODO, prime should account for largest possible overlap, good for now const int prime = 193; const int inverse = 190; int powers[64]; int mod(int x, int p) { return ((x % p) + p) % p; } void number_theoretic_transform_helper(int n, int* input, int* output, int sign) { for (int f = 0; f < n; f++) { output[f] = 0; for (int t = 0; t < n; t++) { output[f] = mod(output[f] + mod(powers[mod(sign * t * f, n)] * input[t], prime), prime); } } } void number_theoretic_transform(int n, int* input, int* output) { number_theoretic_transform_helper(n, input, output, -1); } void inverse_number_theoretic_transform(int n, int* input, int* output) { number_theoretic_transform_helper(n, input, output, 1); for (int f = 0; f < n; f++) { output[f] = mod(output[f] * inverse, prime); } } void fast_number_theoretic_transform_helper(int length, int input_offset, int stride, vector<int>& input, int output_offset, int output_stride, vector<int>& output, int sign) { if (length == 1) { output[output_offset] = input[input_offset]; } else { int half = length / 2; fast_number_theoretic_transform_helper(half, input_offset, stride * 2, input, output_offset, output_stride, output, sign); fast_number_theoretic_transform_helper(half, input_offset + stride, stride * 2, input, output_offset + half * output_stride, output_stride, output, sign); for (int i = 0; i < half; i++) { int a = output[output_offset + i * output_stride]; int b = output[output_offset + (i + half) * output_stride]; int c = mod(a + mod(powers[mod(-i * n / length * sign, n)] * b, prime), prime); int d = mod(a + mod(powers[mod((half - i) * n / length * sign, n)] * b, prime), prime); output[output_offset + i * output_stride] = c; output[output_offset + (i + half) * output_stride] = d; } } } void fast_number_theoretic_transform(int length, int input_offset, int stride, vector<int>& input, int output_offset, int output_stride, vector<int>& output) { fast_number_theoretic_transform_helper(length, input_offset, stride, input, output_offset, output_stride, output, 1); } void inverse_fast_number_theoretic_transform(int length, int input_offset, int stride, vector<int>& input, int output_offset, int output_stride, vector<int>& output) { fast_number_theoretic_transform_helper(length, input_offset, stride, input, output_offset, output_stride, output, -1); for (int f = 0; f < length; f++) { // TODO - What I really needed here is the multiplicative inverse of length, not the multiplicative inverse of 64 output[output_offset + f * output_stride] = mod(output[output_offset + f * output_stride] * inverse, prime); } } void init_powers() { int p = 1; for (int i = 0; i < n; i++) { powers[i] = p; p = mod(p * a, prime); } } /* clc;clear; it1 = [1 1 0;0 1 0;0 1 0]; it2 = [1 0 0;1 1 0;0 0 0]; IT1 = [it1 zeros(3, 3);zeros(3, 6)]; IT2 = [it2 zeros(3, 3);zeros(3, 6)]; IF1 = fft2(IT1); IF2 = fft2(IT2); CF = IF1 .* IF2; CT = ifft2(CF) conv2(it1,it2) */ int main(int argc, char** argv) { init_powers(); vector<vector<int>> img1(3, vector<int>(3, 0)); vector<vector<int>> img2(3, vector<int>(3, 0)); img1[0][0] = 1; img1[0][1] = 1; img1[0][2] = 0; img1[1][0] = 0; img1[1][1] = 1; img1[1][2] = 0; img1[2][0] = 0; img1[2][1] = 1; img1[2][2] = 0; img2[0][0] = 0; img2[0][1] = 0; img2[0][2] = 0; img2[1][0] = 0; img2[1][1] = 1; img2[1][2] = 1; img2[2][0] = 0; img2[2][1] = 0; img2[2][2] = 1; vector<int> padded_image1(64, 0); vector<int> padded_image2(64, 0); vector<int> image1_rows(64, 0); vector<int> image2_rows(64, 0); vector<int> image1_rows_cols(64, 0); vector<int> image2_rows_cols(64, 0); vector<int> product (64, 0); vector<int> product_rows(64, 0); vector<int> product_rows_cols(64, 0); for (int row = 0; row < img1.size(); row++) { for (int col = 0; col < img1[0].size(); col++) { padded_image1[row * 8 + col] = img1[row][col]; } } for (int row = 0; row < img2.size(); row++) { for (int col = 0; col < img2[0].size(); col++) { padded_image2[row * 8 + col] = img2[img2.size() - row - 1][img2[0].size() - col - 1]; } } for (int row = 0; row < 8; row++) { fast_number_theoretic_transform(8, row * 8, 1, padded_image1, row * 8, 1, image1_rows); fast_number_theoretic_transform(8, row * 8, 1, padded_image2, row * 8, 1, image2_rows); } for (int col = 0; col < 8; col++) { fast_number_theoretic_transform(8, col, 8, image1_rows, col, 8, image1_rows_cols); fast_number_theoretic_transform(8, col, 8, image2_rows, col, 8, image2_rows_cols); } for (int i = 0; i < 64; i++) { product[i] = mod(image1_rows_cols[i] * image2_rows_cols[i], prime); } for (int row = 0; row < 8; row++) { inverse_fast_number_theoretic_transform(8, row * 8, 1, product, row * 8, 1, product_rows); } for (int col = 0; col < 8; col++) { inverse_fast_number_theoretic_transform(8, col, 8, product_rows, col, 8, product_rows_cols); } for (int row = 0; row < 8; row++) { for (int col = 0; col < 8; col++) { // TODO, eliminate this compensation cout << mod(product_rows_cols[row * 8 + col] * 64, prime) << " "; } cout << endl; } return 0; }<commit_msg>Improve Galois field implementation<commit_after>#include <iostream> #include <cassert> using namespace std; // This code represents GF(8), a Galois field of 8 elements // Each element in the field is represented by a polynomial with cofficients in GF(2) [i.e. a single bit] // We use an integer to represent the polynomial. Therefore, 00001011 represents the polynomial x^3 + x + 1 // Operations are done modulo a irreducible_polynomial polynomial, in this case, 00001011 // Beyond the constants, the code can be adapted to other irreducible polynomials and thus fields of different size // // For example, this is a larger finite field of 1024 elements, this will take a while to run through the full brute-force testing // // const int degree = 10; // const int irreducible_polynomial = 1877; // const int degree = 3; const int irreducible_polynomial = 11; const int N = 1 << degree; int add(int i, int j) { // Adding a pair of polynomial is simply bitwise xor return i ^ j; } int additive_inverse(int i) { return i; } int mul(int i, int j) { // The idea of this algorithm is that when we write i to be f(x) and j to be g(x) // If we write g(x) as a sum of monomials, then we can write it as // g(x) = c2 x^2 + c1 x^1 + c0 x^0 // // Then the product can be written as // f(x)g(x) = c2 f(x) x^2 + c_1 f(x) x^1 + c_0 f(x) x^0 // = ((c2 f(x) x + c1 f(x))x) + c0 f(x) // = ((((0)x + c2 f(x)) x + c1 f(x))x) + c0 f(x) // // The formula does look complicated, but the code isn't. // // The evaluation starts from the innermost bracket, every time we want to evaluate the // outer bracket, we multiply by x and then add f(x) if the coefficient is not zero. // // That's it // int result = 0; int mask = 1 << (degree - 1); for (int bit = 0; bit < degree; bit++) { // This operation multiply the current polynomial by x result = result << 1; // Assuming result was a polynomial with degree at most 2 // After the multiply, it is at most 3, so either it is or it is not if ((result & (1 << degree)) != 0) { // In case it is, we compute the mod irreducible_polynomial simply by subtracting it. result = add(result, additive_inverse(irreducible_polynomial)); } // If the coefficient is not 0 if ((mask & j) != 0) { // Add f(x) to the result result = add(result, i); } // And consider the next less significant term mask = mask >> 1; } return result; } // A simple repeated squaring algorithm int power(int a, int n) { if (n == 0) { return 1; } else if (n == 1) { return a; } else { int half = power(a, n / 2); int answer = mul(half, half); if (n % 2 == 1) { answer = mul(answer, a); } return answer; } } // We know that the is multiplicative group is cyclic with order N - 1, // therefore a^(N-1) = 1, so a^(N-2) is the multiplicative inverse int multiplicative_inverse(int a) { return power(a, N - 2); } // The procedure test that the field we generated does satisfy the field axioms. int main() { // closure not tested for (int a = 0; a < N; a++) { // identity rule assert(add(a, 0) == a); assert(add(0, a) == a); assert(mul(a, 1) == a); assert(mul(1, a) == a); // additive inverse assert(add(a, additive_inverse(a)) == 0); if (a != 0) { assert(mul(a, multiplicative_inverse(a)) == 1); } for (int b = 0; b < N; b++) { // commutative assert(add(a, b) == add(b, a)); assert(mul(a, b) == mul(b, a)); for (int c = 0; c < 8; c++) { // associative assert(add(add(a, b), c) == add(a, add(b, c))); assert(mul(mul(a, b), c) == mul(a, mul(b, c))); // distributive assert(mul(add(a, b), c) == add(mul(a, c), mul(b, c))); } } } // TODO: Find a primitive element return 0; }<|endoftext|>
<commit_before>// Copyright Hugh Perkins 2014 hughperkins at gmail // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include <stdexcept> #include <random> #include "Timer.h" #include "ConvolutionalLayer.h" #include "LayerMaker.h" #include "ActivationFunction.h" #include "StatefulTimer.h" #include "AccuracyHelper.h" #include "NeuralNetMould.h" #include "Layer.h" #include "InputLayer.h" #include "FullyConnectedLayer.h" #include "EpochMaker.h" #include "NeuralNet.h" using namespace std; //static std::mt19937 random; NeuralNet::NeuralNet( int numPlanes, int boardSize ) { cl = new OpenCLHelper(); InputLayerMaker *maker = new InputLayerMaker( this, numPlanes, boardSize ); maker->insert(); } NeuralNet::~NeuralNet() { for( int i = 0; i < layers.size(); i++ ) { delete layers[i]; } delete cl; } OpenCLHelper *NeuralNet::getCl() { return cl; } NeuralNetMould *NeuralNet::maker() { // [static] return new NeuralNetMould(); } FullyConnectedMaker *NeuralNet::fullyConnectedMaker() { return new FullyConnectedMaker( this ); } ConvolutionalMaker *NeuralNet::convolutionalMaker() { return new ConvolutionalMaker( this ); } void NeuralNet::initWeights( int layerIndex, float *weights, float *biasWeights ) { initWeights( layerIndex, weights ); initBiasWeights( layerIndex, biasWeights ); } void NeuralNet::initWeights( int layerIndex, float *weights ) { layers[layerIndex]->initWeights( weights ); } void NeuralNet::initBiasWeights( int layerIndex, float *weights ) { layers[layerIndex]->initBiasWeights( weights ); } void NeuralNet::printWeightsAsCode() { for( int layer = 1; layer < layers.size(); layer++ ) { layers[layer]->printWeightsAsCode(); } } void NeuralNet::printBiasWeightsAsCode() { for( int layer = 1; layer < layers.size(); layer++ ) { layers[layer]->printBiasWeightsAsCode(); } } float NeuralNet::calcLoss(float const *expectedValues ) { return layers[layers.size()-1]->calcLoss( expectedValues ); } EpochMaker *NeuralNet::epochMaker() { return new EpochMaker(this); } InputLayer *NeuralNet::getFirstLayer() { return dynamic_cast<InputLayer*>( layers[0] ); } Layer *NeuralNet::getLastLayer() { return layers[layers.size() - 1]; } Layer *NeuralNet::addLayer( LayerMaker *maker ) { Layer *previousLayer = 0; if( layers.size() > 0 ) { previousLayer = layers[ layers.size() - 1 ]; } maker->setPreviousLayer( previousLayer ); Layer *layer = maker->instance(); layers.push_back( layer ); return layer; } void NeuralNet::setBatchSize( int batchSize ) { for( std::vector<Layer*>::iterator it = layers.begin(); it != layers.end(); it++ ) { (*it)->setBatchSize( batchSize ); } } float NeuralNet::doEpoch( float learningRate, int batchSize, int numImages, float const* images, float const *expectedResults ) { // Timer timer; setBatchSize( batchSize ); int numBatches = numImages / batchSize; float loss = 0; int total = 0; for( int batch = 0; batch < numBatches; batch++ ) { int batchStart = batch * batchSize; int thisBatchSize = batchSize; if( batch == numBatches - 1 ) { thisBatchSize = numImages - batchStart; // eg, we have 5 images, and batchsize is 3 // so last batch size is: 2 = 5 - 3 setBatchSize( thisBatchSize ); } // std::cout << " batch " << batch << " start " << batchStart << " inputsizeperex " << getInputSizePerExample() << // " resultssizeperex " << getResultsSizePerExample() << std::endl; learnBatch( learningRate, &(images[batchStart*getInputSizePerExample()]), &(expectedResults[batchStart*getResultsSizePerExample()]) ); loss += calcLoss( &(expectedResults[batchStart*getResultsSizePerExample()]) ); } // StatefulTimer::dump(); // timer.timeCheck("epoch time"); return loss; } float NeuralNet::doEpochWithCalcTrainingAccuracy( float learningRate, int batchSize, int numImages, float const* images, float const *expectedResults, int const *labels, int *p_totalCorrect ) { // Timer timer; setBatchSize( batchSize ); int numBatches = ( numImages + batchSize - 1 ) / batchSize; std::cout << "numBatches: " << numBatches << std::endl; float loss = 0; int numRight = 0; int total = 0; if( getLastLayer()->boardSize != 1 ) { throw std::runtime_error("Last layer should have board size of 1, and number of planes equal number of categories, if you want to measure training accuracy"); } for( int batch = 0; batch < numBatches; batch++ ) { int batchStart = batch * batchSize; int thisBatchSize = batchSize; if( batch == numBatches - 1 ) { thisBatchSize = numImages - batchStart; // eg, we have 5 images, and batchsize is 3 // so last batch size is: 2 = 5 - 3 setBatchSize( thisBatchSize ); } // std::cout << " batch " << batch << " start " << batchStart << " inputsizeperex " << getInputSizePerExample() << // " resultssizeperex " << getResultsSizePerExample() << std::endl; learnBatch( learningRate, &(images[batchStart*getInputSizePerExample()]), &(expectedResults[batchStart*getResultsSizePerExample()]) ); StatefulTimer::timeCheck("after batch forward-backward prop"); numRight += AccuracyHelper::calcNumRight( thisBatchSize, getLastLayer()->numPlanes, &(labels[batchStart]), getResults() ); StatefulTimer::timeCheck("after batch calc training num right"); loss += calcLoss( &(expectedResults[batchStart*getResultsSizePerExample()]) ); StatefulTimer::timeCheck("after batch calc loss"); } *p_totalCorrect = numRight; // StatefulTimer::dump(); // timer.timeCheck("epoch time"); return loss; } // float *propagate( int N, int batchSize, float const*images) { // float *results = new float[N]; // int numBatches = N / batchSize; // for( int batch = 0; batch < numBatches; batch++ ) { // int batchStart = batch * batchSize; // int batchEndExcl = std::min( N, (batch + 1 ) * batchSize ); // propagateBatch( &(images[batchStart]) ); // std::cout << " batch " << batch << " start " << batchStart << " end " << batchEndExcl << std::endl; // float const *netResults = getResults(); // for( int i = 0; i < batchSize; i++ ) { // results[batchStart + i ] = netResults[i]; // } // } // return results; // } void NeuralNet::propagate( float const*images) { // forward... // Timer timer; dynamic_cast<InputLayer *>(layers[0])->in( images ); for( int layerId = 1; layerId < layers.size(); layerId++ ) { layers[layerId]->propagate(); } // timer.timeCheck("propagate time"); } void NeuralNet::backProp(float learningRate, float const *expectedResults) { // backward... Layer *lastLayer = getLastLayer(); float *errors = new float[ lastLayer->getResultsSize() ]; lastLayer->calcErrors( expectedResults, errors ); float *errorsForNextLayer = 0; for( int layerIdx = layers.size() - 1; layerIdx >= 1; layerIdx-- ) { // no point in propagating to input layer :-P if( layerIdx > 1 ) { errorsForNextLayer = new float[ layers[layerIdx-1]->getResultsSize() ]; } layers[layerIdx]->backPropErrors( learningRate, errors, errorsForNextLayer ); delete[] errors; errors = 0; errors = errorsForNextLayer; errorsForNextLayer = 0; } } void NeuralNet::learnBatch( float learningRate, float const*images, float const *expectedResults ) { // Timer timer; propagate( images); // timer.timeCheck("propagate"); backProp(learningRate, expectedResults ); // timer.timeCheck("backProp"); } int NeuralNet::getNumLayers() { return layers.size(); } float const *NeuralNet::getResults( int layer ) const { return layers[layer]->getResults(); } int NeuralNet::getInputSizePerExample() const { return layers[ 0 ]->getResultsSizePerExample(); } int NeuralNet::getResultsSizePerExample() const { return layers[ layers.size() - 1 ]->getResultsSizePerExample(); } float const *NeuralNet::getResults() const { return getResults( layers.size() - 1 ); } void NeuralNet::print() { int i = 0; for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) { std::cout << "layer " << i << ":" << std::endl; (*it)->print(); i++; } } void NeuralNet::printWeights() { int i = 0; for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) { std::cout << "layer " << i << ":" << std::endl; (*it)->printWeights(); i++; } } void NeuralNet::printOutput() { int i = 0; for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) { std::cout << "layer " << i << ":" << std::endl; (*it)->printOutput(); i++; } } <commit_msg>move [static] to line before method<commit_after>// Copyright Hugh Perkins 2014 hughperkins at gmail // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include <stdexcept> #include <random> #include "Timer.h" #include "ConvolutionalLayer.h" #include "LayerMaker.h" #include "ActivationFunction.h" #include "StatefulTimer.h" #include "AccuracyHelper.h" #include "NeuralNetMould.h" #include "Layer.h" #include "InputLayer.h" #include "FullyConnectedLayer.h" #include "EpochMaker.h" #include "NeuralNet.h" using namespace std; //static std::mt19937 random; NeuralNet::NeuralNet( int numPlanes, int boardSize ) { cl = new OpenCLHelper(); InputLayerMaker *maker = new InputLayerMaker( this, numPlanes, boardSize ); maker->insert(); } NeuralNet::~NeuralNet() { for( int i = 0; i < layers.size(); i++ ) { delete layers[i]; } delete cl; } OpenCLHelper *NeuralNet::getCl() { return cl; } // [static] NeuralNetMould *NeuralNet::maker() { return new NeuralNetMould(); } FullyConnectedMaker *NeuralNet::fullyConnectedMaker() { return new FullyConnectedMaker( this ); } ConvolutionalMaker *NeuralNet::convolutionalMaker() { return new ConvolutionalMaker( this ); } void NeuralNet::initWeights( int layerIndex, float *weights, float *biasWeights ) { initWeights( layerIndex, weights ); initBiasWeights( layerIndex, biasWeights ); } void NeuralNet::initWeights( int layerIndex, float *weights ) { layers[layerIndex]->initWeights( weights ); } void NeuralNet::initBiasWeights( int layerIndex, float *weights ) { layers[layerIndex]->initBiasWeights( weights ); } void NeuralNet::printWeightsAsCode() { for( int layer = 1; layer < layers.size(); layer++ ) { layers[layer]->printWeightsAsCode(); } } void NeuralNet::printBiasWeightsAsCode() { for( int layer = 1; layer < layers.size(); layer++ ) { layers[layer]->printBiasWeightsAsCode(); } } float NeuralNet::calcLoss(float const *expectedValues ) { return layers[layers.size()-1]->calcLoss( expectedValues ); } EpochMaker *NeuralNet::epochMaker() { return new EpochMaker(this); } InputLayer *NeuralNet::getFirstLayer() { return dynamic_cast<InputLayer*>( layers[0] ); } Layer *NeuralNet::getLastLayer() { return layers[layers.size() - 1]; } Layer *NeuralNet::addLayer( LayerMaker *maker ) { Layer *previousLayer = 0; if( layers.size() > 0 ) { previousLayer = layers[ layers.size() - 1 ]; } maker->setPreviousLayer( previousLayer ); Layer *layer = maker->instance(); layers.push_back( layer ); return layer; } void NeuralNet::setBatchSize( int batchSize ) { for( std::vector<Layer*>::iterator it = layers.begin(); it != layers.end(); it++ ) { (*it)->setBatchSize( batchSize ); } } float NeuralNet::doEpoch( float learningRate, int batchSize, int numImages, float const* images, float const *expectedResults ) { // Timer timer; setBatchSize( batchSize ); int numBatches = numImages / batchSize; float loss = 0; int total = 0; for( int batch = 0; batch < numBatches; batch++ ) { int batchStart = batch * batchSize; int thisBatchSize = batchSize; if( batch == numBatches - 1 ) { thisBatchSize = numImages - batchStart; // eg, we have 5 images, and batchsize is 3 // so last batch size is: 2 = 5 - 3 setBatchSize( thisBatchSize ); } // std::cout << " batch " << batch << " start " << batchStart << " inputsizeperex " << getInputSizePerExample() << // " resultssizeperex " << getResultsSizePerExample() << std::endl; learnBatch( learningRate, &(images[batchStart*getInputSizePerExample()]), &(expectedResults[batchStart*getResultsSizePerExample()]) ); loss += calcLoss( &(expectedResults[batchStart*getResultsSizePerExample()]) ); } // StatefulTimer::dump(); // timer.timeCheck("epoch time"); return loss; } float NeuralNet::doEpochWithCalcTrainingAccuracy( float learningRate, int batchSize, int numImages, float const* images, float const *expectedResults, int const *labels, int *p_totalCorrect ) { // Timer timer; setBatchSize( batchSize ); int numBatches = ( numImages + batchSize - 1 ) / batchSize; std::cout << "numBatches: " << numBatches << std::endl; float loss = 0; int numRight = 0; int total = 0; if( getLastLayer()->boardSize != 1 ) { throw std::runtime_error("Last layer should have board size of 1, and number of planes equal number of categories, if you want to measure training accuracy"); } for( int batch = 0; batch < numBatches; batch++ ) { int batchStart = batch * batchSize; int thisBatchSize = batchSize; if( batch == numBatches - 1 ) { thisBatchSize = numImages - batchStart; // eg, we have 5 images, and batchsize is 3 // so last batch size is: 2 = 5 - 3 setBatchSize( thisBatchSize ); } // std::cout << " batch " << batch << " start " << batchStart << " inputsizeperex " << getInputSizePerExample() << // " resultssizeperex " << getResultsSizePerExample() << std::endl; learnBatch( learningRate, &(images[batchStart*getInputSizePerExample()]), &(expectedResults[batchStart*getResultsSizePerExample()]) ); StatefulTimer::timeCheck("after batch forward-backward prop"); numRight += AccuracyHelper::calcNumRight( thisBatchSize, getLastLayer()->numPlanes, &(labels[batchStart]), getResults() ); StatefulTimer::timeCheck("after batch calc training num right"); loss += calcLoss( &(expectedResults[batchStart*getResultsSizePerExample()]) ); StatefulTimer::timeCheck("after batch calc loss"); } *p_totalCorrect = numRight; // StatefulTimer::dump(); // timer.timeCheck("epoch time"); return loss; } // float *propagate( int N, int batchSize, float const*images) { // float *results = new float[N]; // int numBatches = N / batchSize; // for( int batch = 0; batch < numBatches; batch++ ) { // int batchStart = batch * batchSize; // int batchEndExcl = std::min( N, (batch + 1 ) * batchSize ); // propagateBatch( &(images[batchStart]) ); // std::cout << " batch " << batch << " start " << batchStart << " end " << batchEndExcl << std::endl; // float const *netResults = getResults(); // for( int i = 0; i < batchSize; i++ ) { // results[batchStart + i ] = netResults[i]; // } // } // return results; // } void NeuralNet::propagate( float const*images) { // forward... // Timer timer; dynamic_cast<InputLayer *>(layers[0])->in( images ); for( int layerId = 1; layerId < layers.size(); layerId++ ) { layers[layerId]->propagate(); } // timer.timeCheck("propagate time"); } void NeuralNet::backProp(float learningRate, float const *expectedResults) { // backward... Layer *lastLayer = getLastLayer(); float *errors = new float[ lastLayer->getResultsSize() ]; lastLayer->calcErrors( expectedResults, errors ); float *errorsForNextLayer = 0; for( int layerIdx = layers.size() - 1; layerIdx >= 1; layerIdx-- ) { // no point in propagating to input layer :-P if( layerIdx > 1 ) { errorsForNextLayer = new float[ layers[layerIdx-1]->getResultsSize() ]; } layers[layerIdx]->backPropErrors( learningRate, errors, errorsForNextLayer ); delete[] errors; errors = 0; errors = errorsForNextLayer; errorsForNextLayer = 0; } } void NeuralNet::learnBatch( float learningRate, float const*images, float const *expectedResults ) { // Timer timer; propagate( images); // timer.timeCheck("propagate"); backProp(learningRate, expectedResults ); // timer.timeCheck("backProp"); } int NeuralNet::getNumLayers() { return layers.size(); } float const *NeuralNet::getResults( int layer ) const { return layers[layer]->getResults(); } int NeuralNet::getInputSizePerExample() const { return layers[ 0 ]->getResultsSizePerExample(); } int NeuralNet::getResultsSizePerExample() const { return layers[ layers.size() - 1 ]->getResultsSizePerExample(); } float const *NeuralNet::getResults() const { return getResults( layers.size() - 1 ); } void NeuralNet::print() { int i = 0; for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) { std::cout << "layer " << i << ":" << std::endl; (*it)->print(); i++; } } void NeuralNet::printWeights() { int i = 0; for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) { std::cout << "layer " << i << ":" << std::endl; (*it)->printWeights(); i++; } } void NeuralNet::printOutput() { int i = 0; for( std::vector< Layer* >::iterator it = layers.begin(); it != layers.end(); it++ ) { std::cout << "layer " << i << ":" << std::endl; (*it)->printOutput(); i++; } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/options/customize_sync_window_gtk.h" #include <gtk/gtk.h> #include <string> #include "app/gtk_signal.h" #include "app/l10n_util.h" #include "base/message_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/gtk/accessible_widget_helper_gtk.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/options_window.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/glue/data_type_controller.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk // // The contents of the Customize Sync dialog window. class CustomizeSyncWindowGtk { public: explicit CustomizeSyncWindowGtk(Profile* profile); ~CustomizeSyncWindowGtk(); void Show(); bool ClickOk(); void ClickCancel(); private: // The pixel width we wrap labels at. static const int kWrapWidth = 475; GtkWidget* AddCheckbox(GtkWidget* parent, int label_id, bool checked); bool Accept(); static void OnWindowDestroy(GtkWidget* widget, CustomizeSyncWindowGtk* window); static void OnResponse(GtkDialog* dialog, gint response_id, CustomizeSyncWindowGtk* customize_sync_window); CHROMEGTK_CALLBACK_0(CustomizeSyncWindowGtk, void, OnCheckboxClicked); // The customize sync dialog. GtkWidget *dialog_; Profile* profile_; GtkWidget* description_label_; GtkWidget* bookmarks_check_box_; GtkWidget* preferences_check_box_; GtkWidget* themes_check_box_; GtkWidget* autofill_check_box_; // Helper object to manage accessibility metadata. scoped_ptr<AccessibleWidgetHelper> accessible_widget_helper_; DISALLOW_COPY_AND_ASSIGN(CustomizeSyncWindowGtk); }; // The singleton customize sync window object. static CustomizeSyncWindowGtk* customize_sync_window = NULL; /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk, public: CustomizeSyncWindowGtk::CustomizeSyncWindowGtk(Profile* profile) : profile_(profile), description_label_(NULL), bookmarks_check_box_(NULL), preferences_check_box_(NULL), themes_check_box_(NULL), autofill_check_box_(NULL) { syncable::ModelTypeSet registered_types; profile_->GetProfileSyncService()->GetRegisteredDataTypes(&registered_types); syncable::ModelTypeSet preferred_types; profile_->GetProfileSyncService()->GetPreferredDataTypes(&preferred_types); std::string dialog_name = l10n_util::GetStringUTF8( IDS_CUSTOMIZE_SYNC_WINDOW_TITLE); dialog_ = gtk_dialog_new_with_buttons( dialog_name.c_str(), // Customize sync window is shared between all browser windows. NULL, // Non-modal. GTK_DIALOG_NO_SEPARATOR, GTK_STOCK_OK, GTK_RESPONSE_OK, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), gtk_util::kContentAreaSpacing); accessible_widget_helper_.reset(new AccessibleWidgetHelper( dialog_, profile)); accessible_widget_helper_->SendOpenWindowNotification(dialog_name); GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); description_label_ = gtk_label_new(l10n_util::GetStringUTF8( IDS_CUSTOMIZE_SYNC_DESCRIPTION).c_str()); gtk_label_set_line_wrap(GTK_LABEL(description_label_), TRUE); gtk_widget_set_size_request(description_label_, kWrapWidth, -1); gtk_box_pack_start(GTK_BOX(vbox), description_label_, FALSE, FALSE, 0); accessible_widget_helper_->SetWidgetName(description_label_, IDS_CUSTOMIZE_SYNC_DESCRIPTION); DCHECK(registered_types.count(syncable::BOOKMARKS)); bool bookmarks_checked = preferred_types.count(syncable::BOOKMARKS) != 0; bookmarks_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_BOOKMARKS, bookmarks_checked); if (registered_types.count(syncable::PREFERENCES)) { bool prefs_checked = preferred_types.count(syncable::PREFERENCES) != 0; preferences_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_PREFERENCES, prefs_checked); } if (registered_types.count(syncable::THEMES)) { bool themes_checked = preferred_types.count(syncable::THEMES) != 0; themes_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_THEMES, themes_checked); } if (registered_types.count(syncable::AUTOFILL)) { bool autofill_checked = preferred_types.count(syncable::AUTOFILL) != 0; autofill_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_AUTOFILL, autofill_checked); } gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), vbox, FALSE, FALSE, 0); gtk_widget_realize(dialog_); gtk_util::SetWindowSizeFromResources(GTK_WINDOW(dialog_), IDS_CUSTOMIZE_SYNC_DIALOG_WIDTH_CHARS, IDS_CUSTOMIZE_SYNC_DIALOG_HEIGHT_LINES, true); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this); gtk_util::ShowDialog(dialog_); } CustomizeSyncWindowGtk::~CustomizeSyncWindowGtk() { } void CustomizeSyncWindowGtk::Show() { // Bring options window to front if it already existed and isn't already // in front gtk_util::PresentWindow(dialog_, 0); } bool CustomizeSyncWindowGtk::ClickOk() { if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) || (preferences_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( preferences_check_box_))) || (themes_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) || (autofill_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_)))) { Accept(); gtk_widget_destroy(GTK_WIDGET(dialog_)); return true; } else { // show the user that something's wrong with this dialog (not perfect, but // a temporary fix) gtk_util::PresentWindow(dialog_, 0); return false; } } void CustomizeSyncWindowGtk::ClickCancel() { gtk_widget_destroy(GTK_WIDGET(dialog_)); } /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk, private: GtkWidget* CustomizeSyncWindowGtk::AddCheckbox(GtkWidget* parent, int label_id, bool checked) { GtkWidget* checkbox = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(label_id).c_str()); gtk_box_pack_start(GTK_BOX(parent), checkbox, FALSE, FALSE, 0); accessible_widget_helper_->SetWidgetName(checkbox, label_id); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), checked); g_signal_connect(checkbox, "clicked", G_CALLBACK(OnCheckboxClickedThunk), this); return checkbox; } bool CustomizeSyncWindowGtk::Accept() { syncable::ModelTypeSet preferred_types; bool bookmarks_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(bookmarks_check_box_)); if (bookmarks_enabled) { preferred_types.insert(syncable::BOOKMARKS); } if (preferences_check_box_) { bool preferences_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(preferences_check_box_)); if (preferences_enabled) { preferred_types.insert(syncable::PREFERENCES); } } if (themes_check_box_) { bool themes_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(themes_check_box_)); if (themes_enabled) { preferred_types.insert(syncable::THEMES); } } if (autofill_check_box_) { bool autofill_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(autofill_check_box_)); if (autofill_enabled) { preferred_types.insert(syncable::AUTOFILL); } } profile_->GetProfileSyncService()->ChangePreferredDataTypes(preferred_types); return true; } // static void CustomizeSyncWindowGtk::OnWindowDestroy(GtkWidget* widget, CustomizeSyncWindowGtk* window) { customize_sync_window = NULL; MessageLoop::current()->DeleteSoon(FROM_HERE, window); } // static void CustomizeSyncWindowGtk::OnResponse( GtkDialog* dialog, gint response_id, CustomizeSyncWindowGtk* customize_sync_window) { if (response_id == GTK_RESPONSE_OK) { customize_sync_window->ClickOk(); } else if (response_id == GTK_RESPONSE_CANCEL) { customize_sync_window->ClickCancel(); } } // Deactivate the "OK" button if you uncheck all the data types. void CustomizeSyncWindowGtk::OnCheckboxClicked(GtkWidget* widget) { bool any_datatypes_selected = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) || (preferences_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( preferences_check_box_))) || (themes_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) || (autofill_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_))); if (any_datatypes_selected) { gtk_dialog_set_response_sensitive( GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, TRUE); } else { gtk_dialog_set_response_sensitive( GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, FALSE); } } /////////////////////////////////////////////////////////////////////////////// // Factory/finder method: void ShowCustomizeSyncWindow(Profile* profile) { DCHECK(profile); // If there's already an existing window, use it. if (!customize_sync_window) { customize_sync_window = new CustomizeSyncWindowGtk(profile); } customize_sync_window->Show(); } bool CustomizeSyncWindowOk() { if (customize_sync_window) { return customize_sync_window->ClickOk(); } else { return true; } } void CustomizeSyncWindowCancel() { if (customize_sync_window) { customize_sync_window->ClickCancel(); } } <commit_msg>GTK: swap ok/cancel button order in sync personalization dialog.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/options/customize_sync_window_gtk.h" #include <gtk/gtk.h> #include <string> #include "app/gtk_signal.h" #include "app/l10n_util.h" #include "base/message_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/gtk/accessible_widget_helper_gtk.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/options_window.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/glue/data_type_controller.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/common/pref_names.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk // // The contents of the Customize Sync dialog window. class CustomizeSyncWindowGtk { public: explicit CustomizeSyncWindowGtk(Profile* profile); ~CustomizeSyncWindowGtk(); void Show(); bool ClickOk(); void ClickCancel(); private: // The pixel width we wrap labels at. static const int kWrapWidth = 475; GtkWidget* AddCheckbox(GtkWidget* parent, int label_id, bool checked); bool Accept(); static void OnWindowDestroy(GtkWidget* widget, CustomizeSyncWindowGtk* window); static void OnResponse(GtkDialog* dialog, gint response_id, CustomizeSyncWindowGtk* customize_sync_window); CHROMEGTK_CALLBACK_0(CustomizeSyncWindowGtk, void, OnCheckboxClicked); // The customize sync dialog. GtkWidget *dialog_; Profile* profile_; GtkWidget* description_label_; GtkWidget* bookmarks_check_box_; GtkWidget* preferences_check_box_; GtkWidget* themes_check_box_; GtkWidget* autofill_check_box_; // Helper object to manage accessibility metadata. scoped_ptr<AccessibleWidgetHelper> accessible_widget_helper_; DISALLOW_COPY_AND_ASSIGN(CustomizeSyncWindowGtk); }; // The singleton customize sync window object. static CustomizeSyncWindowGtk* customize_sync_window = NULL; /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk, public: CustomizeSyncWindowGtk::CustomizeSyncWindowGtk(Profile* profile) : profile_(profile), description_label_(NULL), bookmarks_check_box_(NULL), preferences_check_box_(NULL), themes_check_box_(NULL), autofill_check_box_(NULL) { syncable::ModelTypeSet registered_types; profile_->GetProfileSyncService()->GetRegisteredDataTypes(&registered_types); syncable::ModelTypeSet preferred_types; profile_->GetProfileSyncService()->GetPreferredDataTypes(&preferred_types); std::string dialog_name = l10n_util::GetStringUTF8( IDS_CUSTOMIZE_SYNC_WINDOW_TITLE); dialog_ = gtk_dialog_new_with_buttons( dialog_name.c_str(), // Customize sync window is shared between all browser windows. NULL, // Non-modal. GTK_DIALOG_NO_SEPARATOR, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, NULL); gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), gtk_util::kContentAreaSpacing); accessible_widget_helper_.reset(new AccessibleWidgetHelper( dialog_, profile)); accessible_widget_helper_->SendOpenWindowNotification(dialog_name); GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); description_label_ = gtk_label_new(l10n_util::GetStringUTF8( IDS_CUSTOMIZE_SYNC_DESCRIPTION).c_str()); gtk_label_set_line_wrap(GTK_LABEL(description_label_), TRUE); gtk_widget_set_size_request(description_label_, kWrapWidth, -1); gtk_box_pack_start(GTK_BOX(vbox), description_label_, FALSE, FALSE, 0); accessible_widget_helper_->SetWidgetName(description_label_, IDS_CUSTOMIZE_SYNC_DESCRIPTION); DCHECK(registered_types.count(syncable::BOOKMARKS)); bool bookmarks_checked = preferred_types.count(syncable::BOOKMARKS) != 0; bookmarks_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_BOOKMARKS, bookmarks_checked); if (registered_types.count(syncable::PREFERENCES)) { bool prefs_checked = preferred_types.count(syncable::PREFERENCES) != 0; preferences_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_PREFERENCES, prefs_checked); } if (registered_types.count(syncable::THEMES)) { bool themes_checked = preferred_types.count(syncable::THEMES) != 0; themes_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_THEMES, themes_checked); } if (registered_types.count(syncable::AUTOFILL)) { bool autofill_checked = preferred_types.count(syncable::AUTOFILL) != 0; autofill_check_box_ = AddCheckbox(vbox, IDS_SYNC_DATATYPE_AUTOFILL, autofill_checked); } gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog_)->vbox), vbox, FALSE, FALSE, 0); gtk_widget_realize(dialog_); gtk_util::SetWindowSizeFromResources(GTK_WINDOW(dialog_), IDS_CUSTOMIZE_SYNC_DIALOG_WIDTH_CHARS, IDS_CUSTOMIZE_SYNC_DIALOG_HEIGHT_LINES, true); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnWindowDestroy), this); gtk_util::ShowDialog(dialog_); } CustomizeSyncWindowGtk::~CustomizeSyncWindowGtk() { } void CustomizeSyncWindowGtk::Show() { // Bring options window to front if it already existed and isn't already // in front gtk_util::PresentWindow(dialog_, 0); } bool CustomizeSyncWindowGtk::ClickOk() { if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) || (preferences_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( preferences_check_box_))) || (themes_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) || (autofill_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_)))) { Accept(); gtk_widget_destroy(GTK_WIDGET(dialog_)); return true; } else { // show the user that something's wrong with this dialog (not perfect, but // a temporary fix) gtk_util::PresentWindow(dialog_, 0); return false; } } void CustomizeSyncWindowGtk::ClickCancel() { gtk_widget_destroy(GTK_WIDGET(dialog_)); } /////////////////////////////////////////////////////////////////////////////// // CustomizeSyncWindowGtk, private: GtkWidget* CustomizeSyncWindowGtk::AddCheckbox(GtkWidget* parent, int label_id, bool checked) { GtkWidget* checkbox = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(label_id).c_str()); gtk_box_pack_start(GTK_BOX(parent), checkbox, FALSE, FALSE, 0); accessible_widget_helper_->SetWidgetName(checkbox, label_id); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), checked); g_signal_connect(checkbox, "clicked", G_CALLBACK(OnCheckboxClickedThunk), this); return checkbox; } bool CustomizeSyncWindowGtk::Accept() { syncable::ModelTypeSet preferred_types; bool bookmarks_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(bookmarks_check_box_)); if (bookmarks_enabled) { preferred_types.insert(syncable::BOOKMARKS); } if (preferences_check_box_) { bool preferences_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(preferences_check_box_)); if (preferences_enabled) { preferred_types.insert(syncable::PREFERENCES); } } if (themes_check_box_) { bool themes_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(themes_check_box_)); if (themes_enabled) { preferred_types.insert(syncable::THEMES); } } if (autofill_check_box_) { bool autofill_enabled = gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(autofill_check_box_)); if (autofill_enabled) { preferred_types.insert(syncable::AUTOFILL); } } profile_->GetProfileSyncService()->ChangePreferredDataTypes(preferred_types); return true; } // static void CustomizeSyncWindowGtk::OnWindowDestroy(GtkWidget* widget, CustomizeSyncWindowGtk* window) { customize_sync_window = NULL; MessageLoop::current()->DeleteSoon(FROM_HERE, window); } // static void CustomizeSyncWindowGtk::OnResponse( GtkDialog* dialog, gint response_id, CustomizeSyncWindowGtk* customize_sync_window) { if (response_id == GTK_RESPONSE_OK) { customize_sync_window->ClickOk(); } else if (response_id == GTK_RESPONSE_CANCEL) { customize_sync_window->ClickCancel(); } } // Deactivate the "OK" button if you uncheck all the data types. void CustomizeSyncWindowGtk::OnCheckboxClicked(GtkWidget* widget) { bool any_datatypes_selected = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_check_box_)) || (preferences_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( preferences_check_box_))) || (themes_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(themes_check_box_))) || (autofill_check_box_ && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(autofill_check_box_))); if (any_datatypes_selected) { gtk_dialog_set_response_sensitive( GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, TRUE); } else { gtk_dialog_set_response_sensitive( GTK_DIALOG(customize_sync_window->dialog_), GTK_RESPONSE_OK, FALSE); } } /////////////////////////////////////////////////////////////////////////////// // Factory/finder method: void ShowCustomizeSyncWindow(Profile* profile) { DCHECK(profile); // If there's already an existing window, use it. if (!customize_sync_window) { customize_sync_window = new CustomizeSyncWindowGtk(profile); } customize_sync_window->Show(); } bool CustomizeSyncWindowOk() { if (customize_sync_window) { return customize_sync_window->ClickOk(); } else { return true; } } void CustomizeSyncWindowCancel() { if (customize_sync_window) { customize_sync_window->ClickCancel(); } } <|endoftext|>
<commit_before><commit_msg>IOSS: Remove debugging output<commit_after><|endoftext|>
<commit_before>/* * * ledger_api_blockchain_explorer_tests * ledger-core * * Created by Pierre Pollastri on 10/03/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <gtest/gtest.h> #include <wallet/bitcoin/networks.hpp> #include <wallet/ethereum/ethereumNetworks.hpp> #include <wallet/bitcoin/explorers/LedgerApiBitcoinLikeBlockchainExplorer.hpp> #include <wallet/ethereum/explorers/LedgerApiEthereumLikeBlockchainExplorer.h> #include "BaseFixture.h" template <typename CurrencyExplorer, typename NetworkParameters> class LedgerApiBlockchainExplorerTests : public BaseFixture { public: void SetUp() override { BaseFixture::SetUp(); auto worker = dispatcher->getSerialExecutionContext("worker"); auto client = std::make_shared<HttpClient>(explorerEndpoint, http, worker); explorer = std::make_shared<CurrencyExplorer>(worker, client, params, api::DynamicObject::newInstance()); logger = ledger::core::logger::create("test_logs", dispatcher->getSerialExecutionContext("logger"), resolver, printer, 2000000000 ); } NetworkParameters params; std::string explorerEndpoint; std::shared_ptr<spdlog::logger> logger; std::shared_ptr<CurrencyExplorer> explorer; }; class LedgerApiBitcoinLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests<LedgerApiBitcoinLikeBlockchainExplorer, api::BitcoinLikeNetworkParameters> { public: LedgerApiBitcoinLikeBlockchainExplorerTests() { params = networks::getNetworkParameters("bitcoin"); explorerEndpoint = "http://api.ledgerwallet.com"; } }; TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, StartSession) { auto session = wait(explorer->startSession()); EXPECT_EQ(((std::string *)session)->size(), 36); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetRawTransaction) { auto transaction = wait(explorer->getRawTransaction("9d7945129b78e2f63a72fed93e8ebe38567bdc9318591cfe8c8a7de76c5cb1a3")); auto hex = transaction.toHex(); EXPECT_EQ(hex.str(), "0100000001d62dad27a2bdd0c5e72a6288acb4e0acac088b4bc5588e60ff5c3861c4584d71010000006b483045022100d72a8e43c74764a18c5dfec225f1e60dceb12a9bf4931afa1093f14c471f55d202202cf4ed0956fd68dc9ba9d026a4ae04758092487cebff1618e320dcc12d736577012102b62b6c66c0d69ca3272ed3d0884a40bd4fb50ab08bec6de6d899b7389f40e9b5ffffffff026fa40200000000001976a91459fa62dab1f04b4528e5c5446f4c897b53fc983c88ace58f8b00000000001976a914b026e605bb239cf7eafb6437667f0f7f80e827f488ac00000000"); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash) { auto transaction = wait(explorer->getTransactionByHash("9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda")); auto &tx = *transaction.get(); EXPECT_EQ(tx.inputs.size(), 1); EXPECT_EQ(tx.hash, "9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda"); EXPECT_EQ(tx.inputs[0].value.getValue().toString(), "1634001"); EXPECT_EQ(tx.inputs[0].address.getValue(), "1Nd2kJid5fFmPks9KSRpoHQX4VpkPhuATm"); EXPECT_EQ(tx.fees.getValue().toString(), "11350"); EXPECT_EQ(tx.outputs.size(), 2); EXPECT_EQ(tx.outputs[0].value.toString(), "1000"); EXPECT_EQ(tx.outputs[1].value.toString(), "1621651"); EXPECT_EQ(tx.outputs[0].address.getValue(), "1QKJghDW4kLqCsH2pq3XKKsSSeYNPcL5PD"); EXPECT_EQ(tx.outputs[1].address.getValue(), "19j8biFtMSy5HFRX6mXiurjz3jszg7nLN5"); EXPECT_EQ(tx.block.getValue().hash, "0000000000000000026aa418ef33e0b079a42d348f35bc0a2fa4bc150a9c459d"); EXPECT_EQ(tx.block.getValue().height, 403912); // Checked that real value of 2016-03-23T11:54:21Z corresponds to 1458734061000 EXPECT_EQ(std::chrono::duration_cast<std::chrono::milliseconds>(tx.block.getValue().time.time_since_epoch()).count(), 1458734061000); EXPECT_EQ(std::chrono::duration_cast<std::chrono::milliseconds>(tx.receivedAt.time_since_epoch()).count(), 1458734061000); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_2) { auto transaction = wait(explorer->getTransactionByHash("16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e")); auto &tx = *transaction; EXPECT_EQ(tx.inputs.size(), 1); EXPECT_EQ(tx.hash, "16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e"); EXPECT_EQ(tx.inputs.size(), 1); EXPECT_EQ(tx.outputs.size(), 1); EXPECT_EQ(tx.inputs[0].coinbase.getValue(), "03070c070004ebabf05804496e151608bef5342d8b2800000a425720537570706f727420384d200a666973686572206a696e78696e092f425720506f6f6c2f"); EXPECT_EQ(tx.outputs[0].address.getValue(), "1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF"); EXPECT_EQ(tx.outputs[0].value.toString(), "1380320309"); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_3) { auto transaction = wait(explorer->getTransactionByHash("8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d")); auto &tx = *transaction; EXPECT_EQ(tx.hash, "8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d"); EXPECT_EQ(tx.inputs.size(), 8); EXPECT_EQ(tx.outputs.size(), 2); EXPECT_EQ(tx.inputs[5].value.getValue().toString(), "270000"); EXPECT_EQ(tx.inputs[5].index, 5); EXPECT_EQ(tx.inputs[5].address.getValue(), "1BEG75jXGZgH7QsSNjmm9RGJ2fgWcXVbxm"); EXPECT_EQ(tx.inputs[5].signatureScript.getValue(), "483045022100b21b21023b15be3d71fc660513adc4ef1aaa299ee58b9a5c1b8401015d045622022031847f047494c83b199a743d5edd5dbeb33b2dae03dcdff12485b212061d0463012102a7e1245393aa50cf6e08077ac5f4460c2db9c54858f6b0958d91b8d62f39c3bb"); EXPECT_EQ(tx.inputs[5].previousTxHash.getValue(), "64717373eef15249771032b0153daae92d18ea63e997c1c70a33879698b43329"); EXPECT_EQ(tx.inputs[5].previousTxOutputIndex.getValue(), 9); EXPECT_EQ(tx.outputs[0].address.getValue(), "14w1wdDMV5uSnBd92yf3N9LfgS6TKVzyYr"); EXPECT_EQ(tx.outputs[1].address.getValue(), "1pCL4HJ3wbNXKiDde8eNmu9uMs1Tkd9hD"); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetCurrentBlock) { auto block = wait(explorer->getCurrentBlock()); EXPECT_GT(block->height, 462400); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactions) { auto result = wait(explorer ->getTransactions( {"1H6ZZpRmMnrw8ytepV3BYwMjYYnEkWDqVP", "1DxPxrQtUXVcebgNYETn163RQaEKxAvxqP"}, Option<std::string>(), Option<void *>())); EXPECT_TRUE(result->hasNext); EXPECT_TRUE(result->transactions.size() > 0); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetFees) { auto result = wait(explorer->getFees()); EXPECT_NE(result.size(), 0); if (result.size() > 1) { EXPECT_GE(result[0]->intValue(), result[1]->intValue()); } } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, EndSession) { auto session = wait(explorer->startSession()); EXPECT_EQ(((std::string *) session)->size(), 36); auto u = wait(explorer->killSession(session)); } class LedgerApiEthereumLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests<LedgerApiEthereumLikeBlockchainExplorer, api::EthereumLikeNetworkParameters> { public: LedgerApiEthereumLikeBlockchainExplorerTests() { params = networks::getEthLikeNetworkParameters("ethereum_ropsten"); explorerEndpoint = "http://eth-ropsten.explorers.dev.aws.ledger.fr"; } }; TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetGasPrice) { auto result = wait(explorer->getGasPrice()); EXPECT_NE(result->toUint64(), 0); } TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetEstimatedGasLimit) { auto result = wait(explorer->getEstimatedGasLimit("0x57e8ba2a915285f984988282ab9346c1336a4e11")); EXPECT_GE(result->toUint64(), 10000); } TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, PostEstimatedGasLimit) { auto request = api::EthereumGasLimitRequest( optional<std::string>(), optional<std::string>(), optional<std::string>(), optional<std::string>("0xa9059cbb00000000000000000000000013C5d95f25688f8A" "7544582D9e311f201A56de6300000000000000000000000000" "00000000000000000000000000000000000000"), optional<std::string>(), optional<std::string>(), 1.5); auto result = wait(explorer->getDryrunGasLimit( "0x57e8ba2a915285f984988282ab9346c1336a4e11", request)); EXPECT_GE(result->toUint64(), 10000); } <commit_msg>[review] Use implicit constructor<commit_after>/* * * ledger_api_blockchain_explorer_tests * ledger-core * * Created by Pierre Pollastri on 10/03/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <gtest/gtest.h> #include <wallet/bitcoin/networks.hpp> #include <wallet/ethereum/ethereumNetworks.hpp> #include <wallet/bitcoin/explorers/LedgerApiBitcoinLikeBlockchainExplorer.hpp> #include <wallet/ethereum/explorers/LedgerApiEthereumLikeBlockchainExplorer.h> #include "BaseFixture.h" template <typename CurrencyExplorer, typename NetworkParameters> class LedgerApiBlockchainExplorerTests : public BaseFixture { public: void SetUp() override { BaseFixture::SetUp(); auto worker = dispatcher->getSerialExecutionContext("worker"); auto client = std::make_shared<HttpClient>(explorerEndpoint, http, worker); explorer = std::make_shared<CurrencyExplorer>(worker, client, params, api::DynamicObject::newInstance()); logger = ledger::core::logger::create("test_logs", dispatcher->getSerialExecutionContext("logger"), resolver, printer, 2000000000 ); } NetworkParameters params; std::string explorerEndpoint; std::shared_ptr<spdlog::logger> logger; std::shared_ptr<CurrencyExplorer> explorer; }; class LedgerApiBitcoinLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests<LedgerApiBitcoinLikeBlockchainExplorer, api::BitcoinLikeNetworkParameters> { public: LedgerApiBitcoinLikeBlockchainExplorerTests() { params = networks::getNetworkParameters("bitcoin"); explorerEndpoint = "http://api.ledgerwallet.com"; } }; TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, StartSession) { auto session = wait(explorer->startSession()); EXPECT_EQ(((std::string *)session)->size(), 36); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetRawTransaction) { auto transaction = wait(explorer->getRawTransaction("9d7945129b78e2f63a72fed93e8ebe38567bdc9318591cfe8c8a7de76c5cb1a3")); auto hex = transaction.toHex(); EXPECT_EQ(hex.str(), "0100000001d62dad27a2bdd0c5e72a6288acb4e0acac088b4bc5588e60ff5c3861c4584d71010000006b483045022100d72a8e43c74764a18c5dfec225f1e60dceb12a9bf4931afa1093f14c471f55d202202cf4ed0956fd68dc9ba9d026a4ae04758092487cebff1618e320dcc12d736577012102b62b6c66c0d69ca3272ed3d0884a40bd4fb50ab08bec6de6d899b7389f40e9b5ffffffff026fa40200000000001976a91459fa62dab1f04b4528e5c5446f4c897b53fc983c88ace58f8b00000000001976a914b026e605bb239cf7eafb6437667f0f7f80e827f488ac00000000"); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash) { auto transaction = wait(explorer->getTransactionByHash("9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda")); auto &tx = *transaction.get(); EXPECT_EQ(tx.inputs.size(), 1); EXPECT_EQ(tx.hash, "9fdbe15a16fe282291426df15894ab1473e252bc31f244e4d923a17e11743eda"); EXPECT_EQ(tx.inputs[0].value.getValue().toString(), "1634001"); EXPECT_EQ(tx.inputs[0].address.getValue(), "1Nd2kJid5fFmPks9KSRpoHQX4VpkPhuATm"); EXPECT_EQ(tx.fees.getValue().toString(), "11350"); EXPECT_EQ(tx.outputs.size(), 2); EXPECT_EQ(tx.outputs[0].value.toString(), "1000"); EXPECT_EQ(tx.outputs[1].value.toString(), "1621651"); EXPECT_EQ(tx.outputs[0].address.getValue(), "1QKJghDW4kLqCsH2pq3XKKsSSeYNPcL5PD"); EXPECT_EQ(tx.outputs[1].address.getValue(), "19j8biFtMSy5HFRX6mXiurjz3jszg7nLN5"); EXPECT_EQ(tx.block.getValue().hash, "0000000000000000026aa418ef33e0b079a42d348f35bc0a2fa4bc150a9c459d"); EXPECT_EQ(tx.block.getValue().height, 403912); // Checked that real value of 2016-03-23T11:54:21Z corresponds to 1458734061000 EXPECT_EQ(std::chrono::duration_cast<std::chrono::milliseconds>(tx.block.getValue().time.time_since_epoch()).count(), 1458734061000); EXPECT_EQ(std::chrono::duration_cast<std::chrono::milliseconds>(tx.receivedAt.time_since_epoch()).count(), 1458734061000); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_2) { auto transaction = wait(explorer->getTransactionByHash("16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e")); auto &tx = *transaction; EXPECT_EQ(tx.inputs.size(), 1); EXPECT_EQ(tx.hash, "16da85a108a63ff318458be597f34f0a7f6b9f703528249056ba2f48722ae44e"); EXPECT_EQ(tx.inputs.size(), 1); EXPECT_EQ(tx.outputs.size(), 1); EXPECT_EQ(tx.inputs[0].coinbase.getValue(), "03070c070004ebabf05804496e151608bef5342d8b2800000a425720537570706f727420384d200a666973686572206a696e78696e092f425720506f6f6c2f"); EXPECT_EQ(tx.outputs[0].address.getValue(), "1BQLNJtMDKmMZ4PyqVFfRuBNvoGhjigBKF"); EXPECT_EQ(tx.outputs[0].value.toString(), "1380320309"); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactionByHash_3) { auto transaction = wait(explorer->getTransactionByHash("8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d")); auto &tx = *transaction; EXPECT_EQ(tx.hash, "8d2a0ccbe3a71f3e505be1557995c57f2a26f1951a72931f23a61f18fa4b3d2d"); EXPECT_EQ(tx.inputs.size(), 8); EXPECT_EQ(tx.outputs.size(), 2); EXPECT_EQ(tx.inputs[5].value.getValue().toString(), "270000"); EXPECT_EQ(tx.inputs[5].index, 5); EXPECT_EQ(tx.inputs[5].address.getValue(), "1BEG75jXGZgH7QsSNjmm9RGJ2fgWcXVbxm"); EXPECT_EQ(tx.inputs[5].signatureScript.getValue(), "483045022100b21b21023b15be3d71fc660513adc4ef1aaa299ee58b9a5c1b8401015d045622022031847f047494c83b199a743d5edd5dbeb33b2dae03dcdff12485b212061d0463012102a7e1245393aa50cf6e08077ac5f4460c2db9c54858f6b0958d91b8d62f39c3bb"); EXPECT_EQ(tx.inputs[5].previousTxHash.getValue(), "64717373eef15249771032b0153daae92d18ea63e997c1c70a33879698b43329"); EXPECT_EQ(tx.inputs[5].previousTxOutputIndex.getValue(), 9); EXPECT_EQ(tx.outputs[0].address.getValue(), "14w1wdDMV5uSnBd92yf3N9LfgS6TKVzyYr"); EXPECT_EQ(tx.outputs[1].address.getValue(), "1pCL4HJ3wbNXKiDde8eNmu9uMs1Tkd9hD"); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetCurrentBlock) { auto block = wait(explorer->getCurrentBlock()); EXPECT_GT(block->height, 462400); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetTransactions) { auto result = wait(explorer ->getTransactions( {"1H6ZZpRmMnrw8ytepV3BYwMjYYnEkWDqVP", "1DxPxrQtUXVcebgNYETn163RQaEKxAvxqP"}, Option<std::string>(), Option<void *>())); EXPECT_TRUE(result->hasNext); EXPECT_TRUE(result->transactions.size() > 0); } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, GetFees) { auto result = wait(explorer->getFees()); EXPECT_NE(result.size(), 0); if (result.size() > 1) { EXPECT_GE(result[0]->intValue(), result[1]->intValue()); } } TEST_F(LedgerApiBitcoinLikeBlockchainExplorerTests, EndSession) { auto session = wait(explorer->startSession()); EXPECT_EQ(((std::string *) session)->size(), 36); auto u = wait(explorer->killSession(session)); } class LedgerApiEthereumLikeBlockchainExplorerTests : public LedgerApiBlockchainExplorerTests<LedgerApiEthereumLikeBlockchainExplorer, api::EthereumLikeNetworkParameters> { public: LedgerApiEthereumLikeBlockchainExplorerTests() { params = networks::getEthLikeNetworkParameters("ethereum_ropsten"); explorerEndpoint = "http://eth-ropsten.explorers.dev.aws.ledger.fr"; } }; TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetGasPrice) { auto result = wait(explorer->getGasPrice()); EXPECT_NE(result->toUint64(), 0); } TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, GetEstimatedGasLimit) { auto result = wait(explorer->getEstimatedGasLimit("0x57e8ba2a915285f984988282ab9346c1336a4e11")); EXPECT_GE(result->toUint64(), 10000); } TEST_F(LedgerApiEthereumLikeBlockchainExplorerTests, PostEstimatedGasLimit) { auto request = api::EthereumGasLimitRequest( optional<std::string>(), optional<std::string>(), optional<std::string>(), "0xa9059cbb00000000000000000000000013C5d95f25688f8A" "7544582D9e311f201A56de6300000000000000000000000000" "00000000000000000000000000000000000000", optional<std::string>(), optional<std::string>(), 1.5); auto result = wait(explorer->getDryrunGasLimit( "0x57e8ba2a915285f984988282ab9346c1336a4e11", request)); EXPECT_GE(result->toUint64(), 10000); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/fullscreen_exit_bubble_views.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/views/bubble/bubble.h" #include "grit/generated_resources.h" #include "ui/base/animation/slide_animation.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas_skia.h" #include "ui/gfx/screen.h" #include "views/bubble/bubble_border.h" #include "views/controls/button/text_button.h" #include "views/controls/link.h" #include "views/widget/widget.h" #if defined(OS_WIN) #include "ui/base/l10n/l10n_util_win.h" #endif // FullscreenExitView ---------------------------------------------------------- namespace { // Space between the site info label and the buttons / link. const int kMiddlePaddingPx = 30; } // namespace class FullscreenExitBubbleViews::FullscreenExitView : public views::View, public views::ButtonListener { public: FullscreenExitView(FullscreenExitBubbleViews* bubble, const string16& accelerator, const GURL& url, bool ask_permission); virtual ~FullscreenExitView(); // views::View virtual gfx::Size GetPreferredSize(); // views::ButtonListener virtual void ButtonPressed(views::Button* sender, const views::Event& event); // Hide the accept and deny buttons, exposing the exit link. void HideButtons(); private: string16 GetMessage(const GURL& url); // views::View virtual void Layout(); FullscreenExitBubbleViews* bubble_; // Clickable hint text to show in the bubble. views::Link link_; views::Label message_label_; views::NativeTextButton* accept_button_; views::NativeTextButton* deny_button_; bool show_buttons_; }; FullscreenExitBubbleViews::FullscreenExitView::FullscreenExitView( FullscreenExitBubbleViews* bubble, const string16& accelerator, const GURL& url, bool ask_permission) : bubble_(bubble), accept_button_(NULL), deny_button_(NULL), show_buttons_(ask_permission) { views::BubbleBorder* bubble_border = new views::BubbleBorder(views::BubbleBorder::NONE); bubble_border->set_background_color(Bubble::kBackgroundColor); set_background(new views::BubbleBackground(bubble_border)); set_border(bubble_border); set_focusable(false); message_label_.set_parent_owned(false); message_label_.SetText(GetMessage(url)); message_label_.SetFont(ResourceBundle::GetSharedInstance().GetFont( ResourceBundle::MediumFont)); link_.set_parent_owned(false); link_.set_collapse_when_hidden(false); link_.set_focusable(false); #if !defined(OS_CHROMEOS) link_.SetText( l10n_util::GetStringFUTF16(IDS_EXIT_FULLSCREEN_MODE, accelerator)); #else link_.SetText(l10n_util::GetStringUTF16(IDS_EXIT_FULLSCREEN_MODE)); #endif link_.set_listener(bubble); link_.SetFont(ResourceBundle::GetSharedInstance().GetFont( ResourceBundle::MediumFont)); link_.SetPressedColor(message_label_.enabled_color()); link_.SetEnabledColor(message_label_.enabled_color()); link_.SetVisible(false); link_.SetBackgroundColor(background()->get_color()); message_label_.SetBackgroundColor(background()->get_color()); AddChildView(&message_label_); AddChildView(&link_); accept_button_ = new views::NativeTextButton(this, UTF16ToWide(l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_ALLOW))); accept_button_->set_focusable(false); AddChildView(accept_button_); deny_button_ = new views::NativeTextButton(this, UTF16ToWide(l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_DENY))); deny_button_->set_focusable(false); AddChildView(deny_button_); if (!show_buttons_) HideButtons(); } string16 FullscreenExitBubbleViews::FullscreenExitView::GetMessage( const GURL& url) { if (url.is_empty()) { return l10n_util::GetStringUTF16( IDS_FULLSCREEN_INFOBAR_USER_ENTERED_FULLSCREEN); } if (url.SchemeIsFile()) return l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_FILE_PAGE_NAME); return l10n_util::GetStringFUTF16(IDS_FULLSCREEN_INFOBAR_REQUEST_PERMISSION, UTF8ToUTF16(url.host())); } FullscreenExitBubbleViews::FullscreenExitView::~FullscreenExitView() { } void FullscreenExitBubbleViews::FullscreenExitView::ButtonPressed( views::Button* sender, const views::Event& event) { if (sender == accept_button_) bubble_->OnAcceptFullscreen(); else bubble_->OnCancelFullscreen(); } void FullscreenExitBubbleViews::FullscreenExitView::HideButtons() { show_buttons_ = false; accept_button_->SetVisible(false); deny_button_->SetVisible(false); link_.SetVisible(true); } gfx::Size FullscreenExitBubbleViews::FullscreenExitView::GetPreferredSize() { gfx::Size link_size(link_.GetPreferredSize()); gfx::Size message_label_size(message_label_.GetPreferredSize()); gfx::Size accept_size(accept_button_->GetPreferredSize()); gfx::Size deny_size(deny_button_->GetPreferredSize()); gfx::Insets insets(GetInsets()); int buttons_width = accept_size.width() + kPaddingPx + deny_size.width(); int button_box_width = std::max(buttons_width, link_size.width()); int width = kPaddingPx + message_label_size.width() + kMiddlePaddingPx + button_box_width + kPaddingPx; gfx::Size result(width + insets.width(), kPaddingPx * 2 + accept_size.height() + insets.height()); return result; } void FullscreenExitBubbleViews::FullscreenExitView::Layout() { gfx::Size link_size(link_.GetPreferredSize()); gfx::Size message_label_size(message_label_.GetPreferredSize()); gfx::Size accept_size(accept_button_->GetPreferredSize()); gfx::Size deny_size(deny_button_->GetPreferredSize()); gfx::Insets insets(GetInsets()); int inner_height = height() - insets.height(); int button_box_x = insets.left() + kPaddingPx + message_label_size.width() + kMiddlePaddingPx; int message_label_y = insets.top() + (inner_height - message_label_size.height()) / 2; int link_x = width() - insets.right() - kPaddingPx - link_size.width(); int link_y = insets.top() + (inner_height - link_size.height()) / 2; message_label_.SetPosition(gfx::Point(insets.left() + kPaddingPx, message_label_y)); link_.SetPosition(gfx::Point(link_x, link_y)); if (show_buttons_) { accept_button_->SetPosition(gfx::Point(button_box_x, insets.top() + kPaddingPx)); deny_button_->SetPosition(gfx::Point( button_box_x + accept_size.width() + kPaddingPx, insets.top() + kPaddingPx)); } } // FullscreenExitBubbleViews --------------------------------------------------- FullscreenExitBubbleViews::FullscreenExitBubbleViews(views::Widget* frame, Browser* browser, const GURL& url, bool ask_permission) : FullscreenExitBubble(browser), root_view_(frame->GetRootView()), popup_(NULL), size_animation_(new ui::SlideAnimation(this)), url_(url) { size_animation_->Reset(1); // Create the contents view. views::Accelerator accelerator(ui::VKEY_UNKNOWN, false, false, false); bool got_accelerator = frame->GetAccelerator(IDC_FULLSCREEN, &accelerator); DCHECK(got_accelerator); view_ = new FullscreenExitView(this, accelerator.GetShortcutText(), url, ask_permission); // Initialize the popup. popup_ = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.transparent = true; params.can_activate = false; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = frame->GetNativeView(); params.bounds = GetPopupRect(false); popup_->Init(params); gfx::Size size = GetPopupRect(true).size(); popup_->SetContentsView(view_); // We set layout manager to NULL to prevent the widget from sizing its // contents to the same size as itself. This prevents the widget contents from // shrinking while we animate the height of the popup to give the impression // that it is sliding off the top of the screen. popup_->GetRootView()->SetLayoutManager(NULL); view_->SetBounds(0, 0, size.width(), size.height()); popup_->Show(); // This does not activate the popup. if (!ask_permission) StartWatchingMouse(); } FullscreenExitBubbleViews::~FullscreenExitBubbleViews() { // This is tricky. We may be in an ATL message handler stack, in which case // the popup cannot be deleted yet. We also can't set the popup's ownership // model to NATIVE_WIDGET_OWNS_WIDGET because if the user closed the last tab // while in fullscreen mode, Windows has already destroyed the popup HWND by // the time we get here, and thus either the popup will already have been // deleted (if we set this in our constructor) or the popup will never get // another OnFinalMessage() call (if not, as currently). So instead, we tell // the popup to synchronously hide, and then asynchronously close and delete // itself. popup_->Close(); MessageLoop::current()->DeleteSoon(FROM_HERE, popup_); } void FullscreenExitBubbleViews::LinkClicked( views::Link* source, int event_flags) { ToggleFullscreen(); } void FullscreenExitBubbleViews::OnAcceptFullscreen() { AcceptFullscreen(url_); view_->HideButtons(); StartWatchingMouse(); } void FullscreenExitBubbleViews::OnCancelFullscreen() { CancelFullscreen(); } void FullscreenExitBubbleViews::AnimationProgressed( const ui::Animation* animation) { gfx::Rect popup_rect(GetPopupRect(false)); if (popup_rect.IsEmpty()) { popup_->Hide(); } else { popup_->SetBounds(popup_rect); view_->SetY(popup_rect.height() - view_->height()); popup_->Show(); } } void FullscreenExitBubbleViews::AnimationEnded( const ui::Animation* animation) { AnimationProgressed(animation); } void FullscreenExitBubbleViews::Hide() { size_animation_->SetSlideDuration(kSlideOutDurationMs); size_animation_->Hide(); } void FullscreenExitBubbleViews::Show() { size_animation_->SetSlideDuration(kSlideInDurationMs); size_animation_->Show(); } bool FullscreenExitBubbleViews::IsAnimating() { return size_animation_->GetCurrentValue() != 0; } bool FullscreenExitBubbleViews::IsWindowActive() { return root_view_->GetWidget()->IsActive(); } bool FullscreenExitBubbleViews::WindowContainsPoint(gfx::Point pos) { return root_view_->HitTest(pos); } gfx::Point FullscreenExitBubbleViews::GetCursorScreenPoint() { gfx::Point cursor_pos = gfx::Screen::GetCursorScreenPoint(); gfx::Point transformed_pos(cursor_pos); views::View::ConvertPointToView(NULL, root_view_, &transformed_pos); return transformed_pos; } gfx::Rect FullscreenExitBubbleViews::GetPopupRect( bool ignore_animation_state) const { gfx::Size size(view_->GetPreferredSize()); // NOTE: don't use the bounds of the root_view_. On linux changing window // size is async. Instead we use the size of the screen. gfx::Rect screen_bounds = gfx::Screen::GetMonitorAreaNearestWindow( root_view_->GetWidget()->GetNativeView()); gfx::Point origin(screen_bounds.x() + (screen_bounds.width() - size.width()) / 2, kPopupTopPx + screen_bounds.y()); if (!ignore_animation_state) { int total_height = size.height() + kPopupTopPx; int popup_bottom = size_animation_->CurrentValueBetween( static_cast<double>(total_height), 0.0f); int y_offset = std::min(popup_bottom, kPopupTopPx); size.set_height(size.height() - popup_bottom + y_offset); origin.set_y(origin.y() - y_offset); } return gfx::Rect(origin, size); } <commit_msg>Change SetPosition() to SetBounds() in FullscreenExitView::Layout().<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/fullscreen_exit_bubble_views.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/ui/views/bubble/bubble.h" #include "grit/generated_resources.h" #include "ui/base/animation/slide_animation.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas_skia.h" #include "ui/gfx/screen.h" #include "views/bubble/bubble_border.h" #include "views/controls/button/text_button.h" #include "views/controls/link.h" #include "views/widget/widget.h" #if defined(OS_WIN) #include "ui/base/l10n/l10n_util_win.h" #endif // FullscreenExitView ---------------------------------------------------------- namespace { // Space between the site info label and the buttons / link. const int kMiddlePaddingPx = 30; } // namespace class FullscreenExitBubbleViews::FullscreenExitView : public views::View, public views::ButtonListener { public: FullscreenExitView(FullscreenExitBubbleViews* bubble, const string16& accelerator, const GURL& url, bool ask_permission); virtual ~FullscreenExitView(); // views::View virtual gfx::Size GetPreferredSize(); // views::ButtonListener virtual void ButtonPressed(views::Button* sender, const views::Event& event); // Hide the accept and deny buttons, exposing the exit link. void HideButtons(); private: string16 GetMessage(const GURL& url); // views::View virtual void Layout(); FullscreenExitBubbleViews* bubble_; // Clickable hint text to show in the bubble. views::Link link_; views::Label message_label_; views::NativeTextButton* accept_button_; views::NativeTextButton* deny_button_; bool show_buttons_; }; FullscreenExitBubbleViews::FullscreenExitView::FullscreenExitView( FullscreenExitBubbleViews* bubble, const string16& accelerator, const GURL& url, bool ask_permission) : bubble_(bubble), accept_button_(NULL), deny_button_(NULL), show_buttons_(ask_permission) { views::BubbleBorder* bubble_border = new views::BubbleBorder(views::BubbleBorder::NONE); bubble_border->set_background_color(Bubble::kBackgroundColor); set_background(new views::BubbleBackground(bubble_border)); set_border(bubble_border); set_focusable(false); message_label_.set_parent_owned(false); message_label_.SetText(GetMessage(url)); message_label_.SetFont(ResourceBundle::GetSharedInstance().GetFont( ResourceBundle::MediumFont)); link_.set_parent_owned(false); link_.set_collapse_when_hidden(false); link_.set_focusable(false); #if !defined(OS_CHROMEOS) link_.SetText( l10n_util::GetStringFUTF16(IDS_EXIT_FULLSCREEN_MODE, accelerator)); #else link_.SetText(l10n_util::GetStringUTF16(IDS_EXIT_FULLSCREEN_MODE)); #endif link_.set_listener(bubble); link_.SetFont(ResourceBundle::GetSharedInstance().GetFont( ResourceBundle::MediumFont)); link_.SetPressedColor(message_label_.enabled_color()); link_.SetEnabledColor(message_label_.enabled_color()); link_.SetVisible(false); link_.SetBackgroundColor(background()->get_color()); message_label_.SetBackgroundColor(background()->get_color()); AddChildView(&message_label_); AddChildView(&link_); accept_button_ = new views::NativeTextButton(this, UTF16ToWide(l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_ALLOW))); accept_button_->set_focusable(false); AddChildView(accept_button_); deny_button_ = new views::NativeTextButton(this, UTF16ToWide(l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_DENY))); deny_button_->set_focusable(false); AddChildView(deny_button_); if (!show_buttons_) HideButtons(); } string16 FullscreenExitBubbleViews::FullscreenExitView::GetMessage( const GURL& url) { if (url.is_empty()) { return l10n_util::GetStringUTF16( IDS_FULLSCREEN_INFOBAR_USER_ENTERED_FULLSCREEN); } if (url.SchemeIsFile()) return l10n_util::GetStringUTF16(IDS_FULLSCREEN_INFOBAR_FILE_PAGE_NAME); return l10n_util::GetStringFUTF16(IDS_FULLSCREEN_INFOBAR_REQUEST_PERMISSION, UTF8ToUTF16(url.host())); } FullscreenExitBubbleViews::FullscreenExitView::~FullscreenExitView() { } void FullscreenExitBubbleViews::FullscreenExitView::ButtonPressed( views::Button* sender, const views::Event& event) { if (sender == accept_button_) bubble_->OnAcceptFullscreen(); else bubble_->OnCancelFullscreen(); } void FullscreenExitBubbleViews::FullscreenExitView::HideButtons() { show_buttons_ = false; accept_button_->SetVisible(false); deny_button_->SetVisible(false); link_.SetVisible(true); } gfx::Size FullscreenExitBubbleViews::FullscreenExitView::GetPreferredSize() { gfx::Size link_size(link_.GetPreferredSize()); gfx::Size message_label_size(message_label_.GetPreferredSize()); gfx::Size accept_size(accept_button_->GetPreferredSize()); gfx::Size deny_size(deny_button_->GetPreferredSize()); gfx::Insets insets(GetInsets()); int buttons_width = accept_size.width() + kPaddingPx + deny_size.width(); int button_box_width = std::max(buttons_width, link_size.width()); int width = kPaddingPx + message_label_size.width() + kMiddlePaddingPx + button_box_width + kPaddingPx; gfx::Size result(width + insets.width(), kPaddingPx * 2 + accept_size.height() + insets.height()); return result; } void FullscreenExitBubbleViews::FullscreenExitView::Layout() { gfx::Size link_size(link_.GetPreferredSize()); gfx::Size message_label_size(message_label_.GetPreferredSize()); gfx::Size accept_size(accept_button_->GetPreferredSize()); gfx::Size deny_size(deny_button_->GetPreferredSize()); gfx::Insets insets(GetInsets()); int inner_height = height() - insets.height(); int button_box_x = insets.left() + kPaddingPx + message_label_size.width() + kMiddlePaddingPx; int message_label_y = insets.top() + (inner_height - message_label_size.height()) / 2; int link_x = width() - insets.right() - kPaddingPx - link_size.width(); int link_y = insets.top() + (inner_height - link_size.height()) / 2; message_label_.SetBounds(insets.left() + kPaddingPx, message_label_y, message_label_size.width(), message_label_size.height()); link_.SetBounds(link_x, link_y, link_size.width(), link_size.height()); if (show_buttons_) { accept_button_->SetBounds(button_box_x, insets.top() + kPaddingPx, accept_size.width(), accept_size.height()); deny_button_->SetBounds(button_box_x + accept_size.width() + kPaddingPx, insets.top() + kPaddingPx, deny_size.width(), deny_size.height()); } } // FullscreenExitBubbleViews --------------------------------------------------- FullscreenExitBubbleViews::FullscreenExitBubbleViews(views::Widget* frame, Browser* browser, const GURL& url, bool ask_permission) : FullscreenExitBubble(browser), root_view_(frame->GetRootView()), popup_(NULL), size_animation_(new ui::SlideAnimation(this)), url_(url) { size_animation_->Reset(1); // Create the contents view. views::Accelerator accelerator(ui::VKEY_UNKNOWN, false, false, false); bool got_accelerator = frame->GetAccelerator(IDC_FULLSCREEN, &accelerator); DCHECK(got_accelerator); view_ = new FullscreenExitView(this, accelerator.GetShortcutText(), url, ask_permission); // Initialize the popup. popup_ = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.transparent = true; params.can_activate = false; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = frame->GetNativeView(); params.bounds = GetPopupRect(false); popup_->Init(params); gfx::Size size = GetPopupRect(true).size(); popup_->SetContentsView(view_); // We set layout manager to NULL to prevent the widget from sizing its // contents to the same size as itself. This prevents the widget contents from // shrinking while we animate the height of the popup to give the impression // that it is sliding off the top of the screen. popup_->GetRootView()->SetLayoutManager(NULL); view_->SetBounds(0, 0, size.width(), size.height()); popup_->Show(); // This does not activate the popup. if (!ask_permission) StartWatchingMouse(); } FullscreenExitBubbleViews::~FullscreenExitBubbleViews() { // This is tricky. We may be in an ATL message handler stack, in which case // the popup cannot be deleted yet. We also can't set the popup's ownership // model to NATIVE_WIDGET_OWNS_WIDGET because if the user closed the last tab // while in fullscreen mode, Windows has already destroyed the popup HWND by // the time we get here, and thus either the popup will already have been // deleted (if we set this in our constructor) or the popup will never get // another OnFinalMessage() call (if not, as currently). So instead, we tell // the popup to synchronously hide, and then asynchronously close and delete // itself. popup_->Close(); MessageLoop::current()->DeleteSoon(FROM_HERE, popup_); } void FullscreenExitBubbleViews::LinkClicked( views::Link* source, int event_flags) { ToggleFullscreen(); } void FullscreenExitBubbleViews::OnAcceptFullscreen() { AcceptFullscreen(url_); view_->HideButtons(); StartWatchingMouse(); } void FullscreenExitBubbleViews::OnCancelFullscreen() { CancelFullscreen(); } void FullscreenExitBubbleViews::AnimationProgressed( const ui::Animation* animation) { gfx::Rect popup_rect(GetPopupRect(false)); if (popup_rect.IsEmpty()) { popup_->Hide(); } else { popup_->SetBounds(popup_rect); view_->SetY(popup_rect.height() - view_->height()); popup_->Show(); } } void FullscreenExitBubbleViews::AnimationEnded( const ui::Animation* animation) { AnimationProgressed(animation); } void FullscreenExitBubbleViews::Hide() { size_animation_->SetSlideDuration(kSlideOutDurationMs); size_animation_->Hide(); } void FullscreenExitBubbleViews::Show() { size_animation_->SetSlideDuration(kSlideInDurationMs); size_animation_->Show(); } bool FullscreenExitBubbleViews::IsAnimating() { return size_animation_->GetCurrentValue() != 0; } bool FullscreenExitBubbleViews::IsWindowActive() { return root_view_->GetWidget()->IsActive(); } bool FullscreenExitBubbleViews::WindowContainsPoint(gfx::Point pos) { return root_view_->HitTest(pos); } gfx::Point FullscreenExitBubbleViews::GetCursorScreenPoint() { gfx::Point cursor_pos = gfx::Screen::GetCursorScreenPoint(); gfx::Point transformed_pos(cursor_pos); views::View::ConvertPointToView(NULL, root_view_, &transformed_pos); return transformed_pos; } gfx::Rect FullscreenExitBubbleViews::GetPopupRect( bool ignore_animation_state) const { gfx::Size size(view_->GetPreferredSize()); // NOTE: don't use the bounds of the root_view_. On linux changing window // size is async. Instead we use the size of the screen. gfx::Rect screen_bounds = gfx::Screen::GetMonitorAreaNearestWindow( root_view_->GetWidget()->GetNativeView()); gfx::Point origin(screen_bounds.x() + (screen_bounds.width() - size.width()) / 2, kPopupTopPx + screen_bounds.y()); if (!ignore_animation_state) { int total_height = size.height() + kPopupTopPx; int popup_bottom = size_animation_->CurrentValueBetween( static_cast<double>(total_height), 0.0f); int y_offset = std::min(popup_bottom, kPopupTopPx); size.set_height(size.height() - popup_bottom + y_offset); origin.set_y(origin.y() - y_offset); } return gfx::Rect(origin, size); } <|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 "base/file_util.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_unpacker.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" namespace errors = extension_manifest_errors; namespace keys = extension_manifest_keys; class ExtensionUnpackerTest : public testing::Test { public: void SetupUnpacker(const std::string& crx_name) { FilePath original_path; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path)); original_path = original_path.AppendASCII("extensions") .AppendASCII("unpacker") .AppendASCII(crx_name); ASSERT_TRUE(file_util::PathExists(original_path)) << original_path.value(); // Try bots won't let us write into DIR_TEST_DATA, so we have to create // a temp folder to play in. ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); FilePath crx_path = temp_dir_.path().AppendASCII(crx_name); ASSERT_TRUE(file_util::CopyFile(original_path, crx_path)) << "Original path " << original_path.value() << ", Crx path " << crx_path.value(); unpacker_.reset( new ExtensionUnpacker( crx_path, Extension::INTERNAL, Extension::NO_FLAGS)); } protected: ScopedTempDir temp_dir_; scoped_ptr<ExtensionUnpacker> unpacker_; }; // Crashes intermittently on Windows, see http://crbug.com/109238 #if defined(OS_WIN) #define MAYBE_EmptyDefaultLocale DISABLED_EmptyDefaultLocale #else #define MAYBE_EmptyDefaultLocale EmptyDefaultLocale #endif TEST_F(ExtensionUnpackerTest, MAYBE_EmptyDefaultLocale) { SetupUnpacker("empty_default_locale.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale), unpacker_->error_message()); } // Crashes intermittently on Vista, see http://crbug.com/109385 #if defined(OS_WIN) #define MAYBE_HasDefaultLocaleMissingLocalesFolder \ DISABLED_HasDefaultLocaleMissingLocalesFolder #else #define MAYBE_HasDefaultLocaleMissingLocalesFolder \ HasDefaultLocaleMissingLocalesFolder #endif TEST_F(ExtensionUnpackerTest, MAYBE_HasDefaultLocaleMissingLocalesFolder) { SetupUnpacker("has_default_missing_locales.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kLocalesTreeMissing), unpacker_->error_message()); } // Crashes intermittently on Windows, see http://crbug.com/109238 #if defined(OS_WIN) #define MAYBE_InvalidDefaultLocale DISABLED_InvalidDefaultLocale #else #define MAYBE_InvalidDefaultLocale InvalidDefaultLocale #endif TEST_F(ExtensionUnpackerTest, MAYBE_InvalidDefaultLocale) { SetupUnpacker("invalid_default_locale.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale), unpacker_->error_message()); } TEST_F(ExtensionUnpackerTest, InvalidMessagesFile) { SetupUnpacker("invalid_messages_file.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_TRUE(MatchPattern(unpacker_->error_message(), ASCIIToUTF16("*_locales?en_US?messages.json: Line: 2, column: 3," " Dictionary keys must be quoted."))); } TEST_F(ExtensionUnpackerTest, MissingDefaultData) { SetupUnpacker("missing_default_data.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages), unpacker_->error_message()); } TEST_F(ExtensionUnpackerTest, MissingDefaultLocaleHasLocalesFolder) { SetupUnpacker("missing_default_has_locales.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultLocaleSpecified), unpacker_->error_message()); } TEST_F(ExtensionUnpackerTest, MissingMessagesFile) { SetupUnpacker("missing_messages_file.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_TRUE(MatchPattern(unpacker_->error_message(), ASCIIToUTF16(errors::kLocalesMessagesFileMissing) + ASCIIToUTF16("*_locales?en_US?messages.json"))); } TEST_F(ExtensionUnpackerTest, NoLocaleData) { SetupUnpacker("no_locale_data.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages), unpacker_->error_message()); } TEST_F(ExtensionUnpackerTest, GoodL10n) { SetupUnpacker("good_l10n.crx"); EXPECT_TRUE(unpacker_->Run()); EXPECT_TRUE(unpacker_->error_message().empty()); ASSERT_EQ(2U, unpacker_->parsed_catalogs()->size()); } TEST_F(ExtensionUnpackerTest, NoL10n) { SetupUnpacker("no_l10n.crx"); EXPECT_TRUE(unpacker_->Run()); EXPECT_TRUE(unpacker_->error_message().empty()); EXPECT_EQ(0U, unpacker_->parsed_catalogs()->size()); } <commit_msg>ExtensionUnpackerTest.InvalidMessagesFile is flaky on Windows<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 "base/file_util.h" #include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_unpacker.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" namespace errors = extension_manifest_errors; namespace keys = extension_manifest_keys; class ExtensionUnpackerTest : public testing::Test { public: void SetupUnpacker(const std::string& crx_name) { FilePath original_path; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path)); original_path = original_path.AppendASCII("extensions") .AppendASCII("unpacker") .AppendASCII(crx_name); ASSERT_TRUE(file_util::PathExists(original_path)) << original_path.value(); // Try bots won't let us write into DIR_TEST_DATA, so we have to create // a temp folder to play in. ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); FilePath crx_path = temp_dir_.path().AppendASCII(crx_name); ASSERT_TRUE(file_util::CopyFile(original_path, crx_path)) << "Original path " << original_path.value() << ", Crx path " << crx_path.value(); unpacker_.reset( new ExtensionUnpacker( crx_path, Extension::INTERNAL, Extension::NO_FLAGS)); } protected: ScopedTempDir temp_dir_; scoped_ptr<ExtensionUnpacker> unpacker_; }; // Crashes intermittently on Windows, see http://crbug.com/109238 #if defined(OS_WIN) #define MAYBE_EmptyDefaultLocale DISABLED_EmptyDefaultLocale #else #define MAYBE_EmptyDefaultLocale EmptyDefaultLocale #endif TEST_F(ExtensionUnpackerTest, MAYBE_EmptyDefaultLocale) { SetupUnpacker("empty_default_locale.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale), unpacker_->error_message()); } // Crashes intermittently on Vista, see http://crbug.com/109385 #if defined(OS_WIN) #define MAYBE_HasDefaultLocaleMissingLocalesFolder \ DISABLED_HasDefaultLocaleMissingLocalesFolder #else #define MAYBE_HasDefaultLocaleMissingLocalesFolder \ HasDefaultLocaleMissingLocalesFolder #endif TEST_F(ExtensionUnpackerTest, MAYBE_HasDefaultLocaleMissingLocalesFolder) { SetupUnpacker("has_default_missing_locales.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kLocalesTreeMissing), unpacker_->error_message()); } // Crashes intermittently on Windows, see http://crbug.com/109238 #if defined(OS_WIN) #define MAYBE_InvalidDefaultLocale DISABLED_InvalidDefaultLocale #else #define MAYBE_InvalidDefaultLocale InvalidDefaultLocale #endif TEST_F(ExtensionUnpackerTest, MAYBE_InvalidDefaultLocale) { SetupUnpacker("invalid_default_locale.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale), unpacker_->error_message()); } // Crashes intermittently on Windows, see http://crbug.com/109738 #if defined(OS_WIN) #define MAYBE_InvalidMessagesFile DISABLE_InvalidMessagesFile #else #define MAYBE_InvalidMessagesFile InvalidMessagesFile #endif TEST_F(ExtensionUnpackerTest, MAYBE_InvalidMessagesFile) { SetupUnpacker("invalid_messages_file.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_TRUE(MatchPattern(unpacker_->error_message(), ASCIIToUTF16("*_locales?en_US?messages.json: Line: 2, column: 3," " Dictionary keys must be quoted."))); } TEST_F(ExtensionUnpackerTest, MissingDefaultData) { SetupUnpacker("missing_default_data.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages), unpacker_->error_message()); } TEST_F(ExtensionUnpackerTest, MissingDefaultLocaleHasLocalesFolder) { SetupUnpacker("missing_default_has_locales.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultLocaleSpecified), unpacker_->error_message()); } TEST_F(ExtensionUnpackerTest, MissingMessagesFile) { SetupUnpacker("missing_messages_file.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_TRUE(MatchPattern(unpacker_->error_message(), ASCIIToUTF16(errors::kLocalesMessagesFileMissing) + ASCIIToUTF16("*_locales?en_US?messages.json"))); } TEST_F(ExtensionUnpackerTest, NoLocaleData) { SetupUnpacker("no_locale_data.crx"); EXPECT_FALSE(unpacker_->Run()); EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages), unpacker_->error_message()); } TEST_F(ExtensionUnpackerTest, GoodL10n) { SetupUnpacker("good_l10n.crx"); EXPECT_TRUE(unpacker_->Run()); EXPECT_TRUE(unpacker_->error_message().empty()); ASSERT_EQ(2U, unpacker_->parsed_catalogs()->size()); } TEST_F(ExtensionUnpackerTest, NoL10n) { SetupUnpacker("no_l10n.crx"); EXPECT_TRUE(unpacker_->Run()); EXPECT_TRUE(unpacker_->error_message().empty()); EXPECT_EQ(0U, unpacker_->parsed_catalogs()->size()); } <|endoftext|>
<commit_before>/* * NotebookPlots.cpp * * Copyright (C) 2009-16 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 "SessionRmdNotebook.hpp" #include "NotebookPlots.hpp" #include "NotebookOutput.hpp" #include "../SessionPlots.hpp" #include <boost/format.hpp> #include <boost/foreach.hpp> #include <boost/signals/connection.hpp> #include <core/system/FileMonitor.hpp> #include <core/StringUtils.hpp> #include <core/Exec.hpp> #include <session/SessionModuleContext.hpp> #include <r/RExec.hpp> #include <r/RSexp.hpp> #include <r/session/RGraphics.hpp> #include <r/ROptions.hpp> #define kPlotPrefix "_rs_chunk_plot_" #define kGoldenRatio 1.618 using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace rmarkdown { namespace notebook { namespace { bool isPlotPath(const FilePath& path) { return path.hasExtensionLowerCase(".png") && string_utils::isPrefixOf(path.stem(), kPlotPrefix); } } // anonymous namespace PlotCapture::PlotCapture() : hasPlots_(false), plotPending_(false), lastOrdinal_(0) { } PlotCapture::~PlotCapture() { } void PlotCapture::processPlots(bool ignoreEmpty) { // ensure plot folder exists if (!plotFolder_.exists()) return; // collect plots from the folder std::vector<FilePath> folderContents; Error error = plotFolder_.children(&folderContents); if (error) LOG_ERROR(error); BOOST_FOREACH(const FilePath& path, folderContents) { if (isPlotPath(path)) { // we might find an empty plot file if it hasn't been flushed to disk // yet--ignore these if (ignoreEmpty && path.size() == 0) continue; // emit the plot and the snapshot file events().onPlotOutput(path, snapshotFile_, lastOrdinal_); // we've consumed the snapshot file, so clear it snapshotFile_ = FilePath(); lastOrdinal_ = 0; // clean up the plot so it isn't emitted twice error = path.removeIfExists(); if (error) LOG_ERROR(error); } } } void PlotCapture::saveSnapshot() { // no work to do if we don't have a display list to write if (lastPlot_.isNil()) return; // if there's a plot on the device, write its display list before it's // cleared for the next page FilePath outputFile = plotFolder_.complete( core::system::generateUuid(false) + kDisplayListExt); Error error = r::exec::RFunction(".rs.saveNotebookGraphics", lastPlot_.get(), outputFile.absolutePath()).call(); if (error) LOG_ERROR(error); else snapshotFile_ = outputFile; } void PlotCapture::onExprComplete() { r::sexp::Protect protect; // no action if no plots were created in this chunk if (!hasPlots_) return; // no action if nothing on device list (implies no graphics output) if (!isGraphicsDeviceActive()) return; // if we were expecting a new plot to be produced by the previous // expression, process the plot folder if (plotPending_) { plotPending_ = false; processPlots(true); } // check the current state of the graphics device against the last known // state SEXP plot = R_NilValue; Error error = r::exec::RFunction("recordPlot").call(&plot, &protect); if (error) { LOG_ERROR(error); return; } // detect changes and save last state bool unchanged = false; if (!lastPlot_.isNil()) r::exec::RFunction("identical", plot, lastPlot_.get()).call(&unchanged); lastPlot_.set(plot); // if the state changed, reserve an ordinal at this position if (!unchanged) { OutputPair pair = lastChunkOutput(docId_, chunkId_, nbCtxId_); lastOrdinal_ = ++pair.ordinal; pair.outputType = ChunkOutputPlot; updateLastChunkOutput(docId_, chunkId_, pair); // notify the client so it can create a placeholder json::Object unit; unit[kChunkOutputType] = static_cast<int>(ChunkOutputOrdinal); unit[kChunkOutputValue] = static_cast<int>(lastOrdinal_); unit[kChunkOutputOrdinal] = static_cast<int>(lastOrdinal_); json::Object placeholder; placeholder[kChunkId] = chunkId_; placeholder[kChunkDocId] = docId_; placeholder[kChunkOutputPath] = unit; module_context::enqueClientEvent(ClientEvent( client_events::kChunkOutput, placeholder)); } } void PlotCapture::removeGraphicsDevice() { // take a snapshot of the last plot's display list before we turn off the // device (if we haven't emitted it yet) if (hasPlots_ && sizeBehavior_ == PlotSizeAutomatic && snapshotFile_.empty()) saveSnapshot(); // turn off the graphics device, if it was ever turned on -- this has the // side effect of writing the device's remaining output to files if (isGraphicsDeviceActive()) { Error error = r::exec::RFunction("dev.off").call(); if (error) LOG_ERROR(error); isGraphicsDeviceActive(); processPlots(false); } hasPlots_ = false; } void PlotCapture::onBeforeNewPlot() { if (!lastPlot_.isNil()) { // save the snapshot of the plot to disk if (sizeBehavior_ == PlotSizeAutomatic) saveSnapshot(); } plotPending_ = true; hasPlots_ = true; } void PlotCapture::onNewPlot() { hasPlots_ = true; processPlots(true); } // begins capturing plot output core::Error PlotCapture::connectPlots(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, double height, double width, PlotSizeBehavior sizeBehavior, const FilePath& plotFolder) { // save identifiers docId_ = docId; chunkId_ = chunkId; nbCtxId_ = nbCtxId; // clean up any stale plots from the folder plotFolder_ = plotFolder; std::vector<FilePath> folderContents; Error error = plotFolder.children(&folderContents); if (error) return error; BOOST_FOREACH(const core::FilePath& file, folderContents) { // remove if it looks like a plot if (isPlotPath(file)) { error = file.remove(); if (error) { // this is non-fatal LOG_ERROR(error); } } } // infer height/width if only one is given if (height == 0 && width > 0) height = width / kGoldenRatio; else if (height > 0 && width == 0) width = height * kGoldenRatio; width_ = width; height_ = height; sizeBehavior_ = sizeBehavior; // save old device option deviceOption_.set(r::options::getOption("device")); // set option for notebook graphics device (must succeed) error = setGraphicsOption(); if (error) return error; onBeforeNewPlot_ = plots::events().onBeforeNewPlot.connect( boost::bind(&PlotCapture::onBeforeNewPlot, this)); onBeforeNewGridPage_ = plots::events().onBeforeNewGridPage.connect( boost::bind(&PlotCapture::onBeforeNewPlot, this)); onNewPlot_ = plots::events().onNewPlot.connect( boost::bind(&PlotCapture::onNewPlot, this)); NotebookCapture::connect(); return Success(); } void PlotCapture::disconnect() { if (connected()) { // remove the graphics device if we created it removeGraphicsDevice(); // restore the graphics device option r::options::setOption("device", deviceOption_.get()); onNewPlot_.disconnect(); onBeforeNewPlot_.disconnect(); onBeforeNewGridPage_.disconnect(); } NotebookCapture::disconnect(); } core::Error PlotCapture::setGraphicsOption() { Error error; // create the notebook graphics device r::exec::RFunction setOption(".rs.setNotebookGraphicsOption"); // the folder in which to place the rendered plots (this is a sibling of the // main chunk output folder) setOption.addParam( plotFolder_.absolutePath() + "/" kPlotPrefix "%03d.png"); // device dimensions setOption.addParam(height_); setOption.addParam(width_); // sizing behavior drives units -- user specified units are in inches but // we use pixels when scaling automatically setOption.addParam(sizeBehavior_ == PlotSizeManual ? "in" : "px"); // device parameters setOption.addParam(r::session::graphics::device::devicePixelRatio()); // other args (OS dependent) setOption.addParam(r::session::graphics::extraBitmapParams()); return setOption.call(); } bool PlotCapture::isGraphicsDeviceActive() { r::sexp::Protect protect; SEXP devlist = R_NilValue; Error error = r::exec::RFunction("dev.list").call(&devlist, &protect); if (error) LOG_ERROR(error); if (r::sexp::isNull(devlist)) return false; return true; } core::Error initPlots() { ExecBlock initBlock; initBlock.addFunctions() (boost::bind(module_context::sourceModuleRFile, "NotebookPlots.R")); return initBlock.execute(); } } // namespace notebook } // namespace rmarkdown } // namespace modules } // namespace session } // namespace rstudio <commit_msg>notebook: skip plot processing for empty graphics device<commit_after>/* * NotebookPlots.cpp * * Copyright (C) 2009-16 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 "SessionRmdNotebook.hpp" #include "NotebookPlots.hpp" #include "NotebookOutput.hpp" #include "../SessionPlots.hpp" #include <boost/format.hpp> #include <boost/foreach.hpp> #include <boost/signals/connection.hpp> #include <core/system/FileMonitor.hpp> #include <core/StringUtils.hpp> #include <core/Exec.hpp> #include <session/SessionModuleContext.hpp> #include <r/RExec.hpp> #include <r/RSexp.hpp> #include <r/session/RGraphics.hpp> #include <r/ROptions.hpp> #define kPlotPrefix "_rs_chunk_plot_" #define kGoldenRatio 1.618 using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace rmarkdown { namespace notebook { namespace { bool isPlotPath(const FilePath& path) { return path.hasExtensionLowerCase(".png") && string_utils::isPrefixOf(path.stem(), kPlotPrefix); } } // anonymous namespace PlotCapture::PlotCapture() : hasPlots_(false), plotPending_(false), lastOrdinal_(0) { } PlotCapture::~PlotCapture() { } void PlotCapture::processPlots(bool ignoreEmpty) { // ensure plot folder exists if (!plotFolder_.exists()) return; // collect plots from the folder std::vector<FilePath> folderContents; Error error = plotFolder_.children(&folderContents); if (error) LOG_ERROR(error); BOOST_FOREACH(const FilePath& path, folderContents) { if (isPlotPath(path)) { // we might find an empty plot file if it hasn't been flushed to disk // yet--ignore these if (ignoreEmpty && path.size() == 0) continue; // emit the plot and the snapshot file events().onPlotOutput(path, snapshotFile_, lastOrdinal_); // we've consumed the snapshot file, so clear it snapshotFile_ = FilePath(); lastOrdinal_ = 0; // clean up the plot so it isn't emitted twice error = path.removeIfExists(); if (error) LOG_ERROR(error); } } } void PlotCapture::saveSnapshot() { // no work to do if we don't have a display list to write if (lastPlot_.isNil()) return; // if there's a plot on the device, write its display list before it's // cleared for the next page FilePath outputFile = plotFolder_.complete( core::system::generateUuid(false) + kDisplayListExt); Error error = r::exec::RFunction(".rs.saveNotebookGraphics", lastPlot_.get(), outputFile.absolutePath()).call(); if (error) LOG_ERROR(error); else snapshotFile_ = outputFile; } void PlotCapture::onExprComplete() { r::sexp::Protect protect; // no action if no plots were created in this chunk if (!hasPlots_) return; // no action if nothing on device list (implies no graphics output) if (!isGraphicsDeviceActive()) return; // if we were expecting a new plot to be produced by the previous // expression, process the plot folder if (plotPending_) { plotPending_ = false; processPlots(true); } // check the current state of the graphics device against the last known // state SEXP plot = R_NilValue; Error error = r::exec::RFunction("recordPlot").call(&plot, &protect); if (error) { LOG_ERROR(error); return; } // detect changes and save last state bool unchanged = false; if (!lastPlot_.isNil()) r::exec::RFunction("identical", plot, lastPlot_.get()).call(&unchanged); lastPlot_.set(plot); // if the state changed, reserve an ordinal at this position if (!unchanged) { OutputPair pair = lastChunkOutput(docId_, chunkId_, nbCtxId_); lastOrdinal_ = ++pair.ordinal; pair.outputType = ChunkOutputPlot; updateLastChunkOutput(docId_, chunkId_, pair); // notify the client so it can create a placeholder json::Object unit; unit[kChunkOutputType] = static_cast<int>(ChunkOutputOrdinal); unit[kChunkOutputValue] = static_cast<int>(lastOrdinal_); unit[kChunkOutputOrdinal] = static_cast<int>(lastOrdinal_); json::Object placeholder; placeholder[kChunkId] = chunkId_; placeholder[kChunkDocId] = docId_; placeholder[kChunkOutputPath] = unit; module_context::enqueClientEvent(ClientEvent( client_events::kChunkOutput, placeholder)); } } void PlotCapture::removeGraphicsDevice() { // take a snapshot of the last plot's display list before we turn off the // device (if we haven't emitted it yet) if (hasPlots_ && sizeBehavior_ == PlotSizeAutomatic && snapshotFile_.empty()) saveSnapshot(); // turn off the graphics device, if it was ever turned on -- this has the // side effect of writing the device's remaining output to files if (isGraphicsDeviceActive()) { Error error = r::exec::RFunction("dev.off").call(); if (error) LOG_ERROR(error); // some operations may trigger the graphics device without actually // writing a plot; ignore these if (hasPlots_) processPlots(false); } hasPlots_ = false; } void PlotCapture::onBeforeNewPlot() { if (!lastPlot_.isNil()) { // save the snapshot of the plot to disk if (sizeBehavior_ == PlotSizeAutomatic) saveSnapshot(); } plotPending_ = true; hasPlots_ = true; } void PlotCapture::onNewPlot() { hasPlots_ = true; processPlots(true); } // begins capturing plot output core::Error PlotCapture::connectPlots(const std::string& docId, const std::string& chunkId, const std::string& nbCtxId, double height, double width, PlotSizeBehavior sizeBehavior, const FilePath& plotFolder) { // save identifiers docId_ = docId; chunkId_ = chunkId; nbCtxId_ = nbCtxId; // clean up any stale plots from the folder plotFolder_ = plotFolder; std::vector<FilePath> folderContents; Error error = plotFolder.children(&folderContents); if (error) return error; BOOST_FOREACH(const core::FilePath& file, folderContents) { // remove if it looks like a plot if (isPlotPath(file)) { error = file.remove(); if (error) { // this is non-fatal LOG_ERROR(error); } } } // infer height/width if only one is given if (height == 0 && width > 0) height = width / kGoldenRatio; else if (height > 0 && width == 0) width = height * kGoldenRatio; width_ = width; height_ = height; sizeBehavior_ = sizeBehavior; // save old device option deviceOption_.set(r::options::getOption("device")); // set option for notebook graphics device (must succeed) error = setGraphicsOption(); if (error) return error; onBeforeNewPlot_ = plots::events().onBeforeNewPlot.connect( boost::bind(&PlotCapture::onBeforeNewPlot, this)); onBeforeNewGridPage_ = plots::events().onBeforeNewGridPage.connect( boost::bind(&PlotCapture::onBeforeNewPlot, this)); onNewPlot_ = plots::events().onNewPlot.connect( boost::bind(&PlotCapture::onNewPlot, this)); NotebookCapture::connect(); return Success(); } void PlotCapture::disconnect() { if (connected()) { // remove the graphics device if we created it removeGraphicsDevice(); // restore the graphics device option r::options::setOption("device", deviceOption_.get()); onNewPlot_.disconnect(); onBeforeNewPlot_.disconnect(); onBeforeNewGridPage_.disconnect(); } NotebookCapture::disconnect(); } core::Error PlotCapture::setGraphicsOption() { Error error; // create the notebook graphics device r::exec::RFunction setOption(".rs.setNotebookGraphicsOption"); // the folder in which to place the rendered plots (this is a sibling of the // main chunk output folder) setOption.addParam( plotFolder_.absolutePath() + "/" kPlotPrefix "%03d.png"); // device dimensions setOption.addParam(height_); setOption.addParam(width_); // sizing behavior drives units -- user specified units are in inches but // we use pixels when scaling automatically setOption.addParam(sizeBehavior_ == PlotSizeManual ? "in" : "px"); // device parameters setOption.addParam(r::session::graphics::device::devicePixelRatio()); // other args (OS dependent) setOption.addParam(r::session::graphics::extraBitmapParams()); return setOption.call(); } bool PlotCapture::isGraphicsDeviceActive() { r::sexp::Protect protect; SEXP devlist = R_NilValue; Error error = r::exec::RFunction("dev.list").call(&devlist, &protect); if (error) LOG_ERROR(error); if (r::sexp::isNull(devlist)) return false; return true; } core::Error initPlots() { ExecBlock initBlock; initBlock.addFunctions() (boost::bind(module_context::sourceModuleRFile, "NotebookPlots.R")); return initBlock.execute(); } } // namespace notebook } // namespace rmarkdown } // namespace modules } // namespace session } // namespace rstudio <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/base/init.h> #include <shogun/evaluation/CrossValidation.h> #include <shogun/evaluation/ContingencyTableEvaluation.h> #include <shogun/evaluation/StratifiedCrossValidationSplitting.h> #include <shogun/modelselection/GridSearchModelSelection.h> #include <shogun/modelselection/ModelSelectionParameters.h> #include <shogun/modelselection/ParameterCombination.h> #include <shogun/features/Labels.h> #include <shogun/features/SimpleFeatures.h> #include <shogun/classifier/svm/LibLinear.h> using namespace shogun; void print_message(FILE* target, const char* str) { fprintf(target, "%s", str); } CModelSelectionParameters* create_param_tree() { CModelSelectionParameters* root=new CModelSelectionParameters(); CModelSelectionParameters* c1=new CModelSelectionParameters("C1"); root->append_child(c1); c1->build_values(-15, 15, R_EXP); CModelSelectionParameters* c2=new CModelSelectionParameters("C2"); root->append_child(c2); c2->build_values(-15, 15, R_EXP); return root; } int main(int argc, char **argv) { init_shogun(&print_message, &print_message, &print_message); int32_t num_subsets=5; int32_t num_features=11; /* create some data */ float64_t* matrix=new float64_t[num_features*2]; for (int32_t i=0; i<num_features*2; i++) matrix[i]=i; /* create num_feautres 2-dimensional vectors */ CSimpleFeatures<float64_t>* features=new CSimpleFeatures<float64_t> (); features->set_feature_matrix(matrix, 2, num_features); /* create three labels */ CLabels* labels=new CLabels(num_features); for (index_t i=0; i<num_features; ++i) labels->set_label(i, i%2==0 ? 1 : -1); /* create linear classifier (use -s 2 option to avoid warnings) */ CLibLinear* classifier=new CLibLinear(L2R_L2LOSS_SVC); /* splitting strategy */ CStratifiedCrossValidationSplitting* splitting_strategy= new CStratifiedCrossValidationSplitting(labels, num_subsets); /* accuracy evaluation */ CContingencyTableEvaluation* evaluation_criterium= new CContingencyTableEvaluation(ACCURACY); /* cross validation class for evaluation in model selection */ CCrossValidation* cross=new CCrossValidation(classifier, features, labels, splitting_strategy, evaluation_criterium); /* model parameter selection, deletion is handled by modsel class (SG_UNREF) */ CModelSelectionParameters* param_tree=create_param_tree(); /* this is on the stack and handles all of the above structures in memory */ CGridSearchModelSelection grid_search(param_tree, cross); float64_t result; CParameterCombination* best_combination=grid_search.select_model(result); SG_SPRINT("best parameter(s):\n"); best_combination->print_tree(); SG_SPRINT("result: %f\n", result); /* clean up destroy result parameter */ SG_UNREF(best_combination); SG_SPRINT("\nEND\n"); exit_shogun(); return 0; } <commit_msg>applied interface changes<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2011 Heiko Strathmann * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/base/init.h> #include <shogun/evaluation/CrossValidation.h> #include <shogun/evaluation/ContingencyTableEvaluation.h> #include <shogun/evaluation/StratifiedCrossValidationSplitting.h> #include <shogun/modelselection/GridSearchModelSelection.h> #include <shogun/modelselection/ModelSelectionParameters.h> #include <shogun/modelselection/ParameterCombination.h> #include <shogun/features/Labels.h> #include <shogun/features/SimpleFeatures.h> #include <shogun/classifier/svm/LibLinear.h> using namespace shogun; void print_message(FILE* target, const char* str) { fprintf(target, "%s", str); } CModelSelectionParameters* create_param_tree() { CModelSelectionParameters* root=new CModelSelectionParameters(); CModelSelectionParameters* c1=new CModelSelectionParameters("C1"); root->append_child(c1); c1->build_values(-15, 15, R_EXP); CModelSelectionParameters* c2=new CModelSelectionParameters("C2"); root->append_child(c2); c2->build_values(-15, 15, R_EXP); return root; } int main(int argc, char **argv) { init_shogun(&print_message, &print_message, &print_message); int32_t num_subsets=5; int32_t num_features=11; /* create some data */ float64_t* matrix=new float64_t[num_features*2]; for (int32_t i=0; i<num_features*2; i++) matrix[i]=i; /* create num_feautres 2-dimensional vectors */ CSimpleFeatures<float64_t>* features=new CSimpleFeatures<float64_t> (); features->set_feature_matrix(matrix, 2, num_features); /* create three labels */ CLabels* labels=new CLabels(num_features); for (index_t i=0; i<num_features; ++i) labels->set_label(i, i%2==0 ? 1 : -1); /* create linear classifier (use -s 2 option to avoid warnings) */ CLibLinear* classifier=new CLibLinear(L2R_L2LOSS_SVC); /* splitting strategy */ CStratifiedCrossValidationSplitting* splitting_strategy= new CStratifiedCrossValidationSplitting(labels, num_subsets); /* accuracy evaluation */ CContingencyTableEvaluation* evaluation_criterium= new CContingencyTableEvaluation(ACCURACY); /* cross validation class for evaluation in model selection */ CCrossValidation* cross=new CCrossValidation(classifier, features, labels, splitting_strategy, evaluation_criterium); /* model parameter selection, deletion is handled by modsel class (SG_UNREF) */ CModelSelectionParameters* param_tree=create_param_tree(); /* this is on the stack and handles all of the above structures in memory */ CGridSearchModelSelection grid_search(param_tree, cross); CParameterCombination* best_combination=grid_search.select_model(); SG_SPRINT("best parameter(s):\n"); best_combination->print_tree(); best_combination->apply_to_machine(classifier); SG_SPRINT("result: %f\n", cross->evaluate()); /* clean up destroy result parameter */ SG_UNREF(best_combination); SG_SPRINT("\nEND\n"); exit_shogun(); return 0; } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/error_estimation_factory.h" // libMesh #include "libmesh/adjoint_residual_error_estimator.h" #include "libmesh/getpot.h" #include "libmesh/patch_recovery_error_estimator.h" #include "libmesh/qoi_set.h" namespace GRINS { ErrorEstimatorFactory::ErrorEstimatorFactory() { return; } ErrorEstimatorFactory::~ErrorEstimatorFactory() { return; } std::tr1::shared_ptr<libMesh::ErrorEstimator> ErrorEstimatorFactory::build( const GetPot& input, std::tr1::shared_ptr<QoIBase> qoi_base ) { // check if qoi_base is an empty pointer (user set no QoI), in that case return empty pointer. if( qoi_base == std::tr1::shared_ptr<QoIBase>() ) { return std::tr1::shared_ptr<libMesh::ErrorEstimator>(); } std::string estimator_type = input("MeshAdaptivity/estimator_type", "none"); ErrorEstimatorEnum estimator_enum = this->string_to_enum( estimator_type ); std::tr1::shared_ptr<libMesh::ErrorEstimator> error_estimator; switch( estimator_enum ) { case(ADJOINT_RESIDUAL): { error_estimator.reset( new libMesh::AdjointResidualErrorEstimator ); libMesh::AdjointResidualErrorEstimator* adjoint_error_estimator = libmesh_cast_ptr<libMesh::AdjointResidualErrorEstimator*>( error_estimator.get() ); libMesh::PatchRecoveryErrorEstimator *p1 = new libMesh::PatchRecoveryErrorEstimator; adjoint_error_estimator->primal_error_estimator().reset( p1 ); libMesh::PatchRecoveryErrorEstimator *p2 = new libMesh::PatchRecoveryErrorEstimator; adjoint_error_estimator->dual_error_estimator().reset( p2 ); bool patch_reuse = input( "MeshAdaptivity/patch_reuse", true ); adjoint_error_estimator->primal_error_estimator()->error_norm.set_type( 0, H1_SEMINORM ); p1->set_patch_reuse( patch_reuse ); adjoint_error_estimator->dual_error_estimator()->error_norm.set_type( 0, H1_SEMINORM ); p2->set_patch_reuse( patch_reuse ); } break; case(ADJOINT_REFINEMENT): case(KELLY): case(PATCH_RECOVERY): case(WEIGHTED_PATCH_RECOVERY): case(UNIFORM_REFINEMENT): { libmesh_not_implemented(); } break; default: { std::cerr << "Error: Invalid error estimator type " << estimator_type << std::endl; libmesh_error(); } } // switch( estimator_enum ) return error_estimator; } ErrorEstimatorFactory::ErrorEstimatorEnum ErrorEstimatorFactory::string_to_enum( const std::string& estimator_type ) const { ErrorEstimatorEnum value; if( estimator_type == std::string("adjoint_residual") ) { value = ADJOINT_RESIDUAL; } else if( estimator_type == std::string("adjoint_refinement") ) { value = ADJOINT_REFINEMENT; } else if( estimator_type == std::string("kelly") ) { value = KELLY; } else if( estimator_type == std::string("patch_recovery") ) { value = PATCH_RECOVERY; } else if( estimator_type == std::string("weighted_patch_recovery") ) { value = WEIGHTED_PATCH_RECOVERY; } else if( estimator_type == std::string("uniform_refinement") ) { value = UNIFORM_REFINEMENT; } else { std::cerr << "Error: Invalid error estimator type " << estimator_type << std::endl << "Valid error estimator types are: adjoint_residual" << std::endl << " adjoint_refinement" << std::endl << " kelly" << std::endl << " patch_recovery" << std::endl << " weighted_patch_recovery" << std::endl << " uniform_refinement" << std::endl; libmesh_error(); } return value; } } // namespace GRINS <commit_msg>Meh, no need for error message there because that should never happen.<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License 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. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/error_estimation_factory.h" // libMesh #include "libmesh/adjoint_residual_error_estimator.h" #include "libmesh/getpot.h" #include "libmesh/patch_recovery_error_estimator.h" #include "libmesh/qoi_set.h" namespace GRINS { ErrorEstimatorFactory::ErrorEstimatorFactory() { return; } ErrorEstimatorFactory::~ErrorEstimatorFactory() { return; } std::tr1::shared_ptr<libMesh::ErrorEstimator> ErrorEstimatorFactory::build( const GetPot& input, std::tr1::shared_ptr<QoIBase> qoi_base ) { // check if qoi_base is an empty pointer (user set no QoI), in that case return empty pointer. if( qoi_base == std::tr1::shared_ptr<QoIBase>() ) { return std::tr1::shared_ptr<libMesh::ErrorEstimator>(); } std::string estimator_type = input("MeshAdaptivity/estimator_type", "none"); ErrorEstimatorEnum estimator_enum = this->string_to_enum( estimator_type ); std::tr1::shared_ptr<libMesh::ErrorEstimator> error_estimator; switch( estimator_enum ) { case(ADJOINT_RESIDUAL): { error_estimator.reset( new libMesh::AdjointResidualErrorEstimator ); libMesh::AdjointResidualErrorEstimator* adjoint_error_estimator = libmesh_cast_ptr<libMesh::AdjointResidualErrorEstimator*>( error_estimator.get() ); libMesh::PatchRecoveryErrorEstimator *p1 = new libMesh::PatchRecoveryErrorEstimator; adjoint_error_estimator->primal_error_estimator().reset( p1 ); libMesh::PatchRecoveryErrorEstimator *p2 = new libMesh::PatchRecoveryErrorEstimator; adjoint_error_estimator->dual_error_estimator().reset( p2 ); bool patch_reuse = input( "MeshAdaptivity/patch_reuse", true ); adjoint_error_estimator->primal_error_estimator()->error_norm.set_type( 0, H1_SEMINORM ); p1->set_patch_reuse( patch_reuse ); adjoint_error_estimator->dual_error_estimator()->error_norm.set_type( 0, H1_SEMINORM ); p2->set_patch_reuse( patch_reuse ); } break; case(ADJOINT_REFINEMENT): case(KELLY): case(PATCH_RECOVERY): case(WEIGHTED_PATCH_RECOVERY): case(UNIFORM_REFINEMENT): { libmesh_not_implemented(); } break; // wat?! default: { libmesh_error(); } } // switch( estimator_enum ) return error_estimator; } ErrorEstimatorFactory::ErrorEstimatorEnum ErrorEstimatorFactory::string_to_enum( const std::string& estimator_type ) const { ErrorEstimatorEnum value; if( estimator_type == std::string("adjoint_residual") ) { value = ADJOINT_RESIDUAL; } else if( estimator_type == std::string("adjoint_refinement") ) { value = ADJOINT_REFINEMENT; } else if( estimator_type == std::string("kelly") ) { value = KELLY; } else if( estimator_type == std::string("patch_recovery") ) { value = PATCH_RECOVERY; } else if( estimator_type == std::string("weighted_patch_recovery") ) { value = WEIGHTED_PATCH_RECOVERY; } else if( estimator_type == std::string("uniform_refinement") ) { value = UNIFORM_REFINEMENT; } else { std::cerr << "Error: Invalid error estimator type " << estimator_type << std::endl << "Valid error estimator types are: adjoint_residual" << std::endl << " adjoint_refinement" << std::endl << " kelly" << std::endl << " patch_recovery" << std::endl << " weighted_patch_recovery" << std::endl << " uniform_refinement" << std::endl; libmesh_error(); } return value; } } // namespace GRINS <|endoftext|>
<commit_before>// // Copyright 2012 Francisco Jerez // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include "core/resource.hpp" #include "pipe/p_screen.h" #include "util/u_sampler.h" #include "util/u_format.h" using namespace clover; namespace { class box { public: box(const resource::point &origin, const resource::point &size) : pipe({ (int)origin[0], (int)origin[1], (int)origin[2], (int)size[0], (int)size[1], (int)size[2] }) { } operator const pipe_box *() { return &pipe; } protected: pipe_box pipe; }; } resource::resource(clover::device &dev, clover::memory_obj &obj) : dev(dev), obj(obj), pipe(NULL), offset{0} { } resource::~resource() { } void resource::copy(command_queue &q, const point &origin, const point &region, resource &src_res, const point &src_origin) { point p = offset + origin; q.pipe->resource_copy_region(q.pipe, pipe, 0, p[0], p[1], p[2], src_res.pipe, 0, box(src_res.offset + src_origin, region)); } void * resource::add_map(command_queue &q, cl_map_flags flags, bool blocking, const point &origin, const point &region) { maps.emplace_back(q, *this, flags, blocking, origin, region); return maps.back(); } void resource::del_map(void *p) { auto it = std::find(maps.begin(), maps.end(), p); if (it != maps.end()) maps.erase(it); } unsigned resource::map_count() const { return maps.size(); } pipe_sampler_view * resource::bind_sampler_view(clover::command_queue &q) { pipe_sampler_view info; u_sampler_view_default_template(&info, pipe, pipe->format); return q.pipe->create_sampler_view(q.pipe, pipe, &info); } void resource::unbind_sampler_view(clover::command_queue &q, pipe_sampler_view *st) { q.pipe->sampler_view_destroy(q.pipe, st); } pipe_surface * resource::bind_surface(clover::command_queue &q, bool rw) { pipe_surface info {}; info.format = pipe->format; info.usage = pipe->bind; info.writable = rw; if (pipe->target == PIPE_BUFFER) info.u.buf.last_element = pipe->width0 - 1; return q.pipe->create_surface(q.pipe, pipe, &info); } void resource::unbind_surface(clover::command_queue &q, pipe_surface *st) { q.pipe->surface_destroy(q.pipe, st); } root_resource::root_resource(clover::device &dev, clover::memory_obj &obj, clover::command_queue &q, const std::string &data) : resource(dev, obj) { pipe_resource info {}; if (image *img = dynamic_cast<image *>(&obj)) { info.format = translate_format(img->format()); info.width0 = img->width(); info.height0 = img->height(); info.depth0 = img->depth(); } else { info.width0 = obj.size(); info.height0 = 1; info.depth0 = 1; } info.target = translate_target(obj.type()); info.bind = (PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_COMPUTE_RESOURCE | PIPE_BIND_GLOBAL | PIPE_BIND_TRANSFER_READ | PIPE_BIND_TRANSFER_WRITE); pipe = dev.pipe->resource_create(dev.pipe, &info); if (!pipe) throw error(CL_OUT_OF_RESOURCES); if (!data.empty()) { box rect { { 0, 0, 0 }, { info.width0, info.height0, info.depth0 } }; unsigned cpp = util_format_get_blocksize(info.format); q.pipe->transfer_inline_write(q.pipe, pipe, 0, PIPE_TRANSFER_WRITE, rect, data.data(), cpp * info.width0, cpp * info.width0 * info.height0); } } root_resource::root_resource(clover::device &dev, clover::memory_obj &obj, clover::root_resource &r) : resource(dev, obj) { assert(0); // XXX -- resource shared among dev and r.dev } root_resource::~root_resource() { dev.pipe->resource_destroy(dev.pipe, pipe); } sub_resource::sub_resource(clover::resource &r, point offset) : resource(r.dev, r.obj) { pipe = r.pipe; offset = r.offset + offset; } mapping::mapping(command_queue &q, resource &r, cl_map_flags flags, bool blocking, const resource::point &origin, const resource::point &region) : pctx(q.pipe) { unsigned usage = ((flags & CL_MAP_WRITE ? PIPE_TRANSFER_WRITE : 0 ) | (flags & CL_MAP_READ ? PIPE_TRANSFER_READ : 0 ) | (blocking ? PIPE_TRANSFER_UNSYNCHRONIZED : 0)); p = pctx->transfer_map(pctx, r.pipe, 0, usage, box(origin + r.offset, region), &pxfer); if (!p) { pxfer = NULL; throw error(CL_OUT_OF_RESOURCES); } } mapping::mapping(mapping &&m) : pctx(m.pctx), pxfer(m.pxfer), p(m.p) { m.p = NULL; m.pxfer = NULL; } mapping::~mapping() { if (pxfer) { pctx->transfer_unmap(pctx, pxfer); } } <commit_msg>clover: Fix build since removal of pipe_surface::usage<commit_after>// // Copyright 2012 Francisco Jerez // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #include "core/resource.hpp" #include "pipe/p_screen.h" #include "util/u_sampler.h" #include "util/u_format.h" using namespace clover; namespace { class box { public: box(const resource::point &origin, const resource::point &size) : pipe({ (int)origin[0], (int)origin[1], (int)origin[2], (int)size[0], (int)size[1], (int)size[2] }) { } operator const pipe_box *() { return &pipe; } protected: pipe_box pipe; }; } resource::resource(clover::device &dev, clover::memory_obj &obj) : dev(dev), obj(obj), pipe(NULL), offset{0} { } resource::~resource() { } void resource::copy(command_queue &q, const point &origin, const point &region, resource &src_res, const point &src_origin) { point p = offset + origin; q.pipe->resource_copy_region(q.pipe, pipe, 0, p[0], p[1], p[2], src_res.pipe, 0, box(src_res.offset + src_origin, region)); } void * resource::add_map(command_queue &q, cl_map_flags flags, bool blocking, const point &origin, const point &region) { maps.emplace_back(q, *this, flags, blocking, origin, region); return maps.back(); } void resource::del_map(void *p) { auto it = std::find(maps.begin(), maps.end(), p); if (it != maps.end()) maps.erase(it); } unsigned resource::map_count() const { return maps.size(); } pipe_sampler_view * resource::bind_sampler_view(clover::command_queue &q) { pipe_sampler_view info; u_sampler_view_default_template(&info, pipe, pipe->format); return q.pipe->create_sampler_view(q.pipe, pipe, &info); } void resource::unbind_sampler_view(clover::command_queue &q, pipe_sampler_view *st) { q.pipe->sampler_view_destroy(q.pipe, st); } pipe_surface * resource::bind_surface(clover::command_queue &q, bool rw) { pipe_surface info {}; info.format = pipe->format; info.writable = rw; if (pipe->target == PIPE_BUFFER) info.u.buf.last_element = pipe->width0 - 1; return q.pipe->create_surface(q.pipe, pipe, &info); } void resource::unbind_surface(clover::command_queue &q, pipe_surface *st) { q.pipe->surface_destroy(q.pipe, st); } root_resource::root_resource(clover::device &dev, clover::memory_obj &obj, clover::command_queue &q, const std::string &data) : resource(dev, obj) { pipe_resource info {}; if (image *img = dynamic_cast<image *>(&obj)) { info.format = translate_format(img->format()); info.width0 = img->width(); info.height0 = img->height(); info.depth0 = img->depth(); } else { info.width0 = obj.size(); info.height0 = 1; info.depth0 = 1; } info.target = translate_target(obj.type()); info.bind = (PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_COMPUTE_RESOURCE | PIPE_BIND_GLOBAL | PIPE_BIND_TRANSFER_READ | PIPE_BIND_TRANSFER_WRITE); pipe = dev.pipe->resource_create(dev.pipe, &info); if (!pipe) throw error(CL_OUT_OF_RESOURCES); if (!data.empty()) { box rect { { 0, 0, 0 }, { info.width0, info.height0, info.depth0 } }; unsigned cpp = util_format_get_blocksize(info.format); q.pipe->transfer_inline_write(q.pipe, pipe, 0, PIPE_TRANSFER_WRITE, rect, data.data(), cpp * info.width0, cpp * info.width0 * info.height0); } } root_resource::root_resource(clover::device &dev, clover::memory_obj &obj, clover::root_resource &r) : resource(dev, obj) { assert(0); // XXX -- resource shared among dev and r.dev } root_resource::~root_resource() { dev.pipe->resource_destroy(dev.pipe, pipe); } sub_resource::sub_resource(clover::resource &r, point offset) : resource(r.dev, r.obj) { pipe = r.pipe; offset = r.offset + offset; } mapping::mapping(command_queue &q, resource &r, cl_map_flags flags, bool blocking, const resource::point &origin, const resource::point &region) : pctx(q.pipe) { unsigned usage = ((flags & CL_MAP_WRITE ? PIPE_TRANSFER_WRITE : 0 ) | (flags & CL_MAP_READ ? PIPE_TRANSFER_READ : 0 ) | (blocking ? PIPE_TRANSFER_UNSYNCHRONIZED : 0)); p = pctx->transfer_map(pctx, r.pipe, 0, usage, box(origin + r.offset, region), &pxfer); if (!p) { pxfer = NULL; throw error(CL_OUT_OF_RESOURCES); } } mapping::mapping(mapping &&m) : pctx(m.pctx), pxfer(m.pxfer), p(m.p) { m.p = NULL; m.pxfer = NULL; } mapping::~mapping() { if (pxfer) { pctx->transfer_unmap(pctx, pxfer); } } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "referencefieldvalue.h" #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/stringfmt.h> #include <cassert> using vespalib::IllegalArgumentException; using vespalib::make_string; namespace document { IMPLEMENT_IDENTIFIABLE(ReferenceFieldValue, FieldValue); ReferenceFieldValue::ReferenceFieldValue() : _dataType(nullptr), _documentId(), _altered(true) { } ReferenceFieldValue::ReferenceFieldValue(const ReferenceDataType& dataType) : _dataType(&dataType), _documentId(), _altered(true) { } ReferenceFieldValue::ReferenceFieldValue( const ReferenceDataType& dataType, const DocumentId& documentId) : _dataType(&dataType), _documentId(documentId), _altered(true) { requireIdOfMatchingType(_documentId, _dataType->getTargetType()); } ReferenceFieldValue::~ReferenceFieldValue() { } void ReferenceFieldValue::requireIdOfMatchingType( const DocumentId& id, const DocumentType& type) { if (id.getDocType() != type.getName()) { throw IllegalArgumentException( make_string("Can't assign document ID '%s' (of type '%s') to " "reference of document type '%s'", id.toString().c_str(), id.getDocType().c_str(), type.getName().c_str()), VESPA_STRLOC); } } FieldValue& ReferenceFieldValue::assign(const FieldValue& rhs) { const auto* refValueRhs(dynamic_cast<const ReferenceFieldValue*>(&rhs)); if (refValueRhs != nullptr) { if (refValueRhs == this) { return *this; } _documentId = refValueRhs->_documentId; _dataType = refValueRhs->_dataType; _altered = true; } else { throw IllegalArgumentException( make_string("Can't assign field value of type %s to " "a ReferenceFieldValue", rhs.getDataType()->getName().c_str()), VESPA_STRLOC); } return *this; } void ReferenceFieldValue::setDeserializedDocumentId(const DocumentId& id) { assert(_dataType != nullptr); requireIdOfMatchingType(id, _dataType->getTargetType()); _documentId = id; _altered = false; } ReferenceFieldValue* ReferenceFieldValue::clone() const { assert(_dataType != nullptr); return new ReferenceFieldValue(*_dataType, _documentId); } int ReferenceFieldValue::compare(const FieldValue& rhs) const { const int parentCompare = FieldValue::compare(rhs); if (parentCompare != 0) { return parentCompare; } // Type equality is checked by the parent. const auto& refValueRhs(dynamic_cast<const ReferenceFieldValue&>(rhs)); // TODO PERF: DocumentId does currently _not_ expose any methods that // cheaply allow an ordering to be established. Only (in)equality operators. // IdString::operator== is already implemented in the same way as this, so // don't put this code in your inner loops, kids! return _documentId.toString().compare(refValueRhs._documentId.toString()); } void ReferenceFieldValue::print(std::ostream& os, bool verbose, const std::string& indent) const { (void) verbose; (void) indent; assert(_dataType != nullptr); os << "ReferenceFieldValue(" << *_dataType << ", DocumentId("; _documentId.print(os, false, ""); os << "))"; } bool ReferenceFieldValue::hasChanged() const { return _altered; } void ReferenceFieldValue::accept(FieldValueVisitor& visitor) { visitor.visit(*this); } void ReferenceFieldValue::accept(ConstFieldValueVisitor& visitor) const { visitor.visit(*this); } } // document <commit_msg>Simplify branching<commit_after>// Copyright 2017 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "referencefieldvalue.h" #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/stringfmt.h> #include <cassert> using vespalib::IllegalArgumentException; using vespalib::make_string; namespace document { IMPLEMENT_IDENTIFIABLE(ReferenceFieldValue, FieldValue); ReferenceFieldValue::ReferenceFieldValue() : _dataType(nullptr), _documentId(), _altered(true) { } ReferenceFieldValue::ReferenceFieldValue(const ReferenceDataType& dataType) : _dataType(&dataType), _documentId(), _altered(true) { } ReferenceFieldValue::ReferenceFieldValue( const ReferenceDataType& dataType, const DocumentId& documentId) : _dataType(&dataType), _documentId(documentId), _altered(true) { requireIdOfMatchingType(_documentId, _dataType->getTargetType()); } ReferenceFieldValue::~ReferenceFieldValue() { } void ReferenceFieldValue::requireIdOfMatchingType( const DocumentId& id, const DocumentType& type) { if (id.getDocType() != type.getName()) { throw IllegalArgumentException( make_string("Can't assign document ID '%s' (of type '%s') to " "reference of document type '%s'", id.toString().c_str(), id.getDocType().c_str(), type.getName().c_str()), VESPA_STRLOC); } } FieldValue& ReferenceFieldValue::assign(const FieldValue& rhs) { const auto* refValueRhs(dynamic_cast<const ReferenceFieldValue*>(&rhs)); if (refValueRhs == nullptr) { throw IllegalArgumentException( make_string("Can't assign field value of type %s to " "a ReferenceFieldValue", rhs.getDataType()->getName().c_str()), VESPA_STRLOC); } if (refValueRhs == this) { return *this; } _documentId = refValueRhs->_documentId; _dataType = refValueRhs->_dataType; _altered = true; return *this; } void ReferenceFieldValue::setDeserializedDocumentId(const DocumentId& id) { assert(_dataType != nullptr); requireIdOfMatchingType(id, _dataType->getTargetType()); _documentId = id; _altered = false; } ReferenceFieldValue* ReferenceFieldValue::clone() const { assert(_dataType != nullptr); return new ReferenceFieldValue(*_dataType, _documentId); } int ReferenceFieldValue::compare(const FieldValue& rhs) const { const int parentCompare = FieldValue::compare(rhs); if (parentCompare != 0) { return parentCompare; } // Type equality is checked by the parent. const auto& refValueRhs(dynamic_cast<const ReferenceFieldValue&>(rhs)); // TODO PERF: DocumentId does currently _not_ expose any methods that // cheaply allow an ordering to be established. Only (in)equality operators. // IdString::operator== is already implemented in the same way as this, so // don't put this code in your inner loops, kids! return _documentId.toString().compare(refValueRhs._documentId.toString()); } void ReferenceFieldValue::print(std::ostream& os, bool verbose, const std::string& indent) const { (void) verbose; (void) indent; assert(_dataType != nullptr); os << "ReferenceFieldValue(" << *_dataType << ", DocumentId("; _documentId.print(os, false, ""); os << "))"; } bool ReferenceFieldValue::hasChanged() const { return _altered; } void ReferenceFieldValue::accept(FieldValueVisitor& visitor) { visitor.visit(*this); } void ReferenceFieldValue::accept(ConstFieldValueVisitor& visitor) const { visitor.visit(*this); } } // document <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH #define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH // system #include <vector> // dune-stuff #include <dune/stuff/common/vector.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace Assembler { namespace Local { namespace Codim1 { /** \todo Add neumann boundary treatment \todo When adding neumann: think of numTmpObjectsRequired()! \todo Add penalty parameter **/ template< class LocalFunctionalImp > class Vector { public: typedef LocalFunctionalImp LocalFunctionalType; typedef Vector< LocalFunctionalType > ThisType; typedef typename LocalFunctionalType::RangeFieldType RangeFieldType; //! constructor Vector( const LocalFunctionalType localFunctional ) : localFunctional_( localFunctional ) { } private: //! copy constructor Vector( const ThisType& other ) : localFunctional_( other.localFunctional() ) { } public: const LocalFunctionalType& localFunctional() const { return localFunctional_; } /** \todo Add neumann treatment here! **/ std::vector< unsigned int > numTmpObjectsRequired() const { std::vector< unsigned int > ret( 2, 0 ); // we require 1 tmp vector in this local assembler ret[0] = 1; // the functional itself requires that much local matrices ret[1] = localFunctional_.numTmpObjectsRequired(); return ret; } template< class TestSpaceType, class EntityType, class SystemVectorType, class LocalVectorType > void assembleLocal( const TestSpaceType& testSpace, const EntityType& entity, SystemVectorType& systemVector, std::vector< std::vector< LocalVectorType > >& tmpLocalVectorsContainer ) const { // get the local basefunction set typedef typename TestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalTesBaseFunctionSetType; const LocalTesBaseFunctionSetType localTestBaseFunctionSet = testSpace.baseFunctionSet().local( entity ); // check tmp local vectors assert( tmpLocalVectorsContainer.size() > 1 ); std::vector< LocalVectorType >& tmpLocalVectors = tmpLocalVectorsContainer[0]; if( tmpLocalVectors.size() < 1 ) { tmpLocalVectors.resize( 1, LocalVectorType( testSpace.map().maxLocalSize(), RangeFieldType( 0.0 ) ) ); } // some types typedef typename TestSpaceType::GridViewType GridViewType; typedef typename GridViewType::IntersectionIterator IntersectionIteratorType; typedef typename IntersectionIteratorType::Intersection IntersectionType; typedef typename IntersectionType::EntityPointer EntityPointerType; const GridViewType& gridView = testSpace.gridView(); const IntersectionIteratorType lastIntersection = gridView.iend( entity ); // do loop over all intersections for( IntersectionIteratorType intIt = gridView.ibegin( entity ); intIt != lastIntersection; ++intIt ) { const IntersectionType& intersection = *intIt; if( !intersection.neighbor() && intersection.boundary() ) // if boundary intersection { // clear target vectors Dune::Stuff::Common::clear(tmpLocalVectors[0]); localFunctional_.applyLocal( localTestBaseFunctionSet, intersection, tmpLocalVectors[0], tmpLocalVectorsContainer[1] ); // write local vector to global addToVector( testSpace, entity, tmpLocalVectors[0], systemVector ); }// end if boundary intersection } // done loop over all intersections } // end method assembleLocal private: //! assignment operator ThisType& operator=( const ThisType& ); template< class TestSpaceType, class EntityType, class LocalVectorType, class SystemVectorType > void addToVector( const TestSpaceType& testSpace, const EntityType& entity, const LocalVectorType& localVector, SystemVectorType& systemVector ) const { for( unsigned int j = 0; j < testSpace.baseFunctionSet().local( entity ).size(); ++j ) { const unsigned int globalJ = testSpace.map().toGlobal( entity, j ); systemVector[globalJ] += localVector[j]; } } // end method addToVector const LocalFunctionalType localFunctional_; }; // end class Vector } // end namespace Codim1 } // end namespace Local } // end namespace Assembler } // namespace Discretizations } // namespace Detailed } // end namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH <commit_msg>[assembler.local.codim1.vector] added Neumann<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH #define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH #include <vector> #include <dune/common/shared_ptr.hh> #include <dune/stuff/common/vector.hh> #include <dune/stuff/grid/boundaryinfo.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace Assembler { namespace Local { namespace Codim1 { namespace Vector { template< class LocalFunctionalImp, class BoundaryInfoImp > class Neumann { public: typedef LocalFunctionalImp LocalFunctionalType; typedef BoundaryInfoImp BoundaryInfoType; typedef Neumann< LocalFunctionalType, BoundaryInfoType > ThisType; Neumann(const LocalFunctionalType& _localFunctional, const Dune::shared_ptr< const BoundaryInfoType > _boundaryInfo) : localFunctional_(_localFunctional) , boundaryInfo_(_boundaryInfo) {} const LocalFunctionalType& localFunctional() const { return localFunctional_; } const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo() const { return boundaryInfo_; } std::vector< unsigned int > numTmpObjectsRequired() const { std::vector< unsigned int > ret(2, 0); // we require 1 tmp vector in this local assembler ret[0] = 1; // the functional itself requires that much local matrices ret[1] = localFunctional_.numTmpObjectsRequired(); return ret; } // std::vector< unsigned int > numTmpObjectsRequired() const template< class TestSpaceType, class EntityType, class VectorType, class LocalVectorType > void assembleLocal(const TestSpaceType& testSpace, const EntityType& entity, VectorType& vector, std::vector< std::vector< LocalVectorType > >& tmpLocalVectorsContainer) const { // get the local basefunction set typedef typename TestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalTesBaseFunctionSetType; const LocalTesBaseFunctionSetType localTestBaseFunctionSet = testSpace.baseFunctionSet().local(entity); // check tmp local vectors typedef typename LocalFunctionalType::FunctionSpaceType::RangeFieldType RangeFieldType; assert(tmpLocalVectorsContainer.size() > 1); std::vector< LocalVectorType >& tmpLocalVectors = tmpLocalVectorsContainer[0]; if (tmpLocalVectors.size() < numTmpObjectsRequired()[0]) tmpLocalVectors.resize( numTmpObjectsRequired()[0], LocalVectorType(testSpace.map().maxLocalSize(),RangeFieldType(0))); // do loop over all intersections typedef typename TestSpaceType::GridViewType GridViewType; typedef typename GridViewType::IntersectionIterator IntersectionIteratorType; typedef typename IntersectionIteratorType::Intersection IntersectionType; typedef typename IntersectionType::EntityPointer EntityPointerType; const GridViewType& gridView = testSpace.gridView(); for (IntersectionIteratorType intersectionIt = gridView.ibegin(entity); intersectionIt != gridView.iend(entity); ++intersectionIt) { const IntersectionType& intersection = *intersectionIt; if (boundaryInfo_->neumann(intersection)) { Dune::Stuff::Common::clear(tmpLocalVectors[0]); localFunctional_.applyLocal(localTestBaseFunctionSet, intersection, tmpLocalVectors[0], tmpLocalVectorsContainer[1]); addToVector(testSpace, entity, tmpLocalVectors[0], vector); } } // do loop over all intersections } // void assembleLocal(...) private: Neumann(const ThisType&); ThisType& operator=(const ThisType&); template< class TestSpaceType, class EntityType, class LocalVectorType, class SystemVectorType > void addToVector(const TestSpaceType& testSpace, const EntityType& entity, const LocalVectorType& localVector, SystemVectorType& systemVector) const { for (unsigned int j = 0; j < testSpace.baseFunctionSet().local(entity).size(); ++j) { const unsigned int globalJ = testSpace.map().toGlobal(entity, j); systemVector[globalJ] += localVector[j]; } } // vodi addToVector(...) const LocalFunctionalType& localFunctional_; const Dune::shared_ptr< const BoundaryInfoType > boundaryInfo_; }; // class Neumann } // namespace Vector } // namespace Codim1 } // namespace Local } // namespace Assembler } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_VECTOR_HH <|endoftext|>
<commit_before>#include <cutehmi/services/Service.hpp> #include <cutehmi/services/ServiceManager.hpp> #include <cutehmi/Notification.hpp> #include <QCoreApplication> #include <QThread> namespace cutehmi { namespace services { constexpr int Service::INITIAL_STOP_TIMEOUT; constexpr int Service::INITIAL_START_TIMEOUT; constexpr int Service::INITIAL_REPAIR_TIMEOUT; constexpr const char * Service::INITIAL_NAME; Service::Service(QObject * parent): QObject(parent), m(new Members) { ServiceManager::Instance().add(this); setStatus(DefaultStatus()); } Service::~Service() { stop(); // Wait till either service stops or is interrupted. if (m->stateInterface) while (!m->stateInterface->stopped().active() && !m->stateInterface->interrupted().active()) { // Due to repair and start timeouts service may end up in broken state. Try to stop the service repeatedly. stop(); // QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents) slows down shutdown, so execute this loop aggressively. QCoreApplication::processEvents(); } if (m->serviceable) ServiceManager::Instance().leave(this); ServiceManager::Instance().remove(this); if (m->stateMachine) m->stateMachine->stop(); } int Service::stopTimeout() const { return m->stopTimeout; } void Service::setStopTimeout(int timeout) { if (m->stopTimeout != timeout) { m->stopTimeout = timeout; emit stopTimeoutChanged(); } } int Service::startTimeout() const { return m->startTimeout; } void Service::setStartTimeout(int startTimeout) { if (m->startTimeout != startTimeout) { m->startTimeout = startTimeout; emit startTimeoutChanged(); } } int Service::repairTimeout() const { return m->repairTimeout; } void Service::setRepairTimeout(int repairTimeout) { if (m->repairTimeout != repairTimeout) { m->repairTimeout = repairTimeout; emit repairTimeoutChanged(); } } QString Service::name() const { return m->name; } void Service::setName(const QString & name) { if (m->name != name) { m->name = name; emit nameChanged(); } } QString Service::status() const { return m->status; } void Service::setServiceable(QVariant serviceable) { QObject * qobjectPtr = serviceable.value<QObject *>(); Serviceable * serviceablePtr = dynamic_cast<Serviceable *>(qobjectPtr); if (qobjectPtr != nullptr && serviceablePtr == nullptr) CUTEHMI_WARNING("Object assigned as serviceable to '" << name() << "' service does not implement 'cutehmi::services::Serviceable' interface."); if (m->serviceable != serviceablePtr) { if (m->serviceable) ServiceManager::Instance().leave(this); destroyStateMachine(); if (serviceablePtr) initializeStateMachine(*serviceablePtr); m->serviceable = serviceablePtr; if (m->serviceable) ServiceManager::Instance().manage(this); else setStatus(DefaultStatus()); emit serviceableChanged(); } } QVariant Service::serviceable() const { return QVariant::fromValue(m->serviceable); } void Service::start() { emit started(); } void Service::stop() { emit stopped(); } internal::StateInterface * Service::stateInterface() { return m->stateInterface; } const internal::StateInterface * Service::stateInterface() const { return m->stateInterface; } void Service::activate() { emit activated(); } void Service::setStatus(const QString & status) { if (m->status != status) { m->status = status; emit statusChanged(); } } QString & Service::DefaultStatus() { static QString name = QObject::tr("Unmanaged"); return name; } void Service::destroyStateMachine() { if (m->stateMachine) { m->stateMachine->stop(); m->stateMachine->deleteLater(); m->stateMachine = nullptr; m->stateInterface = nullptr; } } void Service::initializeStateMachine(Serviceable & serviceable) { try { m->stateMachine = new QStateMachine(this); m->stateInterface = new internal::StateInterface(m->stateMachine); connect(m->stateInterface, & internal::StateInterface::statusChanged, this, [this]() { setStatus(m->stateInterface->status()); } ); // Variable m->lastNotifiableState is used to prevent notification spam, i.e. when service fails to leave notifiable state // through intermediate, non-notifiable state (e.g. 'broken' is a notifiable state, 'repairing' is an intermediate state; // without the condition "Service 'XYZ' broke" message would be posted after each failed repair attempt). connect(& m->stateInterface->interrupted(), & QState::entered, [this]() { if (m->lastNotifiableState != & m->stateInterface->interrupted()) Notification::Critical(tr("Stop sequence of '%1' service has been interrupted, because it took more than %2 [ms] to stop the service.").arg(name()).arg(stopTimeout())); m->lastNotifiableState = & m->stateInterface->interrupted(); }); connect(& m->stateInterface->started(), & QState::entered, [this]() { if (m->lastNotifiableState != & m->stateInterface->started()) Notification::Info(tr("Service '%1' has started.").arg(name())); m->lastNotifiableState = & m->stateInterface->started(); }); connect(& m->stateInterface->stopped(), & QState::entered, [this]() { if (m->lastNotifiableState != & m->stateInterface->stopped()) Notification::Info(tr("Service '%1' is stopped.").arg(name())); m->lastNotifiableState = & m->stateInterface->stopped(); }); connect(& m->stateInterface->broken(), & QState::entered, [this]() { if (m->lastNotifiableState != & m->stateInterface->broken()) Notification::Warning(tr("Service '%1' broke.").arg(name())); m->lastNotifiableState = & m->stateInterface->broken(); }); // Configure timeouts. connect(& m->stateInterface->stopping(), & QState::entered, [this]() { if (stopTimeout() >= 0) m->timeoutTimer.start(stopTimeout()); }); // It's safer to stop timeout, so that it won't make false shot. connect(& m->stateInterface->stopping(), & QState::exited, & m->timeoutTimer, & QTimer::stop); connect(& m->stateInterface->evacuating(), & QState::entered, [this]() { if (stopTimeout() >= 0) m->timeoutTimer.start(stopTimeout()); }); // It's safer to stop timeout, so that it won't make false shot. connect(& m->stateInterface->evacuating(), & QState::exited, & m->timeoutTimer, & QTimer::stop); connect(& m->stateInterface->starting(), & QState::entered, [this]() { if (startTimeout() >= 0) m->timeoutTimer.start(startTimeout()); }); // It's safer to stop timeout, so that it won't make false shot. connect(& m->stateInterface->starting(), & QState::exited, & m->timeoutTimer, & QTimer::stop); connect(& m->stateInterface->repairing(), & QState::entered, [this]() { if (repairTimeout() >= 0) m->timeoutTimer.start(repairTimeout()); }); // It's safer to stop timeout, so that it won't make false shot. connect(& m->stateInterface->repairing(), & QState::exited, & m->timeoutTimer, & QTimer::stop); m->stateInterface->stopped().assignProperty(m->stateInterface, "status", tr("Stopped")); m->stateInterface->interrupted().assignProperty(m->stateInterface, "status", tr("Interrupted")); m->stateInterface->starting().assignProperty(m->stateInterface, "status", tr("Starting")); m->stateInterface->started().assignProperty(m->stateInterface, "status", tr("Started")); m->stateInterface->idling().assignProperty(m->stateInterface, "status", tr("Idling")); m->stateInterface->yielding().assignProperty(m->stateInterface, "status", tr("Yielding")); m->stateInterface->active().assignProperty(m->stateInterface, "status", tr("Active")); m->stateInterface->stopping().assignProperty(m->stateInterface, "status", tr("Stopping")); m->stateInterface->broken().assignProperty(m->stateInterface, "status", tr("Broken")); m->stateInterface->repairing().assignProperty(m->stateInterface, "status", tr("Repairing")); m->stateInterface->evacuating().assignProperty(m->stateInterface, "status", tr("Evacuating")); m->stateMachine->addState(& m->stateInterface->stopped()); m->stateMachine->addState(& m->stateInterface->interrupted()); m->stateMachine->addState(& m->stateInterface->starting()); m->stateMachine->addState(& m->stateInterface->started()); m->stateMachine->addState(& m->stateInterface->stopping()); m->stateMachine->addState(& m->stateInterface->broken()); m->stateMachine->addState(& m->stateInterface->repairing()); m->stateMachine->addState(& m->stateInterface->evacuating()); m->stateMachine->setInitialState(& m->stateInterface->stopped()); m->stateInterface->stopped().addTransition(this, & Service::started, & m->stateInterface->starting()); m->stateInterface->started().addTransition(this, & Service::stopped, & m->stateInterface->stopping()); m->stateInterface->broken().addTransition(this, & Service::started, & m->stateInterface->repairing()); m->stateInterface->broken().addTransition(this, & Service::stopped, & m->stateInterface->evacuating()); m->stateInterface->stopping().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->interrupted()); m->stateInterface->starting().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->broken()); m->stateInterface->repairing().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->broken()); m->stateInterface->yielding().addTransition(this, & Service::activated, & m->stateInterface->active()); m->stateInterface->evacuating().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->interrupted()); addTransition(& m->stateInterface->starting(), & m->stateInterface->started(), serviceable.transitionToStarted()); addTransition(& m->stateInterface->repairing(), & m->stateInterface->started(), serviceable.transitionToStarted()); addTransition(& m->stateInterface->stopping(), & m->stateInterface->stopped(), serviceable.transitionToStopped()); addTransition(& m->stateInterface->starting(), & m->stateInterface->broken(), serviceable.transitionToBroken()); addTransition(& m->stateInterface->started(), & m->stateInterface->broken(), serviceable.transitionToBroken()); addTransition(& m->stateInterface->repairing(), & m->stateInterface->broken(), serviceable.transitionToBroken()); if (serviceable.transitionToIdling()) addTransition(& m->stateInterface->active(), & m->stateInterface->idling(), serviceable.transitionToIdling()); addTransition(& m->stateInterface->idling(), & m->stateInterface->yielding(), serviceable.transitionToYielding()); addTransition(& m->stateInterface->evacuating(), & m->stateInterface->stopped(), serviceable.transitionToStopped()); addStatuses(serviceable.configureBroken(& m->stateInterface->broken())); addStatuses(serviceable.configureStarted(& m->stateInterface->active(), & m->stateInterface->idling(), & m->stateInterface->yielding())); addStatuses(serviceable.configureStarting(& m->stateInterface->starting())); addStatuses(serviceable.configureStopping(& m->stateInterface->stopping())); addStatuses(serviceable.configureRepairing(& m->stateInterface->repairing())); addStatuses(serviceable.configureEvacuating(& m->stateInterface->evacuating())); m->stateMachine->start(); QCoreApplication::processEvents(); // This is required in order to truly start state machine and prevent it from ignoring incoming events. } catch (const std::exception & e) { CUTEHMI_CRITICAL("Could not initialize new state machine, because of following exception: " << e.what()); } } void Service::addTransition(QState * source, QState * target, std::unique_ptr<QAbstractTransition> transition) { if (transition) { transition->setParent(source); transition->setTargetState(target); source->addTransition(transition.release()); } else source->addTransition(target); } void Service::addStatuses(std::unique_ptr<Serviceable::ServiceStatuses> statuses) { if (statuses) for (auto stateStatus = statuses->begin(); stateStatus != statuses->end(); ++stateStatus) stateStatus.key()->assignProperty(m->stateInterface, "status", stateStatus.value()); } } } //(c)C: Copyright © 2019-2020, Michał Policht <[email protected]>, Yuri Chornoivan <[email protected]>. All rights reserved. //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. <commit_msg>Print service status in debug output.<commit_after>#include <cutehmi/services/Service.hpp> #include <cutehmi/services/ServiceManager.hpp> #include <cutehmi/Notification.hpp> #include <QCoreApplication> #include <QThread> namespace cutehmi { namespace services { constexpr int Service::INITIAL_STOP_TIMEOUT; constexpr int Service::INITIAL_START_TIMEOUT; constexpr int Service::INITIAL_REPAIR_TIMEOUT; constexpr const char * Service::INITIAL_NAME; Service::Service(QObject * parent): QObject(parent), m(new Members) { ServiceManager::Instance().add(this); setStatus(DefaultStatus()); } Service::~Service() { stop(); // Wait till either service stops or is interrupted. if (m->stateInterface) while (!m->stateInterface->stopped().active() && !m->stateInterface->interrupted().active()) { // Due to repair and start timeouts service may end up in broken state. Try to stop the service repeatedly. stop(); // QCoreApplication::processEvents(QEventLoop::WaitForMoreEvents) slows down shutdown, so execute this loop aggressively. QCoreApplication::processEvents(); } if (m->serviceable) ServiceManager::Instance().leave(this); ServiceManager::Instance().remove(this); if (m->stateMachine) m->stateMachine->stop(); } int Service::stopTimeout() const { return m->stopTimeout; } void Service::setStopTimeout(int timeout) { if (m->stopTimeout != timeout) { m->stopTimeout = timeout; emit stopTimeoutChanged(); } } int Service::startTimeout() const { return m->startTimeout; } void Service::setStartTimeout(int startTimeout) { if (m->startTimeout != startTimeout) { m->startTimeout = startTimeout; emit startTimeoutChanged(); } } int Service::repairTimeout() const { return m->repairTimeout; } void Service::setRepairTimeout(int repairTimeout) { if (m->repairTimeout != repairTimeout) { m->repairTimeout = repairTimeout; emit repairTimeoutChanged(); } } QString Service::name() const { return m->name; } void Service::setName(const QString & name) { if (m->name != name) { m->name = name; emit nameChanged(); } } QString Service::status() const { return m->status; } void Service::setServiceable(QVariant serviceable) { QObject * qobjectPtr = serviceable.value<QObject *>(); Serviceable * serviceablePtr = dynamic_cast<Serviceable *>(qobjectPtr); if (qobjectPtr != nullptr && serviceablePtr == nullptr) CUTEHMI_WARNING("Object assigned as serviceable to '" << name() << "' service does not implement 'cutehmi::services::Serviceable' interface."); if (m->serviceable != serviceablePtr) { if (m->serviceable) ServiceManager::Instance().leave(this); destroyStateMachine(); if (serviceablePtr) initializeStateMachine(*serviceablePtr); m->serviceable = serviceablePtr; if (m->serviceable) ServiceManager::Instance().manage(this); else setStatus(DefaultStatus()); emit serviceableChanged(); } } QVariant Service::serviceable() const { return QVariant::fromValue(m->serviceable); } void Service::start() { emit started(); } void Service::stop() { emit stopped(); } internal::StateInterface * Service::stateInterface() { return m->stateInterface; } const internal::StateInterface * Service::stateInterface() const { return m->stateInterface; } void Service::activate() { emit activated(); } void Service::setStatus(const QString & status) { if (m->status != status) { m->status = status; if (m->serviceable) CUTEHMI_DEBUG(name() << ": " << status); emit statusChanged(); } } QString & Service::DefaultStatus() { static QString name = QObject::tr("Unmanaged"); return name; } void Service::destroyStateMachine() { if (m->stateMachine) { m->stateMachine->stop(); m->stateMachine->deleteLater(); m->stateMachine = nullptr; m->stateInterface = nullptr; } } void Service::initializeStateMachine(Serviceable & serviceable) { try { m->stateMachine = new QStateMachine(this); m->stateInterface = new internal::StateInterface(m->stateMachine); connect(m->stateInterface, & internal::StateInterface::statusChanged, this, [this]() { setStatus(m->stateInterface->status()); } ); // Variable m->lastNotifiableState is used to prevent notification spam, i.e. when service fails to leave notifiable state // through intermediate, non-notifiable state (e.g. 'broken' is a notifiable state, 'repairing' is an intermediate state; // without the condition "Service 'XYZ' broke" message would be posted after each failed repair attempt). connect(& m->stateInterface->interrupted(), & QState::entered, [this]() { if (m->lastNotifiableState != & m->stateInterface->interrupted()) Notification::Critical(tr("Stop sequence of '%1' service has been interrupted, because it took more than %2 [ms] to stop the service.").arg(name()).arg(stopTimeout())); m->lastNotifiableState = & m->stateInterface->interrupted(); }); connect(& m->stateInterface->started(), & QState::entered, [this]() { if (m->lastNotifiableState != & m->stateInterface->started()) Notification::Info(tr("Service '%1' has started.").arg(name())); m->lastNotifiableState = & m->stateInterface->started(); }); connect(& m->stateInterface->stopped(), & QState::entered, [this]() { if (m->lastNotifiableState != & m->stateInterface->stopped()) Notification::Info(tr("Service '%1' is stopped.").arg(name())); m->lastNotifiableState = & m->stateInterface->stopped(); }); connect(& m->stateInterface->broken(), & QState::entered, [this]() { if (m->lastNotifiableState != & m->stateInterface->broken()) Notification::Warning(tr("Service '%1' broke.").arg(name())); m->lastNotifiableState = & m->stateInterface->broken(); }); // Configure timeouts. connect(& m->stateInterface->stopping(), & QState::entered, [this]() { if (stopTimeout() >= 0) m->timeoutTimer.start(stopTimeout()); }); // It's safer to stop timeout, so that it won't make false shot. connect(& m->stateInterface->stopping(), & QState::exited, & m->timeoutTimer, & QTimer::stop); connect(& m->stateInterface->evacuating(), & QState::entered, [this]() { if (stopTimeout() >= 0) m->timeoutTimer.start(stopTimeout()); }); // It's safer to stop timeout, so that it won't make false shot. connect(& m->stateInterface->evacuating(), & QState::exited, & m->timeoutTimer, & QTimer::stop); connect(& m->stateInterface->starting(), & QState::entered, [this]() { if (startTimeout() >= 0) m->timeoutTimer.start(startTimeout()); }); // It's safer to stop timeout, so that it won't make false shot. connect(& m->stateInterface->starting(), & QState::exited, & m->timeoutTimer, & QTimer::stop); connect(& m->stateInterface->repairing(), & QState::entered, [this]() { if (repairTimeout() >= 0) m->timeoutTimer.start(repairTimeout()); }); // It's safer to stop timeout, so that it won't make false shot. connect(& m->stateInterface->repairing(), & QState::exited, & m->timeoutTimer, & QTimer::stop); m->stateInterface->stopped().assignProperty(m->stateInterface, "status", tr("Stopped")); m->stateInterface->interrupted().assignProperty(m->stateInterface, "status", tr("Interrupted")); m->stateInterface->starting().assignProperty(m->stateInterface, "status", tr("Starting")); m->stateInterface->started().assignProperty(m->stateInterface, "status", tr("Started")); m->stateInterface->idling().assignProperty(m->stateInterface, "status", tr("Idling")); m->stateInterface->yielding().assignProperty(m->stateInterface, "status", tr("Yielding")); m->stateInterface->active().assignProperty(m->stateInterface, "status", tr("Active")); m->stateInterface->stopping().assignProperty(m->stateInterface, "status", tr("Stopping")); m->stateInterface->broken().assignProperty(m->stateInterface, "status", tr("Broken")); m->stateInterface->repairing().assignProperty(m->stateInterface, "status", tr("Repairing")); m->stateInterface->evacuating().assignProperty(m->stateInterface, "status", tr("Evacuating")); m->stateMachine->addState(& m->stateInterface->stopped()); m->stateMachine->addState(& m->stateInterface->interrupted()); m->stateMachine->addState(& m->stateInterface->starting()); m->stateMachine->addState(& m->stateInterface->started()); m->stateMachine->addState(& m->stateInterface->stopping()); m->stateMachine->addState(& m->stateInterface->broken()); m->stateMachine->addState(& m->stateInterface->repairing()); m->stateMachine->addState(& m->stateInterface->evacuating()); m->stateMachine->setInitialState(& m->stateInterface->stopped()); m->stateInterface->stopped().addTransition(this, & Service::started, & m->stateInterface->starting()); m->stateInterface->started().addTransition(this, & Service::stopped, & m->stateInterface->stopping()); m->stateInterface->broken().addTransition(this, & Service::started, & m->stateInterface->repairing()); m->stateInterface->broken().addTransition(this, & Service::stopped, & m->stateInterface->evacuating()); m->stateInterface->stopping().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->interrupted()); m->stateInterface->starting().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->broken()); m->stateInterface->repairing().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->broken()); m->stateInterface->yielding().addTransition(this, & Service::activated, & m->stateInterface->active()); m->stateInterface->evacuating().addTransition(& m->timeoutTimer, & QTimer::timeout, & m->stateInterface->interrupted()); addTransition(& m->stateInterface->starting(), & m->stateInterface->started(), serviceable.transitionToStarted()); addTransition(& m->stateInterface->repairing(), & m->stateInterface->started(), serviceable.transitionToStarted()); addTransition(& m->stateInterface->stopping(), & m->stateInterface->stopped(), serviceable.transitionToStopped()); addTransition(& m->stateInterface->starting(), & m->stateInterface->broken(), serviceable.transitionToBroken()); addTransition(& m->stateInterface->started(), & m->stateInterface->broken(), serviceable.transitionToBroken()); addTransition(& m->stateInterface->repairing(), & m->stateInterface->broken(), serviceable.transitionToBroken()); if (serviceable.transitionToIdling()) addTransition(& m->stateInterface->active(), & m->stateInterface->idling(), serviceable.transitionToIdling()); addTransition(& m->stateInterface->idling(), & m->stateInterface->yielding(), serviceable.transitionToYielding()); addTransition(& m->stateInterface->evacuating(), & m->stateInterface->stopped(), serviceable.transitionToStopped()); addStatuses(serviceable.configureBroken(& m->stateInterface->broken())); addStatuses(serviceable.configureStarted(& m->stateInterface->active(), & m->stateInterface->idling(), & m->stateInterface->yielding())); addStatuses(serviceable.configureStarting(& m->stateInterface->starting())); addStatuses(serviceable.configureStopping(& m->stateInterface->stopping())); addStatuses(serviceable.configureRepairing(& m->stateInterface->repairing())); addStatuses(serviceable.configureEvacuating(& m->stateInterface->evacuating())); m->stateMachine->start(); QCoreApplication::processEvents(); // This is required in order to truly start state machine and prevent it from ignoring incoming events. } catch (const std::exception & e) { CUTEHMI_CRITICAL("Could not initialize new state machine, because of following exception: " << e.what()); } } void Service::addTransition(QState * source, QState * target, std::unique_ptr<QAbstractTransition> transition) { if (transition) { transition->setParent(source); transition->setTargetState(target); source->addTransition(transition.release()); } else source->addTransition(target); } void Service::addStatuses(std::unique_ptr<Serviceable::ServiceStatuses> statuses) { if (statuses) for (auto stateStatus = statuses->begin(); stateStatus != statuses->end(); ++stateStatus) stateStatus.key()->assignProperty(m->stateInterface, "status", stateStatus.value()); } } } //(c)C: Copyright © 2019-2020, Michał Policht <[email protected]>, Yuri Chornoivan <[email protected]>. All rights reserved. //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. <|endoftext|>
<commit_before>// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #include <assert.h> #include <dlfcn.h> #include <dirent.h> #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <string> #include <set> // The name of the CoreCLR native runtime DLL. static const char * const coreClrDll = "libcoreclr.so"; // Windows types used by the ExecuteAssembly function typedef unsigned int DWORD; typedef const char16_t* LPCWSTR; typedef const char* LPCSTR; typedef int32_t HRESULT; #define SUCCEEDED(Status) ((HRESULT)(Status) >= 0) // Prototype of the ExecuteAssembly function from the libcoreclr.do typedef HRESULT (*ExecuteAssemblyFunction)( LPCSTR exePath, LPCSTR coreClrPath, LPCSTR appDomainFriendlyName, int propertyCount, LPCSTR* propertyKeys, LPCSTR* propertyValues, int argc, LPCSTR* argv, LPCSTR managedAssemblyPath, DWORD* exitCode); // Display the command line options void DisplayUsage() { fprintf( stderr, "Usage: corerun [OPTIONS] assembly [ARGUMENTS]\n" "Execute the specified managed assembly with the passed in arguments\n\n" "Options:\n" "-c, --clr-path path to the libcoreclr.so and the managed CLR assemblies\n"); } // Get absolute path from the specified path. // Return true in case of a success, false otherwise. bool GetAbsolutePath(const char* path, std::string& absolutePath) { bool result = false; char realPath[PATH_MAX]; if (realpath(path, realPath) != nullptr && realPath[0] != '\0') { absolutePath.assign(realPath); // The realpath should return canonicalized path without the trailing slash assert(absolutePath.back() != '/'); result = true; } return result; } void GetDirectory(const char* path, std::string& directory) { directory.assign(path); size_t lastSlash = directory.rfind('/'); directory.erase(lastSlash); } // Parse the command line arguments bool ParseArguments( const int argc, const char* argv[], const char** clrFilesPath, const char** managedAssemblyPath, int* managedAssemblyArgc, const char*** managedAssemblyArgv) { bool success = false; *clrFilesPath = nullptr; *managedAssemblyPath = nullptr; *managedAssemblyArgv = nullptr; *managedAssemblyArgc = 0; // The command line must contain at least the current exe name and the managed assembly path if (argc >= 2) { for (int i = 1; i < argc; i++) { // Check for an option if (argv[i][0] == '-') { // Path to the libcoreclr.so and the managed CLR assemblies if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--clr-path") == 0) { i++; if (i < argc) { *clrFilesPath = argv[i]; } else { fprintf(stderr, "Option %s: missing path\n", argv[i - 1]); break; } } else if (strcmp(argv[i], "--help") == 0) { DisplayUsage(); break; } else { fprintf(stderr, "Unknown option %s\n", argv[i]); break; } } else { // First argument that is not an option is the managed assembly to execute *managedAssemblyPath = argv[i]; int managedArgvOffset = (i + 1); *managedAssemblyArgc = argc - managedArgvOffset; if (*managedAssemblyArgc != 0) { *managedAssemblyArgv = &argv[managedArgvOffset]; } success = true; break; } } } else { DisplayUsage(); } return success; } // Add all *.dll, *.ni.dll, *.exe, and *.ni.exe files from the specified directory // to the tpaList string; void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList) { const char * const tpaExtensions[] = { ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir ".dll", ".ni.exe", ".exe", }; DIR* dir = opendir(directory); if (dir == nullptr) { return; } std::set<std::string> addedAssemblies; // Walk the directory for each extension separately so that we first get files with .ni.dll extension, // then files with .dll extension, etc. for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; int extLength = strlen(ext); struct dirent* entry; // For all entries in the directory while ((entry = readdir(dir)) != nullptr) { // We are interested in files only if (entry->d_type != DT_REG) { continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for size_t extPos = filename.length() - extLength; if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0)) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Make sure if we have an assembly with multiple extensions present, // we insert only one version of it. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end()) { addedAssemblies.insert(filenameWithoutExt); tpaList.append(directory); tpaList.append("/"); tpaList.append(filename); tpaList.append(":"); } } // Rewind the directory stream to be able to iterate over it for the next extension rewinddir(dir); } closedir(dir); } // // Execute the specified managed assembly. // // Parameters: // currentExePath - Path of the current executable // clrFilesAbsolutePath - Absolute path of a folder where the libcoreclr.so and CLR managed assemblies are stored // managedAssemblyPath - Path to the managed assembly to execute // managedAssemblyArgc - Number of arguments passed to the executed assembly // managedAssemblyArgv - Array of arguments passed to the executed assembly // // Returns: // ExitCode of the assembly // int ExecuteManagedAssembly( const char* currentExeAbsolutePath, const char* clrFilesAbsolutePath, const char* managedAssemblyAbsolutePath, int managedAssemblyArgc, const char** managedAssemblyArgv) { // Indicates failure int exitCode = -1; std::string coreClrDllPath(clrFilesAbsolutePath); coreClrDllPath.append("/"); coreClrDllPath.append(coreClrDll); if (coreClrDllPath.length() >= PATH_MAX) { fprintf(stderr, "Absolute path to libcoreclr.so too long\n"); return -1; } // Get just the path component of the managed assembly path std::string appPath; GetDirectory(managedAssemblyAbsolutePath, appPath); std::string nativeDllSearchDirs(appPath); nativeDllSearchDirs.append(":"); nativeDllSearchDirs.append(clrFilesAbsolutePath); std::string tpaList; AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList); void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW); if (coreclrLib != nullptr) { ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "ExecuteAssembly"); if (executeAssembly != nullptr) { // Allowed property names: // APPBASE // - The base path of the application from which the exe and other assemblies will be loaded // // TRUSTED_PLATFORM_ASSEMBLIES // - The list of complete paths to each of the fully trusted assemblies // // APP_PATHS // - The list of paths which will be probed by the assembly loader // // APP_NI_PATHS // - The list of additional paths that the assembly loader will probe for ngen images // // NATIVE_DLL_SEARCH_DIRECTORIES // - The list of paths that will be probed for native DLLs called by PInvoke // const char *propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES" }; const char *propertyValues[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpaList.c_str(), // APP_PATHS appPath.c_str(), // APP_NI_PATHS appPath.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES nativeDllSearchDirs.c_str() }; HRESULT st = executeAssembly( currentExeAbsolutePath, coreClrDllPath.c_str(), "unixcorerun", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, managedAssemblyArgc, managedAssemblyArgv, managedAssemblyAbsolutePath, (DWORD*)&exitCode); if (!SUCCEEDED(st)) { fprintf(stderr, "ExecuteAssembly failed - status: 0x%08x\n", st); } } else { fprintf(stderr, "Function ExecuteAssembly not found in the libcoreclr.so\n"); } if (dlclose(coreclrLib) != 0) { fprintf(stderr, "Warning - dlclose failed\n"); } } else { char* error = dlerror(); fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error); } return exitCode; } int main(const int argc, const char* argv[]) { const char* clrFilesPath; const char* managedAssemblyPath; const char** managedAssemblyArgv; int managedAssemblyArgc; if (!ParseArguments( argc, argv, &clrFilesPath, &managedAssemblyPath, &managedAssemblyArgc, &managedAssemblyArgv)) { // Invalid command line return -1; } // Check if the specified managed assembly file exists struct stat sb; if (stat(managedAssemblyPath, &sb) == -1) { perror("Managed assembly not found"); return -1; } // Verify that the managed assembly path points to a file if (!S_ISREG(sb.st_mode)) { fprintf(stderr, "The specified managed assembly is not a file\n"); return -1; } // Convert the specified path to CLR files to an absolute path since the libcoreclr.so // requires it. std::string clrFilesAbsolutePath; std::string clrFilesRelativePath; if (clrFilesPath == nullptr) { // There was no CLR files path specified, use the folder of the corerun GetDirectory(argv[0], clrFilesRelativePath); clrFilesPath = clrFilesRelativePath.c_str(); // TODO: consider using an env variable (if defined) as a fall-back. // The windows version of the corerun uses core_root env variable } if (!GetAbsolutePath(clrFilesPath, clrFilesAbsolutePath)) { perror("Failed to convert CLR files path to absolute path"); return -1; } std::string managedAssemblyAbsolutePath; if (!GetAbsolutePath(managedAssemblyPath, managedAssemblyAbsolutePath)) { perror("Failed to convert managed assembly path to absolute path"); return -1; } int exitCode = ExecuteManagedAssembly( argv[0], clrFilesAbsolutePath.c_str(), managedAssemblyAbsolutePath.c_str(), managedAssemblyArgc, managedAssemblyArgv); return exitCode; } <commit_msg>Fix std::out_of_range exception with short filenames (Linux)<commit_after>// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #include <assert.h> #include <dlfcn.h> #include <dirent.h> #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <string> #include <set> // The name of the CoreCLR native runtime DLL. static const char * const coreClrDll = "libcoreclr.so"; // Windows types used by the ExecuteAssembly function typedef unsigned int DWORD; typedef const char16_t* LPCWSTR; typedef const char* LPCSTR; typedef int32_t HRESULT; #define SUCCEEDED(Status) ((HRESULT)(Status) >= 0) // Prototype of the ExecuteAssembly function from the libcoreclr.do typedef HRESULT (*ExecuteAssemblyFunction)( LPCSTR exePath, LPCSTR coreClrPath, LPCSTR appDomainFriendlyName, int propertyCount, LPCSTR* propertyKeys, LPCSTR* propertyValues, int argc, LPCSTR* argv, LPCSTR managedAssemblyPath, DWORD* exitCode); // Display the command line options void DisplayUsage() { fprintf( stderr, "Usage: corerun [OPTIONS] assembly [ARGUMENTS]\n" "Execute the specified managed assembly with the passed in arguments\n\n" "Options:\n" "-c, --clr-path path to the libcoreclr.so and the managed CLR assemblies\n"); } // Get absolute path from the specified path. // Return true in case of a success, false otherwise. bool GetAbsolutePath(const char* path, std::string& absolutePath) { bool result = false; char realPath[PATH_MAX]; if (realpath(path, realPath) != nullptr && realPath[0] != '\0') { absolutePath.assign(realPath); // The realpath should return canonicalized path without the trailing slash assert(absolutePath.back() != '/'); result = true; } return result; } void GetDirectory(const char* path, std::string& directory) { directory.assign(path); size_t lastSlash = directory.rfind('/'); directory.erase(lastSlash); } // Parse the command line arguments bool ParseArguments( const int argc, const char* argv[], const char** clrFilesPath, const char** managedAssemblyPath, int* managedAssemblyArgc, const char*** managedAssemblyArgv) { bool success = false; *clrFilesPath = nullptr; *managedAssemblyPath = nullptr; *managedAssemblyArgv = nullptr; *managedAssemblyArgc = 0; // The command line must contain at least the current exe name and the managed assembly path if (argc >= 2) { for (int i = 1; i < argc; i++) { // Check for an option if (argv[i][0] == '-') { // Path to the libcoreclr.so and the managed CLR assemblies if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--clr-path") == 0) { i++; if (i < argc) { *clrFilesPath = argv[i]; } else { fprintf(stderr, "Option %s: missing path\n", argv[i - 1]); break; } } else if (strcmp(argv[i], "--help") == 0) { DisplayUsage(); break; } else { fprintf(stderr, "Unknown option %s\n", argv[i]); break; } } else { // First argument that is not an option is the managed assembly to execute *managedAssemblyPath = argv[i]; int managedArgvOffset = (i + 1); *managedAssemblyArgc = argc - managedArgvOffset; if (*managedAssemblyArgc != 0) { *managedAssemblyArgv = &argv[managedArgvOffset]; } success = true; break; } } } else { DisplayUsage(); } return success; } // Add all *.dll, *.ni.dll, *.exe, and *.ni.exe files from the specified directory // to the tpaList string; void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList) { const char * const tpaExtensions[] = { ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir ".dll", ".ni.exe", ".exe", }; DIR* dir = opendir(directory); if (dir == nullptr) { return; } std::set<std::string> addedAssemblies; // Walk the directory for each extension separately so that we first get files with .ni.dll extension, // then files with .dll extension, etc. for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; int extLength = strlen(ext); struct dirent* entry; // For all entries in the directory while ((entry = readdir(dir)) != nullptr) { // We are interested in files only if (entry->d_type != DT_REG) { continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for int extPos = filename.length() - extLength; if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0)) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Make sure if we have an assembly with multiple extensions present, // we insert only one version of it. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end()) { addedAssemblies.insert(filenameWithoutExt); tpaList.append(directory); tpaList.append("/"); tpaList.append(filename); tpaList.append(":"); } } // Rewind the directory stream to be able to iterate over it for the next extension rewinddir(dir); } closedir(dir); } // // Execute the specified managed assembly. // // Parameters: // currentExePath - Path of the current executable // clrFilesAbsolutePath - Absolute path of a folder where the libcoreclr.so and CLR managed assemblies are stored // managedAssemblyPath - Path to the managed assembly to execute // managedAssemblyArgc - Number of arguments passed to the executed assembly // managedAssemblyArgv - Array of arguments passed to the executed assembly // // Returns: // ExitCode of the assembly // int ExecuteManagedAssembly( const char* currentExeAbsolutePath, const char* clrFilesAbsolutePath, const char* managedAssemblyAbsolutePath, int managedAssemblyArgc, const char** managedAssemblyArgv) { // Indicates failure int exitCode = -1; std::string coreClrDllPath(clrFilesAbsolutePath); coreClrDllPath.append("/"); coreClrDllPath.append(coreClrDll); if (coreClrDllPath.length() >= PATH_MAX) { fprintf(stderr, "Absolute path to libcoreclr.so too long\n"); return -1; } // Get just the path component of the managed assembly path std::string appPath; GetDirectory(managedAssemblyAbsolutePath, appPath); std::string nativeDllSearchDirs(appPath); nativeDllSearchDirs.append(":"); nativeDllSearchDirs.append(clrFilesAbsolutePath); std::string tpaList; AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList); void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW); if (coreclrLib != nullptr) { ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "ExecuteAssembly"); if (executeAssembly != nullptr) { // Allowed property names: // APPBASE // - The base path of the application from which the exe and other assemblies will be loaded // // TRUSTED_PLATFORM_ASSEMBLIES // - The list of complete paths to each of the fully trusted assemblies // // APP_PATHS // - The list of paths which will be probed by the assembly loader // // APP_NI_PATHS // - The list of additional paths that the assembly loader will probe for ngen images // // NATIVE_DLL_SEARCH_DIRECTORIES // - The list of paths that will be probed for native DLLs called by PInvoke // const char *propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES" }; const char *propertyValues[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpaList.c_str(), // APP_PATHS appPath.c_str(), // APP_NI_PATHS appPath.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES nativeDllSearchDirs.c_str() }; HRESULT st = executeAssembly( currentExeAbsolutePath, coreClrDllPath.c_str(), "unixcorerun", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, managedAssemblyArgc, managedAssemblyArgv, managedAssemblyAbsolutePath, (DWORD*)&exitCode); if (!SUCCEEDED(st)) { fprintf(stderr, "ExecuteAssembly failed - status: 0x%08x\n", st); } } else { fprintf(stderr, "Function ExecuteAssembly not found in the libcoreclr.so\n"); } if (dlclose(coreclrLib) != 0) { fprintf(stderr, "Warning - dlclose failed\n"); } } else { char* error = dlerror(); fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error); } return exitCode; } int main(const int argc, const char* argv[]) { const char* clrFilesPath; const char* managedAssemblyPath; const char** managedAssemblyArgv; int managedAssemblyArgc; if (!ParseArguments( argc, argv, &clrFilesPath, &managedAssemblyPath, &managedAssemblyArgc, &managedAssemblyArgv)) { // Invalid command line return -1; } // Check if the specified managed assembly file exists struct stat sb; if (stat(managedAssemblyPath, &sb) == -1) { perror("Managed assembly not found"); return -1; } // Verify that the managed assembly path points to a file if (!S_ISREG(sb.st_mode)) { fprintf(stderr, "The specified managed assembly is not a file\n"); return -1; } // Convert the specified path to CLR files to an absolute path since the libcoreclr.so // requires it. std::string clrFilesAbsolutePath; std::string clrFilesRelativePath; if (clrFilesPath == nullptr) { // There was no CLR files path specified, use the folder of the corerun GetDirectory(argv[0], clrFilesRelativePath); clrFilesPath = clrFilesRelativePath.c_str(); // TODO: consider using an env variable (if defined) as a fall-back. // The windows version of the corerun uses core_root env variable } if (!GetAbsolutePath(clrFilesPath, clrFilesAbsolutePath)) { perror("Failed to convert CLR files path to absolute path"); return -1; } std::string managedAssemblyAbsolutePath; if (!GetAbsolutePath(managedAssemblyPath, managedAssemblyAbsolutePath)) { perror("Failed to convert managed assembly path to absolute path"); return -1; } int exitCode = ExecuteManagedAssembly( argv[0], clrFilesAbsolutePath.c_str(), managedAssemblyAbsolutePath.c_str(), managedAssemblyArgc, managedAssemblyArgv); return exitCode; } <|endoftext|>
<commit_before> #include "simple_paint_file.h" #include "simple_paint_util.h" #include <iup.h> #include <im_convert.h> #include <im_process.h> void SimplePaintFile::Close() { if (filename) delete[] filename; if (image) imImageDestroy(image); } void SimplePaintFile::SetFilename(const char* new_filename) { if (filename != new_filename) { if (filename) delete[] filename; filename = str_duplicate(new_filename); } } imImage* SimplePaintFile::Read(const char* new_filename) const { int error; imImage* image = imFileImageLoadBitmap(new_filename, 0, &error); if (error) show_file_error(error); return image; } bool SimplePaintFile::Write(const char* new_filename) const { const char* format = imImageGetAttribString(image, "FileFormat"); int error = imFileImageSave(new_filename, format, image); if (error) { show_file_error(error); return false; } return true; } void SimplePaintFile::SetFormat(const char* new_filename) { const char* ext = str_fileext(new_filename); const char* format = "JPEG"; if (str_compare(ext, "jpg", 0) || str_compare(ext, "jpeg", 0)) format = "JPEG"; else if (str_compare(ext, "bmp", 0)) format = "BMP"; else if (str_compare(ext, "png", 0)) format = "PNG"; else if (str_compare(ext, "tga", 0)) format = "TGA"; else if (str_compare(ext, "tif", 0) || str_compare(ext, "tiff", 0)) format = "TIFF"; imImageSetAttribString(image, "FileFormat", format); } bool SimplePaintFile::SaveCheck() { if (dirty) { switch (IupAlarm("Warning", "File not saved! Save it now?", "Yes", "No", "Cancel")) { case 1: /* save the changes and continue */ SaveFile(); break; case 2: /* ignore the changes and continue */ break; case 3: /* cancel */ return false; } } return true; } void SimplePaintFile::SaveFile() { if (Write(filename)) dirty = false; } bool SimplePaintFile::SaveAsFile(const char* new_filename) { SetFormat(new_filename); if (Write(new_filename)) { SetFilename(new_filename); dirty = false; return true; } return false; } static void image_fill_white(imImage* image) { float color[3]; color[0] = 255; color[1] = 255; color[2] = 255; imProcessRenderConstant(image, color); } bool SimplePaintFile::New(int width, int height) { imImage* new_image = imImageCreate(width, height, IM_RGB, IM_BYTE); if (!new_image) { show_file_error(IM_ERR_MEM); return false; } /* new image default contents */ image_fill_white(new_image); /* default file format */ imImageSetAttribString(new_image, "FileFormat", "JPEG"); SetImage(new_image); /* set properties */ SetFilename(0); dirty = false; return true; } void SimplePaintFile::SetImage(imImage* new_image, bool release) { /* remove previous one if any */ if (release && image) imImageDestroy(image); /* set properties (leave filename as it is) */ dirty = true; image = new_image; } void SimplePaintFile::New(imImage* new_image) { /* this tests are necessary only for open and paste */ /* we are going to support only RGB images with no alpha */ imImageRemoveAlpha(new_image); if (new_image->color_space != IM_RGB) { imImage* rgb_image = imImageCreateBased(new_image, -1, -1, IM_RGB, -1); imConvertColorSpace(new_image, rgb_image); imImageDestroy(new_image); new_image = rgb_image; } /* default file format */ const char* format = imImageGetAttribString(new_image, "FileFormat"); if (!format) imImageSetAttribString(new_image, "FileFormat", "JPEG"); SetImage(new_image); } bool SimplePaintFile::Open(const char* new_filename) { imImage* new_image = Read(new_filename); if (new_image) { New(new_image); /* set properties */ dirty = false; SetFilename(new_filename); return true; } return false; } <commit_msg><commit_after> #include "simple_paint_file.h" #include "simple_paint_util.h" #include <iup.h> #include <im_convert.h> #include <im_process.h> void SimplePaintFile::Close() { if (filename) delete[] filename; if (image) imImageDestroy(image); } void SimplePaintFile::SetFilename(const char* new_filename) { if (filename != new_filename) { if (filename) delete[] filename; filename = str_duplicate(new_filename); } } imImage* SimplePaintFile::Read(const char* new_filename) const { int error; imImage* image = imFileImageLoadBitmap(new_filename, 0, &error); if (error) show_file_error(error); return image; } bool SimplePaintFile::Write(const char* new_filename) const { const char* format = imImageGetAttribString(image, "FileFormat"); int error = imFileImageSave(new_filename, format, image); if (error) { show_file_error(error); return false; } return true; } void SimplePaintFile::SetFormat(const char* new_filename) { const char* ext = str_fileext(new_filename); const char* format = "JPEG"; if (str_compare(ext, "jpg", 0) || str_compare(ext, "jpeg", 0)) format = "JPEG"; else if (str_compare(ext, "bmp", 0)) format = "BMP"; else if (str_compare(ext, "png", 0)) format = "PNG"; else if (str_compare(ext, "tga", 0)) format = "TGA"; else if (str_compare(ext, "tif", 0) || str_compare(ext, "tiff", 0)) format = "TIFF"; imImageSetAttribString(image, "FileFormat", format); } bool SimplePaintFile::SaveCheck() { if (dirty) { switch (IupAlarm("Warning", "File not saved! Save it now?", "Yes", "No", "Cancel")) { case 1: /* save the changes and continue */ SaveFile(); break; case 2: /* ignore the changes and continue */ break; case 3: /* cancel */ return false; } } return true; } void SimplePaintFile::SaveFile() { if (Write(filename)) dirty = false; } bool SimplePaintFile::SaveAsFile(const char* new_filename) { SetFormat(new_filename); if (Write(new_filename)) { SetFilename(new_filename); dirty = false; return true; } return false; } static void image_fill_white(imImage* image) { float color[3]; color[0] = 255; color[1] = 255; color[2] = 255; imProcessRenderConstant(image, color); } bool SimplePaintFile::New(int width, int height) { imImage* new_image = imImageCreate(width, height, IM_RGB, IM_BYTE); if (!new_image) { show_file_error(IM_ERR_MEM); return false; } /* new image default contents */ image_fill_white(new_image); /* default file format */ imImageSetAttribString(new_image, "FileFormat", "JPEG"); SetImage(new_image); /* set properties */ SetFilename(0); dirty = false; return true; } void SimplePaintFile::SetImage(imImage* new_image, bool release) { /* remove previous one if any */ if (release && image) imImageDestroy(image); /* set properties (leave filename as it is) */ dirty = true; image = new_image; } void SimplePaintFile::New(imImage* new_image) { /* this tests are necessary only for open and paste */ /* we are going to support only RGB images with no alpha */ imImageRemoveAlpha(new_image); if (new_image->color_space != IM_RGB) { imImage* rgb_image = imImageCreateBased(new_image, -1, -1, IM_RGB, -1); imConvertColorSpace(new_image, rgb_image); imImageDestroy(new_image); new_image = rgb_image; } /* default file format */ const char* format = imImageGetAttribString(new_image, "FileFormat"); if (!format) imImageSetAttribString(new_image, "FileFormat", "JPEG"); SetImage(new_image); } bool SimplePaintFile::Open(const char* new_filename) { imImage* new_image = Read(new_filename); if (new_image) { New(new_image); /* set properties */ dirty = false; SetFilename(new_filename); return true; } return false; } <|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. */ /** * @author Intel, Evgueni Brevnov * @version $Revision: 1.1 $ */ #include <stdlib.h> #include <apr_thread_mutex.h> #include "open/hythread.h" #include "open/jthread.h" #include "open/gc.h" #include "jni.h" #include "jni_direct.h" #include "environment.h" #include "classloader.h" #include "compile.h" #include "nogc.h" #include "jni_utils.h" #include "vm_stats.h" #include "thread_dump.h" #include "interpreter.h" #include "finalize.h" #define LOG_DOMAIN "vm.core.shutdown" #include "cxxlog.h" #define PROCESS_EXCEPTION(messageId, message) \ { \ LECHO(messageId, message << "Internal error: "); \ \ if (jni_env->ExceptionCheck()== JNI_TRUE) \ { \ jni_env->ExceptionDescribe(); \ jni_env->ExceptionClear(); \ } \ \ return JNI_ERR; \ } \ /** * Calls java.lang.System.execShutdownSequence() method. * * @param jni_env JNI environment of the current thread */ static jint exec_shutdown_sequence(JNIEnv * jni_env) { jclass system_class; jmethodID shutdown_method; assert(hythread_is_suspend_enabled()); BEGIN_RAISE_AREA; system_class = jni_env->FindClass("java/lang/System"); if (jni_env->ExceptionCheck() == JNI_TRUE || system_class == NULL) { // This is debug message only. May appear when VM is already in shutdown stage. PROCESS_EXCEPTION(38, "{0}can't find java.lang.System class."); } shutdown_method = jni_env->GetStaticMethodID(system_class, "execShutdownSequence", "()V"); if (jni_env->ExceptionCheck() == JNI_TRUE || shutdown_method == NULL) { PROCESS_EXCEPTION(39, "{0}can't find java.lang.System.execShutdownSequence() method."); } jni_env->CallStaticVoidMethod(system_class, shutdown_method); if (jni_env->ExceptionCheck() == JNI_TRUE) { PROCESS_EXCEPTION(40, "{0}java.lang.System.execShutdownSequence() method completed with an exception."); } END_RAISE_AREA; return JNI_OK; } static void vm_shutdown_callback() { hythread_suspend_enable(); set_unwindable(false); vm_thread_t vm_thread = jthread_self_vm_thread(); assert(vm_thread); jobject java_thread = vm_thread->java_thread; assert(java_thread); IDATA UNUSED status = jthread_detach(java_thread); assert(status == TM_ERROR_NONE); hythread_exit(NULL); } static void vm_thread_cancel(vm_thread_t thread) { assert(thread); // grab hythread global lock hythread_global_lock(); IDATA UNUSED status = jthread_vm_detach(thread); assert(status == TM_ERROR_NONE); hythread_cancel((hythread_t)thread); // release hythread global lock hythread_global_unlock(); } /** * Stops running java threads by throwing an exception * up to the first native frame. * * @param[in] vm_env a global VM environment */ static void vm_shutdown_stop_java_threads(Global_Env * vm_env) { hythread_t self; hythread_t * running_threads; hythread_t native_thread; hythread_iterator_t it; VM_thread *vm_thread; self = hythread_self(); // Collect running java threads. // Set callbacks to let threads exit TRACE2("shutdown", "stopping threads, self " << self); it = hythread_iterator_create(NULL); running_threads = (hythread_t *)apr_palloc(vm_env->mem_pool, hythread_iterator_size(it) * sizeof(hythread_t)); int size = 0; while(native_thread = hythread_iterator_next(&it)) { vm_thread = jthread_get_vm_thread(native_thread); if (native_thread != self && vm_thread != NULL) { hythread_set_safepoint_callback(native_thread, vm_shutdown_callback); running_threads[size] = native_thread; ++size; } } hythread_iterator_release(&it); TRACE2("shutdown", "joining threads"); // join running threads // blocked and waiting threads won't be joined for (int i = 0; i < size; i++) { hythread_join_timed(running_threads[i], 100/size + 1, 0); } TRACE2("shutdown", "cancelling threads"); // forcedly kill remaining threads // There is a small chance that some of these threads are not in the point // safe for killing, e.g. in malloc() it = hythread_iterator_create(NULL); while(native_thread = hythread_iterator_next(&it)) { vm_thread = jthread_get_vm_thread(native_thread); // we should not cancel self and // non-java threads (i.e. vm_thread == NULL) if (native_thread != self && vm_thread != NULL) { vm_thread_cancel(vm_thread); TRACE2("shutdown", "cancelling " << native_thread); STD_FREE(vm_thread); } } hythread_iterator_release(&it); TRACE2("shutdown", "shutting down threads complete"); } /** * Waits until all non-daemon threads finish their execution, * initiates VM shutdown sequence and stops running threads if any. * * @param[in] java_vm JVM that should be destroyed * @param[in] java_thread current java thread */ jint vm_destroy(JavaVM_Internal * java_vm, jthread java_thread) { IDATA status; JNIEnv * jni_env; jobject uncaught_exception; assert(hythread_is_suspend_enabled()); jni_env = jthread_get_JNI_env(java_thread); // Wait until all non-daemon threads finish their execution. status = jthread_wait_for_all_nondaemon_threads(); if (status != TM_ERROR_NONE) { TRACE("Failed to wait for all non-daemon threads completion."); return JNI_ERR; } // Print out gathered data. #ifdef VM_STATS VM_Statistics::get_vm_stats().print(); #endif // Remember thread's uncaught exception if any. uncaught_exception = jni_env->ExceptionOccurred(); jni_env->ExceptionClear(); // Execute pending shutdown hooks & finalizers status = exec_shutdown_sequence(jni_env); if (status != JNI_OK) return (jint)status; if(get_native_finalizer_thread_flag()) wait_native_fin_threads_detached(); if(get_native_ref_enqueue_thread_flag()) wait_native_ref_thread_detached(); // Raise uncaught exception to current thread. // It will be properly processed in jthread_java_detach(). if (uncaught_exception) { exn_raise_object(uncaught_exception); } // Send VM_Death event and switch to DEAD phase. // This should be the last event sent by VM. // This event should be sent before Agent_OnUnload called. jvmti_send_vm_death_event(); // prepare thread manager to shutdown hythread_shutdowning(); // Stop all (except current) java threads // before destroying VM-wide data. vm_shutdown_stop_java_threads(java_vm->vm_env); // TODO: ups we don't stop native threads as well :-(( // We are lucky! Currently, there are no such threads. // Detach current main thread. status = jthread_detach(java_thread); // check detach status if (status != TM_ERROR_NONE) return JNI_ERR; // Shutdown signals extern void shutdown_signals(); shutdown_signals(); // Call Agent_OnUnload() for agents and unload agents. java_vm->vm_env->TI->Shutdown(java_vm); // Block thread creation. // TODO: investigate how to achieve that with ThreadManager // Starting this moment any exception occurred in java thread will cause // entire java stack unwinding to the most recent native frame. // JNI is not available as well. assert(java_vm->vm_env->vm_state == Global_Env::VM_RUNNING); java_vm->vm_env->vm_state = Global_Env::VM_SHUTDOWNING; TRACE2("shutdown", "vm_destroy complete"); return JNI_OK; } static IDATA vm_interrupt_process(void * data) { vm_thread_t * threadBuf; int i; threadBuf = (vm_thread_t *)data; i = 0; // Join all threads. while (threadBuf[i] != NULL) { hythread_join((hythread_t)threadBuf[i]); STD_FREE(threadBuf[i]); i++; } STD_FREE(threadBuf); // Return 130 to be compatible with RI. exit(130); } /** * Initiates VM shutdown sequence. */ static IDATA vm_interrupt_entry_point(void * data) { JNIEnv * jni_env; JavaVMAttachArgs args; JavaVM * java_vm; jint status; java_vm = (JavaVM *)data; args.version = JNI_VERSION_1_2; args.group = NULL; args.name = "InterruptionHandler"; status = AttachCurrentThread(java_vm, (void **)&jni_env, &args); if (status == JNI_OK) { exec_shutdown_sequence(jni_env); DetachCurrentThread(java_vm); } return status; } /** * Release allocated resourses. */ static IDATA vm_dump_process(void * data) { vm_thread_t * threadBuf; int i; threadBuf = (vm_thread_t *)data; i = 0; // Join all threads and release allocated resources. while (threadBuf[i] != NULL) { hythread_join((hythread_t)threadBuf[i]); STD_FREE(threadBuf[i]); i++; } STD_FREE(threadBuf); return TM_ERROR_NONE; } /** * Dumps all java stacks. */ static IDATA vm_dump_entry_point(void * data) { JNIEnv * jni_env; JavaVMAttachArgs args; JavaVM * java_vm; jint status; java_vm = (JavaVM *)data; args.version = JNI_VERSION_1_2; args.group = NULL; args.name = "DumpHandler"; status = AttachCurrentThread(java_vm, (void **)&jni_env, &args); if (status == JNI_OK) { // TODO: specify particular VM to notify. jvmti_notify_data_dump_request(); st_print_all(stdout); DetachCurrentThread(java_vm); } return status; } /** * Current process received an interruption signal (Ctrl+C pressed). * Shutdown all running VMs and terminate the process. */ void vm_interrupt_handler(int UNREF x) { JavaVM ** vmBuf; vm_thread_t * threadBuf; int nVMs; IDATA status; status = JNI_GetCreatedJavaVMs(NULL, 0, &nVMs); assert(nVMs <= 1); if (status != JNI_OK) return; vmBuf = (JavaVM **) STD_MALLOC(nVMs * sizeof(JavaVM *)); status = JNI_GetCreatedJavaVMs(vmBuf, nVMs, &nVMs); assert(nVMs <= 1); if (status != JNI_OK) goto cleanup; threadBuf = (vm_thread_t*) STD_MALLOC((nVMs + 1) * sizeof(vm_thread_t)); assert(threadBuf); // Create a new thread for each VM to avoid scalability and deadlock problems. for (int i = 0; i < nVMs; i++) { threadBuf[i] = jthread_allocate_thread(); status = hythread_create_ex((hythread_t)threadBuf[i], NULL, 0, 0, NULL, vm_interrupt_entry_point, (void *)vmBuf[i]); assert(status == TM_ERROR_NONE); } // spawn a new thread which will terminate the process. status = hythread_create(NULL, 0, 0, 0, vm_interrupt_process, (void *)threadBuf); assert(status == TM_ERROR_NONE); // set a NULL terminator threadBuf[nVMs] = NULL; cleanup: STD_FREE(vmBuf); } /** * Current process received an ??? signal (Ctrl+Break pressed). * Prints java stack traces for each VM running in the current process. */ void vm_dump_handler(int UNREF x) { int nVMs; vm_thread_t *threadBuf; jint status = JNI_GetCreatedJavaVMs(NULL, 0, &nVMs); assert(nVMs <= 1); if (status != JNI_OK) return; JavaVM ** vmBuf = (JavaVM **) STD_MALLOC(nVMs * sizeof(JavaVM *)); status = JNI_GetCreatedJavaVMs(vmBuf, nVMs, &nVMs); assert(nVMs <= 1); if (status != JNI_OK) { goto cleanup; } threadBuf = (vm_thread_t*)STD_MALLOC((nVMs + 1) * sizeof(vm_thread_t)); assert(threadBuf); // Create a new thread for each VM to avoid scalability and deadlock problems. IDATA UNUSED hy_status; for (int i = 0; i < nVMs; i++) { threadBuf[i] = jthread_allocate_thread(); hy_status = hythread_create_ex((hythread_t)threadBuf[i], NULL, 0, 0, NULL, vm_dump_entry_point, (void *)vmBuf[i]); assert(hy_status == TM_ERROR_NONE); } // spawn a new thread which will release resources. hy_status = hythread_create(NULL, 0, 0, 0, vm_dump_process, (void *)threadBuf); assert(hy_status == TM_ERROR_NONE); cleanup: STD_FREE(vmBuf); } <commit_msg>Applied VM side fix for HARMONY-5019 [jdktools][jpda] Agent has to ensure that all of its threads are terminated when Agent_OnUnload exits<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. */ /** * @author Intel, Evgueni Brevnov * @version $Revision: 1.1 $ */ #include <stdlib.h> #include <apr_thread_mutex.h> #include "open/hythread.h" #include "open/jthread.h" #include "open/gc.h" #include "jni.h" #include "jni_direct.h" #include "environment.h" #include "classloader.h" #include "compile.h" #include "nogc.h" #include "jni_utils.h" #include "vm_stats.h" #include "thread_dump.h" #include "interpreter.h" #include "finalize.h" #define LOG_DOMAIN "vm.core.shutdown" #include "cxxlog.h" #define PROCESS_EXCEPTION(messageId, message) \ { \ LECHO(messageId, message << "Internal error: "); \ \ if (jni_env->ExceptionCheck()== JNI_TRUE) \ { \ jni_env->ExceptionDescribe(); \ jni_env->ExceptionClear(); \ } \ \ return JNI_ERR; \ } \ /** * Calls java.lang.System.execShutdownSequence() method. * * @param jni_env JNI environment of the current thread */ static jint exec_shutdown_sequence(JNIEnv * jni_env) { jclass system_class; jmethodID shutdown_method; assert(hythread_is_suspend_enabled()); BEGIN_RAISE_AREA; system_class = jni_env->FindClass("java/lang/System"); if (jni_env->ExceptionCheck() == JNI_TRUE || system_class == NULL) { // This is debug message only. May appear when VM is already in shutdown stage. PROCESS_EXCEPTION(38, "{0}can't find java.lang.System class."); } shutdown_method = jni_env->GetStaticMethodID(system_class, "execShutdownSequence", "()V"); if (jni_env->ExceptionCheck() == JNI_TRUE || shutdown_method == NULL) { PROCESS_EXCEPTION(39, "{0}can't find java.lang.System.execShutdownSequence() method."); } jni_env->CallStaticVoidMethod(system_class, shutdown_method); if (jni_env->ExceptionCheck() == JNI_TRUE) { PROCESS_EXCEPTION(40, "{0}java.lang.System.execShutdownSequence() method completed with an exception."); } END_RAISE_AREA; return JNI_OK; } static void vm_shutdown_callback() { hythread_suspend_enable(); set_unwindable(false); vm_thread_t vm_thread = jthread_self_vm_thread(); assert(vm_thread); jobject java_thread = vm_thread->java_thread; assert(java_thread); IDATA UNUSED status = jthread_detach(java_thread); assert(status == TM_ERROR_NONE); hythread_exit(NULL); } static void vm_thread_cancel(vm_thread_t thread) { assert(thread); // grab hythread global lock hythread_global_lock(); IDATA UNUSED status = jthread_vm_detach(thread); assert(status == TM_ERROR_NONE); hythread_cancel((hythread_t)thread); // release hythread global lock hythread_global_unlock(); } /** * Stops running java threads by throwing an exception * up to the first native frame. * * @param[in] vm_env a global VM environment */ static void vm_shutdown_stop_java_threads(Global_Env * vm_env) { hythread_t self; hythread_t * running_threads; hythread_t native_thread; hythread_iterator_t it; VM_thread *vm_thread; self = hythread_self(); // Collect running java threads. // Set callbacks to let threads exit TRACE2("shutdown", "stopping threads, self " << self); it = hythread_iterator_create(NULL); running_threads = (hythread_t *)apr_palloc(vm_env->mem_pool, hythread_iterator_size(it) * sizeof(hythread_t)); int size = 0; while(native_thread = hythread_iterator_next(&it)) { vm_thread = jthread_get_vm_thread(native_thread); if (native_thread != self && vm_thread != NULL) { hythread_set_safepoint_callback(native_thread, vm_shutdown_callback); running_threads[size] = native_thread; ++size; } } hythread_iterator_release(&it); TRACE2("shutdown", "joining threads"); // join running threads // blocked and waiting threads won't be joined for (int i = 0; i < size; i++) { hythread_join_timed(running_threads[i], 100/size + 1, 0); } TRACE2("shutdown", "cancelling threads"); // forcedly kill remaining threads // There is a small chance that some of these threads are not in the point // safe for killing, e.g. in malloc() it = hythread_iterator_create(NULL); while(native_thread = hythread_iterator_next(&it)) { vm_thread = jthread_get_vm_thread(native_thread); // we should not cancel self and // non-java threads (i.e. vm_thread == NULL) if (native_thread != self && vm_thread != NULL) { vm_thread_cancel(vm_thread); TRACE2("shutdown", "cancelling " << native_thread); STD_FREE(vm_thread); } } hythread_iterator_release(&it); TRACE2("shutdown", "shutting down threads complete"); } /** * Waits until all non-daemon threads finish their execution, * initiates VM shutdown sequence and stops running threads if any. * * @param[in] java_vm JVM that should be destroyed * @param[in] java_thread current java thread */ jint vm_destroy(JavaVM_Internal * java_vm, jthread java_thread) { IDATA status; JNIEnv * jni_env; jobject uncaught_exception; assert(hythread_is_suspend_enabled()); jni_env = jthread_get_JNI_env(java_thread); // Wait until all non-daemon threads finish their execution. status = jthread_wait_for_all_nondaemon_threads(); if (status != TM_ERROR_NONE) { TRACE("Failed to wait for all non-daemon threads completion."); return JNI_ERR; } // Print out gathered data. #ifdef VM_STATS VM_Statistics::get_vm_stats().print(); #endif // Remember thread's uncaught exception if any. uncaught_exception = jni_env->ExceptionOccurred(); jni_env->ExceptionClear(); // Execute pending shutdown hooks & finalizers status = exec_shutdown_sequence(jni_env); if (status != JNI_OK) return (jint)status; if(get_native_finalizer_thread_flag()) wait_native_fin_threads_detached(); if(get_native_ref_enqueue_thread_flag()) wait_native_ref_thread_detached(); // Raise uncaught exception to current thread. // It will be properly processed in jthread_java_detach(). if (uncaught_exception) { exn_raise_object(uncaught_exception); } // Send VM_Death event and switch to DEAD phase. // This should be the last event sent by VM. // This event should be sent before Agent_OnUnload called. jvmti_send_vm_death_event(); // prepare thread manager to shutdown hythread_shutdowning(); // Call Agent_OnUnload() for agents and unload agents. // Gregory - // We cannot call this function after vm_shutdown_stop_java_threads!!! // In this case agent's thread won't be shutdown properly, and the // code of agent's thread will run in unmapped address space // of unloaded agent's library. This is bad and will almost certainly crash. java_vm->vm_env->TI->Shutdown(java_vm); // Stop all (except current) java threads // before destroying VM-wide data. vm_shutdown_stop_java_threads(java_vm->vm_env); // TODO: ups we don't stop native threads as well :-(( // We are lucky! Currently, there are no such threads. // Detach current main thread. status = jthread_detach(java_thread); // check detach status if (status != TM_ERROR_NONE) return JNI_ERR; // Shutdown signals extern void shutdown_signals(); shutdown_signals(); // Block thread creation. // TODO: investigate how to achieve that with ThreadManager // Starting this moment any exception occurred in java thread will cause // entire java stack unwinding to the most recent native frame. // JNI is not available as well. assert(java_vm->vm_env->vm_state == Global_Env::VM_RUNNING); java_vm->vm_env->vm_state = Global_Env::VM_SHUTDOWNING; TRACE2("shutdown", "vm_destroy complete"); return JNI_OK; } static IDATA vm_interrupt_process(void * data) { vm_thread_t * threadBuf; int i; threadBuf = (vm_thread_t *)data; i = 0; // Join all threads. while (threadBuf[i] != NULL) { hythread_join((hythread_t)threadBuf[i]); STD_FREE(threadBuf[i]); i++; } STD_FREE(threadBuf); // Return 130 to be compatible with RI. exit(130); } /** * Initiates VM shutdown sequence. */ static IDATA vm_interrupt_entry_point(void * data) { JNIEnv * jni_env; JavaVMAttachArgs args; JavaVM * java_vm; jint status; java_vm = (JavaVM *)data; args.version = JNI_VERSION_1_2; args.group = NULL; args.name = "InterruptionHandler"; status = AttachCurrentThread(java_vm, (void **)&jni_env, &args); if (status == JNI_OK) { exec_shutdown_sequence(jni_env); DetachCurrentThread(java_vm); } return status; } /** * Release allocated resourses. */ static IDATA vm_dump_process(void * data) { vm_thread_t * threadBuf; int i; threadBuf = (vm_thread_t *)data; i = 0; // Join all threads and release allocated resources. while (threadBuf[i] != NULL) { hythread_join((hythread_t)threadBuf[i]); STD_FREE(threadBuf[i]); i++; } STD_FREE(threadBuf); return TM_ERROR_NONE; } /** * Dumps all java stacks. */ static IDATA vm_dump_entry_point(void * data) { JNIEnv * jni_env; JavaVMAttachArgs args; JavaVM * java_vm; jint status; java_vm = (JavaVM *)data; args.version = JNI_VERSION_1_2; args.group = NULL; args.name = "DumpHandler"; status = AttachCurrentThread(java_vm, (void **)&jni_env, &args); if (status == JNI_OK) { // TODO: specify particular VM to notify. jvmti_notify_data_dump_request(); st_print_all(stdout); DetachCurrentThread(java_vm); } return status; } /** * Current process received an interruption signal (Ctrl+C pressed). * Shutdown all running VMs and terminate the process. */ void vm_interrupt_handler(int UNREF x) { JavaVM ** vmBuf; vm_thread_t * threadBuf; int nVMs; IDATA status; status = JNI_GetCreatedJavaVMs(NULL, 0, &nVMs); assert(nVMs <= 1); if (status != JNI_OK) return; vmBuf = (JavaVM **) STD_MALLOC(nVMs * sizeof(JavaVM *)); status = JNI_GetCreatedJavaVMs(vmBuf, nVMs, &nVMs); assert(nVMs <= 1); if (status != JNI_OK) goto cleanup; threadBuf = (vm_thread_t*) STD_MALLOC((nVMs + 1) * sizeof(vm_thread_t)); assert(threadBuf); // Create a new thread for each VM to avoid scalability and deadlock problems. for (int i = 0; i < nVMs; i++) { threadBuf[i] = jthread_allocate_thread(); status = hythread_create_ex((hythread_t)threadBuf[i], NULL, 0, 0, NULL, vm_interrupt_entry_point, (void *)vmBuf[i]); assert(status == TM_ERROR_NONE); } // spawn a new thread which will terminate the process. status = hythread_create(NULL, 0, 0, 0, vm_interrupt_process, (void *)threadBuf); assert(status == TM_ERROR_NONE); // set a NULL terminator threadBuf[nVMs] = NULL; cleanup: STD_FREE(vmBuf); } /** * Current process received an ??? signal (Ctrl+Break pressed). * Prints java stack traces for each VM running in the current process. */ void vm_dump_handler(int UNREF x) { int nVMs; vm_thread_t *threadBuf; jint status = JNI_GetCreatedJavaVMs(NULL, 0, &nVMs); assert(nVMs <= 1); if (status != JNI_OK) return; JavaVM ** vmBuf = (JavaVM **) STD_MALLOC(nVMs * sizeof(JavaVM *)); status = JNI_GetCreatedJavaVMs(vmBuf, nVMs, &nVMs); assert(nVMs <= 1); if (status != JNI_OK) { goto cleanup; } threadBuf = (vm_thread_t*)STD_MALLOC((nVMs + 1) * sizeof(vm_thread_t)); assert(threadBuf); // Create a new thread for each VM to avoid scalability and deadlock problems. IDATA UNUSED hy_status; for (int i = 0; i < nVMs; i++) { threadBuf[i] = jthread_allocate_thread(); hy_status = hythread_create_ex((hythread_t)threadBuf[i], NULL, 0, 0, NULL, vm_dump_entry_point, (void *)vmBuf[i]); assert(hy_status == TM_ERROR_NONE); } // spawn a new thread which will release resources. hy_status = hythread_create(NULL, 0, 0, 0, vm_dump_process, (void *)threadBuf); assert(hy_status == TM_ERROR_NONE); cleanup: STD_FREE(vmBuf); } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file PreFlightCheck.cpp */ #include "PreFlightCheck.hpp" #include <drivers/drv_hrt.h> #include <HealthFlags.h> #include <lib/parameters/param.h> #include <systemlib/mavlink_log.h> #include <uORB/Subscription.hpp> #include <uORB/topics/subsystem_info.h> using namespace time_literals; static constexpr unsigned max_mandatory_gyro_count = 1; static constexpr unsigned max_optional_gyro_count = 3; static constexpr unsigned max_mandatory_accel_count = 1; static constexpr unsigned max_optional_accel_count = 3; static constexpr unsigned max_mandatory_mag_count = 1; static constexpr unsigned max_optional_mag_count = 4; static constexpr unsigned max_mandatory_baro_count = 1; static constexpr unsigned max_optional_baro_count = 1; bool PreFlightCheck::preflightCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, vehicle_status_flags_s &status_flags, const bool checkGNSS, bool reportFailures, const bool prearm, const hrt_abstime &time_since_boot) { if (time_since_boot < 2_s) { // the airspeed driver filter doesn't deliver the actual value yet reportFailures = false; } const bool hil_enabled = (status.hil_state == vehicle_status_s::HIL_STATE_ON); bool checkSensors = !hil_enabled; const bool checkRC = (status.rc_input_mode == vehicle_status_s::RC_IN_MODE_DEFAULT); const bool checkDynamic = !hil_enabled; const bool checkPower = (status_flags.condition_power_input_valid && !status_flags.circuit_breaker_engaged_power_check); const bool checkFailureDetector = true; bool checkAirspeed = false; /* Perform airspeed check only if circuit breaker is not * engaged and it's not a rotary wing */ if (!status_flags.circuit_breaker_engaged_airspd_check && (status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING || status.is_vtol)) { checkAirspeed = true; } reportFailures = (reportFailures && status_flags.condition_system_hotplug_timeout && !status_flags.condition_calibration_enabled); bool failed = false; /* ---- MAG ---- */ if (checkSensors) { bool prime_found = false; int32_t prime_id = -1; param_get(param_find("CAL_MAG_PRIME"), &prime_id); int32_t sys_has_mag = 1; param_get(param_find("SYS_HAS_MAG"), &sys_has_mag); bool mag_fail_reported = false; /* check all sensors individually, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_mag_count; i++) { const bool required = (i < max_mandatory_mag_count) && (sys_has_mag == 1); const bool report_fail = (reportFailures && !failed && !mag_fail_reported); int32_t device_id = -1; if (magnometerCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) { if ((prime_id > 0) && (device_id == prime_id)) { prime_found = true; } } else { if (required) { failed = true; mag_fail_reported = true; } } } if (sys_has_mag == 1) { /* check if the primary device is present */ if (!prime_found) { if (reportFailures && !failed) { mavlink_log_critical(mavlink_log_pub, "Primary compass not found"); } set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_MAG, false, true, false, status); failed = true; } /* mag consistency checks (need to be performed after the individual checks) */ if (!magConsistencyCheck(mavlink_log_pub, status, (reportFailures && !failed))) { failed = true; } } } /* ---- ACCEL ---- */ if (checkSensors) { bool prime_found = false; int32_t prime_id = -1; param_get(param_find("CAL_ACC_PRIME"), &prime_id); bool accel_fail_reported = false; /* check all sensors individually, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_accel_count; i++) { const bool required = (i < max_mandatory_accel_count); const bool report_fail = (reportFailures && !failed && !accel_fail_reported); int32_t device_id = -1; if (accelerometerCheck(mavlink_log_pub, status, i, !required, checkDynamic, device_id, report_fail)) { if ((prime_id > 0) && (device_id == prime_id)) { prime_found = true; } } else { if (required) { failed = true; accel_fail_reported = true; } } } /* check if the primary device is present */ if (!prime_found) { if (reportFailures && !failed) { mavlink_log_critical(mavlink_log_pub, "Primary accelerometer not found"); } set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_ACC, false, true, false, status); failed = true; } } /* ---- GYRO ---- */ if (checkSensors) { bool prime_found = false; int32_t prime_id = -1; param_get(param_find("CAL_GYRO_PRIME"), &prime_id); bool gyro_fail_reported = false; /* check all sensors individually, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_gyro_count; i++) { const bool required = (i < max_mandatory_gyro_count); const bool report_fail = (reportFailures && !failed && !gyro_fail_reported); int32_t device_id = -1; if (gyroCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) { if ((prime_id > 0) && (device_id == prime_id)) { prime_found = true; } } else { if (required) { failed = true; gyro_fail_reported = true; } } } /* check if the primary device is present */ if (!prime_found) { if (reportFailures && !failed) { mavlink_log_critical(mavlink_log_pub, "Primary gyro not found"); } set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_GYRO, false, true, false, status); failed = true; } } /* ---- BARO ---- */ if (checkSensors) { //bool prime_found = false; int32_t prime_id = -1; param_get(param_find("CAL_BARO_PRIME"), &prime_id); int32_t sys_has_baro = 1; param_get(param_find("SYS_HAS_BARO"), &sys_has_baro); bool baro_fail_reported = false; /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_baro_count; i++) { const bool required = (i < max_mandatory_baro_count) && (sys_has_baro == 1); const bool report_fail = (reportFailures && !failed && !baro_fail_reported); int32_t device_id = -1; if (baroCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) { if ((prime_id > 0) && (device_id == prime_id)) { //prime_found = true; } } else { if (required) { failed = true; baro_fail_reported = true; } } } // TODO there is no logic in place to calibrate the primary baro yet // // check if the primary device is present // if (false) { // if (reportFailures && !failed) { // mavlink_log_critical(mavlink_log_pub, "Primary barometer not operational"); // } // set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_ABSPRESSURE, false, true, false, status); // failed = true; // } } /* ---- IMU CONSISTENCY ---- */ // To be performed after the individual sensor checks have completed if (checkSensors) { if (!imuConsistencyCheck(mavlink_log_pub, status, (reportFailures && !failed))) { failed = true; } } /* ---- AIRSPEED ---- */ if (checkAirspeed) { int32_t optional = 0; param_get(param_find("FW_ARSP_MODE"), &optional); if (!airspeedCheck(mavlink_log_pub, status, (bool)optional, reportFailures && !failed, prearm) && !(bool)optional) { failed = true; } } /* ---- RC CALIBRATION ---- */ if (checkRC) { if (rcCalibrationCheck(mavlink_log_pub, reportFailures && !failed, status.is_vtol) != OK) { if (reportFailures) { mavlink_log_critical(mavlink_log_pub, "RC calibration check failed"); } failed = true; set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_RCRECEIVER, status_flags.rc_signal_found_once, true, false, status); status_flags.rc_calibration_valid = false; } else { // The calibration is fine, but only set the overall health state to true if the signal is not currently lost status_flags.rc_calibration_valid = true; set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_RCRECEIVER, status_flags.rc_signal_found_once, true, !status.rc_signal_lost, status); } } /* ---- SYSTEM POWER ---- */ if (checkPower) { if (!powerCheck(mavlink_log_pub, status, (reportFailures && !failed), prearm)) { failed = true; } } /* ---- Navigation EKF ---- */ // only check EKF2 data if EKF2 is selected as the estimator and GNSS checking is enabled int32_t estimator_type = -1; if (status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING && !status.is_vtol) { param_get(param_find("SYS_MC_EST_GROUP"), &estimator_type); } else { // EKF2 is currently the only supported option for FW & VTOL estimator_type = 2; } if (estimator_type == 2) { // don't report ekf failures for the first 10 seconds to allow time for the filter to start bool report_ekf_fail = (time_since_boot > 10_s); if (!ekf2Check(mavlink_log_pub, status, false, reportFailures && report_ekf_fail && !failed, checkGNSS)) { failed = true; } } /* ---- Failure Detector ---- */ if (checkFailureDetector) { if (!failureDetectorCheck(mavlink_log_pub, status, (reportFailures && !failed), prearm)) { failed = true; } } /* Report status */ return !failed; } bool PreFlightCheck::check_calibration(const char *param_template, const int32_t device_id) { bool calibration_found = false; char s[20]; int instance = 0; /* old style transition: check param values */ while (!calibration_found) { sprintf(s, param_template, instance); const param_t parm = param_find_no_notification(s); /* if the calibration param is not present, abort */ if (parm == PARAM_INVALID) { break; } /* if param get succeeds */ int32_t calibration_devid = -1; if (param_get(parm, &calibration_devid) == PX4_OK) { /* if the devid matches, exit early */ if (device_id == calibration_devid) { calibration_found = true; break; } } instance++; } return calibration_found; } <commit_msg>commander: skip all mag checks if SYS_HAS_MAG is 0<commit_after>/**************************************************************************** * * Copyright (c) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file PreFlightCheck.cpp */ #include "PreFlightCheck.hpp" #include <drivers/drv_hrt.h> #include <HealthFlags.h> #include <lib/parameters/param.h> #include <systemlib/mavlink_log.h> #include <uORB/Subscription.hpp> #include <uORB/topics/subsystem_info.h> using namespace time_literals; static constexpr unsigned max_mandatory_gyro_count = 1; static constexpr unsigned max_optional_gyro_count = 3; static constexpr unsigned max_mandatory_accel_count = 1; static constexpr unsigned max_optional_accel_count = 3; static constexpr unsigned max_mandatory_mag_count = 1; static constexpr unsigned max_optional_mag_count = 4; static constexpr unsigned max_mandatory_baro_count = 1; static constexpr unsigned max_optional_baro_count = 1; bool PreFlightCheck::preflightCheck(orb_advert_t *mavlink_log_pub, vehicle_status_s &status, vehicle_status_flags_s &status_flags, const bool checkGNSS, bool reportFailures, const bool prearm, const hrt_abstime &time_since_boot) { if (time_since_boot < 2_s) { // the airspeed driver filter doesn't deliver the actual value yet reportFailures = false; } const bool hil_enabled = (status.hil_state == vehicle_status_s::HIL_STATE_ON); bool checkSensors = !hil_enabled; const bool checkRC = (status.rc_input_mode == vehicle_status_s::RC_IN_MODE_DEFAULT); const bool checkDynamic = !hil_enabled; const bool checkPower = (status_flags.condition_power_input_valid && !status_flags.circuit_breaker_engaged_power_check); const bool checkFailureDetector = true; bool checkAirspeed = false; /* Perform airspeed check only if circuit breaker is not * engaged and it's not a rotary wing */ if (!status_flags.circuit_breaker_engaged_airspd_check && (status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_FIXED_WING || status.is_vtol)) { checkAirspeed = true; } reportFailures = (reportFailures && status_flags.condition_system_hotplug_timeout && !status_flags.condition_calibration_enabled); bool failed = false; /* ---- MAG ---- */ if (checkSensors) { int32_t sys_has_mag = 1; param_get(param_find("SYS_HAS_MAG"), &sys_has_mag); if (sys_has_mag == 1) { bool prime_found = false; int32_t prime_id = -1; param_get(param_find("CAL_MAG_PRIME"), &prime_id); bool mag_fail_reported = false; /* check all sensors individually, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_mag_count; i++) { const bool required = (i < max_mandatory_mag_count) && (sys_has_mag == 1); const bool report_fail = (reportFailures && !failed && !mag_fail_reported); int32_t device_id = -1; if (magnometerCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) { if ((prime_id > 0) && (device_id == prime_id)) { prime_found = true; } } else { if (required) { failed = true; mag_fail_reported = true; } } } /* check if the primary device is present */ if (!prime_found) { if (reportFailures && !failed) { mavlink_log_critical(mavlink_log_pub, "Primary compass not found"); } set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_MAG, false, true, false, status); failed = true; } /* mag consistency checks (need to be performed after the individual checks) */ if (!magConsistencyCheck(mavlink_log_pub, status, (reportFailures && !failed))) { failed = true; } } } /* ---- ACCEL ---- */ if (checkSensors) { bool prime_found = false; int32_t prime_id = -1; param_get(param_find("CAL_ACC_PRIME"), &prime_id); bool accel_fail_reported = false; /* check all sensors individually, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_accel_count; i++) { const bool required = (i < max_mandatory_accel_count); const bool report_fail = (reportFailures && !failed && !accel_fail_reported); int32_t device_id = -1; if (accelerometerCheck(mavlink_log_pub, status, i, !required, checkDynamic, device_id, report_fail)) { if ((prime_id > 0) && (device_id == prime_id)) { prime_found = true; } } else { if (required) { failed = true; accel_fail_reported = true; } } } /* check if the primary device is present */ if (!prime_found) { if (reportFailures && !failed) { mavlink_log_critical(mavlink_log_pub, "Primary accelerometer not found"); } set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_ACC, false, true, false, status); failed = true; } } /* ---- GYRO ---- */ if (checkSensors) { bool prime_found = false; int32_t prime_id = -1; param_get(param_find("CAL_GYRO_PRIME"), &prime_id); bool gyro_fail_reported = false; /* check all sensors individually, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_gyro_count; i++) { const bool required = (i < max_mandatory_gyro_count); const bool report_fail = (reportFailures && !failed && !gyro_fail_reported); int32_t device_id = -1; if (gyroCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) { if ((prime_id > 0) && (device_id == prime_id)) { prime_found = true; } } else { if (required) { failed = true; gyro_fail_reported = true; } } } /* check if the primary device is present */ if (!prime_found) { if (reportFailures && !failed) { mavlink_log_critical(mavlink_log_pub, "Primary gyro not found"); } set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_GYRO, false, true, false, status); failed = true; } } /* ---- BARO ---- */ if (checkSensors) { //bool prime_found = false; int32_t prime_id = -1; param_get(param_find("CAL_BARO_PRIME"), &prime_id); int32_t sys_has_baro = 1; param_get(param_find("SYS_HAS_BARO"), &sys_has_baro); bool baro_fail_reported = false; /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_baro_count; i++) { const bool required = (i < max_mandatory_baro_count) && (sys_has_baro == 1); const bool report_fail = (reportFailures && !failed && !baro_fail_reported); int32_t device_id = -1; if (baroCheck(mavlink_log_pub, status, i, !required, device_id, report_fail)) { if ((prime_id > 0) && (device_id == prime_id)) { //prime_found = true; } } else { if (required) { failed = true; baro_fail_reported = true; } } } // TODO there is no logic in place to calibrate the primary baro yet // // check if the primary device is present // if (false) { // if (reportFailures && !failed) { // mavlink_log_critical(mavlink_log_pub, "Primary barometer not operational"); // } // set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_ABSPRESSURE, false, true, false, status); // failed = true; // } } /* ---- IMU CONSISTENCY ---- */ // To be performed after the individual sensor checks have completed if (checkSensors) { if (!imuConsistencyCheck(mavlink_log_pub, status, (reportFailures && !failed))) { failed = true; } } /* ---- AIRSPEED ---- */ if (checkAirspeed) { int32_t optional = 0; param_get(param_find("FW_ARSP_MODE"), &optional); if (!airspeedCheck(mavlink_log_pub, status, (bool)optional, reportFailures && !failed, prearm) && !(bool)optional) { failed = true; } } /* ---- RC CALIBRATION ---- */ if (checkRC) { if (rcCalibrationCheck(mavlink_log_pub, reportFailures && !failed, status.is_vtol) != OK) { if (reportFailures) { mavlink_log_critical(mavlink_log_pub, "RC calibration check failed"); } failed = true; set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_RCRECEIVER, status_flags.rc_signal_found_once, true, false, status); status_flags.rc_calibration_valid = false; } else { // The calibration is fine, but only set the overall health state to true if the signal is not currently lost status_flags.rc_calibration_valid = true; set_health_flags(subsystem_info_s::SUBSYSTEM_TYPE_RCRECEIVER, status_flags.rc_signal_found_once, true, !status.rc_signal_lost, status); } } /* ---- SYSTEM POWER ---- */ if (checkPower) { if (!powerCheck(mavlink_log_pub, status, (reportFailures && !failed), prearm)) { failed = true; } } /* ---- Navigation EKF ---- */ // only check EKF2 data if EKF2 is selected as the estimator and GNSS checking is enabled int32_t estimator_type = -1; if (status.vehicle_type == vehicle_status_s::VEHICLE_TYPE_ROTARY_WING && !status.is_vtol) { param_get(param_find("SYS_MC_EST_GROUP"), &estimator_type); } else { // EKF2 is currently the only supported option for FW & VTOL estimator_type = 2; } if (estimator_type == 2) { // don't report ekf failures for the first 10 seconds to allow time for the filter to start bool report_ekf_fail = (time_since_boot > 10_s); if (!ekf2Check(mavlink_log_pub, status, false, reportFailures && report_ekf_fail && !failed, checkGNSS)) { failed = true; } } /* ---- Failure Detector ---- */ if (checkFailureDetector) { if (!failureDetectorCheck(mavlink_log_pub, status, (reportFailures && !failed), prearm)) { failed = true; } } /* Report status */ return !failed; } bool PreFlightCheck::check_calibration(const char *param_template, const int32_t device_id) { bool calibration_found = false; char s[20]; int instance = 0; /* old style transition: check param values */ while (!calibration_found) { sprintf(s, param_template, instance); const param_t parm = param_find_no_notification(s); /* if the calibration param is not present, abort */ if (parm == PARAM_INVALID) { break; } /* if param get succeeds */ int32_t calibration_devid = -1; if (param_get(parm, &calibration_devid) == PX4_OK) { /* if the devid matches, exit early */ if (device_id == calibration_devid) { calibration_found = true; break; } } instance++; } return calibration_found; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rootactiontriggercontainer.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:14:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <classes/rootactiontriggercontainer.hxx> #include <classes/actiontriggercontainer.hxx> #include <classes/actiontriggerpropertyset.hxx> #include <classes/actiontriggerseparatorpropertyset.hxx> #include <helper/actiontriggerhelper.hxx> #include <threadhelp/resetableguard.hxx> #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif using namespace rtl; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::beans; namespace framework { static Sequence< sal_Int8 > impl_getStaticIdentifier() { static sal_uInt8 pGUID[16] = { 0x17, 0x0F, 0xA2, 0xC9, 0xCA, 0x50, 0x4A, 0xD3, 0xA6, 0x3B, 0x39, 0x99, 0xC5, 0x96, 0x43, 0x27 }; static ::com::sun::star::uno::Sequence< sal_Int8 > seqID((sal_Int8*)pGUID,16) ; return seqID ; } RootActionTriggerContainer::RootActionTriggerContainer( const Menu* pMenu, const Reference< XMultiServiceFactory >& rServiceManager ) : PropertySetContainer( rServiceManager ) , m_pMenu( pMenu ) , m_bContainerCreated( sal_False ) , m_bContainerChanged( sal_False ) , m_bInContainerCreation( sal_False ) { } RootActionTriggerContainer::~RootActionTriggerContainer() { } Sequence< sal_Int8 > RootActionTriggerContainer::GetUnoTunnelId() const { return impl_getStaticIdentifier(); } const Menu* RootActionTriggerContainer::GetMenu() { if ( !m_bContainerChanged ) return m_pMenu; else { ResetableGuard aGuard( m_aLock ); Menu* pNewMenu = new PopupMenu; ActionTriggerHelper::CreateMenuFromActionTriggerContainer( pNewMenu, this ); m_pMenu = pNewMenu; m_bContainerChanged = sal_False; return m_pMenu; } } // XInterface Any SAL_CALL RootActionTriggerContainer::queryInterface( const Type& aType ) throw ( RuntimeException ) { Any a = ::cppu::queryInterface( aType , SAL_STATIC_CAST( XMultiServiceFactory* , this ), SAL_STATIC_CAST( XServiceInfo* , this ), SAL_STATIC_CAST( XUnoTunnel* , this ), SAL_STATIC_CAST( XTypeProvider* , this )); if( a.hasValue() ) { return a; } return PropertySetContainer::queryInterface( aType ); } void SAL_CALL RootActionTriggerContainer::acquire() throw () { PropertySetContainer::acquire(); } void SAL_CALL RootActionTriggerContainer::release() throw () { PropertySetContainer::release(); } // XMultiServiceFactory Reference< XInterface > SAL_CALL RootActionTriggerContainer::createInstance( const ::rtl::OUString& aServiceSpecifier ) throw ( Exception, RuntimeException ) { if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGER )) return (OWeakObject *)( new ActionTriggerPropertySet( m_xServiceManager )); else if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGERCONTAINER )) return (OWeakObject *)( new ActionTriggerContainer( m_xServiceManager )); else if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGERSEPARATOR )) return (OWeakObject *)( new ActionTriggerSeparatorPropertySet( m_xServiceManager )); else throw com::sun::star::uno::RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM( "Unknown service specifier!" )), (OWeakObject *)this ); } Reference< XInterface > SAL_CALL RootActionTriggerContainer::createInstanceWithArguments( const ::rtl::OUString& ServiceSpecifier, const Sequence< Any >& Arguments ) throw ( Exception, RuntimeException ) { return createInstance( ServiceSpecifier ); } Sequence< ::rtl::OUString > SAL_CALL RootActionTriggerContainer::getAvailableServiceNames() throw ( RuntimeException ) { Sequence< ::rtl::OUString > aSeq( 3 ); aSeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGER )); aSeq[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERCONTAINER )); aSeq[2] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERSEPARATOR )); return aSeq; } // XIndexContainer void SAL_CALL RootActionTriggerContainer::insertByIndex( sal_Int32 Index, const Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) FillContainer(); if ( !m_bInContainerCreation ) m_bContainerChanged = sal_True; PropertySetContainer::insertByIndex( Index, Element ); } void SAL_CALL RootActionTriggerContainer::removeByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) FillContainer(); if ( !m_bInContainerCreation ) m_bContainerChanged = sal_True; PropertySetContainer::removeByIndex( Index ); } // XIndexReplace void SAL_CALL RootActionTriggerContainer::replaceByIndex( sal_Int32 Index, const Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) FillContainer(); if ( !m_bInContainerCreation ) m_bContainerChanged = sal_True; PropertySetContainer::replaceByIndex( Index, Element ); } // XIndexAccess sal_Int32 SAL_CALL RootActionTriggerContainer::getCount() throw ( RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) { if ( m_pMenu ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); return m_pMenu->GetItemCount(); } else return 0; } else { return PropertySetContainer::getCount(); } } Any SAL_CALL RootActionTriggerContainer::getByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) FillContainer(); return PropertySetContainer::getByIndex( Index ); } // XElementAccess Type SAL_CALL RootActionTriggerContainer::getElementType() throw (::com::sun::star::uno::RuntimeException) { return ::getCppuType(( Reference< XPropertySet >*)0); } sal_Bool SAL_CALL RootActionTriggerContainer::hasElements() throw (::com::sun::star::uno::RuntimeException) { if ( m_pMenu ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); return ( m_pMenu->GetItemCount() > 0 ); } return sal_False; } // XServiceInfo ::rtl::OUString SAL_CALL RootActionTriggerContainer::getImplementationName() throw ( RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATIONNAME_ROOTACTIONTRIGGERCONTAINER )); } sal_Bool SAL_CALL RootActionTriggerContainer::supportsService( const ::rtl::OUString& ServiceName ) throw ( RuntimeException ) { if ( ServiceName.equalsAscii( SERVICENAME_ACTIONTRIGGERCONTAINER )) return sal_True; return sal_False; } Sequence< ::rtl::OUString > SAL_CALL RootActionTriggerContainer::getSupportedServiceNames() throw ( RuntimeException ) { Sequence< ::rtl::OUString > seqServiceNames( 1 ); seqServiceNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERCONTAINER )); return seqServiceNames; } // XUnoTunnel sal_Int64 SAL_CALL RootActionTriggerContainer::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw ( RuntimeException ) { if ( aIdentifier == impl_getStaticIdentifier() ) return (sal_Int64)this; else return 0; } // XTypeProvider Sequence< Type > SAL_CALL RootActionTriggerContainer::getTypes() throw ( RuntimeException ) { // Optimize this method ! // We initialize a static variable only one time. And we don't must use a mutex at every call! // For the first call; pTypeCollection is NULL - for the second call pTypeCollection is different from NULL! static ::cppu::OTypeCollection* pTypeCollection = NULL ; if ( pTypeCollection == NULL ) { // Ready for multithreading; get global mutex for first call of this method only! see before osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ; // Control these pointer again ... it can be, that another instance will be faster then these! if ( pTypeCollection == NULL ) { // Create a static typecollection ... static ::cppu::OTypeCollection aTypeCollection( ::getCppuType(( const Reference< XMultiServiceFactory >*)NULL ) , ::getCppuType(( const Reference< XIndexContainer >*)NULL ) , ::getCppuType(( const Reference< XIndexAccess >*)NULL ) , ::getCppuType(( const Reference< XIndexReplace >*)NULL ) , ::getCppuType(( const Reference< XServiceInfo >*)NULL ) , ::getCppuType(( const Reference< XTypeProvider >*)NULL ) , ::getCppuType(( const Reference< XUnoTunnel >*)NULL ) ) ; // ... and set his address to static pointer! pTypeCollection = &aTypeCollection ; } } return pTypeCollection->getTypes() ; } Sequence< sal_Int8 > SAL_CALL RootActionTriggerContainer::getImplementationId() throw ( RuntimeException ) { // Create one Id for all instances of this class. // Use ethernet address to do this! (sal_True) // Optimize this method // We initialize a static variable only one time. And we don't must use a mutex at every call! // For the first call; pID is NULL - for the second call pID is different from NULL! static ::cppu::OImplementationId* pID = NULL ; if ( pID == NULL ) { // Ready for multithreading; get global mutex for first call of this method only! see before osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ; // Control these pointer again ... it can be, that another instance will be faster then these! if ( pID == NULL ) { // Create a new static ID ... static ::cppu::OImplementationId aID( sal_False ) ; // ... and set his address to static pointer! pID = &aID ; } } return pID->getImplementationId() ; } // private implementation helper void RootActionTriggerContainer::FillContainer() { m_bContainerCreated = sal_True; m_bInContainerCreation = sal_True; Reference<XIndexContainer> xXIndexContainer( (OWeakObject *)this, UNO_QUERY ); ActionTriggerHelper::FillActionTriggerContainerFromMenu( xXIndexContainer, m_pMenu ); m_bInContainerCreation = sal_False; } } <commit_msg>INTEGRATION: CWS warnings01 (1.5.32); FILE MERGED 2005/11/16 13:10:33 pl 1.5.32.2: #i55991# removed warnings 2005/10/28 14:48:31 cd 1.5.32.1: #i55991# Warning free code changes for gcc<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rootactiontriggercontainer.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:14:51 $ * * 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 * ************************************************************************/ #include <classes/rootactiontriggercontainer.hxx> #include <classes/actiontriggercontainer.hxx> #include <classes/actiontriggerpropertyset.hxx> #include <classes/actiontriggerseparatorpropertyset.hxx> #include <helper/actiontriggerhelper.hxx> #include <threadhelp/resetableguard.hxx> #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif using namespace rtl; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::beans; namespace framework { static Sequence< sal_Int8 > impl_getStaticIdentifier() { static sal_uInt8 pGUID[16] = { 0x17, 0x0F, 0xA2, 0xC9, 0xCA, 0x50, 0x4A, 0xD3, 0xA6, 0x3B, 0x39, 0x99, 0xC5, 0x96, 0x43, 0x27 }; static ::com::sun::star::uno::Sequence< sal_Int8 > seqID((sal_Int8*)pGUID,16) ; return seqID ; } RootActionTriggerContainer::RootActionTriggerContainer( const Menu* pMenu, const Reference< XMultiServiceFactory >& rServiceManager ) : PropertySetContainer( rServiceManager ) , m_bContainerCreated( sal_False ) , m_bContainerChanged( sal_False ) , m_bInContainerCreation( sal_False ) , m_pMenu( pMenu ) { } RootActionTriggerContainer::~RootActionTriggerContainer() { } Sequence< sal_Int8 > RootActionTriggerContainer::GetUnoTunnelId() const { return impl_getStaticIdentifier(); } const Menu* RootActionTriggerContainer::GetMenu() { if ( !m_bContainerChanged ) return m_pMenu; else { ResetableGuard aGuard( m_aLock ); Menu* pNewMenu = new PopupMenu; ActionTriggerHelper::CreateMenuFromActionTriggerContainer( pNewMenu, this ); m_pMenu = pNewMenu; m_bContainerChanged = sal_False; return m_pMenu; } } // XInterface Any SAL_CALL RootActionTriggerContainer::queryInterface( const Type& aType ) throw ( RuntimeException ) { Any a = ::cppu::queryInterface( aType , SAL_STATIC_CAST( XMultiServiceFactory* , this ), SAL_STATIC_CAST( XServiceInfo* , this ), SAL_STATIC_CAST( XUnoTunnel* , this ), SAL_STATIC_CAST( XTypeProvider* , this )); if( a.hasValue() ) { return a; } return PropertySetContainer::queryInterface( aType ); } void SAL_CALL RootActionTriggerContainer::acquire() throw () { PropertySetContainer::acquire(); } void SAL_CALL RootActionTriggerContainer::release() throw () { PropertySetContainer::release(); } // XMultiServiceFactory Reference< XInterface > SAL_CALL RootActionTriggerContainer::createInstance( const ::rtl::OUString& aServiceSpecifier ) throw ( Exception, RuntimeException ) { if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGER )) return (OWeakObject *)( new ActionTriggerPropertySet( m_xServiceManager )); else if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGERCONTAINER )) return (OWeakObject *)( new ActionTriggerContainer( m_xServiceManager )); else if ( aServiceSpecifier.equalsAscii( SERVICENAME_ACTIONTRIGGERSEPARATOR )) return (OWeakObject *)( new ActionTriggerSeparatorPropertySet( m_xServiceManager )); else throw com::sun::star::uno::RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM( "Unknown service specifier!" )), (OWeakObject *)this ); } Reference< XInterface > SAL_CALL RootActionTriggerContainer::createInstanceWithArguments( const ::rtl::OUString& ServiceSpecifier, const Sequence< Any >& /*Arguments*/ ) throw ( Exception, RuntimeException ) { return createInstance( ServiceSpecifier ); } Sequence< ::rtl::OUString > SAL_CALL RootActionTriggerContainer::getAvailableServiceNames() throw ( RuntimeException ) { Sequence< ::rtl::OUString > aSeq( 3 ); aSeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGER )); aSeq[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERCONTAINER )); aSeq[2] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERSEPARATOR )); return aSeq; } // XIndexContainer void SAL_CALL RootActionTriggerContainer::insertByIndex( sal_Int32 Index, const Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) FillContainer(); if ( !m_bInContainerCreation ) m_bContainerChanged = sal_True; PropertySetContainer::insertByIndex( Index, Element ); } void SAL_CALL RootActionTriggerContainer::removeByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) FillContainer(); if ( !m_bInContainerCreation ) m_bContainerChanged = sal_True; PropertySetContainer::removeByIndex( Index ); } // XIndexReplace void SAL_CALL RootActionTriggerContainer::replaceByIndex( sal_Int32 Index, const Any& Element ) throw ( IllegalArgumentException, IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) FillContainer(); if ( !m_bInContainerCreation ) m_bContainerChanged = sal_True; PropertySetContainer::replaceByIndex( Index, Element ); } // XIndexAccess sal_Int32 SAL_CALL RootActionTriggerContainer::getCount() throw ( RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) { if ( m_pMenu ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); return m_pMenu->GetItemCount(); } else return 0; } else { return PropertySetContainer::getCount(); } } Any SAL_CALL RootActionTriggerContainer::getByIndex( sal_Int32 Index ) throw ( IndexOutOfBoundsException, WrappedTargetException, RuntimeException ) { ResetableGuard aGuard( m_aLock ); if ( !m_bContainerCreated ) FillContainer(); return PropertySetContainer::getByIndex( Index ); } // XElementAccess Type SAL_CALL RootActionTriggerContainer::getElementType() throw (::com::sun::star::uno::RuntimeException) { return ::getCppuType(( Reference< XPropertySet >*)0); } sal_Bool SAL_CALL RootActionTriggerContainer::hasElements() throw (::com::sun::star::uno::RuntimeException) { if ( m_pMenu ) { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); return ( m_pMenu->GetItemCount() > 0 ); } return sal_False; } // XServiceInfo ::rtl::OUString SAL_CALL RootActionTriggerContainer::getImplementationName() throw ( RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATIONNAME_ROOTACTIONTRIGGERCONTAINER )); } sal_Bool SAL_CALL RootActionTriggerContainer::supportsService( const ::rtl::OUString& ServiceName ) throw ( RuntimeException ) { if ( ServiceName.equalsAscii( SERVICENAME_ACTIONTRIGGERCONTAINER )) return sal_True; return sal_False; } Sequence< ::rtl::OUString > SAL_CALL RootActionTriggerContainer::getSupportedServiceNames() throw ( RuntimeException ) { Sequence< ::rtl::OUString > seqServiceNames( 1 ); seqServiceNames[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICENAME_ACTIONTRIGGERCONTAINER )); return seqServiceNames; } // XUnoTunnel sal_Int64 SAL_CALL RootActionTriggerContainer::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw ( RuntimeException ) { if ( aIdentifier == impl_getStaticIdentifier() ) return reinterpret_cast< sal_Int64 >( this ); else return 0; } // XTypeProvider Sequence< Type > SAL_CALL RootActionTriggerContainer::getTypes() throw ( RuntimeException ) { // Optimize this method ! // We initialize a static variable only one time. And we don't must use a mutex at every call! // For the first call; pTypeCollection is NULL - for the second call pTypeCollection is different from NULL! static ::cppu::OTypeCollection* pTypeCollection = NULL ; if ( pTypeCollection == NULL ) { // Ready for multithreading; get global mutex for first call of this method only! see before osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ; // Control these pointer again ... it can be, that another instance will be faster then these! if ( pTypeCollection == NULL ) { // Create a static typecollection ... static ::cppu::OTypeCollection aTypeCollection( ::getCppuType(( const Reference< XMultiServiceFactory >*)NULL ) , ::getCppuType(( const Reference< XIndexContainer >*)NULL ) , ::getCppuType(( const Reference< XIndexAccess >*)NULL ) , ::getCppuType(( const Reference< XIndexReplace >*)NULL ) , ::getCppuType(( const Reference< XServiceInfo >*)NULL ) , ::getCppuType(( const Reference< XTypeProvider >*)NULL ) , ::getCppuType(( const Reference< XUnoTunnel >*)NULL ) ) ; // ... and set his address to static pointer! pTypeCollection = &aTypeCollection ; } } return pTypeCollection->getTypes() ; } Sequence< sal_Int8 > SAL_CALL RootActionTriggerContainer::getImplementationId() throw ( RuntimeException ) { // Create one Id for all instances of this class. // Use ethernet address to do this! (sal_True) // Optimize this method // We initialize a static variable only one time. And we don't must use a mutex at every call! // For the first call; pID is NULL - for the second call pID is different from NULL! static ::cppu::OImplementationId* pID = NULL ; if ( pID == NULL ) { // Ready for multithreading; get global mutex for first call of this method only! see before osl::MutexGuard aGuard( osl::Mutex::getGlobalMutex() ) ; // Control these pointer again ... it can be, that another instance will be faster then these! if ( pID == NULL ) { // Create a new static ID ... static ::cppu::OImplementationId aID( sal_False ) ; // ... and set his address to static pointer! pID = &aID ; } } return pID->getImplementationId() ; } // private implementation helper void RootActionTriggerContainer::FillContainer() { m_bContainerCreated = sal_True; m_bInContainerCreation = sal_True; Reference<XIndexContainer> xXIndexContainer( (OWeakObject *)this, UNO_QUERY ); ActionTriggerHelper::FillActionTriggerContainerFromMenu( xXIndexContainer, m_pMenu ); m_bInContainerCreation = sal_False; } } <|endoftext|>
<commit_before>// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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. // Author: [email protected] (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/compiler/cpp/cpp_service.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> namespace google { namespace protobuf { namespace compiler { namespace cpp { ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor, const string& dllexport_decl) : descriptor_(descriptor) { vars_["classname"] = descriptor_->name(); vars_["full_name"] = descriptor_->full_name(); if (dllexport_decl.empty()) { vars_["dllexport"] = ""; } else { vars_["dllexport"] = dllexport_decl + " "; } } ServiceGenerator::~ServiceGenerator() {} void ServiceGenerator::GenerateDeclarations(io::Printer* printer) { // Forward-declare the stub type. printer->Print(vars_, "class $classname$_Stub;\n" "\n"); GenerateInterface(printer); GenerateStubDefinition(printer); } void ServiceGenerator::GenerateInterface(io::Printer* printer) { printer->Print(vars_, "class $dllexport$$classname$ : public ::google::protobuf::Service {\n" " protected:\n" " // This class should be treated as an abstract interface.\n" " inline $classname$() {};\n" " public:\n" " virtual ~$classname$();\n"); printer->Indent(); printer->Print(vars_, "\n" "typedef $classname$_Stub Stub;\n" "\n" "static const ::google::protobuf::ServiceDescriptor* descriptor();\n" "\n"); GenerateMethodSignatures(VIRTUAL, printer); printer->Print( "\n" "// implements Service ----------------------------------------------\n" "\n" "const ::google::protobuf::ServiceDescriptor* GetDescriptor();\n" "void CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" " ::google::protobuf::RpcController* controller,\n" " const ::google::protobuf::Message* request,\n" " ::google::protobuf::Message* response,\n" " ::google::protobuf::Closure* done);\n" "const ::google::protobuf::Message& GetRequestPrototype(\n" " const ::google::protobuf::MethodDescriptor* method) const;\n" "const ::google::protobuf::Message& GetResponsePrototype(\n" " const ::google::protobuf::MethodDescriptor* method) const;\n"); printer->Outdent(); printer->Print(vars_, "\n" " private:\n" " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n" "};\n" "\n"); } void ServiceGenerator::GenerateStubDefinition(io::Printer* printer) { printer->Print(vars_, "class $dllexport$$classname$_Stub : public $classname$ {\n" " public:\n"); printer->Indent(); printer->Print(vars_, "$classname$_Stub(::google::protobuf::RpcChannel* channel);\n" "$classname$_Stub(::google::protobuf::RpcChannel* channel,\n" " ::google::protobuf::Service::ChannelOwnership ownership);\n" "~$classname$_Stub();\n" "\n" "inline ::google::protobuf::RpcChannel* channel() { return channel_; }\n" "\n" "// implements $classname$ ------------------------------------------\n" "\n"); GenerateMethodSignatures(NON_VIRTUAL, printer); printer->Outdent(); printer->Print(vars_, " private:\n" " ::google::protobuf::RpcChannel* channel_;\n" " bool owns_channel_;\n" " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n" "};\n" "\n"); } void ServiceGenerator::GenerateMethodSignatures( VirtualOrNon virtual_or_non, io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["name"] = method->name(); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); sub_vars["virtual"] = virtual_or_non == VIRTUAL ? "virtual " : ""; printer->Print(sub_vars, "$virtual$void $name$(::google::protobuf::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ::google::protobuf::Closure* done);\n"); } } // =================================================================== void ServiceGenerator::GenerateDescriptorInitializer( io::Printer* printer, int index) { map<string, string> vars; vars["classname"] = descriptor_->name(); vars["index"] = SimpleItoa(index); printer->Print(vars, "$classname$_descriptor_ = file->service($index$);\n"); } // =================================================================== void ServiceGenerator::GenerateImplementation(io::Printer* printer) { printer->Print(vars_, "$classname$::~$classname$() {}\n" "\n" "const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\n" " return $classname$_descriptor_;\n" "}\n" "\n" "const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\n" " return $classname$_descriptor_;\n" "}\n" "\n"); // Generate methods of the interface. GenerateNotImplementedMethods(printer); GenerateCallMethod(printer); GenerateGetPrototype(REQUEST, printer); GenerateGetPrototype(RESPONSE, printer); // Generate stub implementation. printer->Print(vars_, "$classname$_Stub::$classname$_Stub(::google::protobuf::RpcChannel* channel)\n" " : channel_(channel), owns_channel_(false) {}\n" "$classname$_Stub::$classname$_Stub(\n" " ::google::protobuf::RpcChannel* channel,\n" " ::google::protobuf::Service::ChannelOwnership ownership)\n" " : channel_(channel),\n" " owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\n" "$classname$_Stub::~$classname$_Stub() {\n" " if (owns_channel_) delete channel_;\n" "}\n" "\n"); GenerateStubMethods(printer); } void ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["classname"] = descriptor_->name(); sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); printer->Print(sub_vars, "void $classname$::$name$(::google::protobuf::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ::google::protobuf::Closure* done) {\n" " controller->SetFailed(\"Method $name$() not implemented.\");\n" " done->Run();\n" "}\n" "\n"); } } void ServiceGenerator::GenerateCallMethod(io::Printer* printer) { printer->Print(vars_, "void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" " ::google::protobuf::RpcController* controller,\n" " const ::google::protobuf::Message* request,\n" " ::google::protobuf::Message* response,\n" " ::google::protobuf::Closure* done) {\n" " GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\n" " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); // Note: ::google::protobuf::down_cast does not work here because it only works on pointers, // not references. printer->Print(sub_vars, " case $index$:\n" " $name$(controller,\n" " ::google::protobuf::down_cast<const $input_type$*>(request),\n" " ::google::protobuf::down_cast< $output_type$*>(response),\n" " done);\n" " break;\n"); } printer->Print(vars_, " default:\n" " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" " break;\n" " }\n" "}\n" "\n"); } void ServiceGenerator::GenerateGetPrototype(RequestOrResponse which, io::Printer* printer) { if (which == REQUEST) { printer->Print(vars_, "const ::google::protobuf::Message& $classname$::GetRequestPrototype(\n"); } else { printer->Print(vars_, "const ::google::protobuf::Message& $classname$::GetResponsePrototype(\n"); } printer->Print(vars_, " const ::google::protobuf::MethodDescriptor* method) const {\n" " GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\n" " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); const Descriptor* type = (which == REQUEST) ? method->input_type() : method->output_type(); map<string, string> sub_vars; sub_vars["index"] = SimpleItoa(i); sub_vars["type"] = ClassName(type, true); printer->Print(sub_vars, " case $index$:\n" " return $type$::default_instance();\n"); } printer->Print(vars_, " default:\n" " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" " return *reinterpret_cast< ::google::protobuf::Message*>(NULL);\n" " }\n" "}\n" "\n"); } void ServiceGenerator::GenerateStubMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["classname"] = descriptor_->name(); sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); printer->Print(sub_vars, "void $classname$_Stub::$name$(::google::protobuf::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ::google::protobuf::Closure* done) {\n" " channel_->CallMethod($classname$_descriptor_->method($index$),\n" " controller, request, response, done);\n" "}\n"); } } } // namespace cpp } // namespace compiler } // namespace protobuf } // namespace google <commit_msg>Avoid an "unused parameter" warning when using high warning levels.<commit_after>// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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. // Author: [email protected] (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/compiler/cpp/cpp_service.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> namespace google { namespace protobuf { namespace compiler { namespace cpp { ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor, const string& dllexport_decl) : descriptor_(descriptor) { vars_["classname"] = descriptor_->name(); vars_["full_name"] = descriptor_->full_name(); if (dllexport_decl.empty()) { vars_["dllexport"] = ""; } else { vars_["dllexport"] = dllexport_decl + " "; } } ServiceGenerator::~ServiceGenerator() {} void ServiceGenerator::GenerateDeclarations(io::Printer* printer) { // Forward-declare the stub type. printer->Print(vars_, "class $classname$_Stub;\n" "\n"); GenerateInterface(printer); GenerateStubDefinition(printer); } void ServiceGenerator::GenerateInterface(io::Printer* printer) { printer->Print(vars_, "class $dllexport$$classname$ : public ::google::protobuf::Service {\n" " protected:\n" " // This class should be treated as an abstract interface.\n" " inline $classname$() {};\n" " public:\n" " virtual ~$classname$();\n"); printer->Indent(); printer->Print(vars_, "\n" "typedef $classname$_Stub Stub;\n" "\n" "static const ::google::protobuf::ServiceDescriptor* descriptor();\n" "\n"); GenerateMethodSignatures(VIRTUAL, printer); printer->Print( "\n" "// implements Service ----------------------------------------------\n" "\n" "const ::google::protobuf::ServiceDescriptor* GetDescriptor();\n" "void CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" " ::google::protobuf::RpcController* controller,\n" " const ::google::protobuf::Message* request,\n" " ::google::protobuf::Message* response,\n" " ::google::protobuf::Closure* done);\n" "const ::google::protobuf::Message& GetRequestPrototype(\n" " const ::google::protobuf::MethodDescriptor* method) const;\n" "const ::google::protobuf::Message& GetResponsePrototype(\n" " const ::google::protobuf::MethodDescriptor* method) const;\n"); printer->Outdent(); printer->Print(vars_, "\n" " private:\n" " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n" "};\n" "\n"); } void ServiceGenerator::GenerateStubDefinition(io::Printer* printer) { printer->Print(vars_, "class $dllexport$$classname$_Stub : public $classname$ {\n" " public:\n"); printer->Indent(); printer->Print(vars_, "$classname$_Stub(::google::protobuf::RpcChannel* channel);\n" "$classname$_Stub(::google::protobuf::RpcChannel* channel,\n" " ::google::protobuf::Service::ChannelOwnership ownership);\n" "~$classname$_Stub();\n" "\n" "inline ::google::protobuf::RpcChannel* channel() { return channel_; }\n" "\n" "// implements $classname$ ------------------------------------------\n" "\n"); GenerateMethodSignatures(NON_VIRTUAL, printer); printer->Outdent(); printer->Print(vars_, " private:\n" " ::google::protobuf::RpcChannel* channel_;\n" " bool owns_channel_;\n" " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n" "};\n" "\n"); } void ServiceGenerator::GenerateMethodSignatures( VirtualOrNon virtual_or_non, io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["name"] = method->name(); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); sub_vars["virtual"] = virtual_or_non == VIRTUAL ? "virtual " : ""; printer->Print(sub_vars, "$virtual$void $name$(::google::protobuf::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ::google::protobuf::Closure* done);\n"); } } // =================================================================== void ServiceGenerator::GenerateDescriptorInitializer( io::Printer* printer, int index) { map<string, string> vars; vars["classname"] = descriptor_->name(); vars["index"] = SimpleItoa(index); printer->Print(vars, "$classname$_descriptor_ = file->service($index$);\n"); } // =================================================================== void ServiceGenerator::GenerateImplementation(io::Printer* printer) { printer->Print(vars_, "$classname$::~$classname$() {}\n" "\n" "const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\n" " return $classname$_descriptor_;\n" "}\n" "\n" "const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\n" " return $classname$_descriptor_;\n" "}\n" "\n"); // Generate methods of the interface. GenerateNotImplementedMethods(printer); GenerateCallMethod(printer); GenerateGetPrototype(REQUEST, printer); GenerateGetPrototype(RESPONSE, printer); // Generate stub implementation. printer->Print(vars_, "$classname$_Stub::$classname$_Stub(::google::protobuf::RpcChannel* channel)\n" " : channel_(channel), owns_channel_(false) {}\n" "$classname$_Stub::$classname$_Stub(\n" " ::google::protobuf::RpcChannel* channel,\n" " ::google::protobuf::Service::ChannelOwnership ownership)\n" " : channel_(channel),\n" " owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\n" "$classname$_Stub::~$classname$_Stub() {\n" " if (owns_channel_) delete channel_;\n" "}\n" "\n"); GenerateStubMethods(printer); } void ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["classname"] = descriptor_->name(); sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); printer->Print(sub_vars, "void $classname$::$name$(::google::protobuf::RpcController* controller,\n" " const $input_type$*,\n" " $output_type$*,\n" " ::google::protobuf::Closure* done) {\n" " controller->SetFailed(\"Method $name$() not implemented.\");\n" " done->Run();\n" "}\n" "\n"); } } void ServiceGenerator::GenerateCallMethod(io::Printer* printer) { printer->Print(vars_, "void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" " ::google::protobuf::RpcController* controller,\n" " const ::google::protobuf::Message* request,\n" " ::google::protobuf::Message* response,\n" " ::google::protobuf::Closure* done) {\n" " GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\n" " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); // Note: ::google::protobuf::down_cast does not work here because it only works on pointers, // not references. printer->Print(sub_vars, " case $index$:\n" " $name$(controller,\n" " ::google::protobuf::down_cast<const $input_type$*>(request),\n" " ::google::protobuf::down_cast< $output_type$*>(response),\n" " done);\n" " break;\n"); } printer->Print(vars_, " default:\n" " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" " break;\n" " }\n" "}\n" "\n"); } void ServiceGenerator::GenerateGetPrototype(RequestOrResponse which, io::Printer* printer) { if (which == REQUEST) { printer->Print(vars_, "const ::google::protobuf::Message& $classname$::GetRequestPrototype(\n"); } else { printer->Print(vars_, "const ::google::protobuf::Message& $classname$::GetResponsePrototype(\n"); } printer->Print(vars_, " const ::google::protobuf::MethodDescriptor* method) const {\n" " GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\n" " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); const Descriptor* type = (which == REQUEST) ? method->input_type() : method->output_type(); map<string, string> sub_vars; sub_vars["index"] = SimpleItoa(i); sub_vars["type"] = ClassName(type, true); printer->Print(sub_vars, " case $index$:\n" " return $type$::default_instance();\n"); } printer->Print(vars_, " default:\n" " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" " return *reinterpret_cast< ::google::protobuf::Message*>(NULL);\n" " }\n" "}\n" "\n"); } void ServiceGenerator::GenerateStubMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["classname"] = descriptor_->name(); sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); printer->Print(sub_vars, "void $classname$_Stub::$name$(::google::protobuf::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ::google::protobuf::Closure* done) {\n" " channel_->CallMethod($classname$_descriptor_->method($index$),\n" " controller, request, response, done);\n" "}\n"); } } } // namespace cpp } // namespace compiler } // namespace protobuf } // namespace google <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLShaderStringBuilder.h" #include "GrSKSLPrettyPrint.h" #include "SkAutoMalloc.h" #include "SkSLCompiler.h" #include "SkSLGLSLCodeGenerator.h" #include "SkTraceEvent.h" #include "gl/GrGLGpu.h" #include "ir/SkSLProgram.h" #define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X) #define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X) // Print the source code for all shaders generated. static const bool c_PrintShaders{false}; static void print_source_lines_with_numbers(const char* source, std::function<void(const char*)> println) { SkTArray<SkString> lines; SkStrSplit(source, "\n", kStrict_SkStrSplitMode, &lines); for (int i = 0; i < lines.count(); ++i) { SkString& line = lines[i]; line.prependf("%4i\t", i + 1); println(line.c_str()); } } // Prints shaders one line at the time. This ensures they don't get truncated by the adb log. static void print_sksl_line_by_line(const char** skslStrings, int* lengths, int count, std::function<void(const char*)> println = [](const char* ln) { SkDebugf("%s\n", ln); }) { SkSL::String sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false); println("SKSL:"); print_source_lines_with_numbers(sksl.c_str(), println); } static void print_glsl_line_by_line(const SkSL::String& glsl, std::function<void(const char*)> println = [](const char* ln) { SkDebugf("%s\n", ln); }) { println("GLSL:"); print_source_lines_with_numbers(glsl.c_str(), println); } std::unique_ptr<SkSL::Program> GrSkSLtoGLSL(const GrGLContext& context, GrGLenum type, const char** skslStrings, int* lengths, int count, const SkSL::Program::Settings& settings, SkSL::String* glsl) { // Trace event for shader preceding driver compilation bool traceShader; TRACE_EVENT_CATEGORY_GROUP_ENABLED("skia.gpu", &traceShader); if (traceShader) { SkString shaderDebugString; print_sksl_line_by_line(skslStrings, lengths, count, [&](const char* ln) { shaderDebugString.append(ln); shaderDebugString.append("\n"); }); TRACE_EVENT_INSTANT1("skia.gpu", "skia_gpu::GLShader", TRACE_EVENT_SCOPE_THREAD, "shader", TRACE_STR_COPY(shaderDebugString.c_str())); } SkSL::String sksl; #ifdef SK_DEBUG sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false); #else for (int i = 0; i < count; i++) { sksl.append(skslStrings[i], lengths[i]); } #endif SkSL::Compiler* compiler = context.compiler(); std::unique_ptr<SkSL::Program> program; SkSL::Program::Kind programKind; switch (type) { case GR_GL_VERTEX_SHADER: programKind = SkSL::Program::kVertex_Kind; break; case GR_GL_FRAGMENT_SHADER: programKind = SkSL::Program::kFragment_Kind; break; case GR_GL_GEOMETRY_SHADER: programKind = SkSL::Program::kGeometry_Kind; break; } program = compiler->convertProgram(programKind, sksl, settings); if (!program || !compiler->toGLSL(*program, glsl)) { SkDebugf("SKSL compilation error\n----------------------\n"); print_sksl_line_by_line(skslStrings, lengths, count); SkDebugf("\nErrors:\n%s\n", compiler->errorText().c_str()); SkDEBUGFAIL("SKSL compilation failed!\n"); return nullptr; } return program; } GrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx, GrGLuint programId, GrGLenum type, const char* glsl, int glslLength, GrGpu::Stats* stats, const SkSL::Program::Settings& settings) { const GrGLInterface* gli = glCtx.interface(); // Specify GLSL source to the driver. GrGLuint shaderId; GR_GL_CALL_RET(gli, shaderId, CreateShader(type)); if (0 == shaderId) { return 0; } GR_GL_CALL(gli, ShaderSource(shaderId, 1, &glsl, &glslLength)); stats->incShaderCompilations(); GR_GL_CALL(gli, CompileShader(shaderId)); // Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds. bool checkCompiled = kChromium_GrGLDriver != glCtx.driver(); #ifdef SK_DEBUG checkCompiled = true; #endif if (checkCompiled) { GrGLint compiled = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled)); if (!compiled) { SkDebugf("GLSL compilation error\n----------------------\n"); print_glsl_line_by_line(glsl); GrGLint infoLen = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen)); SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger if (infoLen > 0) { // retrieve length even though we don't need it to workaround bug in Chromium cmd // buffer param validation. GrGLsizei length = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get())); SkDebugf("Errors:\n%s\n", (const char*) log.get()); } SkDEBUGFAIL("GLSL compilation failed!"); GR_GL_CALL(gli, DeleteShader(shaderId)); return 0; } } if (c_PrintShaders) { const char* typeName = "Unknown"; switch (type) { case GR_GL_VERTEX_SHADER: typeName = "Vertex"; break; case GR_GL_GEOMETRY_SHADER: typeName = "Geometry"; break; case GR_GL_FRAGMENT_SHADER: typeName = "Fragment"; break; } SkDebugf("---- %s shader ----------------------------------------------------\n", typeName); print_glsl_line_by_line(glsl); } // Attach the shader, but defer deletion until after we have linked the program. // This works around a bug in the Android emulator's GLES2 wrapper which // will immediately delete the shader object and free its memory even though it's // attached to a program, which then causes glLinkProgram to fail. GR_GL_CALL(gli, AttachShader(programId, shaderId)); return shaderId; } void GrGLPrintShader(const GrGLContext& context, GrGLenum type, const char** skslStrings, int* lengths, int count, const SkSL::Program::Settings& settings) { print_sksl_line_by_line(skslStrings, lengths, count); SkSL::String glsl; if (GrSkSLtoGLSL(context, type, skslStrings, lengths, count, settings, &glsl)) { print_glsl_line_by_line(glsl); } } <commit_msg>Roll external/skia 64ca6be98..06ab3836f (1 commits)<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLShaderStringBuilder.h" #include "GrSKSLPrettyPrint.h" #include "SkAutoMalloc.h" #include "SkSLCompiler.h" #include "SkSLGLSLCodeGenerator.h" #include "SkTraceEvent.h" #include "gl/GrGLGpu.h" #include "ir/SkSLProgram.h" #define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X) #define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X) // Print the source code for all shaders generated. static const bool gPrintSKSL = false; static const bool gPrintGLSL = false; static void print_source_lines_with_numbers(const char* source, std::function<void(const char*)> println) { SkTArray<SkString> lines; SkStrSplit(source, "\n", kStrict_SkStrSplitMode, &lines); for (int i = 0; i < lines.count(); ++i) { SkString& line = lines[i]; line.prependf("%4i\t", i + 1); println(line.c_str()); } } // Prints shaders one line at the time. This ensures they don't get truncated by the adb log. static void print_sksl_line_by_line(const char** skslStrings, int* lengths, int count, std::function<void(const char*)> println = [](const char* ln) { SkDebugf("%s\n", ln); }) { SkSL::String sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false); println("SKSL:"); print_source_lines_with_numbers(sksl.c_str(), println); } static void print_glsl_line_by_line(const SkSL::String& glsl, std::function<void(const char*)> println = [](const char* ln) { SkDebugf("%s\n", ln); }) { println("GLSL:"); print_source_lines_with_numbers(glsl.c_str(), println); } void print_shader_banner(GrGLenum type) { const char* typeName = "Unknown"; switch (type) { case GR_GL_VERTEX_SHADER: typeName = "Vertex"; break; case GR_GL_GEOMETRY_SHADER: typeName = "Geometry"; break; case GR_GL_FRAGMENT_SHADER: typeName = "Fragment"; break; } SkDebugf("---- %s shader ----------------------------------------------------\n", typeName); } std::unique_ptr<SkSL::Program> GrSkSLtoGLSL(const GrGLContext& context, GrGLenum type, const char** skslStrings, int* lengths, int count, const SkSL::Program::Settings& settings, SkSL::String* glsl) { // Trace event for shader preceding driver compilation bool traceShader; TRACE_EVENT_CATEGORY_GROUP_ENABLED("skia.gpu", &traceShader); if (traceShader) { SkString shaderDebugString; print_sksl_line_by_line(skslStrings, lengths, count, [&](const char* ln) { shaderDebugString.append(ln); shaderDebugString.append("\n"); }); TRACE_EVENT_INSTANT1("skia.gpu", "skia_gpu::GLShader", TRACE_EVENT_SCOPE_THREAD, "shader", TRACE_STR_COPY(shaderDebugString.c_str())); } SkSL::String sksl; #ifdef SK_DEBUG sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false); #else for (int i = 0; i < count; i++) { sksl.append(skslStrings[i], lengths[i]); } #endif SkSL::Compiler* compiler = context.compiler(); std::unique_ptr<SkSL::Program> program; SkSL::Program::Kind programKind; switch (type) { case GR_GL_VERTEX_SHADER: programKind = SkSL::Program::kVertex_Kind; break; case GR_GL_FRAGMENT_SHADER: programKind = SkSL::Program::kFragment_Kind; break; case GR_GL_GEOMETRY_SHADER: programKind = SkSL::Program::kGeometry_Kind; break; } program = compiler->convertProgram(programKind, sksl, settings); if (!program || !compiler->toGLSL(*program, glsl)) { SkDebugf("SKSL compilation error\n----------------------\n"); print_sksl_line_by_line(skslStrings, lengths, count); SkDebugf("\nErrors:\n%s\n", compiler->errorText().c_str()); SkDEBUGFAIL("SKSL compilation failed!\n"); return nullptr; } if (gPrintSKSL) { print_shader_banner(type); print_sksl_line_by_line(skslStrings, lengths, count); } return program; } GrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx, GrGLuint programId, GrGLenum type, const char* glsl, int glslLength, GrGpu::Stats* stats, const SkSL::Program::Settings& settings) { const GrGLInterface* gli = glCtx.interface(); // Specify GLSL source to the driver. GrGLuint shaderId; GR_GL_CALL_RET(gli, shaderId, CreateShader(type)); if (0 == shaderId) { return 0; } GR_GL_CALL(gli, ShaderSource(shaderId, 1, &glsl, &glslLength)); stats->incShaderCompilations(); GR_GL_CALL(gli, CompileShader(shaderId)); // Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds. bool checkCompiled = kChromium_GrGLDriver != glCtx.driver(); #ifdef SK_DEBUG checkCompiled = true; #endif if (checkCompiled) { GrGLint compiled = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled)); if (!compiled) { SkDebugf("GLSL compilation error\n----------------------\n"); print_glsl_line_by_line(glsl); GrGLint infoLen = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen)); SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger if (infoLen > 0) { // retrieve length even though we don't need it to workaround bug in Chromium cmd // buffer param validation. GrGLsizei length = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get())); SkDebugf("Errors:\n%s\n", (const char*) log.get()); } SkDEBUGFAIL("GLSL compilation failed!"); GR_GL_CALL(gli, DeleteShader(shaderId)); return 0; } } if (gPrintGLSL) { print_shader_banner(type); print_glsl_line_by_line(glsl); } // Attach the shader, but defer deletion until after we have linked the program. // This works around a bug in the Android emulator's GLES2 wrapper which // will immediately delete the shader object and free its memory even though it's // attached to a program, which then causes glLinkProgram to fail. GR_GL_CALL(gli, AttachShader(programId, shaderId)); return shaderId; } void GrGLPrintShader(const GrGLContext& context, GrGLenum type, const char** skslStrings, int* lengths, int count, const SkSL::Program::Settings& settings) { print_sksl_line_by_line(skslStrings, lengths, count); SkSL::String glsl; if (GrSkSLtoGLSL(context, type, skslStrings, lengths, count, settings, &glsl)) { print_glsl_line_by_line(glsl); } } <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLShaderStringBuilder.h" #include "GrSKSLPrettyPrint.h" #include "SkAutoMalloc.h" #include "SkSLCompiler.h" #include "SkSLGLSLCodeGenerator.h" #include "SkTraceEvent.h" #include "gl/GrGLGpu.h" #include "ir/SkSLProgram.h" #define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X) #define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X) // Print the source code for all shaders generated. static const bool c_PrintShaders{false}; static SkString list_source_with_line_numbers(const char* source) { SkTArray<SkString> lines; SkStrSplit(source, "\n", kStrict_SkStrSplitMode, &lines); SkString result; for (int line = 0; line < lines.count(); ++line) { // Print the shader one line at the time so it doesn't get truncated by the adb log. result.appendf("%4i\t%s\n", line + 1, lines[line].c_str()); } return result; } SkString list_shaders(const char** skslStrings, int* lengths, int count, const SkSL::String& glsl) { SkString sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false); SkString result("SKSL:\n"); result.append(list_source_with_line_numbers(sksl.c_str())); if (!glsl.isEmpty()) { result.append("GLSL:\n"); result.append(list_source_with_line_numbers(glsl.c_str())); } return result; } std::unique_ptr<SkSL::Program> translate_to_glsl(const GrGLContext& context, GrGLenum type, const char** skslStrings, int* lengths, int count, const SkSL::Program::Settings& settings, SkSL::String* glsl) { SkString sksl; #ifdef SK_DEBUG sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false); #else for (int i = 0; i < count; i++) { sksl.append(skslStrings[i], lengths[i]); } #endif SkSL::Compiler* compiler = context.compiler(); std::unique_ptr<SkSL::Program> program; SkSL::Program::Kind programKind; switch (type) { case GR_GL_VERTEX_SHADER: programKind = SkSL::Program::kVertex_Kind; break; case GR_GL_FRAGMENT_SHADER: programKind = SkSL::Program::kFragment_Kind; break; case GR_GL_GEOMETRY_SHADER: programKind = SkSL::Program::kGeometry_Kind; break; } program = compiler->convertProgram(programKind, sksl, settings); if (!program || !compiler->toGLSL(*program, glsl)) { SkDebugf("SKSL compilation error\n----------------------\n"); SkDebugf(list_shaders(skslStrings, lengths, count, *glsl).c_str()); SkDebugf("\nErrors:\n%s\n", compiler->errorText().c_str()); SkDEBUGFAIL("SKSL compilation failed!\n"); return nullptr; } return program; } GrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx, GrGLuint programId, GrGLenum type, const char** skslStrings, int* lengths, int count, GrGpu::Stats* stats, const SkSL::Program::Settings& settings, SkSL::Program::Inputs* outInputs) { const GrGLInterface* gli = glCtx.interface(); SkSL::String glsl; auto program = translate_to_glsl(glCtx, type, skslStrings, lengths, count, settings, &glsl); if (!program) { return 0; } // Specify GLSL source to the driver. GrGLuint shaderId; GR_GL_CALL_RET(gli, shaderId, CreateShader(type)); if (0 == shaderId) { return 0; } const char* glslChars = glsl.c_str(); GrGLint glslLength = (GrGLint) glsl.size(); GR_GL_CALL(gli, ShaderSource(shaderId, 1, &glslChars, &glslLength)); // Lazy initialized pretty-printed shaders for dumping. SkString shaderDebugString; // Trace event for shader preceding driver compilation bool traceShader; TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), &traceShader); if (traceShader) { if (shaderDebugString.isEmpty()) { shaderDebugString = list_shaders(skslStrings, lengths, count, glsl); } TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), "skia_gpu::GLShader", TRACE_EVENT_SCOPE_THREAD, "shader", TRACE_STR_COPY(shaderDebugString.c_str())); } stats->incShaderCompilations(); GR_GL_CALL(gli, CompileShader(shaderId)); // Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds. bool checkCompiled = kChromium_GrGLDriver != glCtx.driver(); #ifdef SK_DEBUG checkCompiled = true; #endif if (checkCompiled) { GrGLint compiled = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled)); if (!compiled) { if (shaderDebugString.isEmpty()) { shaderDebugString = list_shaders(skslStrings, lengths, count, glsl); } SkDebugf("GLSL compilation error\n----------------------\n"); SkDebugf(shaderDebugString.c_str()); GrGLint infoLen = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen)); SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger if (infoLen > 0) { // retrieve length even though we don't need it to workaround bug in Chromium cmd // buffer param validation. GrGLsizei length = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get())); SkDebugf("Errors:\n%s\n", (const char*) log.get()); } SkDEBUGFAIL("GLSL compilation failed!"); GR_GL_CALL(gli, DeleteShader(shaderId)); return 0; } } if (c_PrintShaders) { const char* typeName = "Unknown"; switch (type) { case GR_GL_VERTEX_SHADER: typeName = "Vertex"; break; case GR_GL_GEOMETRY_SHADER: typeName = "Geometry"; break; case GR_GL_FRAGMENT_SHADER: typeName = "Fragment"; break; } SkDebugf("---- %s shader ----------------------------------------------------\n", typeName); if (shaderDebugString.isEmpty()) { shaderDebugString = list_shaders(skslStrings, lengths, count, glsl); } SkDebugf(shaderDebugString.c_str()); } // Attach the shader, but defer deletion until after we have linked the program. // This works around a bug in the Android emulator's GLES2 wrapper which // will immediately delete the shader object and free its memory even though it's // attached to a program, which then causes glLinkProgram to fail. GR_GL_CALL(gli, AttachShader(programId, shaderId)); *outInputs = program->fInputs; return shaderId; } void GrGLPrintShader(const GrGLContext& context, GrGLenum type, const char** skslStrings, int* lengths, int count, const SkSL::Program::Settings& settings) { SkSL::String glsl; if (translate_to_glsl(context, type, skslStrings, lengths, count, settings, &glsl)) { SkDebugf(list_shaders(skslStrings, lengths, count, glsl).c_str()); } } <commit_msg>gl: print shader sources one line at a time<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLShaderStringBuilder.h" #include "GrSKSLPrettyPrint.h" #include "SkAutoMalloc.h" #include "SkSLCompiler.h" #include "SkSLGLSLCodeGenerator.h" #include "SkTraceEvent.h" #include "gl/GrGLGpu.h" #include "ir/SkSLProgram.h" #define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X) #define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X) // Print the source code for all shaders generated. static const bool c_PrintShaders{false}; static void print_source_lines_with_numbers(const char* source, std::function<void(const char*)> println) { SkTArray<SkString> lines; SkStrSplit(source, "\n", kStrict_SkStrSplitMode, &lines); for (int i = 0; i < lines.count(); ++i) { SkString& line = lines[i]; line.prependf("%4i\t", i + 1); println(line.c_str()); } } // Prints shaders one line at the time. This ensures they don't get truncated by the adb log. static void print_shaders_line_by_line(const char** skslStrings, int* lengths, int count, const SkSL::String& glsl, std::function<void(const char*)> println = [](const char* ln) { SkDebugf("%s\n", ln); }) { SkString sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false); println("SKSL:"); print_source_lines_with_numbers(sksl.c_str(), println); if (!glsl.isEmpty()) { println("GLSL:"); print_source_lines_with_numbers(glsl.c_str(), println); } } std::unique_ptr<SkSL::Program> translate_to_glsl(const GrGLContext& context, GrGLenum type, const char** skslStrings, int* lengths, int count, const SkSL::Program::Settings& settings, SkSL::String* glsl) { SkString sksl; #ifdef SK_DEBUG sksl = GrSKSLPrettyPrint::PrettyPrint(skslStrings, lengths, count, false); #else for (int i = 0; i < count; i++) { sksl.append(skslStrings[i], lengths[i]); } #endif SkSL::Compiler* compiler = context.compiler(); std::unique_ptr<SkSL::Program> program; SkSL::Program::Kind programKind; switch (type) { case GR_GL_VERTEX_SHADER: programKind = SkSL::Program::kVertex_Kind; break; case GR_GL_FRAGMENT_SHADER: programKind = SkSL::Program::kFragment_Kind; break; case GR_GL_GEOMETRY_SHADER: programKind = SkSL::Program::kGeometry_Kind; break; } program = compiler->convertProgram(programKind, sksl, settings); if (!program || !compiler->toGLSL(*program, glsl)) { SkDebugf("SKSL compilation error\n----------------------\n"); print_shaders_line_by_line(skslStrings, lengths, count, *glsl); SkDebugf("\nErrors:\n%s\n", compiler->errorText().c_str()); SkDEBUGFAIL("SKSL compilation failed!\n"); return nullptr; } return program; } GrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx, GrGLuint programId, GrGLenum type, const char** skslStrings, int* lengths, int count, GrGpu::Stats* stats, const SkSL::Program::Settings& settings, SkSL::Program::Inputs* outInputs) { const GrGLInterface* gli = glCtx.interface(); SkSL::String glsl; auto program = translate_to_glsl(glCtx, type, skslStrings, lengths, count, settings, &glsl); if (!program) { return 0; } // Specify GLSL source to the driver. GrGLuint shaderId; GR_GL_CALL_RET(gli, shaderId, CreateShader(type)); if (0 == shaderId) { return 0; } const char* glslChars = glsl.c_str(); GrGLint glslLength = (GrGLint) glsl.size(); GR_GL_CALL(gli, ShaderSource(shaderId, 1, &glslChars, &glslLength)); // Trace event for shader preceding driver compilation bool traceShader; TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), &traceShader); if (traceShader) { SkString shaderDebugString; print_shaders_line_by_line(skslStrings, lengths, count, glsl, [&](const char* ln) { shaderDebugString.append(ln); shaderDebugString.append("\n"); }); TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), "skia_gpu::GLShader", TRACE_EVENT_SCOPE_THREAD, "shader", TRACE_STR_COPY(shaderDebugString.c_str())); } stats->incShaderCompilations(); GR_GL_CALL(gli, CompileShader(shaderId)); // Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds. bool checkCompiled = kChromium_GrGLDriver != glCtx.driver(); #ifdef SK_DEBUG checkCompiled = true; #endif if (checkCompiled) { GrGLint compiled = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled)); if (!compiled) { SkDebugf("GLSL compilation error\n----------------------\n"); print_shaders_line_by_line(skslStrings, lengths, count, glsl); GrGLint infoLen = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen)); SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger if (infoLen > 0) { // retrieve length even though we don't need it to workaround bug in Chromium cmd // buffer param validation. GrGLsizei length = GR_GL_INIT_ZERO; GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get())); SkDebugf("Errors:\n%s\n", (const char*) log.get()); } SkDEBUGFAIL("GLSL compilation failed!"); GR_GL_CALL(gli, DeleteShader(shaderId)); return 0; } } if (c_PrintShaders) { const char* typeName = "Unknown"; switch (type) { case GR_GL_VERTEX_SHADER: typeName = "Vertex"; break; case GR_GL_GEOMETRY_SHADER: typeName = "Geometry"; break; case GR_GL_FRAGMENT_SHADER: typeName = "Fragment"; break; } SkDebugf("---- %s shader ----------------------------------------------------\n", typeName); print_shaders_line_by_line(skslStrings, lengths, count, glsl); } // Attach the shader, but defer deletion until after we have linked the program. // This works around a bug in the Android emulator's GLES2 wrapper which // will immediately delete the shader object and free its memory even though it's // attached to a program, which then causes glLinkProgram to fail. GR_GL_CALL(gli, AttachShader(programId, shaderId)); *outInputs = program->fInputs; return shaderId; } void GrGLPrintShader(const GrGLContext& context, GrGLenum type, const char** skslStrings, int* lengths, int count, const SkSL::Program::Settings& settings) { SkSL::String glsl; if (translate_to_glsl(context, type, skslStrings, lengths, count, settings, &glsl)) { print_shaders_line_by_line(skslStrings, lengths, count, glsl); } } <|endoftext|>
<commit_before>#ifndef SIMULATE_ENGINE_BASE_HPP_ #define SIMULATE_ENGINE_BASE_HPP_ #include "clotho/powerset/variable_subset.hpp" #include "clotho/utility/random_generator.hpp" #include "clotho/classifiers/region_classifier.hpp" #include <vector> #include <utility> template < class URNG, class AlleleType, class LogType, class TimerType > class simulate_engine_base { public: typedef URNG rng_type; typedef AlleleType allele_type; typedef LogType log_type; typedef TimerType timer_type; typedef unsigned long block_type; typedef clotho::utility::random_generator< rng_type, allele_type > allele_generator; typedef clotho::powersets::variable_subset< allele_type, block_type > sequence_type; typedef typename sequence_type::pointer sequence_pointer; typedef typename sequence_type::powerset_type allele_set_type; typedef clotho::classifiers::region_classifier< allele_type > classifier_type; typedef clotho::utility::random_generator< rng_type, classifier_type > classifier_generator; typedef std::pair< sequence_pointer, sequence_pointer > individual_type; typedef std::vector< individual_type > population_type; typedef typename population_type::iterator population_iterator; }; #endif // SIMULATE_ENGINE_BASE_HPP_ <commit_msg>Added compilation specific dependencies for specific types<commit_after>#ifndef SIMULATE_ENGINE_BASE_HPP_ #define SIMULATE_ENGINE_BASE_HPP_ #include "qtl_config.hpp" #include <vector> #include <utility> template < class URNG, class AlleleType, class LogType, class TimerType > class simulate_engine_base { public: typedef URNG rng_type; typedef AlleleType allele_type; typedef LogType log_type; typedef TimerType timer_type; typedef BLOCK_UNIT_TYPE block_type; typedef clotho::utility::random_generator< rng_type, allele_type > allele_generator; typedef SUBSETTYPE< allele_type, block_type > sequence_type; typedef typename sequence_type::pointer sequence_pointer; typedef typename sequence_type::powerset_type allele_set_type; typedef RECOMBTYPE classifier_type; typedef clotho::utility::random_generator< rng_type, classifier_type > classifier_generator; typedef std::pair< sequence_pointer, sequence_pointer > individual_type; typedef std::vector< individual_type > population_type; typedef typename population_type::iterator population_iterator; }; #endif // SIMULATE_ENGINE_BASE_HPP_ <|endoftext|>
<commit_before>#include "streamline.h" #include "inc_glut.h" #include "color.h" #include "svg_line.h" namespace INMOST { void GetVelocity(Element c, const Tag & velocity_tag, ElementType vel_adj, coord pnt, coord & ret) { coord cnt; const Storage::real eps = 1.0e-8; Storage::real dist = 0; ret[0] = ret[1] = ret[2] = 0; c->Centroid(cnt.data()); if ((cnt - pnt).length() < 1.0e-5) { ret = coord(c->RealArray(velocity_tag).data()); } else //inverse distance algorithm (consider wlsqr with linear basis) { ElementArray<Element> adj = c->BridgeAdjacencies(vel_adj == NODE ? CELL : NODE,vel_adj); adj.push_back(c); for (ElementArray<Element>::iterator it = adj.begin(); it != adj.end(); ++it) { it->Centroid(cnt.data()); coord vel = coord(it->RealArray(velocity_tag).data()); Storage::real l = (cnt - pnt).length() + eps; Storage::real omega = 1.0 / (l*l); ret += vel*omega; dist += omega; } ret /= dist; } } Storage::real GetSize(Cell c) { Storage::real bounds[3][2] = { { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 } }; ElementArray<Node> nodes = c->getNodes(); for (ElementArray<Node>::iterator n = nodes.begin(); n != nodes.end(); ++n) { Storage::real_array cnt = n->Coords(); for (int k = 0; k < 3; ++k) { if (bounds[k][0] > cnt[k]) bounds[k][0] = cnt[k]; if (bounds[k][1] < cnt[k]) bounds[k][1] = cnt[k]; } } Storage::real ret = 1.0e+20; for (int k = 0; k < 3; ++k) if (bounds[k][1] - bounds[k][0]) ret = std::min(ret, bounds[k][1] - bounds[k][0]); if (ret > 1.0e+19) std::cout << __FILE__ << ":" << __LINE__ << " oops" << std::endl; return ret; } Storage::real GetSize(Element n, const Tag & size_tag) { ElementArray<Cell> cells = n->getCells(); Storage::real minsize = 1.0e+20, size; for (ElementArray<Cell>::iterator c = cells.begin(); c != cells.end(); ++c) { size = c->RealDF(size_tag); if (minsize > size) minsize = size; } if (minsize > 1.0e+19) std::cout << __FILE__ << ":" << __LINE__ << " oops" << std::endl; return minsize; } void BuildStreamlines(Mesh *mesh, Tag vel, ElementType vel_def, std::vector<Streamline> & output) { if (!vel.isDefined(vel_def)) { std::cout << __FILE__ << ":" << __LINE__ << " Velocity was not defined on " << ElementTypeName(vel_def) << std::endl; return; } if (vel.GetDataType() != DATA_REAL) { std::cout << __FILE__ << ":" << __LINE__ << " Data type for velocity is not floating point" << std::endl; return; } if (vel.GetSize() != 3) { std::cout << __FILE__ << ":" << __LINE__ << " Expected 3 entries in velocity field for streamlines" << std::endl; return; } printf("preparing octree around mesh, was sets %d\n", mesh->NumberOfSets()); Octree octsearch = Octree(mesh->CreateSet("octsearch").first); octsearch.Construct(vel_def, false); //auto-detect octree or quadtree printf("done, sets %d\n", mesh->NumberOfSets()); printf("building streamlines\n"); Tag cell_size = mesh->CreateTag("STREAMLINES_TEMPORARY_CELL_SIZES", DATA_REAL, CELL, NONE, 1); Storage::real velmax = 0, velmin = 1.0e20, l; for (Mesh::iteratorCell c = mesh->BeginCell(); c != mesh->EndCell(); ++c) { coord velv(c->RealArray(vel).data()); l = velv.length(); if (l > velmax) velmax = l; if (l < velmin) velmin = l; c->RealDF(cell_size) = GetSize(c->self()); } velmax = log(velmax + 1.0e-25); velmin = log(velmin + 1.0e-25); { MarkerType visited = mesh->CreateMarker(); printf("started building streamlines from boundary elements\n"); int tot = 0; for (Mesh::iteratorElement f = mesh->BeginElement(vel_def); f != mesh->EndElement(); ++f) if (f->Boundary()) tot++; printf("total elements: %d\n",tot); int k = 0; for (Mesh::iteratorElement f = mesh->BeginElement(vel_def); f != mesh->EndElement(); ++f) if (f->Boundary()) { coord v(f->RealArray(vel).data()); if (v.length() > 1.0e-4) { coord nrm(0,0,0); if( f->GetElementType() == FACE ) f->getAsFace().UnitNormal(nrm.data()); else { coord ncur; int nn = 0; ElementArray<Face> faces = f->getFaces(); for (ElementArray<Face>::iterator ff = faces.begin(); ff != faces.end(); ++ff) if (ff->Boundary()) { ff->UnitNormal(ncur.data()); nrm+=ncur; nn++; } if( nn ) nrm /= (double)nn; else std::cout << __FILE__ << ":" << __LINE__ << " No boundary faces around boundary element" << std::endl; } double dir = nrm^v; if( dir > 0.0 ) //velocity points out of mesh dir = -1; else dir = 1; //velocity points into mesh coord cntf; f->Centroid(cntf.data()); output.push_back(Streamline(octsearch, cntf, vel, vel_def, cell_size, velmin, velmax, dir, visited)); ElementArray<Edge> edges = f->getEdges(); for (ElementArray<Edge>::iterator n = edges.begin(); n != edges.end(); ++n) { coord cntn; n->Centroid(cntn.data()); if (cntn[2] == cntf[2]) { const Storage::real coef[4] = { 0.4, 0.8 }; for (int q = 0; q < 2; ++q) output.push_back(Streamline(octsearch, cntf*coef[q] + cntn*(1 - coef[q]), vel, vel_def, cell_size, velmin, velmax, 1.0, visited)); } } } k++; if (k % 100 == 0) { printf("%5.2f%%\r", (double)k / (double)tot*100.0); fflush(stdout); } } printf("done from boundary faces, total streamlines = %lu\n", output.size()); printf("started building streamlines from unvisited cells\n"); tot = 0; for (Mesh::iteratorCell it = mesh->BeginCell(); it != mesh->EndCell(); ++it) if (!it->GetMarker(visited)) tot++; printf("total elements: %d\n", tot); k = 0; for (Mesh::iteratorCell it = mesh->BeginCell(); it != mesh->EndCell(); ++it) { if (!it->GetMarker(visited)) { coord cntc; it->Centroid(cntc.data()); if (coord(it->RealArray(vel).data()).length() > 1.0e-4) { output.push_back(Streamline(octsearch, cntc, vel, vel_def, cell_size, velmin, velmax, 1.0, 0)); output.push_back(Streamline(octsearch, cntc, vel, vel_def, cell_size, velmin, velmax, -1.0, 0)); } } k++; if (k % 100 == 0) { printf("%5.2f%%\r", (double)k / (double)tot*100.0); fflush(stdout); } } printf("done from unvisited cells, total streamlines = %lu\n", output.size()); mesh->ReleaseMarker(visited,vel_def); } mesh->DeleteTag(cell_size); printf("done, total streamlines = %lu\n", output.size()); printf("killing octree, was sets %d\n", mesh->NumberOfSets()); octsearch.Destroy(); printf("done, sets %d\n", mesh->NumberOfSets()); } Streamline::Streamline(const Octree & octsearch, coord pos, Tag velocity_tag, ElementType velocity_defined, Tag cell_size, Storage::real velocity_min, Storage::real velocity_max, Storage::real sign, MarkerType visited) { Storage::real coef, len, size; coord next = pos, vel; Element c; const int maxsteps = 250; points.reserve(maxsteps / 2); velarr.reserve(maxsteps / 2); points.push_back(pos); velarr.push_back(0); while (points.size() < maxsteps) { c = octsearch.FindClosestCell(next.data()); if (!c.isValid()) break; //check we are inside mesh /* ElementArray<Cell> cells = c->BridgeAdjacencies2Cell(NODE); bool inside = false; for (ElementArray<Cell>::iterator it = cells.begin(); it != cells.end() && !inside; ++it) if( it->Inside(next.data()) ) inside = true; if( !inside ) break; */ c.SetMarker(visited); GetVelocity(c, velocity_tag, velocity_defined, next, vel); len = vel.length(); if (len < 1.0e-4) break; size = GetSize(c, cell_size);// c->RealDF(cell_size); coef = 0.05*size / len; next += vel*coef*sign; points.push_back(next); velarr.push_back((log(len + 1.0e-25) - velocity_min) / (velocity_max - velocity_min)); } //printf("%ld %ld\n",points.size(),velarr.size()); } GLUquadric * cylqs = NULL; void drawcylinder(coord a, coord b, double width) { double matrix[16]; if (cylqs == NULL) { cylqs = gluNewQuadric(); gluQuadricNormals(cylqs, GLU_SMOOTH); gluQuadricOrientation(cylqs, GLU_OUTSIDE); gluQuadricDrawStyle(cylqs, GLU_FILL);//GLU_SILHOUETTE } glPushMatrix(); glTranslated(a[0], a[1], a[2]); get_matrix(a, b, matrix); glMultMatrixd(matrix); gluCylinder(cylqs, width, width, sqrt((b - a) ^ (b - a)), 4, 2); glPopMatrix(); } void Streamline::Draw(int reduced) { if (reduced) { glBegin(GL_LINE_STRIP); for (unsigned int i = 0; i < points.size() - 1; i++) { glColor3f(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1])); glVertex3d(points[i][0], points[i][1], points[i][2]); } glEnd(); } else for (unsigned int i = 0; i < points.size() - 1; i++) { glColor3f(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1])); drawcylinder(points[i], points[i + 1], 0.25*abs(points[i + 1] - points[i])); } } void Streamline::SVGDraw(std::ostream & file, double modelview[16], double projection[16], int viewport[4]) { for (unsigned int i = 0; i < points.size() - 1; i++) { double * v0 = points[i].data(); double * v1 = points[i + 1].data(); color_t c(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1])); file << "<g stroke=\"" << c.svg_rgb() << "\">" << std::endl; svg_line(file, v0[0], v0[1], v0[2], v1[0], v1[1], v1[2], modelview, projection, viewport); file << "</g>" << std::endl; } } } <commit_msg>Streamlines in OldDrawGrid<commit_after>#include "streamline.h" #include "inc_glut.h" #include "color.h" #include "svg_line.h" namespace INMOST { void GetVelocity(Element c, const Tag & velocity_tag, ElementType vel_adj, coord pnt, coord & ret) { coord cnt; const Storage::real eps = 1.0e-8; Storage::real dist = 0; ret[0] = ret[1] = ret[2] = 0; c->Centroid(cnt.data()); if ((cnt - pnt).length() < 1.0e-5) { ret = coord(c->RealArray(velocity_tag).data()); } else //inverse distance algorithm (consider wlsqr with linear basis) { ElementArray<Element> adj = c->BridgeAdjacencies(vel_adj == NODE ? CELL : NODE,vel_adj); adj.push_back(c); for (ElementArray<Element>::iterator it = adj.begin(); it != adj.end(); ++it) { it->Centroid(cnt.data()); coord vel = coord(it->RealArray(velocity_tag).data()); Storage::real l = (cnt - pnt).length() + eps; Storage::real omega = 1.0 / (l*l); ret += vel*omega; dist += omega; } ret /= dist; } } Storage::real GetSize(Cell c) { Storage::real bounds[3][2] = { { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 } }; ElementArray<Node> nodes = c->getNodes(); for (ElementArray<Node>::iterator n = nodes.begin(); n != nodes.end(); ++n) { Storage::real_array cnt = n->Coords(); for (int k = 0; k < 3; ++k) { if (bounds[k][0] > cnt[k]) bounds[k][0] = cnt[k]; if (bounds[k][1] < cnt[k]) bounds[k][1] = cnt[k]; } } Storage::real ret = 1.0e+20; for (int k = 0; k < 3; ++k) if (bounds[k][1] - bounds[k][0]) ret = std::min(ret, bounds[k][1] - bounds[k][0]); if (ret > 1.0e+19) std::cout << __FILE__ << ":" << __LINE__ << " oops" << std::endl; return ret; } void GetBbox(Element c, Storage::real bounds[3][2]) { bounds[0][0] = 1.0e20; bounds[0][1] = -1.0e20; bounds[1][0] = 1.0e20; bounds[1][1] = -1.0e20; bounds[2][0] = 1.0e20; bounds[2][1] = -1.0e20; //bounds[3][2] = { { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 }, { 1.0e20, -1.0e20 } }; ElementArray<Node> nodes = c->getNodes(); for (ElementArray<Node>::iterator n = nodes.begin(); n != nodes.end(); ++n) { Storage::real_array cnt = n->Coords(); for (int k = 0; k < 3; ++k) { if (bounds[k][0] > cnt[k]) bounds[k][0] = cnt[k]; if (bounds[k][1] < cnt[k]) bounds[k][1] = cnt[k]; } } return; //Storage::real ret = 1.0e+20; //for (int k = 0; k < 3; ++k) if (bounds[k][1] - bounds[k][0]) // ret = std::min(ret, bounds[k][1] - bounds[k][0]); //if (ret > 1.0e+19) std::cout << __FILE__ << ":" << __LINE__ << " oops" << std::endl; //return ret; } double GetSizeProj(double bounds[3][2], const coord & v) { double vl = v.length(); if( !vl ) return 0; coord uv = v/vl; double ret = 0; for(int k = 0; k < 3; ++k) ret += fabs(uv[k]*(bounds[k][1]-bounds[k][0])); return ret; } double GetSizeProj(Element c, const coord & v) { double bounds[3][2]; GetBbox(c,bounds); return GetSizeProj(bounds,v); } Storage::real GetSize(Element n, const Tag & size_tag) { ElementArray<Cell> cells = n->getCells(); Storage::real minsize = 1.0e+20, size; for (ElementArray<Cell>::iterator c = cells.begin(); c != cells.end(); ++c) { size = c->RealDF(size_tag); if (minsize > size) minsize = size; } if (minsize > 1.0e+19) std::cout << __FILE__ << ":" << __LINE__ << " oops" << std::endl; return minsize; } void BuildStreamlines(Mesh *mesh, Tag vel, ElementType vel_def, std::vector<Streamline> & output) { if (!vel.isDefined(vel_def)) { std::cout << __FILE__ << ":" << __LINE__ << " Velocity was not defined on " << ElementTypeName(vel_def) << std::endl; return; } if (vel.GetDataType() != DATA_REAL) { std::cout << __FILE__ << ":" << __LINE__ << " Data type for velocity is not floating point" << std::endl; return; } if (vel.GetSize() != 3) { std::cout << __FILE__ << ":" << __LINE__ << " Expected 3 entries in velocity field for streamlines" << std::endl; return; } printf("preparing octree around mesh, was sets %d\n", mesh->NumberOfSets()); Octree octsearch = Octree(mesh->CreateSet("octsearch").first); octsearch.Construct(vel_def, false); //auto-detect octree or quadtree printf("done, sets %d\n", mesh->NumberOfSets()); printf("building streamlines\n"); Tag cell_size = mesh->CreateTag("STREAMLINES_TEMPORARY_CELL_SIZES", DATA_REAL, CELL, NONE, 1); Storage::real velmax = 0, velmin = 1.0e20, l; for (Mesh::iteratorCell c = mesh->BeginCell(); c != mesh->EndCell(); ++c) { coord velv(c->RealArray(vel).data()); l = velv.length(); if (l > velmax) velmax = l; if (l < velmin) velmin = l; c->RealDF(cell_size) = GetSize(c->self()); } velmax = log(velmax + 1.0e-25); velmin = log(velmin + 1.0e-25); { MarkerType visited = mesh->CreateMarker(); int tot = 0; int k = 0; /* printf("started building streamlines from boundary elements\n"); for (Mesh::iteratorElement f = mesh->BeginElement(vel_def); f != mesh->EndElement(); ++f) if (f->Boundary()) tot++; printf("total elements: %d\n",tot); for (Mesh::iteratorElement f = mesh->BeginElement(vel_def); f != mesh->EndElement(); ++f) if (f->Boundary()) { coord v(f->RealArray(vel).data()); if (v.length() > 1.0e-4) { coord nrm(0,0,0); if( f->GetElementType() == FACE ) f->getAsFace().UnitNormal(nrm.data()); else { coord ncur; int nn = 0; ElementArray<Face> faces = f->getFaces(); for (ElementArray<Face>::iterator ff = faces.begin(); ff != faces.end(); ++ff) if (ff->Boundary()) { ff->UnitNormal(ncur.data()); nrm+=ncur; nn++; } if( nn ) nrm /= (double)nn; else std::cout << __FILE__ << ":" << __LINE__ << " No boundary faces around boundary element" << std::endl; } double dir = nrm^v; if( dir > 0.0 ) //velocity points out of mesh dir = -1; else dir = 1; //velocity points into mesh coord cntf; f->Centroid(cntf.data()); output.push_back(Streamline(octsearch, cntf, vel, vel_def, cell_size, velmin, velmax, dir, visited)); ElementArray<Edge> edges = f->getEdges(); for (ElementArray<Edge>::iterator n = edges.begin(); n != edges.end(); ++n) { coord cntn; n->Centroid(cntn.data()); if (cntn[2] == cntf[2]) { const Storage::real coef[4] = { 0.4, 0.8 }; for (int q = 0; q < 2; ++q) output.push_back(Streamline(octsearch, cntf*coef[q] + cntn*(1 - coef[q]), vel, vel_def, cell_size, velmin, velmax, 1.0, visited)); } } } k++; if (k % 100 == 0) { printf("%5.2f%%\r", (double)k / (double)tot*100.0); fflush(stdout); } } printf("done from boundary faces, total streamlines = %lu\n", output.size()); */ printf("started building streamlines from unvisited cells\n"); tot = 0; for (Mesh::iteratorCell it = mesh->BeginCell(); it != mesh->EndCell(); ++it) if (!it->GetMarker(visited)) tot++; printf("total elements: %d\n", tot); k = 0; for (Mesh::iteratorCell it = mesh->BeginCell(); it != mesh->EndCell(); ++it) { if (!it->GetMarker(visited)) { coord cntc; it->Centroid(cntc.data()); if (coord(it->RealArray(vel).data()).length() > 1.0e-4) { output.push_back(Streamline(octsearch, cntc, vel, vel_def, cell_size, velmin, velmax, 1.0, visited)); output.push_back(Streamline(octsearch, cntc, vel, vel_def, cell_size, velmin, velmax, -1.0, visited)); } } k++; if (k % 100 == 0) { printf("%5.2f%%\r", (double)k / (double)tot*100.0); fflush(stdout); } } printf("done from unvisited cells, total streamlines = %lu\n", output.size()); mesh->ReleaseMarker(visited,vel_def); } mesh->DeleteTag(cell_size); printf("done, total streamlines = %lu\n", output.size()); printf("killing octree, was sets %d\n", mesh->NumberOfSets()); octsearch.Destroy(); printf("done, sets %d\n", mesh->NumberOfSets()); } Streamline::Streamline(const Octree & octsearch, coord pos, Tag velocity_tag, ElementType velocity_defined, Tag cell_size, Storage::real velocity_min, Storage::real velocity_max, Storage::real sign, MarkerType visited) { Storage::real coef, len, size; coord next = pos, vel; Element c; const int maxsteps = 8000; points.reserve(maxsteps / 2); velarr.reserve(maxsteps / 2); points.push_back(pos); velarr.push_back(0); while (points.size() < maxsteps) { c = octsearch.FindClosestCell(next.data()); if (!c.isValid()) break; //if( !c.getAsCell().Inside(next.data()) ) break; //check we are inside mesh /* ElementArray<Cell> cells = c->BridgeAdjacencies2Cell(NODE); bool inside = false; for (ElementArray<Cell>::iterator it = cells.begin(); it != cells.end() && !inside; ++it) if( it->Inside(next.data()) ) inside = true; if( !inside ) break; */ c.SetMarker(visited); GetVelocity(c, velocity_tag, velocity_defined, next, vel); len = vel.length(); if (len < 1.0e-7) break; //size = GetSize(c, cell_size);// c->RealDF(cell_size); size = GetSizeProj(c,vel); coef = 0.02*size / len; next += vel*coef*sign; points.push_back(next); velarr.push_back((log(len + 1.0e-25) - velocity_min) / (velocity_max - velocity_min)); } //printf("%ld %ld\n",points.size(),velarr.size()); } GLUquadric * cylqs = NULL; void drawcylinder(coord a, coord b, double width) { double matrix[16]; if (cylqs == NULL) { cylqs = gluNewQuadric(); gluQuadricNormals(cylqs, GLU_SMOOTH); gluQuadricOrientation(cylqs, GLU_OUTSIDE); gluQuadricDrawStyle(cylqs, GLU_FILL);//GLU_SILHOUETTE } glPushMatrix(); glTranslated(a[0], a[1], a[2]); get_matrix(a, b, matrix); glMultMatrixd(matrix); gluCylinder(cylqs, width, width, sqrt((b - a) ^ (b - a)), 4, 2); glPopMatrix(); } void Streamline::Draw(int reduced) { if (reduced) { glBegin(GL_LINE_STRIP); for (unsigned int i = 0; i < points.size() - 1; i++) { glColor3f(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1])); glVertex3d(points[i][0], points[i][1], points[i][2]); } glEnd(); } else for (unsigned int i = 0; i < points.size() - 1; i++) { glColor3f(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1])); drawcylinder(points[i], points[i + 1], 0.5*abs(points[i + 1] - points[i])); } } void Streamline::SVGDraw(std::ostream & file, double modelview[16], double projection[16], int viewport[4]) { for (unsigned int i = 0; i < points.size() - 1; i++) { double * v0 = points[i].data(); double * v1 = points[i + 1].data(); color_t c(velarr[i + 1] * 0.65, 0.65*(velarr[i + 1] < 0.5 ? velarr[i] : 1.0 - velarr[i]), 0.65*(1 - velarr[i + 1])); file << "<g stroke=\"" << c.svg_rgb() << "\">" << std::endl; svg_line(file, v0[0], v0[1], v0[2], v1[0], v1[1], v1[2], modelview, projection, viewport); file << "</g>" << std::endl; } } } <|endoftext|>
<commit_before>#include "inmost.h" using namespace INMOST; //TODO: //attach scale to rescale grid //attach slice grid to cut cylinder //option to set shear rate / pressure drop / maximum velocity //setup BC //cmake compilation //setup on mesh: // // FORCE - 3 entries // // BOUNDARY_CONDITION_VELOCITY - 7 entries // r = (a5,a6,a7) // n.(a1*u + a2*t) = n.r // (I - nn.)(a3*u + a4*t) = (I-nn.)r // // BOUNDARY_CONDITION_PRESSURE - 1 entry // // REFERENCE_VELOCITY - 3 entries // // REFERENCE_PRESSURE - 1 entry // typedef Storage::real real; int main(int argc, char ** argv) { if( argc < 2 ) { std::cout << "Usage: " << argv[0] << " mesh [axis=2 (0:x,1:y,2:z)] [control=0 (0:shear rate,1:pressure drop,2:maximal velocity)] [control_value=10] [visc=1.0e-5] [mesh_out=grid_out.pmf]" << std::endl; return 0; } Mesh * m = new Mesh; m->SetFileOption("VERBOSITY","2"); try { m->Load(argv[1]); } catch(...) { std::cout << "Cannot load the mesh " << argv[1] << std::endl; return -1; } std::string fout = "grid_out.pmf"; int axis = 2; double visc = 1.0e-5; int control = 0; double control_value = 10; double Len = 8; double Diam = 1; double shear = 10;//0; //shear rate double dp = 0;//36e-6; double vmax = 0; if( argc > 2 ) axis = atoi(argv[2]); if( argc > 3 ) control = atoi(argv[3]); if( argc > 4 ) control_value = atof(argv[4]); if( argc > 5 ) visc = atof(argv[5]); if( argc > 6 ) fout = std::string(argv[6]); if( axis < 0 || axis > 2 ) { std::cout << "bad axis: " << axis << " should be 0 - x, 1 - y, 2 - z" << std::endl; return -1; } if( control < 0 || control > 2 ) { std::cout << "bad control: " << control << " should be 0 - shear rate, 1 - pressure drop, 2 - maximal velocity" << std::endl; return -1; } if( visc <= 0 ) { std::cout << "bad viscosity: " << visc << std::endl; return -1; } if( control == 0 ) { shear = control_value; dp = vmax = 0; } else if( control == 1 ) { dp = control_value; shear = vmax = 0; } else if( control == 2 ) { vmax = control_value; dp = shear = 0; } double cmax[3] = {-1.0e20,-1.0e20,-1.0e20}, cmin[3] = {1.0e20,1.0e20,1.0e20}; for(Mesh::iteratorNode n = m->BeginNode(); n != m->EndNode(); ++n) { Storage::real_array c = n->Coords(); for(int k = 0; k < 3; ++k) { if( cmax[k] < c[k] ) cmax[k] = c[k]; if( cmin[k] > c[k] ) cmin[k] = c[k]; } } Len = cmax[axis] - cmin[axis]; Diam = std::max(cmax[(axis+1)%3]-cmin[(axis+1)%3],cmax[(axis+2)%3]-cmin[(axis+2)%3]); if( shear ) { dp = 4*Len/Diam*shear*visc; vmax = Diam*Diam*dp/(16*visc*Len); } else if( dp ) { vmax = Diam*Diam*dp/(16*visc*Len); shear = 4*vmax/Diam; } else if( vmax ) { shear = 4*vmax/Diam; dp = 4*Len/Diam*shear*visc; } std::cout << "viscosity " << visc << " shear " << shear << " dp " << dp << " vmax " << vmax << " length " << Len << " diameter " << Diam << std::endl; //TagRealArray force = m->CreateTag("FORCE",DATA_REAL,CELL,NONE,3); TagRealArray bc = m->CreateTag("BOUNDARY_CONDITION_VELOCITY",DATA_REAL,FACE,FACE,7); TagReal bcp = m->CreateTag("BOUNDARY_CONDITION_PRESSURE",DATA_REAL,FACE,FACE,1); TagRealArray uvw = m->CreateTag("UVW",DATA_REAL,CELL,NONE,3); TagRealArray uvw_ref = m->CreateTag("REFERENCE_VELOCITY",DATA_REAL,CELL,NONE,3); //depends on viscosity TagReal p_ref = m->CreateTag("REFERENCE_PRESSURE",DATA_REAL,CELL,NONE,1); TagReal p = m->CreateTag("P",DATA_REAL,CELL,NONE,1); //this should not be needed? for(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) if( it->Boundary() ) it->FixNormalOrientation(); double cnt0[3]; cnt0[axis] = 0; cnt0[(axis+1)%2] = (cmax[(axis+1)%2] + cmin[(axis+1)%2])*0.5; cnt0[(axis+2)%2] = (cmax[(axis+2)%2] + cmin[(axis+2)%2])*0.5; for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) { double cnt[3]; it->Barycenter(cnt); double r = sqrt(pow(cnt[(axis+1)%2]-cnt0[(axis+1)%2],2)+pow(cnt[(axis+2)%2]-cnt0[(axis+2)%2],2)); uvw(*it,3,1).Zero(); p[*it] = 0; uvw_ref(*it,3,1).Zero(); uvw_ref(*it,3,1)(axis,0) = (Diam*Diam/4.0-r*r)*dp/(4.0*visc*Len); p_ref[*it] = dp*(cnt[axis]-cmin[axis])/Len; } for(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) if( it->Boundary() ) { double n[3]; it->UnitNormal(n); if( fabs(n[axis]-1) < 1.0e-3 ) // outflow { bcp[*it] = 0+10; } else if( fabs(n[axis]+1) < 1.0e-3 ) //inflow { bcp[*it] = dp+10; } else //no-slip walls { bc[*it][0] = 1; bc[*it][1] = 0; bc[*it][2] = 1; bc[*it][3] = 0; bc[*it][4] = 0; bc[*it][5] = 0; bc[*it][6] = 0; } } std::cout << "Saving output to " << fout << std::endl; m->Save(fout); return 0; } <commit_msg>sync N-S pousielle test<commit_after>#include "inmost.h" using namespace INMOST; //TODO: //attach scale to rescale grid //attach slice grid to cut cylinder //option to set shear rate / pressure drop / maximum velocity //setup BC //cmake compilation //setup on mesh: // // FORCE - 3 entries // // BOUNDARY_CONDITION_VELOCITY - 7 entries // r = (a5,a6,a7) // n.(a1*u + a2*t) = n.r // (I - nn.)(a3*u + a4*t) = (I-nn.)r // // BOUNDARY_CONDITION_PRESSURE - 1 entry // // REFERENCE_VELOCITY - 3 entries // // REFERENCE_PRESSURE - 1 entry // typedef Storage::real real; int main(int argc, char ** argv) { if( argc < 2 ) { std::cout << "Usage: " << argv[0] << " mesh [axis=2 (0:x,1:y,2:z)] [control=0 (0:shear rate,1:pressure drop,2:maximal velocity)] [control_value=10] [visc=1.0e-5] [mesh_out=grid_out.pmf] [addsym=0]" << std::endl; return 0; } Mesh * m = new Mesh; m->SetFileOption("VERBOSITY","2"); try { m->Load(argv[1]); } catch(...) { std::cout << "Cannot load the mesh " << argv[1] << std::endl; return -1; } std::string fout = "grid_out.pmf"; int axis = 2; double visc = 1.0e-5; int control = 0; double control_value = 10; double Len = 8; double Diam = 1; double shear = 10;//0; //shear rate double dp = 0;//36e-6; double vmax = 0; double addsym = 0; if( argc > 2 ) axis = atoi(argv[2]); if( argc > 3 ) control = atoi(argv[3]); if( argc > 4 ) control_value = atof(argv[4]); if( argc > 5 ) visc = atof(argv[5]); if( argc > 6 ) fout = std::string(argv[6]); if( argc > 7 ) addsym = atof(argv[7]); if( axis < 0 || axis > 2 ) { std::cout << "bad axis: " << axis << " should be 0 - x, 1 - y, 2 - z" << std::endl; return -1; } if( control < 0 || control > 2 ) { std::cout << "bad control: " << control << " should be 0 - shear rate, 1 - pressure drop, 2 - maximal velocity" << std::endl; return -1; } if( visc <= 0 ) { std::cout << "bad viscosity: " << visc << std::endl; return -1; } if( control == 0 ) { shear = control_value; dp = vmax = 0; } else if( control == 1 ) { dp = control_value; shear = vmax = 0; } else if( control == 2 ) { vmax = control_value; dp = shear = 0; } double cmax[3] = {-1.0e20,-1.0e20,-1.0e20}, cmin[3] = {1.0e20,1.0e20,1.0e20}; for(Mesh::iteratorNode n = m->BeginNode(); n != m->EndNode(); ++n) { Storage::real_array c = n->Coords(); for(int k = 0; k < 3; ++k) { if( cmax[k] < c[k] ) cmax[k] = c[k]; if( cmin[k] > c[k] ) cmin[k] = c[k]; } } Len = cmax[axis] - cmin[axis]; Diam = std::max(cmax[(axis+1)%3]-cmin[(axis+1)%3],cmax[(axis+2)%3]-cmin[(axis+2)%3]); if( shear ) { dp = 4*Len/Diam*shear*visc; vmax = Diam*Diam*dp/(16*visc*Len); } else if( dp ) { vmax = Diam*Diam*dp/(16*visc*Len); shear = 4*vmax/Diam; } else if( vmax ) { shear = 4*vmax/Diam; dp = 4*Len/Diam*shear*visc; } std::cout << "viscosity " << visc << " shear " << shear << " dp " << dp << " vmax " << vmax << " length " << Len << " diameter " << Diam << std::endl; //TagRealArray force = m->CreateTag("FORCE",DATA_REAL,CELL,NONE,3); TagRealArray bc = m->CreateTag("BOUNDARY_CONDITION_VELOCITY",DATA_REAL,FACE,FACE,7); TagReal bcp = m->CreateTag("BOUNDARY_CONDITION_PRESSURE",DATA_REAL,FACE,FACE,1); TagRealArray uvw = m->CreateTag("UVW",DATA_REAL,CELL,NONE,3); TagRealArray uvw_ref = m->CreateTag("REFERENCE_VELOCITY",DATA_REAL,CELL,NONE,3); //depends on viscosity TagReal p_ref = m->CreateTag("REFERENCE_PRESSURE",DATA_REAL,CELL,NONE,1); TagReal p = m->CreateTag("P",DATA_REAL,CELL,NONE,1); //this should not be needed? for(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) if( it->Boundary() ) it->FixNormalOrientation(); double cnt0[3], p0 = 10; cnt0[axis] = 0; cnt0[(axis+1)%2] = (cmax[(axis+1)%2] + cmin[(axis+1)%2])*0.5; cnt0[(axis+2)%2] = (cmax[(axis+2)%2] + cmin[(axis+2)%2])*0.5; std::cout << "center " << cnt0[0] << " " << cnt0[1] << " " << cnt0[2] << std::endl; for(Mesh::iteratorCell it = m->BeginCell(); it != m->EndCell(); ++it) { double cnt[3]; it->Barycenter(cnt); double r = sqrt(pow(cnt[(axis+1)%2]-cnt0[(axis+1)%2],2)+pow(cnt[(axis+2)%2]-cnt0[(axis+2)%2],2)); uvw(*it,3,1).Zero(); p[*it] = 0; uvw_ref(*it,3,1).Zero(); uvw_ref(*it,3,1)(axis,0) = (Diam*Diam/4.0-r*r)*dp/(4.0*visc*Len); p_ref[*it] = p0 + dp*(cmax[axis] - cnt[axis])/Len - 0.5*addsym*uvw_ref(*it,3,1).DotProduct(uvw_ref(*it,3,1)); } for(Mesh::iteratorFace it = m->BeginFace(); it != m->EndFace(); ++it) if( it->Boundary() ) { double n[3]; it->UnitNormal(n); if( fabs(n[axis]-1) < 1.0e-3 ) // outflow { bcp[*it] = 0+p0; } else if( fabs(n[axis]+1) < 1.0e-3 ) //inflow { bcp[*it] = dp+p0; } else //no-slip walls { bc[*it][0] = 1; bc[*it][1] = 0; bc[*it][2] = 1; bc[*it][3] = 0; bc[*it][4] = 0; bc[*it][5] = 0; bc[*it][6] = 0; } } std::cout << "Saving output to " << fout << std::endl; m->Save(fout); return 0; } <|endoftext|>
<commit_before>/** @copyright * Copyright (c) 2018, Stuart W Baker * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @file TivaCanNullTx.hxx * This file implements a test driver for CAN on Tiva. * * @author Stuart W. Baker * @date 6 June 2018 */ #ifndef _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_ #define _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_ #include "TivaDev.hxx" /** Specialization of Tiva CAN driver for testing purposes. */ class TivaCanNullTx : public TivaCan { public: /** Constructor. * @param name name of this device instance in the file system * @param base base address of this device * @param interrupt interrupt number of this device */ TivaCanNullTx(const char *name, unsigned long base, uint32_t interrupt) : TivaCan(name, base, interrupt) , readTimeFirst_(0) , readTime10000_(0) , readCount_(0) { } /** Destructor. */ ~TivaCanNullTx() { } /** Get the latest performance time stamp. * @param count the number of messages that have been received in total * @return if count < @ref MESSAGE_COUNT, the time since the first message * was received, else, the time between the first message received * and the 10,000th message received. */ long long get_timestamp_and_count(unsigned *count) { long long result; portENTER_CRITICAL(); *count = readCount_; if (readCount_ >= MESSAGE_COUNT) { result = readTime10000_ - readTimeFirst_; } else { result = OSTime::get_monotonic() - readTimeFirst_; } portEXIT_CRITICAL(); return result; } private: static constexpr size_t MESSAGE_COUNT = 10000; /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ ssize_t read(File *file, void *buf, size_t count) override { if (readCount_ == 0) { readTimeFirst_ = OSTime::get_monotonic(); } ssize_t result = Can::read(file, buf, count); if (result > 0) { readCount_ += result / sizeof(struct can_frame); if (readCount_ >= MESSAGE_COUNT && readTime10000_ == 0) { readTime10000_ = OSTime::get_monotonic(); } } return result; } /** Write to a file or device. * @param file file reference for this device * @param buf location to find write data * @param count number of bytes to write * @return number of bytes written upon success, -1 upon failure with errno * containing the cause */ ssize_t write(File *file, const void *buf, size_t count) override { /* drop all the write data on the floor */ return count; } long long readTimeFirst_; /**< timestamp of first read in nsec */ long long readTime10000_; /**< timestamp of 10,000th read in nsec */ size_t readCount_; /**< running count of all the reads */ DISALLOW_COPY_AND_ASSIGN(TivaCanNullTx); }; #endif /* _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_ */ <commit_msg>Fix the logic to be more time accurate.<commit_after>/** @copyright * Copyright (c) 2018, Stuart W Baker * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @file TivaCanNullTx.hxx * This file implements a test driver for CAN on Tiva. * * @author Stuart W. Baker * @date 6 June 2018 */ #ifndef _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_ #define _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_ #include "TivaDev.hxx" /** Specialization of Tiva CAN driver for testing purposes. */ class TivaCanNullTx : public TivaCan { public: /** Constructor. * @param name name of this device instance in the file system * @param base base address of this device * @param interrupt interrupt number of this device */ TivaCanNullTx(const char *name, unsigned long base, uint32_t interrupt) : TivaCan(name, base, interrupt) , readTimeFirst_(0) , readTime10000_(0) , readCount_(0) { } /** Destructor. */ ~TivaCanNullTx() { } /** Get the latest performance time stamp. * @param count the number of messages that have been received in total * @return if count < @ref MESSAGE_COUNT, the time since the first message * was received, else, the time between the first message received * and the 10,000th message received. */ long long get_timestamp_and_count(unsigned *count) { long long result; portENTER_CRITICAL(); *count = readCount_; if (readCount_ >= MESSAGE_COUNT) { result = readTime10000_ - readTimeFirst_; } else { result = OSTime::get_monotonic() - readTimeFirst_; } portEXIT_CRITICAL(); return result; } private: static constexpr size_t MESSAGE_COUNT = 10000; /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ ssize_t read(File *file, void *buf, size_t count) override { ssize_t result = Can::read(file, buf, count); if (result > 0) { if (readCount_ == 0) { readTimeFirst_ = OSTime::get_monotonic(); } readCount_ += result / sizeof(struct can_frame); if (readCount_ >= MESSAGE_COUNT && readTime10000_ == 0) { readTime10000_ = OSTime::get_monotonic(); } } return result; } /** Write to a file or device. * @param file file reference for this device * @param buf location to find write data * @param count number of bytes to write * @return number of bytes written upon success, -1 upon failure with errno * containing the cause */ ssize_t write(File *file, const void *buf, size_t count) override { /* drop all the write data on the floor */ return count; } long long readTimeFirst_; /**< timestamp of first read in nsec */ long long readTime10000_; /**< timestamp of 10,000th read in nsec */ size_t readCount_; /**< running count of all the reads */ DISALLOW_COPY_AND_ASSIGN(TivaCanNullTx); }; #endif /* _FREERTOS_DRIVERS_TI_TIVACANNULLTX_HXX_ */ <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_io_ChildProcess.h" #include "jnc_io_IoLib.h" namespace jnc { namespace io { //.............................................................................. #if (_JNC_OS_WIN) bool createStdioPipe( handle_t* readHandle, handle_t* writeHandle, dword_t readMode, dword_t writeMode ) { static int32_t pipeId = 0; char buffer[256];wait pid timeout sl::String_w pipeName(ref::BufKind_Stack, buffer, sizeof(buffer)); pipeName.format( L"\\\\.\\pipe\\jnc.ChildProcess.%p.%d", sys::getCurrentProcessId(), sys::atomicInc(&pipeId) ); axl::io::win::NamedPipe pipe; axl::io::win::File file; SECURITY_ATTRIBUTES secAttr = { 0 }; secAttr.nLength = sizeof(SECURITY_ATTRIBUTES); secAttr.bInheritHandle = true; bool result = pipe.create( pipeName, PIPE_ACCESS_INBOUND | readMode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 0, 0, 0, &secAttr ) && file.create( pipeName, GENERIC_WRITE, 0, &secAttr, OPEN_EXISTING, writeMode ); if (!result) return false; *readHandle = pipe.detach(); *writeHandle = file.detach(); return true; } #else bool exec(const char* commandLine) { char buffer[256]; sl::Array<char*> argv(ref::BufKind_Stack, buffer, sizeof(buffer)); sl::String string = commandLine; size_t length = string.getLength(); for (;;) { string.trimLeft(); if (string.isEmpty()) break; argv.append(string.p()); size_t pos = string.findOneOf(sl::StringDetails::getWhitespace()); if (pos == -1) break; string[pos] = 0; string = string.getSubString(pos + 1); } if (argv.isEmpty()) { err::setError("empty command line"); return false; } argv.append(NULL); int result = ::execvp(argv[0], argv.p()); ASSERT(result == -1); err::setLastSystemError(); return false; } #endif //.............................................................................. JNC_DEFINE_OPAQUE_CLASS_TYPE( ChildProcess, "io.ChildProcess", g_ioLibGuid, IoLibCacheSlot_ChildProcess, ChildProcess, NULL ) JNC_BEGIN_TYPE_FUNCTION_MAP(ChildProcess) JNC_MAP_CONSTRUCTOR(&jnc::construct<ChildProcess>) JNC_MAP_DESTRUCTOR(&jnc::destruct<ChildProcess>) JNC_MAP_FUNCTION("start", &ChildProcess::start) JNC_MAP_FUNCTION("close", &ChildProcess::close) JNC_MAP_FUNCTION("wait", &ChildProcess::wait) JNC_MAP_FUNCTION("waitAndClose", &ChildProcess::waitAndClose) JNC_MAP_FUNCTION("terminate", &ChildProcess::terminate) JNC_END_TYPE_FUNCTION_MAP() //.............................................................................. ChildProcess::ChildProcess() { jnc::construct<FileStream>(m_stdin); jnc::construct<FileStream>(m_stdout); jnc::construct<FileStream>(m_stderr); } ChildProcess::~ChildProcess() { close(); } bool JNC_CDECL ChildProcess::start( DataPtr commandLinePtr, uint_t flags ) { close(); bool isMergedStdoutStderr = (flags & ChildProcessFlag_MergeStdoutStderr) != 0; #if (_JNC_OS_WIN) sl::String_w cmdLine = (char*)commandLinePtr.m_p; bool_t result; axl::io::win::File parentStdin; axl::io::win::File parentStdout; axl::io::win::File parentStderr; axl::io::win::File childStdin; axl::io::win::File childStdout; axl::io::win::File childStderr; result = createStdioPipe(childStdin.p(), parentStdin.p(), 0, FILE_FLAG_OVERLAPPED) && createStdioPipe(parentStdout.p(), childStdout.p(), FILE_FLAG_OVERLAPPED, 0) && (isMergedStdoutStderr || createStdioPipe(parentStderr.p(), childStderr.p(), FILE_FLAG_OVERLAPPED, 0)); if (!result) return false; STARTUPINFOW startupInfo = { 0 }; startupInfo.cb = sizeof(STARTUPINFO); startupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; startupInfo.hStdInput = childStdin; startupInfo.hStdOutput = childStdout; startupInfo.hStdError = isMergedStdoutStderr ? childStdout : childStderr; startupInfo.wShowWindow = SW_HIDE; result = m_process.createProcess(cmdLine, true, CREATE_NEW_CONSOLE, &startupInfo); if (!result) return false; attachFileStream(m_stdin, &parentStdin); attachFileStream(m_stdout, &parentStdout); attachFileStream(m_stderr, &parentStderr); #else axl::io::psx::Pipe stdinPipe; axl::io::psx::Pipe stdoutPipe; axl::io::psx::Pipe stderrPipe; bool result = stdinPipe.create() && stdinPipe.m_writeFile.setBlockingMode(false) && stdoutPipe.create() && stdoutPipe.m_readFile.setBlockingMode(false) && (isMergedStdoutStderr || stderrPipe.create() && stderrPipe.m_readFile.setBlockingMode(false)); if (!result) return false; pid_t pid = ::fork(); switch (pid) { case -1: err::setLastSystemError(); return false; case 0: ::dup2(stdinPipe.m_readFile, STDIN_FILENO); ::dup2(stdoutPipe.m_writeFile, STDOUT_FILENO); ::dup2(isMergedStdoutStderr ? stdoutPipe.m_writeFile : stderrPipe.m_writeFile, STDERR_FILENO); exec((char*)commandLinePtr.m_p); ::fprintf(stderr, "POSIX exec error: %s\n", err::getLastErrorDescription().sz()); ::abort(); ASSERT(false); default: m_pid = pid; } attachFileStream(m_stdin, &stdinPipe.m_writeFile); attachFileStream(m_stdout, &stdoutPipe.m_readFile); attachFileStream(m_stderr, &stderrPipe.m_readFile); #endif return true; } void JNC_CDECL ChildProcess::close() { m_stdin->close(); m_stdout->close(); m_stderr->close(); #if (_JNC_OS_WIN) m_process.close(); #endif } uint_t JNC_CDECL ChildProcess::getExitCode() { #if (_JNC_OS_WIN) dword_t exitCode = 0; m_process.getExitCode(&exitCode); return exitCode; #endif return 0; } bool JNC_CDECL ChildProcess::wait(uint_t timeout) { return true; } void JNC_CDECL ChildProcess::waitAndClose(uint_t timeout) { close(); } bool JNC_CDECL ChildProcess::terminate() { return true; } void ChildProcess::attachFileStream( io::FileStream* fileStream, AxlOsFile* file ) { fileStream->close(); if (!file->isOpen()) return; fileStream->m_file.m_file.attach(file->detach()); fileStream->m_fileStreamKind = FileStreamKind_Pipe; /* fileStream->setReadParallelism(m_readParallelism); fileStream->setReadBlockSize(m_readBlockSize); fileStream->setReadBufferSize(m_readBufferSize); fileStream->setWriteBufferSize(m_writeBufferSize); fileStream->setOptions(m_options); */ #if (_JNC_OS_WIN) ASSERT(!fileStream->m_overlappedIo); fileStream->m_overlappedIo = AXL_MEM_NEW(FileStream::OverlappedIo); #else #endif fileStream->AsyncIoDevice::open(); fileStream->m_ioThread.start(); } //.............................................................................. } // namespace io } // namespace jnc <commit_msg>[jnc_io] added proper handling for execvp success/failure (via a dedicated pipe with FD_CLOEXEC)<commit_after>//.............................................................................. // // This file is part of the Jancy toolkit. // // Jancy is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/jancy/license.txt // //.............................................................................. #include "pch.h" #include "jnc_io_ChildProcess.h" #include "jnc_io_IoLib.h" namespace jnc { namespace io { //.............................................................................. #if (_JNC_OS_WIN) bool createStdioPipe( handle_t* readHandle, handle_t* writeHandle, dword_t readMode, dword_t writeMode ) { static int32_t pipeId = 0; char buffer[256];wait pid timeout sl::String_w pipeName(ref::BufKind_Stack, buffer, sizeof(buffer)); pipeName.format( L"\\\\.\\pipe\\jnc.ChildProcess.%p.%d", sys::getCurrentProcessId(), sys::atomicInc(&pipeId) ); axl::io::win::NamedPipe pipe; axl::io::win::File file; SECURITY_ATTRIBUTES secAttr = { 0 }; secAttr.nLength = sizeof(SECURITY_ATTRIBUTES); secAttr.bInheritHandle = true; bool result = pipe.create( pipeName, PIPE_ACCESS_INBOUND | readMode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 0, 0, 0, &secAttr ) && file.create( pipeName, GENERIC_WRITE, 0, &secAttr, OPEN_EXISTING, writeMode ); if (!result) return false; *readHandle = pipe.detach(); *writeHandle = file.detach(); return true; } #else void exec(const char* commandLine) // returns on failure only { char buffer[256]; sl::Array<char*> argv(ref::BufKind_Stack, buffer, sizeof(buffer)); sl::String string = commandLine; size_t length = string.getLength(); for (;;) { string.trimLeft(); if (string.isEmpty()) break; argv.append(string.p()); size_t pos = string.findOneOf(sl::StringDetails::getWhitespace()); if (pos == -1) break; string[pos] = 0; string = string.getSubString(pos + 1); } if (argv.isEmpty()) { err::setError("empty command line"); return; } argv.append(NULL); int result = ::execvp(argv[0], argv.p()); ASSERT(result == -1); err::setLastSystemError(); } #endif //.............................................................................. JNC_DEFINE_OPAQUE_CLASS_TYPE( ChildProcess, "io.ChildProcess", g_ioLibGuid, IoLibCacheSlot_ChildProcess, ChildProcess, NULL ) JNC_BEGIN_TYPE_FUNCTION_MAP(ChildProcess) JNC_MAP_CONSTRUCTOR(&jnc::construct<ChildProcess>) JNC_MAP_DESTRUCTOR(&jnc::destruct<ChildProcess>) JNC_MAP_FUNCTION("start", &ChildProcess::start) JNC_MAP_FUNCTION("close", &ChildProcess::close) JNC_MAP_FUNCTION("wait", &ChildProcess::wait) JNC_MAP_FUNCTION("waitAndClose", &ChildProcess::waitAndClose) JNC_MAP_FUNCTION("terminate", &ChildProcess::terminate) JNC_END_TYPE_FUNCTION_MAP() //.............................................................................. ChildProcess::ChildProcess() { jnc::construct<FileStream>(m_stdin); jnc::construct<FileStream>(m_stdout); jnc::construct<FileStream>(m_stderr); } ChildProcess::~ChildProcess() { close(); } bool JNC_CDECL ChildProcess::start( DataPtr commandLinePtr, uint_t flags ) { close(); bool isMergedStdoutStderr = (flags & ChildProcessFlag_MergeStdoutStderr) != 0; #if (_JNC_OS_WIN) sl::String_w cmdLine = (char*)commandLinePtr.m_p; bool_t result; axl::io::win::File parentStdin; axl::io::win::File parentStdout; axl::io::win::File parentStderr; axl::io::win::File childStdin; axl::io::win::File childStdout; axl::io::win::File childStderr; result = createStdioPipe(childStdin.p(), parentStdin.p(), 0, FILE_FLAG_OVERLAPPED) && createStdioPipe(parentStdout.p(), childStdout.p(), FILE_FLAG_OVERLAPPED, 0) && (isMergedStdoutStderr || createStdioPipe(parentStderr.p(), childStderr.p(), FILE_FLAG_OVERLAPPED, 0)); if (!result) return false; STARTUPINFOW startupInfo = { 0 }; startupInfo.cb = sizeof(STARTUPINFO); startupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; startupInfo.hStdInput = childStdin; startupInfo.hStdOutput = childStdout; startupInfo.hStdError = isMergedStdoutStderr ? childStdout : childStderr; startupInfo.wShowWindow = SW_HIDE; result = m_process.createProcess(cmdLine, true, CREATE_NEW_CONSOLE, &startupInfo); if (!result) return false; attachFileStream(m_stdin, &parentStdin); attachFileStream(m_stdout, &parentStdout); attachFileStream(m_stderr, &parentStderr); #else axl::io::psx::Pipe stdinPipe; axl::io::psx::Pipe stdoutPipe; axl::io::psx::Pipe stderrPipe; axl::io::psx::Pipe execPipe; bool result = stdinPipe.create() && stdinPipe.m_writeFile.setBlockingMode(false) && stdoutPipe.create() && stdoutPipe.m_readFile.setBlockingMode(false) && (isMergedStdoutStderr || stderrPipe.create() && stderrPipe.m_readFile.setBlockingMode(false)) && execPipe.create(); if (!result) return false; execPipe.m_writeFile.fcntl(F_SETFD, FD_CLOEXEC); err::Error error; pid_t pid = ::fork(); switch (pid) { case -1: err::setLastSystemError(); return false; case 0: ::dup2(stdinPipe.m_readFile, STDIN_FILENO); ::dup2(stdoutPipe.m_writeFile, STDOUT_FILENO); ::dup2(isMergedStdoutStderr ? stdoutPipe.m_writeFile : stderrPipe.m_writeFile, STDERR_FILENO); exec((char*)commandLinePtr.m_p); error = err::getLastError(); execPipe.m_writeFile.write(error, error->m_size); execPipe.m_writeFile.flush(); ::_exit(-1); ASSERT(false); default: execPipe.m_writeFile.close(); fd_set rdset; FD_ZERO(&rdset); FD_SET(execPipe.m_readFile, &rdset); char buffer[256]; size_t size = execPipe.m_readFile.read(buffer, sizeof(buffer)); if (size == 0 || size == -1) { m_pid = pid; break; } if (((err::ErrorHdr*)buffer)->m_size == size) err::setError((err::ErrorHdr*)buffer); else err::setError("POSIX execvp failed"); // unlikely fallback return false; } attachFileStream(m_stdin, &stdinPipe.m_writeFile); attachFileStream(m_stdout, &stdoutPipe.m_readFile); attachFileStream(m_stderr, &stderrPipe.m_readFile); #endif return true; } void JNC_CDECL ChildProcess::close() { m_stdin->close(); m_stdout->close(); m_stderr->close(); #if (_JNC_OS_WIN) m_process.close(); #endif } uint_t JNC_CDECL ChildProcess::getExitCode() { #if (_JNC_OS_WIN) dword_t exitCode = 0; m_process.getExitCode(&exitCode); return exitCode; #endif return 0; } bool JNC_CDECL ChildProcess::wait(uint_t timeout) { return true; } void JNC_CDECL ChildProcess::waitAndClose(uint_t timeout) { close(); } bool JNC_CDECL ChildProcess::terminate() { return true; } void ChildProcess::attachFileStream( io::FileStream* fileStream, AxlOsFile* file ) { fileStream->close(); if (!file->isOpen()) return; fileStream->m_file.m_file.attach(file->detach()); fileStream->m_fileStreamKind = FileStreamKind_Pipe; /* fileStream->setReadParallelism(m_readParallelism); fileStream->setReadBlockSize(m_readBlockSize); fileStream->setReadBufferSize(m_readBufferSize); fileStream->setWriteBufferSize(m_writeBufferSize); fileStream->setOptions(m_options); */ #if (_JNC_OS_WIN) ASSERT(!fileStream->m_overlappedIo); fileStream->m_overlappedIo = AXL_MEM_NEW(FileStream::OverlappedIo); #endif fileStream->AsyncIoDevice::open(); fileStream->m_ioThread.start(); } //.............................................................................. } // namespace io } // namespace jnc <|endoftext|>
<commit_before>/* -*- mode: c++; indent-tabs-mode: nil -*- */ /* The thaw depth evaluator gets the subsurface temperature. This computes the thaw depth over time. This is SecondaryVariablesFieldEvaluator and depends on the subsurface temperature, Authors: Ahmad Jan ([email protected]) */ #ifndef AMANZI_FLOWRELATIONS_INITIAL_ELEV_EVALUATOR_ #define AMANZI_FLOWRELATIONS_INITIAL_ELVE_EVALUATOR_ #include "Factory.hh" #include "secondary_variable_field_evaluator.hh" namespace Amanzi { namespace Flow { class InitialElevationEvaluator : public SecondaryVariableFieldEvaluator { public: explicit InitialElevationEvaluator(Teuchos::ParameterList& plist); InitialElevationEvaluator(const InitialElevationEvaluator& other); Teuchos::RCP<FieldEvaluator> Clone() const; protected: // Required methods from SecondaryVariableFieldEvaluator virtual void EvaluateField_(const Teuchos::Ptr<State>& S, const Teuchos::Ptr<CompositeVector>& result); virtual void EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S, Key wrt_key, const Teuchos::Ptr<CompositeVector>& result); virtual bool HasFieldChanged(const Teuchos::Ptr<State>& S, Key request); virtual void EnsureCompatibility(const Teuchos::Ptr<State>& S); bool updated_once_; Key domain_; Key bp_key_; private: static Utils::RegisteredFactory<FieldEvaluator,InitialElevationEvaluator> reg_; }; } //namespace } //namespace #endif <commit_msg>fixes mismatched pragma hh protection<commit_after>/* -*- mode: c++; indent-tabs-mode: nil -*- */ /* The thaw depth evaluator gets the subsurface temperature. This computes the thaw depth over time. This is SecondaryVariablesFieldEvaluator and depends on the subsurface temperature, Authors: Ahmad Jan ([email protected]) */ #pragma once #include "Factory.hh" #include "secondary_variable_field_evaluator.hh" namespace Amanzi { namespace Flow { class InitialElevationEvaluator : public SecondaryVariableFieldEvaluator { public: explicit InitialElevationEvaluator(Teuchos::ParameterList& plist); InitialElevationEvaluator(const InitialElevationEvaluator& other); Teuchos::RCP<FieldEvaluator> Clone() const; protected: // Required methods from SecondaryVariableFieldEvaluator virtual void EvaluateField_(const Teuchos::Ptr<State>& S, const Teuchos::Ptr<CompositeVector>& result); virtual void EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S, Key wrt_key, const Teuchos::Ptr<CompositeVector>& result); virtual bool HasFieldChanged(const Teuchos::Ptr<State>& S, Key request); virtual void EnsureCompatibility(const Teuchos::Ptr<State>& S); bool updated_once_; Key domain_; Key bp_key_; private: static Utils::RegisteredFactory<FieldEvaluator,InitialElevationEvaluator> reg_; }; } //namespace } //namespace <|endoftext|>
<commit_before>/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module_typedefs.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/compile_assert.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/system_wrappers/interface/thread_annotations.h" #include "webrtc/system_wrappers/interface/thread_wrapper.h" #include "webrtc/test/testsupport/gtest_disable.h" namespace webrtc { const int kSampleRateHz = 16000; const int kNumSamples10ms = kSampleRateHz / 100; const int kFrameSizeMs = 10; // Multiple of 10. const int kFrameSizeSamples = kFrameSizeMs / 10 * kNumSamples10ms; const int kPayloadSizeBytes = kFrameSizeSamples * sizeof(int16_t); const uint8_t kPayloadType = 111; class RtpUtility { public: RtpUtility(int samples_per_packet, uint8_t payload_type) : samples_per_packet_(samples_per_packet), payload_type_(payload_type) {} virtual ~RtpUtility() {} void Populate(WebRtcRTPHeader* rtp_header) { rtp_header->header.sequenceNumber = 0xABCD; rtp_header->header.timestamp = 0xABCDEF01; rtp_header->header.payloadType = payload_type_; rtp_header->header.markerBit = false; rtp_header->header.ssrc = 0x1234; rtp_header->header.numCSRCs = 0; rtp_header->frameType = kAudioFrameSpeech; rtp_header->header.payload_type_frequency = kSampleRateHz; rtp_header->type.Audio.channel = 1; rtp_header->type.Audio.isCNG = false; } void Forward(WebRtcRTPHeader* rtp_header) { ++rtp_header->header.sequenceNumber; rtp_header->header.timestamp += samples_per_packet_; } private: int samples_per_packet_; uint8_t payload_type_; }; class PacketizationCallbackStub : public AudioPacketizationCallback { public: PacketizationCallbackStub() : num_calls_(0), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()) {} virtual int32_t SendData( FrameType frame_type, uint8_t payload_type, uint32_t timestamp, const uint8_t* payload_data, uint16_t payload_len_bytes, const RTPFragmentationHeader* fragmentation) OVERRIDE { CriticalSectionScoped lock(crit_sect_.get()); ++num_calls_; return 0; } int num_calls() const { CriticalSectionScoped lock(crit_sect_.get()); return num_calls_; } private: int num_calls_ GUARDED_BY(crit_sect_); const scoped_ptr<CriticalSectionWrapper> crit_sect_; }; class AudioCodingModuleTest : public ::testing::Test { protected: AudioCodingModuleTest() : id_(1), rtp_utility_(new RtpUtility(kFrameSizeSamples, kPayloadType)), clock_(Clock::GetRealTimeClock()) {} ~AudioCodingModuleTest() {} void TearDown() {} void SetUp() { acm_.reset(AudioCodingModule::Create(id_, clock_)); AudioCodingModule::Codec("L16", &codec_, kSampleRateHz, 1); codec_.pltype = kPayloadType; // Register L16 codec in ACM. ASSERT_EQ(0, acm_->RegisterReceiveCodec(codec_)); ASSERT_EQ(0, acm_->RegisterSendCodec(codec_)); rtp_utility_->Populate(&rtp_header_); input_frame_.sample_rate_hz_ = kSampleRateHz; input_frame_.samples_per_channel_ = kSampleRateHz * 10 / 1000; // 10 ms. COMPILE_ASSERT(kSampleRateHz * 10 / 1000 <= AudioFrame::kMaxDataSizeSamples, audio_frame_too_small); memset(input_frame_.data_, 0, input_frame_.samples_per_channel_ * sizeof(input_frame_.data_[0])); ASSERT_EQ(0, acm_->RegisterTransportCallback(&packet_cb_)); } void InsertPacketAndPullAudio() { InsertPacket(); PullAudio(); } void InsertPacket() { const uint8_t kPayload[kPayloadSizeBytes] = {0}; ASSERT_EQ(0, acm_->IncomingPacket(kPayload, kPayloadSizeBytes, rtp_header_)); rtp_utility_->Forward(&rtp_header_); } void PullAudio() { AudioFrame audio_frame; ASSERT_EQ(0, acm_->PlayoutData10Ms(-1, &audio_frame)); } void InsertAudio() { ASSERT_EQ(0, acm_->Add10MsData(input_frame_)); } void Encode() { int32_t encoded_bytes = acm_->Process(); // Expect to get one packet with two bytes per sample, or no packet at all, // depending on how many 10 ms blocks go into |codec_.pacsize|. EXPECT_TRUE(encoded_bytes == 2 * codec_.pacsize || encoded_bytes == 0); } const int id_; scoped_ptr<RtpUtility> rtp_utility_; scoped_ptr<AudioCodingModule> acm_; PacketizationCallbackStub packet_cb_; WebRtcRTPHeader rtp_header_; AudioFrame input_frame_; CodecInst codec_; Clock* clock_; }; // Check if the statistics are initialized correctly. Before any call to ACM // all fields have to be zero. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(InitializedToZero)) { AudioDecodingCallStats stats; acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(0, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(0, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); } // Apply an initial playout delay. Calls to AudioCodingModule::PlayoutData10ms() // should result in generating silence, check the associated field. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(SilenceGeneratorCalled)) { AudioDecodingCallStats stats; const int kInitialDelay = 100; acm_->SetInitialPlayoutDelay(kInitialDelay); int num_calls = 0; for (int time_ms = 0; time_ms < kInitialDelay; time_ms += kFrameSizeMs, ++num_calls) { InsertPacketAndPullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(0, stats.calls_to_neteq); EXPECT_EQ(num_calls, stats.calls_to_silence_generator); EXPECT_EQ(0, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); } // Insert some packets and pull audio. Check statistics are valid. Then, // simulate packet loss and check if PLC and PLC-to-CNG statistics are // correctly updated. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(NetEqCalls)) { AudioDecodingCallStats stats; const int kNumNormalCalls = 10; for (int num_calls = 0; num_calls < kNumNormalCalls; ++num_calls) { InsertPacketAndPullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(kNumNormalCalls, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(kNumNormalCalls, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); const int kNumPlc = 3; const int kNumPlcCng = 5; // Simulate packet-loss. NetEq first performs PLC then PLC fades to CNG. for (int n = 0; n < kNumPlc + kNumPlcCng; ++n) { PullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(kNumNormalCalls + kNumPlc + kNumPlcCng, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(kNumNormalCalls, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(kNumPlc, stats.decoded_plc); EXPECT_EQ(kNumPlcCng, stats.decoded_plc_cng); } TEST_F(AudioCodingModuleTest, VerifyOutputFrame) { AudioFrame audio_frame; const int kSampleRateHz = 32000; EXPECT_EQ(0, acm_->PlayoutData10Ms(kSampleRateHz, &audio_frame)); EXPECT_EQ(id_, audio_frame.id_); EXPECT_EQ(0u, audio_frame.timestamp_); EXPECT_GT(audio_frame.num_channels_, 0); EXPECT_EQ(kSampleRateHz / 100, audio_frame.samples_per_channel_); EXPECT_EQ(kSampleRateHz, audio_frame.sample_rate_hz_); } TEST_F(AudioCodingModuleTest, FailOnZeroDesiredFrequency) { AudioFrame audio_frame; EXPECT_EQ(-1, acm_->PlayoutData10Ms(0, &audio_frame)); } class AudioCodingModuleMtTest : public AudioCodingModuleTest { protected: static const int kNumPackets = 10000; static const int kNumPullCalls = 10000; AudioCodingModuleMtTest() : AudioCodingModuleTest(), send_thread_(ThreadWrapper::CreateThread(CbSendThread, this, kRealtimePriority, "send")), insert_packet_thread_(ThreadWrapper::CreateThread(CbInsertPacketThread, this, kRealtimePriority, "insert_packet")), pull_audio_thread_(ThreadWrapper::CreateThread(CbPullAudioThread, this, kRealtimePriority, "pull_audio")), test_complete_(EventWrapper::Create()), send_count_(0), insert_packet_count_(0), pull_audio_count_(0), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), next_insert_packet_time_ms_(0), fake_clock_(new SimulatedClock(0)) { clock_ = fake_clock_; } ~AudioCodingModuleMtTest() {} void SetUp() { AudioCodingModuleTest::SetUp(); unsigned int thread_id = 0; ASSERT_TRUE(send_thread_->Start(thread_id)); ASSERT_TRUE(insert_packet_thread_->Start(thread_id)); ASSERT_TRUE(pull_audio_thread_->Start(thread_id)); } void TearDown() { AudioCodingModuleTest::TearDown(); pull_audio_thread_->Stop(); send_thread_->Stop(); insert_packet_thread_->Stop(); } EventTypeWrapper RunTest() { return test_complete_->Wait(60000); } private: static bool CbSendThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context)->CbSendImpl(); } // The send thread doesn't have to care about the current simulated time, // since only the AcmReceiver is using the clock. bool CbSendImpl() { ++send_count_; InsertAudio(); Encode(); if (packet_cb_.num_calls() > kNumPackets) { CriticalSectionScoped lock(crit_sect_.get()); if (pull_audio_count_ > kNumPullCalls) { // Both conditions for completion are met. End the test. test_complete_->Set(); } } return true; } static bool CbInsertPacketThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context) ->CbInsertPacketImpl(); } bool CbInsertPacketImpl() { { CriticalSectionScoped lock(crit_sect_.get()); if (clock_->TimeInMilliseconds() < next_insert_packet_time_ms_) { return true; } next_insert_packet_time_ms_ += 10; } // Now we're not holding the crit sect when calling ACM. ++insert_packet_count_; InsertPacket(); return true; } static bool CbPullAudioThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context) ->CbPullAudioImpl(); } bool CbPullAudioImpl() { { CriticalSectionScoped lock(crit_sect_.get()); // Don't let the insert thread fall behind. if (next_insert_packet_time_ms_ < clock_->TimeInMilliseconds()) { return true; } ++pull_audio_count_; } // Now we're not holding the crit sect when calling ACM. PullAudio(); fake_clock_->AdvanceTimeMilliseconds(10); return true; } scoped_ptr<ThreadWrapper> send_thread_; scoped_ptr<ThreadWrapper> insert_packet_thread_; scoped_ptr<ThreadWrapper> pull_audio_thread_; const scoped_ptr<EventWrapper> test_complete_; int send_count_; int insert_packet_count_; int pull_audio_count_ GUARDED_BY(crit_sect_); const scoped_ptr<CriticalSectionWrapper> crit_sect_; int64_t next_insert_packet_time_ms_ GUARDED_BY(crit_sect_); SimulatedClock* fake_clock_; }; TEST_F(AudioCodingModuleMtTest, DoTest) { EXPECT_EQ(kEventSignaled, RunTest()); } } // namespace webrtc <commit_msg>Disable AudioCodingModuleMtTest due to memcheck and tsan failures.<commit_after>/* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module.h" #include "webrtc/modules/audio_coding/main/interface/audio_coding_module_typedefs.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/compile_assert.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" #include "webrtc/system_wrappers/interface/thread_annotations.h" #include "webrtc/system_wrappers/interface/thread_wrapper.h" #include "webrtc/test/testsupport/gtest_disable.h" namespace webrtc { const int kSampleRateHz = 16000; const int kNumSamples10ms = kSampleRateHz / 100; const int kFrameSizeMs = 10; // Multiple of 10. const int kFrameSizeSamples = kFrameSizeMs / 10 * kNumSamples10ms; const int kPayloadSizeBytes = kFrameSizeSamples * sizeof(int16_t); const uint8_t kPayloadType = 111; class RtpUtility { public: RtpUtility(int samples_per_packet, uint8_t payload_type) : samples_per_packet_(samples_per_packet), payload_type_(payload_type) {} virtual ~RtpUtility() {} void Populate(WebRtcRTPHeader* rtp_header) { rtp_header->header.sequenceNumber = 0xABCD; rtp_header->header.timestamp = 0xABCDEF01; rtp_header->header.payloadType = payload_type_; rtp_header->header.markerBit = false; rtp_header->header.ssrc = 0x1234; rtp_header->header.numCSRCs = 0; rtp_header->frameType = kAudioFrameSpeech; rtp_header->header.payload_type_frequency = kSampleRateHz; rtp_header->type.Audio.channel = 1; rtp_header->type.Audio.isCNG = false; } void Forward(WebRtcRTPHeader* rtp_header) { ++rtp_header->header.sequenceNumber; rtp_header->header.timestamp += samples_per_packet_; } private: int samples_per_packet_; uint8_t payload_type_; }; class PacketizationCallbackStub : public AudioPacketizationCallback { public: PacketizationCallbackStub() : num_calls_(0), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()) {} virtual int32_t SendData( FrameType frame_type, uint8_t payload_type, uint32_t timestamp, const uint8_t* payload_data, uint16_t payload_len_bytes, const RTPFragmentationHeader* fragmentation) OVERRIDE { CriticalSectionScoped lock(crit_sect_.get()); ++num_calls_; return 0; } int num_calls() const { CriticalSectionScoped lock(crit_sect_.get()); return num_calls_; } private: int num_calls_ GUARDED_BY(crit_sect_); const scoped_ptr<CriticalSectionWrapper> crit_sect_; }; class AudioCodingModuleTest : public ::testing::Test { protected: AudioCodingModuleTest() : id_(1), rtp_utility_(new RtpUtility(kFrameSizeSamples, kPayloadType)), clock_(Clock::GetRealTimeClock()) {} ~AudioCodingModuleTest() {} void TearDown() {} void SetUp() { acm_.reset(AudioCodingModule::Create(id_, clock_)); AudioCodingModule::Codec("L16", &codec_, kSampleRateHz, 1); codec_.pltype = kPayloadType; // Register L16 codec in ACM. ASSERT_EQ(0, acm_->RegisterReceiveCodec(codec_)); ASSERT_EQ(0, acm_->RegisterSendCodec(codec_)); rtp_utility_->Populate(&rtp_header_); input_frame_.sample_rate_hz_ = kSampleRateHz; input_frame_.samples_per_channel_ = kSampleRateHz * 10 / 1000; // 10 ms. COMPILE_ASSERT(kSampleRateHz * 10 / 1000 <= AudioFrame::kMaxDataSizeSamples, audio_frame_too_small); memset(input_frame_.data_, 0, input_frame_.samples_per_channel_ * sizeof(input_frame_.data_[0])); ASSERT_EQ(0, acm_->RegisterTransportCallback(&packet_cb_)); } void InsertPacketAndPullAudio() { InsertPacket(); PullAudio(); } void InsertPacket() { const uint8_t kPayload[kPayloadSizeBytes] = {0}; ASSERT_EQ(0, acm_->IncomingPacket(kPayload, kPayloadSizeBytes, rtp_header_)); rtp_utility_->Forward(&rtp_header_); } void PullAudio() { AudioFrame audio_frame; ASSERT_EQ(0, acm_->PlayoutData10Ms(-1, &audio_frame)); } void InsertAudio() { ASSERT_EQ(0, acm_->Add10MsData(input_frame_)); } void Encode() { int32_t encoded_bytes = acm_->Process(); // Expect to get one packet with two bytes per sample, or no packet at all, // depending on how many 10 ms blocks go into |codec_.pacsize|. EXPECT_TRUE(encoded_bytes == 2 * codec_.pacsize || encoded_bytes == 0); } const int id_; scoped_ptr<RtpUtility> rtp_utility_; scoped_ptr<AudioCodingModule> acm_; PacketizationCallbackStub packet_cb_; WebRtcRTPHeader rtp_header_; AudioFrame input_frame_; CodecInst codec_; Clock* clock_; }; // Check if the statistics are initialized correctly. Before any call to ACM // all fields have to be zero. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(InitializedToZero)) { AudioDecodingCallStats stats; acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(0, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(0, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); } // Apply an initial playout delay. Calls to AudioCodingModule::PlayoutData10ms() // should result in generating silence, check the associated field. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(SilenceGeneratorCalled)) { AudioDecodingCallStats stats; const int kInitialDelay = 100; acm_->SetInitialPlayoutDelay(kInitialDelay); int num_calls = 0; for (int time_ms = 0; time_ms < kInitialDelay; time_ms += kFrameSizeMs, ++num_calls) { InsertPacketAndPullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(0, stats.calls_to_neteq); EXPECT_EQ(num_calls, stats.calls_to_silence_generator); EXPECT_EQ(0, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); } // Insert some packets and pull audio. Check statistics are valid. Then, // simulate packet loss and check if PLC and PLC-to-CNG statistics are // correctly updated. TEST_F(AudioCodingModuleTest, DISABLED_ON_ANDROID(NetEqCalls)) { AudioDecodingCallStats stats; const int kNumNormalCalls = 10; for (int num_calls = 0; num_calls < kNumNormalCalls; ++num_calls) { InsertPacketAndPullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(kNumNormalCalls, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(kNumNormalCalls, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(0, stats.decoded_plc); EXPECT_EQ(0, stats.decoded_plc_cng); const int kNumPlc = 3; const int kNumPlcCng = 5; // Simulate packet-loss. NetEq first performs PLC then PLC fades to CNG. for (int n = 0; n < kNumPlc + kNumPlcCng; ++n) { PullAudio(); } acm_->GetDecodingCallStatistics(&stats); EXPECT_EQ(kNumNormalCalls + kNumPlc + kNumPlcCng, stats.calls_to_neteq); EXPECT_EQ(0, stats.calls_to_silence_generator); EXPECT_EQ(kNumNormalCalls, stats.decoded_normal); EXPECT_EQ(0, stats.decoded_cng); EXPECT_EQ(kNumPlc, stats.decoded_plc); EXPECT_EQ(kNumPlcCng, stats.decoded_plc_cng); } TEST_F(AudioCodingModuleTest, VerifyOutputFrame) { AudioFrame audio_frame; const int kSampleRateHz = 32000; EXPECT_EQ(0, acm_->PlayoutData10Ms(kSampleRateHz, &audio_frame)); EXPECT_EQ(id_, audio_frame.id_); EXPECT_EQ(0u, audio_frame.timestamp_); EXPECT_GT(audio_frame.num_channels_, 0); EXPECT_EQ(kSampleRateHz / 100, audio_frame.samples_per_channel_); EXPECT_EQ(kSampleRateHz, audio_frame.sample_rate_hz_); } TEST_F(AudioCodingModuleTest, FailOnZeroDesiredFrequency) { AudioFrame audio_frame; EXPECT_EQ(-1, acm_->PlayoutData10Ms(0, &audio_frame)); } class AudioCodingModuleMtTest : public AudioCodingModuleTest { protected: static const int kNumPackets = 10000; static const int kNumPullCalls = 10000; AudioCodingModuleMtTest() : AudioCodingModuleTest(), send_thread_(ThreadWrapper::CreateThread(CbSendThread, this, kRealtimePriority, "send")), insert_packet_thread_(ThreadWrapper::CreateThread(CbInsertPacketThread, this, kRealtimePriority, "insert_packet")), pull_audio_thread_(ThreadWrapper::CreateThread(CbPullAudioThread, this, kRealtimePriority, "pull_audio")), test_complete_(EventWrapper::Create()), send_count_(0), insert_packet_count_(0), pull_audio_count_(0), crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), next_insert_packet_time_ms_(0), fake_clock_(new SimulatedClock(0)) { clock_ = fake_clock_; } ~AudioCodingModuleMtTest() {} void SetUp() { AudioCodingModuleTest::SetUp(); unsigned int thread_id = 0; ASSERT_TRUE(send_thread_->Start(thread_id)); ASSERT_TRUE(insert_packet_thread_->Start(thread_id)); ASSERT_TRUE(pull_audio_thread_->Start(thread_id)); } void TearDown() { AudioCodingModuleTest::TearDown(); pull_audio_thread_->Stop(); send_thread_->Stop(); insert_packet_thread_->Stop(); } EventTypeWrapper RunTest() { return test_complete_->Wait(60000); } private: static bool CbSendThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context)->CbSendImpl(); } // The send thread doesn't have to care about the current simulated time, // since only the AcmReceiver is using the clock. bool CbSendImpl() { ++send_count_; InsertAudio(); Encode(); if (packet_cb_.num_calls() > kNumPackets) { CriticalSectionScoped lock(crit_sect_.get()); if (pull_audio_count_ > kNumPullCalls) { // Both conditions for completion are met. End the test. test_complete_->Set(); } } return true; } static bool CbInsertPacketThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context) ->CbInsertPacketImpl(); } bool CbInsertPacketImpl() { { CriticalSectionScoped lock(crit_sect_.get()); if (clock_->TimeInMilliseconds() < next_insert_packet_time_ms_) { return true; } next_insert_packet_time_ms_ += 10; } // Now we're not holding the crit sect when calling ACM. ++insert_packet_count_; InsertPacket(); return true; } static bool CbPullAudioThread(void* context) { return reinterpret_cast<AudioCodingModuleMtTest*>(context) ->CbPullAudioImpl(); } bool CbPullAudioImpl() { { CriticalSectionScoped lock(crit_sect_.get()); // Don't let the insert thread fall behind. if (next_insert_packet_time_ms_ < clock_->TimeInMilliseconds()) { return true; } ++pull_audio_count_; } // Now we're not holding the crit sect when calling ACM. PullAudio(); fake_clock_->AdvanceTimeMilliseconds(10); return true; } scoped_ptr<ThreadWrapper> send_thread_; scoped_ptr<ThreadWrapper> insert_packet_thread_; scoped_ptr<ThreadWrapper> pull_audio_thread_; const scoped_ptr<EventWrapper> test_complete_; int send_count_; int insert_packet_count_; int pull_audio_count_ GUARDED_BY(crit_sect_); const scoped_ptr<CriticalSectionWrapper> crit_sect_; int64_t next_insert_packet_time_ms_ GUARDED_BY(crit_sect_); SimulatedClock* fake_clock_; }; TEST_F(AudioCodingModuleMtTest, DISABLED_DoTest) { EXPECT_EQ(kEventSignaled, RunTest()); } } // namespace webrtc <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/gem/protocol/wheel_speed_rpt_7a.h" #include "gtest/gtest.h" namespace apollo { namespace canbus { namespace gem { class Wheelspeedrpt7aTest : public ::testing::Test { public: virtual void SetUp() {} }; TEST_F(Wheelspeedrpt7aTest, reset) { Wheelspeedrpt7a wheelspeed; int32_t length = 8; ChassisDetail chassis_detail; uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14}; wheelspeed.Parse(bytes, length, &chassis_detail); EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\ .wheel_spd_rear_right(), 4884); EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\ .wheel_spd_rear_left(), 4370); EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\ .wheel_spd_front_right(), 772); EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\ .wheel_spd_front_left(), 258); } } // namespace gem } // namespace canbus } // namespace apollo <commit_msg>Update wheel_speed_rpt_7a_test.cc<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/canbus/vehicle/gem/protocol/wheel_speed_rpt_7a.h" #include "gtest/gtest.h" namespace apollo { namespace canbus { namespace gem { class Wheelspeedrpt7aTest : public ::testing::Test { public: virtual void SetUp() {} }; TEST_F(Wheelspeedrpt7aTest, reset) { Wheelspeedrpt7a wheelspeed; int32_t length = 8; ChassisDetail chassis_detail; uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14}; wheelspeed.Parse(bytes, length, &chassis_detail); EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\ .wheel_spd_rear_right(), 4884); EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\ .wheel_spd_rear_left(), 4370); EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\ .wheel_spd_front_right(), 772); EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\ .wheel_spd_front_left(), 258); } } // namespace gem } // namespace canbus } // namespace apollo <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "vsenvironmentdetector.h" #include <logging/translator.h> #include <tools/qbsassert.h> #include <tools/qttools.h> #include <tools/stringconstants.h> #include <tools/stringutils.h> #include <QtCore/qdebug.h> #include <QtCore/qdir.h> #include <QtCore/qprocess.h> #include <QtCore/qtemporaryfile.h> #include <QtCore/qtextstream.h> #ifdef Q_OS_WIN #include <QtCore/qt_windows.h> #include <shlobj.h> #endif namespace qbs { namespace Internal { static QString windowsSystem32Path() { #ifdef Q_OS_WIN wchar_t str[UNICODE_STRING_MAX_CHARS]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, 0, str))) return QString::fromUtf16(reinterpret_cast<ushort*>(str)); #endif return {}; } VsEnvironmentDetector::VsEnvironmentDetector(QString vcvarsallPath) : m_windowsSystemDirPath(windowsSystem32Path()) , m_vcvarsallPath(std::move(vcvarsallPath)) { } bool VsEnvironmentDetector::start(MSVC *msvc) { return start(std::vector<MSVC *>{ msvc }); } bool VsEnvironmentDetector::start(std::vector<MSVC *> msvcs) { std::sort(msvcs.begin(), msvcs.end(), [] (const MSVC *a, const MSVC *b) -> bool { return a->vcInstallPath < b->vcInstallPath; }); std::vector<MSVC *> compatibleMSVCs; QString lastVcInstallPath; bool someMSVCDetected = false; for (MSVC * const msvc : msvcs) { if (lastVcInstallPath != msvc->vcInstallPath) { lastVcInstallPath = msvc->vcInstallPath; if (!compatibleMSVCs.empty()) { if (startDetection(compatibleMSVCs)) someMSVCDetected = true; compatibleMSVCs.clear(); } } compatibleMSVCs.push_back(msvc); } if (startDetection(compatibleMSVCs)) someMSVCDetected = true; return someMSVCDetected; } QString VsEnvironmentDetector::findVcVarsAllBat(const MSVC &msvc, std::vector<QString> &searchedPaths) const { // ### We can only rely on MSVC.vcInstallPath being set // when this is called from utilitiesextension.cpp :-( // If we knew the vsInstallPath at this point we could just use that // instead of searching for vcvarsall.bat candidates. QDir dir(msvc.vcInstallPath); for (;;) { if (!dir.cdUp()) return {}; if (dir.dirName() == QLatin1String("VC")) break; } const QString vcvarsallbat = QStringLiteral("vcvarsall.bat"); QString path = vcvarsallbat; QString fullPath = dir.absoluteFilePath(path); if (dir.exists(path)) return fullPath; else searchedPaths.push_back(fullPath); path = QStringLiteral("Auxiliary/Build/") + vcvarsallbat; fullPath = dir.absoluteFilePath(path); if (dir.exists(path)) return fullPath; else searchedPaths.push_back(fullPath); return {}; } bool VsEnvironmentDetector::startDetection(const std::vector<MSVC *> &compatibleMSVCs) { std::vector<QString> searchedPaths; if (!m_vcvarsallPath.isEmpty() && !QFileInfo::exists(m_vcvarsallPath)) { m_errorString = Tr::tr("%1 does not exist.").arg(m_vcvarsallPath); return false; } const auto vcvarsallbat = !m_vcvarsallPath.isEmpty() ? m_vcvarsallPath : findVcVarsAllBat(**compatibleMSVCs.begin(), searchedPaths); if (vcvarsallbat.isEmpty()) { if (!searchedPaths.empty()) { m_errorString = Tr::tr( "Cannot find 'vcvarsall.bat' at any of the following locations:\n\t") + join(searchedPaths, QStringLiteral("\n\t")); } else { m_errorString = Tr::tr("Cannot find 'vcvarsall.bat'."); } return false; } QTemporaryFile tmpFile(QDir::tempPath() + QLatin1Char('/') + QStringLiteral("XXXXXX.bat")); if (!tmpFile.open()) { m_errorString = Tr::tr("Cannot open temporary file '%1' for writing.").arg( tmpFile.fileName()); return false; } writeBatchFile(&tmpFile, vcvarsallbat, compatibleMSVCs); tmpFile.flush(); QProcess process; static const QString shellFilePath = QStringLiteral("cmd.exe"); process.start(shellFilePath, QStringList() << QStringLiteral("/C") << tmpFile.fileName()); if (!process.waitForStarted()) { m_errorString = Tr::tr("Failed to start '%1'.").arg(shellFilePath); return false; } process.waitForFinished(-1); if (process.exitStatus() != QProcess::NormalExit) { m_errorString = Tr::tr("Process '%1' did not exit normally.").arg(shellFilePath); return false; } if (process.exitCode() != 0) { m_errorString = Tr::tr("Failed to detect Visual Studio environment."); return false; } parseBatOutput(process.readAllStandardOutput(), compatibleMSVCs); return true; } static void batClearVars(QTextStream &s, const QStringList &varnames) { for (const QString &varname : varnames) s << "set " << varname << '=' << Qt::endl; } static void batPrintVars(QTextStream &s, const QStringList &varnames) { for (const QString &varname : varnames) s << "echo " << varname << "=%" << varname << '%' << Qt::endl; } static QString vcArchitecture(const MSVC *msvc) { QString vcArch = msvc->architecture; if (msvc->architecture == StringConstants::armv7Arch()) vcArch = StringConstants::armArch(); if (msvc->architecture == StringConstants::x86_64Arch()) vcArch = StringConstants::amd64Arch(); const QString hostPrefixes[] = { StringConstants::x86Arch(), QStringLiteral("amd64_"), QStringLiteral("x86_") }; for (const QString &hostPrefix : hostPrefixes) { if (QFile::exists(msvc->clPathForArchitecture(hostPrefix + vcArch))) { vcArch.prepend(hostPrefix); break; } } return vcArch; } void VsEnvironmentDetector::writeBatchFile(QIODevice *device, const QString &vcvarsallbat, const std::vector<MSVC *> &msvcs) const { const QStringList varnames = QStringList() << StringConstants::pathEnvVar() << QStringLiteral("INCLUDE") << QStringLiteral("LIB") << QStringLiteral("WindowsSdkDir") << QStringLiteral("WindowsSDKVersion") << QStringLiteral("VSINSTALLDIR"); QTextStream s(device); using Qt::endl; s << "@echo off" << endl; // Avoid execution of powershell (in vsdevcmd.bat), which is not in the cleared PATH s << "set VSCMD_SKIP_SENDTELEMETRY=1" << endl; for (const MSVC *msvc : msvcs) { s << "echo --" << msvc->architecture << "--" << endl << "setlocal" << endl; batClearVars(s, varnames); s << "set PATH=" << m_windowsSystemDirPath << endl; // vcvarsall.bat needs tools from here s << "call \"" << vcvarsallbat << "\" " << vcArchitecture(msvc) << " || exit /b 1" << endl; batPrintVars(s, varnames); s << "endlocal" << endl; } } void VsEnvironmentDetector::parseBatOutput(const QByteArray &output, std::vector<MSVC *> msvcs) { QString arch; QProcessEnvironment *targetEnv = nullptr; const auto lines = output.split('\n'); for (QByteArray line : lines) { line = line.trimmed(); if (line.isEmpty()) continue; if (line.startsWith("--") && line.endsWith("--")) { line.remove(0, 2); line.chop(2); arch = QString::fromLocal8Bit(line); targetEnv = &msvcs.front()->environment; msvcs.erase(msvcs.begin()); } else { int idx = line.indexOf('='); if (idx < 0) continue; QBS_CHECK(targetEnv); const QString name = QString::fromLocal8Bit(line.left(idx)); QString value = QString::fromLocal8Bit(line.mid(idx + 1)); if (name.compare(StringConstants::pathEnvVar(), Qt::CaseInsensitive) == 0) value.remove(m_windowsSystemDirPath); if (value.endsWith(QLatin1Char(';'))) value.chop(1); if (value.endsWith(QLatin1Char('\\'))) value.chop(1); targetEnv->insert(name, value); } } } } // namespace Internal } // namespace qbs <commit_msg>Remove deleting trailing slash from VS env vars<commit_after>/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "vsenvironmentdetector.h" #include <logging/translator.h> #include <tools/qbsassert.h> #include <tools/qttools.h> #include <tools/stringconstants.h> #include <tools/stringutils.h> #include <QtCore/qdebug.h> #include <QtCore/qdir.h> #include <QtCore/qprocess.h> #include <QtCore/qtemporaryfile.h> #include <QtCore/qtextstream.h> #ifdef Q_OS_WIN #include <QtCore/qt_windows.h> #include <shlobj.h> #endif namespace qbs { namespace Internal { static QString windowsSystem32Path() { #ifdef Q_OS_WIN wchar_t str[UNICODE_STRING_MAX_CHARS]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, 0, str))) return QString::fromUtf16(reinterpret_cast<ushort*>(str)); #endif return {}; } VsEnvironmentDetector::VsEnvironmentDetector(QString vcvarsallPath) : m_windowsSystemDirPath(windowsSystem32Path()) , m_vcvarsallPath(std::move(vcvarsallPath)) { } bool VsEnvironmentDetector::start(MSVC *msvc) { return start(std::vector<MSVC *>{ msvc }); } bool VsEnvironmentDetector::start(std::vector<MSVC *> msvcs) { std::sort(msvcs.begin(), msvcs.end(), [] (const MSVC *a, const MSVC *b) -> bool { return a->vcInstallPath < b->vcInstallPath; }); std::vector<MSVC *> compatibleMSVCs; QString lastVcInstallPath; bool someMSVCDetected = false; for (MSVC * const msvc : msvcs) { if (lastVcInstallPath != msvc->vcInstallPath) { lastVcInstallPath = msvc->vcInstallPath; if (!compatibleMSVCs.empty()) { if (startDetection(compatibleMSVCs)) someMSVCDetected = true; compatibleMSVCs.clear(); } } compatibleMSVCs.push_back(msvc); } if (startDetection(compatibleMSVCs)) someMSVCDetected = true; return someMSVCDetected; } QString VsEnvironmentDetector::findVcVarsAllBat(const MSVC &msvc, std::vector<QString> &searchedPaths) const { // ### We can only rely on MSVC.vcInstallPath being set // when this is called from utilitiesextension.cpp :-( // If we knew the vsInstallPath at this point we could just use that // instead of searching for vcvarsall.bat candidates. QDir dir(msvc.vcInstallPath); for (;;) { if (!dir.cdUp()) return {}; if (dir.dirName() == QLatin1String("VC")) break; } const QString vcvarsallbat = QStringLiteral("vcvarsall.bat"); QString path = vcvarsallbat; QString fullPath = dir.absoluteFilePath(path); if (dir.exists(path)) return fullPath; else searchedPaths.push_back(fullPath); path = QStringLiteral("Auxiliary/Build/") + vcvarsallbat; fullPath = dir.absoluteFilePath(path); if (dir.exists(path)) return fullPath; else searchedPaths.push_back(fullPath); return {}; } bool VsEnvironmentDetector::startDetection(const std::vector<MSVC *> &compatibleMSVCs) { std::vector<QString> searchedPaths; if (!m_vcvarsallPath.isEmpty() && !QFileInfo::exists(m_vcvarsallPath)) { m_errorString = Tr::tr("%1 does not exist.").arg(m_vcvarsallPath); return false; } const auto vcvarsallbat = !m_vcvarsallPath.isEmpty() ? m_vcvarsallPath : findVcVarsAllBat(**compatibleMSVCs.begin(), searchedPaths); if (vcvarsallbat.isEmpty()) { if (!searchedPaths.empty()) { m_errorString = Tr::tr( "Cannot find 'vcvarsall.bat' at any of the following locations:\n\t") + join(searchedPaths, QStringLiteral("\n\t")); } else { m_errorString = Tr::tr("Cannot find 'vcvarsall.bat'."); } return false; } QTemporaryFile tmpFile(QDir::tempPath() + QLatin1Char('/') + QStringLiteral("XXXXXX.bat")); if (!tmpFile.open()) { m_errorString = Tr::tr("Cannot open temporary file '%1' for writing.").arg( tmpFile.fileName()); return false; } writeBatchFile(&tmpFile, vcvarsallbat, compatibleMSVCs); tmpFile.flush(); QProcess process; static const QString shellFilePath = QStringLiteral("cmd.exe"); process.start(shellFilePath, QStringList() << QStringLiteral("/C") << tmpFile.fileName()); if (!process.waitForStarted()) { m_errorString = Tr::tr("Failed to start '%1'.").arg(shellFilePath); return false; } process.waitForFinished(-1); if (process.exitStatus() != QProcess::NormalExit) { m_errorString = Tr::tr("Process '%1' did not exit normally.").arg(shellFilePath); return false; } if (process.exitCode() != 0) { m_errorString = Tr::tr("Failed to detect Visual Studio environment."); return false; } parseBatOutput(process.readAllStandardOutput(), compatibleMSVCs); return true; } static void batClearVars(QTextStream &s, const QStringList &varnames) { for (const QString &varname : varnames) s << "set " << varname << '=' << Qt::endl; } static void batPrintVars(QTextStream &s, const QStringList &varnames) { for (const QString &varname : varnames) s << "echo " << varname << "=%" << varname << '%' << Qt::endl; } static QString vcArchitecture(const MSVC *msvc) { QString vcArch = msvc->architecture; if (msvc->architecture == StringConstants::armv7Arch()) vcArch = StringConstants::armArch(); if (msvc->architecture == StringConstants::x86_64Arch()) vcArch = StringConstants::amd64Arch(); const QString hostPrefixes[] = { StringConstants::x86Arch(), QStringLiteral("amd64_"), QStringLiteral("x86_") }; for (const QString &hostPrefix : hostPrefixes) { if (QFile::exists(msvc->clPathForArchitecture(hostPrefix + vcArch))) { vcArch.prepend(hostPrefix); break; } } return vcArch; } void VsEnvironmentDetector::writeBatchFile(QIODevice *device, const QString &vcvarsallbat, const std::vector<MSVC *> &msvcs) const { const QStringList varnames = QStringList() << StringConstants::pathEnvVar() << QStringLiteral("INCLUDE") << QStringLiteral("LIB") << QStringLiteral("WindowsSdkDir") << QStringLiteral("WindowsSDKVersion") << QStringLiteral("VSINSTALLDIR"); QTextStream s(device); using Qt::endl; s << "@echo off" << endl; // Avoid execution of powershell (in vsdevcmd.bat), which is not in the cleared PATH s << "set VSCMD_SKIP_SENDTELEMETRY=1" << endl; for (const MSVC *msvc : msvcs) { s << "echo --" << msvc->architecture << "--" << endl << "setlocal" << endl; batClearVars(s, varnames); s << "set PATH=" << m_windowsSystemDirPath << endl; // vcvarsall.bat needs tools from here s << "call \"" << vcvarsallbat << "\" " << vcArchitecture(msvc) << " || exit /b 1" << endl; batPrintVars(s, varnames); s << "endlocal" << endl; } } void VsEnvironmentDetector::parseBatOutput(const QByteArray &output, std::vector<MSVC *> msvcs) { QString arch; QProcessEnvironment *targetEnv = nullptr; const auto lines = output.split('\n'); for (QByteArray line : lines) { line = line.trimmed(); if (line.isEmpty()) continue; if (line.startsWith("--") && line.endsWith("--")) { line.remove(0, 2); line.chop(2); arch = QString::fromLocal8Bit(line); targetEnv = &msvcs.front()->environment; msvcs.erase(msvcs.begin()); } else { int idx = line.indexOf('='); if (idx < 0) continue; QBS_CHECK(targetEnv); const QString name = QString::fromLocal8Bit(line.left(idx)); QString value = QString::fromLocal8Bit(line.mid(idx + 1)); if (name.compare(StringConstants::pathEnvVar(), Qt::CaseInsensitive) == 0) value.remove(m_windowsSystemDirPath); if (value.endsWith(QLatin1Char(';'))) value.chop(1); targetEnv->insert(name, value); } } } } // namespace Internal } // namespace qbs <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file data_validator_group.cpp * * A data validation group to identify anomalies in data streams * * @author Lorenz Meier <[email protected]> */ #include "data_validator_group.h" #include <ecl/ecl.h> DataValidatorGroup::DataValidatorGroup(unsigned siblings) : _first(nullptr), _curr_best(-1), _prev_best(-1), _first_failover_time(0), _toggle_count(0) { DataValidator *next = _first; for (unsigned i = 0; i < siblings; i++) { next = new DataValidator(next); } _first = next; } DataValidatorGroup::~DataValidatorGroup() { } void DataValidatorGroup::set_timeout(uint64_t timeout_interval_us) { DataValidator *next = _first; while (next != nullptr) { next->set_timeout(timeout_interval_us); next = next->sibling(); } } void DataValidatorGroup::put(unsigned index, uint64_t timestamp, float val[3], uint64_t error_count, int priority) { DataValidator *next = _first; unsigned i = 0; while (next != nullptr) { if (i == index) { next->put(timestamp, val, error_count, priority); break; } next = next->sibling(); i++; } } float* DataValidatorGroup::get_best(uint64_t timestamp, int *index) { DataValidator *next = _first; // XXX This should eventually also include voting int pre_check_best = _curr_best; float pre_check_confidence = 1.0f; int pre_check_prio = -1; float max_confidence = -1.0f; int max_priority = -1000; int max_index = -1; DataValidator *best = nullptr; unsigned i = 0; while (next != nullptr) { float confidence = next->confidence(timestamp); if (i == pre_check_best) { pre_check_prio = next->priority(); pre_check_confidence = confidence; } /* * Switch if: * 1) the confidence is higher and priority is equal or higher * 2) the confidence is no less than 1% different and the priority is higher */ if (((max_confidence < MIN_REGULAR_CONFIDENCE) && (confidence >= MIN_REGULAR_CONFIDENCE)) || (confidence > max_confidence && (next->priority() >= max_priority)) || (fabsf(confidence - max_confidence) < 0.01f && (next->priority() > max_priority)) ) { max_index = i; max_confidence = confidence; max_priority = next->priority(); best = next; } next = next->sibling(); i++; } /* the current best sensor is not matching the previous best sensor */ if (max_index != _curr_best) { bool true_failsafe = true; /* check wether the switch was a failsafe or preferring a higher priority sensor */ if (pre_check_prio != -1 && pre_check_prio < max_priority && fabsf(pre_check_confidence - max_confidence) < 0.1f) { /* this is not a failover */ true_failsafe = false; } /* if we're no initialized, initialize the bookkeeping but do not count a failsafe */ if (_curr_best < 0) { _prev_best = max_index; } else { /* we were initialized before, this is a real failsafe */ _prev_best = pre_check_best; if (true_failsafe) { _toggle_count++; /* if this is the first time, log when we failed */ if (_first_failover_time == 0) { _first_failover_time = timestamp; } } } /* for all cases we want to keep a record of the best index */ _curr_best = max_index; } *index = max_index; return (best) ? best->value() : nullptr; } float DataValidatorGroup::get_vibration_factor(uint64_t timestamp) { DataValidator *next = _first; float vibe = 0.0f; /* find the best RMS value of a non-timed out sensor */ while (next != nullptr) { if (next->confidence(timestamp) > 0.5f) { float* rms = next->rms(); for (unsigned j = 0; j < 3; j++) { if (rms[j] > vibe) { vibe = rms[j]; } } } next = next->sibling(); } return vibe; } void DataValidatorGroup::print() { /* print the group's state */ ECL_INFO("validator: best: %d, prev best: %d, failsafe: %s (# %u)", _curr_best, _prev_best, (_toggle_count > 0) ? "YES" : "NO", _toggle_count); DataValidator *next = _first; unsigned i = 0; while (next != nullptr) { if (next->used()) { ECL_INFO("sensor #%u, prio: %d", i, next->priority()); next->print(); } next = next->sibling(); i++; } } unsigned DataValidatorGroup::failover_count() { return _toggle_count; } <commit_msg>Data validator: Fix compile warning on signedness<commit_after>/**************************************************************************** * * Copyright (c) 2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file data_validator_group.cpp * * A data validation group to identify anomalies in data streams * * @author Lorenz Meier <[email protected]> */ #include "data_validator_group.h" #include <ecl/ecl.h> DataValidatorGroup::DataValidatorGroup(unsigned siblings) : _first(nullptr), _curr_best(-1), _prev_best(-1), _first_failover_time(0), _toggle_count(0) { DataValidator *next = _first; for (unsigned i = 0; i < siblings; i++) { next = new DataValidator(next); } _first = next; } DataValidatorGroup::~DataValidatorGroup() { } void DataValidatorGroup::set_timeout(uint64_t timeout_interval_us) { DataValidator *next = _first; while (next != nullptr) { next->set_timeout(timeout_interval_us); next = next->sibling(); } } void DataValidatorGroup::put(unsigned index, uint64_t timestamp, float val[3], uint64_t error_count, int priority) { DataValidator *next = _first; unsigned i = 0; while (next != nullptr) { if (i == index) { next->put(timestamp, val, error_count, priority); break; } next = next->sibling(); i++; } } float* DataValidatorGroup::get_best(uint64_t timestamp, int *index) { DataValidator *next = _first; // XXX This should eventually also include voting int pre_check_best = _curr_best; float pre_check_confidence = 1.0f; int pre_check_prio = -1; float max_confidence = -1.0f; int max_priority = -1000; int max_index = -1; DataValidator *best = nullptr; unsigned i = 0; while (next != nullptr) { float confidence = next->confidence(timestamp); if (static_cast<int>(i) == pre_check_best) { pre_check_prio = next->priority(); pre_check_confidence = confidence; } /* * Switch if: * 1) the confidence is higher and priority is equal or higher * 2) the confidence is no less than 1% different and the priority is higher */ if (((max_confidence < MIN_REGULAR_CONFIDENCE) && (confidence >= MIN_REGULAR_CONFIDENCE)) || (confidence > max_confidence && (next->priority() >= max_priority)) || (fabsf(confidence - max_confidence) < 0.01f && (next->priority() > max_priority)) ) { max_index = i; max_confidence = confidence; max_priority = next->priority(); best = next; } next = next->sibling(); i++; } /* the current best sensor is not matching the previous best sensor */ if (max_index != _curr_best) { bool true_failsafe = true; /* check wether the switch was a failsafe or preferring a higher priority sensor */ if (pre_check_prio != -1 && pre_check_prio < max_priority && fabsf(pre_check_confidence - max_confidence) < 0.1f) { /* this is not a failover */ true_failsafe = false; } /* if we're no initialized, initialize the bookkeeping but do not count a failsafe */ if (_curr_best < 0) { _prev_best = max_index; } else { /* we were initialized before, this is a real failsafe */ _prev_best = pre_check_best; if (true_failsafe) { _toggle_count++; /* if this is the first time, log when we failed */ if (_first_failover_time == 0) { _first_failover_time = timestamp; } } } /* for all cases we want to keep a record of the best index */ _curr_best = max_index; } *index = max_index; return (best) ? best->value() : nullptr; } float DataValidatorGroup::get_vibration_factor(uint64_t timestamp) { DataValidator *next = _first; float vibe = 0.0f; /* find the best RMS value of a non-timed out sensor */ while (next != nullptr) { if (next->confidence(timestamp) > 0.5f) { float* rms = next->rms(); for (unsigned j = 0; j < 3; j++) { if (rms[j] > vibe) { vibe = rms[j]; } } } next = next->sibling(); } return vibe; } void DataValidatorGroup::print() { /* print the group's state */ ECL_INFO("validator: best: %d, prev best: %d, failsafe: %s (# %u)", _curr_best, _prev_best, (_toggle_count > 0) ? "YES" : "NO", _toggle_count); DataValidator *next = _first; unsigned i = 0; while (next != nullptr) { if (next->used()) { ECL_INFO("sensor #%u, prio: %d", i, next->priority()); next->print(); } next = next->sibling(); i++; } } unsigned DataValidatorGroup::failover_count() { return _toggle_count; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractSelectedRows.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkExtractSelectedRows.h" #include "vtkAnnotation.h" #include "vtkAnnotationLayers.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCommand.h" #include "vtkConvertSelection.h" #include "vtkDataArray.h" #include "vtkEdgeListIterator.h" #include "vtkEventForwarderCommand.h" #include "vtkExtractSelection.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSignedCharArray.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkTree.h" #include "vtkVertexListIterator.h" #include <vtksys/stl/map> #include <vtkstd/vector> vtkCxxRevisionMacro(vtkExtractSelectedRows, "1.1"); vtkStandardNewMacro(vtkExtractSelectedRows); //---------------------------------------------------------------------------- vtkExtractSelectedRows::vtkExtractSelectedRows() { this->AddOriginalRowIdsArray = false; this->SetNumberOfInputPorts(3); } //---------------------------------------------------------------------------- vtkExtractSelectedRows::~vtkExtractSelectedRows() { } //---------------------------------------------------------------------------- int vtkExtractSelectedRows::FillInputPortInformation(int port, vtkInformation* info) { if (port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable"); return 1; } else if (port == 1) { info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection"); return 1; } else if (port == 2) { info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkAnnotationLayers"); return 1; } return 0; } //---------------------------------------------------------------------------- void vtkExtractSelectedRows::SetSelectionConnection(vtkAlgorithmOutput* in) { this->SetInputConnection(1, in); } //---------------------------------------------------------------------------- void vtkExtractSelectedRows::SetAnnotationLayersConnection(vtkAlgorithmOutput* in) { this->SetInputConnection(2, in); } //---------------------------------------------------------------------------- int vtkExtractSelectedRows::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkTable* input = vtkTable::GetData(inputVector[0]); vtkSelection* inputSelection = vtkSelection::GetData(inputVector[1]); vtkAnnotationLayers* inputAnnotations = vtkAnnotationLayers::GetData(inputVector[2]); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkTable* output = vtkTable::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); if(!inputSelection && !inputAnnotations) { vtkErrorMacro("No vtkSelection or vtkAnnotationLayers provided as input."); return 0; } vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New(); int numSelections = 0; if(inputSelection) { selection->DeepCopy(inputSelection); numSelections++; } // If input annotations are provided, extract their selections only if // they are enabled and not hidden. if(inputAnnotations) { for(unsigned int i=0; i<inputAnnotations->GetNumberOfAnnotations(); ++i) { vtkAnnotation* a = inputAnnotations->GetAnnotation(i); if ((a->GetInformation()->Has(vtkAnnotation::ENABLE()) && a->GetInformation()->Get(vtkAnnotation::ENABLE())==0) || (a->GetInformation()->Has(vtkAnnotation::ENABLE()) && a->GetInformation()->Get(vtkAnnotation::ENABLE())==1 && a->GetInformation()->Has(vtkAnnotation::HIDE()) && a->GetInformation()->Get(vtkAnnotation::HIDE())==0)) { continue; } selection->Union(a->GetSelection()); numSelections++; } } // Handle case where there was no input selection and no enabled, non-hidden // annotations if(numSelections == 0) { output->ShallowCopy(input); return 1; } // Convert the selection to an INDICES selection vtkSmartPointer<vtkSelection> converted; converted.TakeReference(vtkConvertSelection::ToSelectionType( selection, input, vtkSelectionNode::INDICES, 0, vtkSelectionNode::ROW)); if (!converted.GetPointer()) { vtkErrorMacro("Selection conversion to INDICES failed."); return 0; } vtkIdTypeArray* originalRowIds = vtkIdTypeArray::New(); originalRowIds->SetName("vtkOriginalRowIds"); output->GetRowData()->CopyStructure(input->GetRowData()); for (unsigned int i = 0; i < converted->GetNumberOfNodes(); ++i) { vtkSelectionNode* node = converted->GetNode(i); if (node->GetFieldType() == vtkSelectionNode::ROW) { vtkIdTypeArray* list = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); if (list) { vtkIdType numTuples = list->GetNumberOfTuples(); for (vtkIdType j = 0; j < numTuples; ++j) { vtkIdType val = list->GetValue(j); output->InsertNextRow(input->GetRow(val)); if (this->AddOriginalRowIdsArray) { originalRowIds->InsertNextValue(val); } } } } } if (this->AddOriginalRowIdsArray) { output->AddColumn(originalRowIds); } originalRowIds->Delete(); return 1; } //---------------------------------------------------------------------------- void vtkExtractSelectedRows::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "AddOriginalRowIdsArray: " << this->AddOriginalRowIdsArray << endl; } <commit_msg>BUG: don't segfault when trying to select from a vtkTable with 0 rows<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractSelectedRows.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkExtractSelectedRows.h" #include "vtkAnnotation.h" #include "vtkAnnotationLayers.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCommand.h" #include "vtkConvertSelection.h" #include "vtkDataArray.h" #include "vtkEdgeListIterator.h" #include "vtkEventForwarderCommand.h" #include "vtkExtractSelection.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSignedCharArray.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkTree.h" #include "vtkVertexListIterator.h" #include <vtksys/stl/map> #include <vtkstd/vector> vtkCxxRevisionMacro(vtkExtractSelectedRows, "1.2"); vtkStandardNewMacro(vtkExtractSelectedRows); //---------------------------------------------------------------------------- vtkExtractSelectedRows::vtkExtractSelectedRows() { this->AddOriginalRowIdsArray = false; this->SetNumberOfInputPorts(3); } //---------------------------------------------------------------------------- vtkExtractSelectedRows::~vtkExtractSelectedRows() { } //---------------------------------------------------------------------------- int vtkExtractSelectedRows::FillInputPortInformation(int port, vtkInformation* info) { if (port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable"); return 1; } else if (port == 1) { info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection"); return 1; } else if (port == 2) { info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkAnnotationLayers"); return 1; } return 0; } //---------------------------------------------------------------------------- void vtkExtractSelectedRows::SetSelectionConnection(vtkAlgorithmOutput* in) { this->SetInputConnection(1, in); } //---------------------------------------------------------------------------- void vtkExtractSelectedRows::SetAnnotationLayersConnection(vtkAlgorithmOutput* in) { this->SetInputConnection(2, in); } //---------------------------------------------------------------------------- int vtkExtractSelectedRows::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkTable* input = vtkTable::GetData(inputVector[0]); vtkSelection* inputSelection = vtkSelection::GetData(inputVector[1]); vtkAnnotationLayers* inputAnnotations = vtkAnnotationLayers::GetData(inputVector[2]); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkTable* output = vtkTable::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); if(!inputSelection && !inputAnnotations) { vtkErrorMacro("No vtkSelection or vtkAnnotationLayers provided as input."); return 0; } vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New(); int numSelections = 0; if(inputSelection) { selection->DeepCopy(inputSelection); numSelections++; } // If input annotations are provided, extract their selections only if // they are enabled and not hidden. if(inputAnnotations) { for(unsigned int i=0; i<inputAnnotations->GetNumberOfAnnotations(); ++i) { vtkAnnotation* a = inputAnnotations->GetAnnotation(i); if ((a->GetInformation()->Has(vtkAnnotation::ENABLE()) && a->GetInformation()->Get(vtkAnnotation::ENABLE())==0) || (a->GetInformation()->Has(vtkAnnotation::ENABLE()) && a->GetInformation()->Get(vtkAnnotation::ENABLE())==1 && a->GetInformation()->Has(vtkAnnotation::HIDE()) && a->GetInformation()->Get(vtkAnnotation::HIDE())==0)) { continue; } selection->Union(a->GetSelection()); numSelections++; } } // Handle case where there was no input selection and no enabled, non-hidden // annotations if(numSelections == 0) { output->ShallowCopy(input); return 1; } // Convert the selection to an INDICES selection vtkSmartPointer<vtkSelection> converted; converted.TakeReference(vtkConvertSelection::ToSelectionType( selection, input, vtkSelectionNode::INDICES, 0, vtkSelectionNode::ROW)); if (!converted.GetPointer()) { vtkErrorMacro("Selection conversion to INDICES failed."); return 0; } vtkIdTypeArray* originalRowIds = vtkIdTypeArray::New(); originalRowIds->SetName("vtkOriginalRowIds"); output->GetRowData()->CopyStructure(input->GetRowData()); //dodge segfault on empty tables if(converted->GetNumberOfNodes() > input->GetNumberOfRows()) { vtkErrorMacro("Attempting to select more rows than the table contains."); return 0; } for (unsigned int i = 0; i < converted->GetNumberOfNodes(); ++i) { vtkSelectionNode* node = converted->GetNode(i); if (node->GetFieldType() == vtkSelectionNode::ROW) { vtkIdTypeArray* list = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); if (list) { vtkIdType numTuples = list->GetNumberOfTuples(); for (vtkIdType j = 0; j < numTuples; ++j) { vtkIdType val = list->GetValue(j); output->InsertNextRow(input->GetRow(val)); if (this->AddOriginalRowIdsArray) { originalRowIds->InsertNextValue(val); } } } } } if (this->AddOriginalRowIdsArray) { output->AddColumn(originalRowIds); } originalRowIds->Delete(); return 1; } //---------------------------------------------------------------------------- void vtkExtractSelectedRows::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "AddOriginalRowIdsArray: " << this->AddOriginalRowIdsArray << endl; } <|endoftext|>
<commit_before>/* Copyright 2014 Adam Grandquist 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. */ /** * @author Adam Grandquist * @copyright Apache */ #include "ReQL-expr.hpp" #include "ReQL.hpp" #include <limits> namespace ReQL { Expr::Expr() { Query _val = expr(_reql_new_null()); sub_query.push_back(_val); query = _reql_new_datum(_val.query); } Expr::Expr(_ReQL_Op val) { query = val; } Expr::Expr(std::string val) { Query _val = expr(_reql_new_string(val)); sub_query.push_back(_val); query = _reql_new_datum(_val.query); } Expr::Expr(double val) { Query _val = expr(_reql_new_number(val)); sub_query.push_back(_val); query = _reql_new_datum(_val.query); } Expr::Expr(bool val) { Query _val = expr(_reql_new_bool(val)); sub_query.push_back(_val); query = _reql_new_datum(_val.query); } Expr::Expr(std::vector<Query> val) { if (val.size() > std::numeric_limits<std::uint32_t>::max()) { throw; } sub_query.assign(val.begin(), val.end()); Query _val = expr(_reql_new_array(static_cast<std::uint32_t>(val.size()))); sub_query.push_back(_val); for (auto iter=val.cbegin(); iter!=val.cend(); ++iter) { _reql_array_append(_val.query, iter->query); } query = _reql_new_make_array(_val.query); } Expr::Expr(std::map<std::string, Query> val) { if (val.size() > std::numeric_limits<std::uint32_t>::max()) { throw; } Query _val = expr(_reql_new_object(static_cast<std::uint32_t>(val.size()))); sub_query.push_back(_val); for (auto iter=val.cbegin(); iter!=val.cend(); ++iter) { Query key(iter->first); sub_query.push_back(key); sub_query.push_back(iter->second); _reql_object_add(_val.query, key.query, iter->second.query); } query = _reql_new_make_obj(_val.query); } Expr::~Expr() { delete query; } Query expr() { return Query(); } Query expr(_ReQL_Op val) { return Query(val); } Query expr(std::string val) { return Query(val); } Query expr(double val) { return Query(val); } Query expr(bool val) { return Query(val); } Query expr(std::vector<Query> val) { return Query(val); } Query expr(std::map<std::string, Query> val) { return Query(val); } } <commit_msg>Catch and delete values that don't get owned properly.<commit_after>/* Copyright 2014 Adam Grandquist 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. */ /** * @author Adam Grandquist * @copyright Apache */ #include "ReQL-expr.hpp" #include "ReQL.hpp" #include <limits> namespace ReQL { Expr::Expr() { Query _val = expr(_reql_new_null()); sub_query.push_back(_val); query = _reql_new_datum(_val.query); } Expr::Expr(_ReQL_Op val) { query = val; } Expr::Expr(std::string val) { Query _val = expr(_reql_new_string(val)); sub_query.push_back(_val); query = _reql_new_datum(_val.query); } Expr::Expr(double val) { Query _val = expr(_reql_new_number(val)); sub_query.push_back(_val); query = _reql_new_datum(_val.query); } Expr::Expr(bool val) { Query _val = expr(_reql_new_bool(val)); sub_query.push_back(_val); query = _reql_new_datum(_val.query); } Expr::Expr(std::vector<Query> val) { if (val.size() > std::numeric_limits<std::uint32_t>::max()) { throw; } sub_query.assign(val.begin(), val.end()); Query _val = expr(_reql_new_array(static_cast<std::uint32_t>(val.size()))); sub_query.push_back(_val); for (auto iter=val.cbegin(); iter!=val.cend(); ++iter) { _reql_array_append(_val.query, iter->query); } query = _reql_new_make_array(_val.query); } Expr::Expr(std::map<std::string, Query> val) { if (val.size() > std::numeric_limits<std::uint32_t>::max()) { throw; } Query _val = expr(_reql_new_object(static_cast<std::uint32_t>(val.size()))); sub_query.push_back(_val); for (auto iter=val.cbegin(); iter!=val.cend(); ++iter) { Query key(iter->first); sub_query.push_back(key); sub_query.push_back(iter->second); _reql_object_add(_val.query, key.query, iter->second.query); } query = _reql_new_make_obj(_val.query); } Expr::~Expr() { switch (_reql_datum_type(query)) { case _REQL_R_ARRAY: { delete [] query->obj.datum.json.array.arr; break; } case _REQL_R_OBJECT: { delete [] query->obj.datum.json.object.pair; break; } default: break; } delete query; } Query expr() { return Query(); } Query expr(_ReQL_Op val) { return Query(val); } Query expr(std::string val) { return Query(val); } Query expr(double val) { return Query(val); } Query expr(bool val) { return Query(val); } Query expr(std::vector<Query> val) { return Query(val); } Query expr(std::map<std::string, Query> val) { return Query(val); } } <|endoftext|>
<commit_before>#include "SoapyAudio.hpp" #ifdef USE_HAMLIB RigThread::RigThread() { terminated.store(true); } RigThread::~RigThread() { } #ifdef __APPLE__ void *RigThread::threadMain() { terminated.store(false); run(); return this; }; void *RigThread::pthread_helper(void *context) { return ((RigThread *) context)->threadMain(); }; #else void RigThread::threadMain() { terminated.store(false); run(); }; #endif void RigThread::setup(rig_model_t rig_model, std::string rig_file, int serial_rate) { rigModel = rig_model; rigFile = rig_file; serialRate = serial_rate; }; void RigThread::run() { int retcode, status; SoapySDR_log(SOAPY_SDR_DEBUG, "Rig thread starting."); rig = rig_init(rigModel); strncpy(rig->state.rigport.pathname, rigFile.c_str(), FILPATHLEN - 1); rig->state.rigport.parm.serial.rate = serialRate; retcode = rig_open(rig); char *info_buf = (char *)rig_get_info(rig); SoapySDR_logf(SOAPY_SDR_DEBUG, "Rig Info: %s", info_buf); while (!terminated.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(150)); if (freqChanged.load()) { status = rig_get_freq(rig, RIG_VFO_CURR, &freq); if (freq != newFreq) { freq = newFreq; rig_set_freq(rig, RIG_VFO_CURR, freq); SoapySDR_logf(SOAPY_SDR_DEBUG, "Set Rig Freq: %f", newFreq); } freqChanged.store(false); } else { status = rig_get_freq(rig, RIG_VFO_CURR, &freq); } SoapySDR_logf(SOAPY_SDR_DEBUG, "Rig Freq: %f", freq); } rig_close(rig); SoapySDR_log(SOAPY_SDR_DEBUG, "Rig thread exiting."); }; freq_t RigThread::getFrequency() { if (freqChanged.load()) { return newFreq; } else { return freq; } } void RigThread::setFrequency(freq_t new_freq) { newFreq = new_freq; freqChanged.store(true); } void RigThread::terminate() { terminated.store(true); }; bool RigThread::isTerminated() { return terminated.load(); } #endif<commit_msg>Missing rig_cleanup.<commit_after>#include "SoapyAudio.hpp" #ifdef USE_HAMLIB RigThread::RigThread() { terminated.store(true); } RigThread::~RigThread() { } #ifdef __APPLE__ void *RigThread::threadMain() { terminated.store(false); run(); return this; }; void *RigThread::pthread_helper(void *context) { return ((RigThread *) context)->threadMain(); }; #else void RigThread::threadMain() { terminated.store(false); run(); }; #endif void RigThread::setup(rig_model_t rig_model, std::string rig_file, int serial_rate) { rigModel = rig_model; rigFile = rig_file; serialRate = serial_rate; }; void RigThread::run() { int retcode, status; SoapySDR_log(SOAPY_SDR_DEBUG, "Rig thread starting."); rig = rig_init(rigModel); strncpy(rig->state.rigport.pathname, rigFile.c_str(), FILPATHLEN - 1); rig->state.rigport.parm.serial.rate = serialRate; retcode = rig_open(rig); char *info_buf = (char *)rig_get_info(rig); SoapySDR_logf(SOAPY_SDR_DEBUG, "Rig Info: %s", info_buf); while (!terminated.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(150)); if (freqChanged.load()) { status = rig_get_freq(rig, RIG_VFO_CURR, &freq); if (freq != newFreq) { freq = newFreq; rig_set_freq(rig, RIG_VFO_CURR, freq); SoapySDR_logf(SOAPY_SDR_DEBUG, "Set Rig Freq: %f", newFreq); } freqChanged.store(false); } else { status = rig_get_freq(rig, RIG_VFO_CURR, &freq); } SoapySDR_logf(SOAPY_SDR_DEBUG, "Rig Freq: %f", freq); } rig_close(rig); rig_cleanup(rig); SoapySDR_log(SOAPY_SDR_DEBUG, "Rig thread exiting."); }; freq_t RigThread::getFrequency() { if (freqChanged.load()) { return newFreq; } else { return freq; } } void RigThread::setFrequency(freq_t new_freq) { newFreq = new_freq; freqChanged.store(true); } void RigThread::terminate() { terminated.store(true); }; bool RigThread::isTerminated() { return terminated.load(); } #endif<|endoftext|>
<commit_before>// // Decoder.hpp // Clock Signal // // Created by Thomas Harte on 30/12/20. // Copyright © 2020 Thomas Harte. All rights reserved. // #ifndef InstructionSets_PowerPC_Decoder_hpp #define InstructionSets_PowerPC_Decoder_hpp #include "Instruction.hpp" namespace InstructionSet { namespace PowerPC { enum class Model { /// i.e. 32-bit, with POWER carry-over instructions. MPC601, /// i.e. 32-bit, no POWER instructions. MPC603, /// i.e. 64-bit. MPC620, }; constexpr bool is64bit(Model model) { return model == Model::MPC620; } constexpr bool is32bit(Model model) { return !is64bit(model); } constexpr bool is601(Model model) { return model == Model::MPC601; } /*! Implements PowerPC instruction decoding. @c model Indicates the instruction set to decode. @c validate_reserved_bits If set to @c true, check that all reserved bits are 0 and produce an invalid opcode if not. Otherwise does no inspection of reserved bits. TODO: determine what specific models of PowerPC do re: reserved bits. */ template <Model model, bool validate_reserved_bits = false> struct Decoder { Instruction decode(uint32_t opcode); }; } } #endif /* InstructionSets_PowerPC_Decoder_hpp */ <commit_msg>Improve accuracy of comment.<commit_after>// // Decoder.hpp // Clock Signal // // Created by Thomas Harte on 30/12/20. // Copyright © 2020 Thomas Harte. All rights reserved. // #ifndef InstructionSets_PowerPC_Decoder_hpp #define InstructionSets_PowerPC_Decoder_hpp #include "Instruction.hpp" namespace InstructionSet { namespace PowerPC { enum class Model { /// i.e. 32-bit, with POWER carry-over instructions. MPC601, /// i.e. 32-bit, no POWER instructions. MPC603, /// i.e. 64-bit. MPC620, }; constexpr bool is64bit(Model model) { return model == Model::MPC620; } constexpr bool is32bit(Model model) { return !is64bit(model); } constexpr bool is601(Model model) { return model == Model::MPC601; } /*! Implements PowerPC instruction decoding. @c model Indicates the instruction set to decode. @c validate_reserved_bits If set to @c true, check that all reserved bits are 0 or 1 as required and produce an invalid opcode if not. Otherwise does no inspection of reserved bits. TODO: determine what specific models of PowerPC do re: reserved bits. */ template <Model model, bool validate_reserved_bits = false> struct Decoder { Instruction decode(uint32_t opcode); }; } } #endif /* InstructionSets_PowerPC_Decoder_hpp */ <|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 "SkPathPriv.h" #include "SkRecords.h" namespace SkRecords { PreCachedPath::PreCachedPath(const SkPath& path) : SkPath(path) { this->updateBoundsCache(); #if 0 // Disabled to see if we ever really race on this. It costs time, chromium:496982. SkPathPriv::FirstDirection junk; (void)SkPathPriv::CheapComputeFirstDirection(*this, &junk); #endif } TypedMatrix::TypedMatrix(const SkMatrix& matrix) : SkMatrix(matrix) { (void)this->getType(); } } <commit_msg>Pre-cache SkPath's genID in PreCachedPath too<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 "SkPathPriv.h" #include "SkRecords.h" namespace SkRecords { PreCachedPath::PreCachedPath(const SkPath& path) : SkPath(path) { this->updateBoundsCache(); (void)this->getGenerationID(); #if 0 // Disabled to see if we ever really race on this. It costs time, chromium:496982. SkPathPriv::FirstDirection junk; (void)SkPathPriv::CheapComputeFirstDirection(*this, &junk); #endif } TypedMatrix::TypedMatrix(const SkMatrix& matrix) : SkMatrix(matrix) { (void)this->getType(); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsgdefaultglyphnode_p_p.h" #include <qopenglshaderprogram.h> #include <QtGui/private/qtextureglyphcache_gl_p.h> #include <private/qfontengine_p.h> #include <private/qopenglextensions_p.h> #include <private/qsgtexture_p.h> #include <private/qrawfont_p.h> QT_BEGIN_NAMESPACE class QSGTextMaskMaterialData : public QSGMaterialShader { public: QSGTextMaskMaterialData(); virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect); virtual char const *const *attributeNames() const; private: virtual void initialize(); virtual const char *vertexShader() const; virtual const char *fragmentShader() const; int m_matrix_id; int m_color_id; int m_textureScale_id; }; const char *QSGTextMaskMaterialData::vertexShader() const { return "uniform highp mat4 matrix; \n" "uniform highp vec2 textureScale; \n" "attribute highp vec4 vCoord; \n" "attribute highp vec2 tCoord; \n" "varying highp vec2 sampleCoord; \n" "void main() { \n" " sampleCoord = tCoord * textureScale; \n" " gl_Position = matrix * vCoord; \n" "}"; } const char *QSGTextMaskMaterialData::fragmentShader() const { return "varying highp vec2 sampleCoord; \n" "uniform sampler2D texture; \n" "uniform lowp vec4 color; \n" "void main() { \n" " gl_FragColor = color * texture2D(texture, sampleCoord).a; \n" "}"; } char const *const *QSGTextMaskMaterialData::attributeNames() const { static char const *const attr[] = { "vCoord", "tCoord", 0 }; return attr; } QSGTextMaskMaterialData::QSGTextMaskMaterialData() { } void QSGTextMaskMaterialData::initialize() { m_matrix_id = program()->uniformLocation("matrix"); m_color_id = program()->uniformLocation("color"); m_textureScale_id = program()->uniformLocation("textureScale"); } void QSGTextMaskMaterialData::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect) { Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type()); QSGTextMaskMaterial *material = static_cast<QSGTextMaskMaterial *>(newEffect); QSGTextMaskMaterial *oldMaterial = static_cast<QSGTextMaskMaterial *>(oldEffect); if (oldMaterial == 0 || material->color() != oldMaterial->color() || state.isOpacityDirty()) { QVector4D color(material->color().redF(), material->color().greenF(), material->color().blueF(), material->color().alphaF()); color *= state.opacity(); program()->setUniformValue(m_color_id, color); } bool updated = material->ensureUpToDate(); Q_ASSERT(material->texture()); Q_ASSERT(oldMaterial == 0 || oldMaterial->texture()); if (updated || oldMaterial == 0 || oldMaterial->texture()->textureId() != material->texture()->textureId()) { program()->setUniformValue(m_textureScale_id, QVector2D(1.0 / material->cacheTextureWidth(), 1.0 / material->cacheTextureHeight())); glBindTexture(GL_TEXTURE_2D, material->texture()->textureId()); // Set the mag/min filters to be linear. We only need to do this when the texture // has been recreated. if (updated) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } } if (state.isMatrixDirty()) program()->setUniformValue(m_matrix_id, state.combinedMatrix()); } QSGTextMaskMaterial::QSGTextMaskMaterial(const QRawFont &font) : m_texture(0), m_glyphCache(), m_font(font) { init(); } QSGTextMaskMaterial::~QSGTextMaskMaterial() { } void QSGTextMaskMaterial::init() { Q_ASSERT(m_font.isValid()); QFontEngineGlyphCache::Type type = QFontEngineGlyphCache::Raster_A8; setFlag(Blending, true); QOpenGLContext *ctx = const_cast<QOpenGLContext *>(QOpenGLContext::currentContext()); Q_ASSERT(ctx != 0); QRawFontPrivate *fontD = QRawFontPrivate::get(m_font); if (fontD->fontEngine != 0) { m_glyphCache = fontD->fontEngine->glyphCache(ctx, type, QTransform()); if (!m_glyphCache || m_glyphCache->cacheType() != type) { m_glyphCache = new QOpenGLTextureGlyphCache(type, QTransform()); fontD->fontEngine->setGlyphCache(ctx, m_glyphCache.data()); } } } void QSGTextMaskMaterial::populate(const QPointF &p, const QVector<quint32> &glyphIndexes, const QVector<QPointF> &glyphPositions, QSGGeometry *geometry, QRectF *boundingRect, QPointF *baseLine) { Q_ASSERT(m_font.isValid()); QVector<QFixedPoint> fixedPointPositions; for (int i=0; i<glyphPositions.size(); ++i) fixedPointPositions.append(QFixedPoint::fromPointF(glyphPositions.at(i))); QTextureGlyphCache *cache = glyphCache(); QRawFontPrivate *fontD = QRawFontPrivate::get(m_font); cache->populate(fontD->fontEngine, glyphIndexes.size(), glyphIndexes.constData(), fixedPointPositions.data()); cache->fillInPendingGlyphs(); int margin = cache->glyphMargin(); Q_ASSERT(geometry->indexType() == GL_UNSIGNED_SHORT); geometry->allocate(glyphIndexes.size() * 4, glyphIndexes.size() * 6); QVector4D *vp = (QVector4D *)geometry->vertexDataAsTexturedPoint2D(); Q_ASSERT(geometry->stride() == sizeof(QVector4D)); ushort *ip = geometry->indexDataAsUShort(); QPointF position(p.x(), p.y() - m_font.ascent()); bool supportsSubPixelPositions = fontD->fontEngine->supportsSubPixelPositions(); for (int i=0; i<glyphIndexes.size(); ++i) { QFixed subPixelPosition; if (supportsSubPixelPositions) subPixelPosition = cache->subPixelPositionForX(QFixed::fromReal(glyphPositions.at(i).x())); QTextureGlyphCache::GlyphAndSubPixelPosition glyph(glyphIndexes.at(i), subPixelPosition); const QTextureGlyphCache::Coord &c = cache->coords.value(glyph); QPointF glyphPosition = glyphPositions.at(i) + position; int x = qRound(glyphPosition.x()) + c.baseLineX - margin; int y = qRound(glyphPosition.y()) - c.baseLineY - margin; *boundingRect |= QRectF(x + margin, y + margin, c.w, c.h); float cx1 = x; float cx2 = x + c.w; float cy1 = y; float cy2 = y + c.h; float tx1 = c.x; float tx2 = (c.x + c.w); float ty1 = c.y; float ty2 = (c.y + c.h); if (baseLine->isNull()) *baseLine = glyphPosition; vp[4 * i + 0] = QVector4D(cx1, cy1, tx1, ty1); vp[4 * i + 1] = QVector4D(cx2, cy1, tx2, ty1); vp[4 * i + 2] = QVector4D(cx1, cy2, tx1, ty2); vp[4 * i + 3] = QVector4D(cx2, cy2, tx2, ty2); int o = i * 4; ip[6 * i + 0] = o + 0; ip[6 * i + 1] = o + 2; ip[6 * i + 2] = o + 3; ip[6 * i + 3] = o + 3; ip[6 * i + 4] = o + 1; ip[6 * i + 5] = o + 0; } } QSGMaterialType *QSGTextMaskMaterial::type() const { static QSGMaterialType type; return &type; } QOpenGLTextureGlyphCache *QSGTextMaskMaterial::glyphCache() const { return static_cast<QOpenGLTextureGlyphCache*>(m_glyphCache.data()); } QSGMaterialShader *QSGTextMaskMaterial::createShader() const { return new QSGTextMaskMaterialData; } int QSGTextMaskMaterial::compare(const QSGMaterial *o) const { Q_ASSERT(o && type() == o->type()); const QSGTextMaskMaterial *other = static_cast<const QSGTextMaskMaterial *>(o); if (m_glyphCache != other->m_glyphCache) return m_glyphCache - other->m_glyphCache; QRgb c1 = m_color.rgba(); QRgb c2 = other->m_color.rgba(); return int(c2 < c1) - int(c1 < c2); } bool QSGTextMaskMaterial::ensureUpToDate() { QSize glyphCacheSize(glyphCache()->width(), glyphCache()->height()); if (glyphCacheSize != m_size) { if (m_texture) delete m_texture; m_texture = new QSGPlainTexture(); m_texture->setTextureId(glyphCache()->texture()); m_texture->setTextureSize(QSize(glyphCache()->width(), glyphCache()->height())); m_texture->setOwnsTexture(false); m_size = glyphCacheSize; return true; } else { return false; } } int QSGTextMaskMaterial::cacheTextureWidth() const { return glyphCache()->width(); } int QSGTextMaskMaterial::cacheTextureHeight() const { return glyphCache()->height(); } QT_END_NAMESPACE <commit_msg>Compile, qtextureglyphcache_gl_p.h -> qopengltextureglyphcache_p.h<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsgdefaultglyphnode_p_p.h" #include <qopenglshaderprogram.h> #include <QtGui/private/qopengltextureglyphcache_p.h> #include <private/qfontengine_p.h> #include <private/qopenglextensions_p.h> #include <private/qsgtexture_p.h> #include <private/qrawfont_p.h> QT_BEGIN_NAMESPACE class QSGTextMaskMaterialData : public QSGMaterialShader { public: QSGTextMaskMaterialData(); virtual void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect); virtual char const *const *attributeNames() const; private: virtual void initialize(); virtual const char *vertexShader() const; virtual const char *fragmentShader() const; int m_matrix_id; int m_color_id; int m_textureScale_id; }; const char *QSGTextMaskMaterialData::vertexShader() const { return "uniform highp mat4 matrix; \n" "uniform highp vec2 textureScale; \n" "attribute highp vec4 vCoord; \n" "attribute highp vec2 tCoord; \n" "varying highp vec2 sampleCoord; \n" "void main() { \n" " sampleCoord = tCoord * textureScale; \n" " gl_Position = matrix * vCoord; \n" "}"; } const char *QSGTextMaskMaterialData::fragmentShader() const { return "varying highp vec2 sampleCoord; \n" "uniform sampler2D texture; \n" "uniform lowp vec4 color; \n" "void main() { \n" " gl_FragColor = color * texture2D(texture, sampleCoord).a; \n" "}"; } char const *const *QSGTextMaskMaterialData::attributeNames() const { static char const *const attr[] = { "vCoord", "tCoord", 0 }; return attr; } QSGTextMaskMaterialData::QSGTextMaskMaterialData() { } void QSGTextMaskMaterialData::initialize() { m_matrix_id = program()->uniformLocation("matrix"); m_color_id = program()->uniformLocation("color"); m_textureScale_id = program()->uniformLocation("textureScale"); } void QSGTextMaskMaterialData::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect) { Q_ASSERT(oldEffect == 0 || newEffect->type() == oldEffect->type()); QSGTextMaskMaterial *material = static_cast<QSGTextMaskMaterial *>(newEffect); QSGTextMaskMaterial *oldMaterial = static_cast<QSGTextMaskMaterial *>(oldEffect); if (oldMaterial == 0 || material->color() != oldMaterial->color() || state.isOpacityDirty()) { QVector4D color(material->color().redF(), material->color().greenF(), material->color().blueF(), material->color().alphaF()); color *= state.opacity(); program()->setUniformValue(m_color_id, color); } bool updated = material->ensureUpToDate(); Q_ASSERT(material->texture()); Q_ASSERT(oldMaterial == 0 || oldMaterial->texture()); if (updated || oldMaterial == 0 || oldMaterial->texture()->textureId() != material->texture()->textureId()) { program()->setUniformValue(m_textureScale_id, QVector2D(1.0 / material->cacheTextureWidth(), 1.0 / material->cacheTextureHeight())); glBindTexture(GL_TEXTURE_2D, material->texture()->textureId()); // Set the mag/min filters to be linear. We only need to do this when the texture // has been recreated. if (updated) { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } } if (state.isMatrixDirty()) program()->setUniformValue(m_matrix_id, state.combinedMatrix()); } QSGTextMaskMaterial::QSGTextMaskMaterial(const QRawFont &font) : m_texture(0), m_glyphCache(), m_font(font) { init(); } QSGTextMaskMaterial::~QSGTextMaskMaterial() { } void QSGTextMaskMaterial::init() { Q_ASSERT(m_font.isValid()); QFontEngineGlyphCache::Type type = QFontEngineGlyphCache::Raster_A8; setFlag(Blending, true); QOpenGLContext *ctx = const_cast<QOpenGLContext *>(QOpenGLContext::currentContext()); Q_ASSERT(ctx != 0); QRawFontPrivate *fontD = QRawFontPrivate::get(m_font); if (fontD->fontEngine != 0) { m_glyphCache = fontD->fontEngine->glyphCache(ctx, type, QTransform()); if (!m_glyphCache || m_glyphCache->cacheType() != type) { m_glyphCache = new QOpenGLTextureGlyphCache(type, QTransform()); fontD->fontEngine->setGlyphCache(ctx, m_glyphCache.data()); } } } void QSGTextMaskMaterial::populate(const QPointF &p, const QVector<quint32> &glyphIndexes, const QVector<QPointF> &glyphPositions, QSGGeometry *geometry, QRectF *boundingRect, QPointF *baseLine) { Q_ASSERT(m_font.isValid()); QVector<QFixedPoint> fixedPointPositions; for (int i=0; i<glyphPositions.size(); ++i) fixedPointPositions.append(QFixedPoint::fromPointF(glyphPositions.at(i))); QTextureGlyphCache *cache = glyphCache(); QRawFontPrivate *fontD = QRawFontPrivate::get(m_font); cache->populate(fontD->fontEngine, glyphIndexes.size(), glyphIndexes.constData(), fixedPointPositions.data()); cache->fillInPendingGlyphs(); int margin = cache->glyphMargin(); Q_ASSERT(geometry->indexType() == GL_UNSIGNED_SHORT); geometry->allocate(glyphIndexes.size() * 4, glyphIndexes.size() * 6); QVector4D *vp = (QVector4D *)geometry->vertexDataAsTexturedPoint2D(); Q_ASSERT(geometry->stride() == sizeof(QVector4D)); ushort *ip = geometry->indexDataAsUShort(); QPointF position(p.x(), p.y() - m_font.ascent()); bool supportsSubPixelPositions = fontD->fontEngine->supportsSubPixelPositions(); for (int i=0; i<glyphIndexes.size(); ++i) { QFixed subPixelPosition; if (supportsSubPixelPositions) subPixelPosition = cache->subPixelPositionForX(QFixed::fromReal(glyphPositions.at(i).x())); QTextureGlyphCache::GlyphAndSubPixelPosition glyph(glyphIndexes.at(i), subPixelPosition); const QTextureGlyphCache::Coord &c = cache->coords.value(glyph); QPointF glyphPosition = glyphPositions.at(i) + position; int x = qRound(glyphPosition.x()) + c.baseLineX - margin; int y = qRound(glyphPosition.y()) - c.baseLineY - margin; *boundingRect |= QRectF(x + margin, y + margin, c.w, c.h); float cx1 = x; float cx2 = x + c.w; float cy1 = y; float cy2 = y + c.h; float tx1 = c.x; float tx2 = (c.x + c.w); float ty1 = c.y; float ty2 = (c.y + c.h); if (baseLine->isNull()) *baseLine = glyphPosition; vp[4 * i + 0] = QVector4D(cx1, cy1, tx1, ty1); vp[4 * i + 1] = QVector4D(cx2, cy1, tx2, ty1); vp[4 * i + 2] = QVector4D(cx1, cy2, tx1, ty2); vp[4 * i + 3] = QVector4D(cx2, cy2, tx2, ty2); int o = i * 4; ip[6 * i + 0] = o + 0; ip[6 * i + 1] = o + 2; ip[6 * i + 2] = o + 3; ip[6 * i + 3] = o + 3; ip[6 * i + 4] = o + 1; ip[6 * i + 5] = o + 0; } } QSGMaterialType *QSGTextMaskMaterial::type() const { static QSGMaterialType type; return &type; } QOpenGLTextureGlyphCache *QSGTextMaskMaterial::glyphCache() const { return static_cast<QOpenGLTextureGlyphCache*>(m_glyphCache.data()); } QSGMaterialShader *QSGTextMaskMaterial::createShader() const { return new QSGTextMaskMaterialData; } int QSGTextMaskMaterial::compare(const QSGMaterial *o) const { Q_ASSERT(o && type() == o->type()); const QSGTextMaskMaterial *other = static_cast<const QSGTextMaskMaterial *>(o); if (m_glyphCache != other->m_glyphCache) return m_glyphCache - other->m_glyphCache; QRgb c1 = m_color.rgba(); QRgb c2 = other->m_color.rgba(); return int(c2 < c1) - int(c1 < c2); } bool QSGTextMaskMaterial::ensureUpToDate() { QSize glyphCacheSize(glyphCache()->width(), glyphCache()->height()); if (glyphCacheSize != m_size) { if (m_texture) delete m_texture; m_texture = new QSGPlainTexture(); m_texture->setTextureId(glyphCache()->texture()); m_texture->setTextureSize(QSize(glyphCache()->width(), glyphCache()->height())); m_texture->setOwnsTexture(false); m_size = glyphCacheSize; return true; } else { return false; } } int QSGTextMaskMaterial::cacheTextureWidth() const { return glyphCache()->width(); } int QSGTextMaskMaterial::cacheTextureHeight() const { return glyphCache()->height(); } QT_END_NAMESPACE <|endoftext|>
<commit_before>/* dtkComposerNodeLoopDataComposite.cpp --- * * Author: Thibaud Kloczko * Copyright (C) 2011 - Thibaud Kloczko, Inria. * Created: Wed Oct 12 16:02:18 2011 (+0200) * Version: $Id$ * Last-Updated: Fri Oct 14 16:27:22 2011 (+0200) * By: Julien Wintz * Update #: 140 */ /* Commentary: * */ /* Change log: * */ #include "dtkComposerNodeLoopDataComposite.h" #include <dtkComposer/dtkComposerEdge> #include <dtkComposer/dtkComposerNode> #include <dtkComposer/dtkComposerNodeControlBlock> #include <dtkComposer/dtkComposerNodeNumber> #include <dtkComposer/dtkComposerNodeProperty> #include <dtkCore/dtkAbstractData> #include <dtkCore/dtkAbstractDataComposite> #include <dtkCore/dtkAbstractProcess> #include <dtkCore/dtkGlobal> #include <dtkCore/dtkLog> #define DTK_DEBUG_COMPOSER_INTERACTION 1 #define DTK_DEBUG_COMPOSER_EVALUATION 1 // ///////////////////////////////////////////////////////////////// // dtkComposerNodeLoopDataCompositePrivate declaration // ///////////////////////////////////////////////////////////////// class dtkComposerNodeLoopDataCompositePrivate { public: dtkComposerNodeControlBlock *block_loop; public: dtkxarch_int from_default; dtkxarch_int to_default; dtkxarch_int step_default; dtkxarch_int from; dtkxarch_int to; dtkxarch_int step; dtkxarch_int index; dtkAbstractData *item; dtkAbstractDataComposite *composite; bool valid_input_composite; }; // ///////////////////////////////////////////////////////////////// // dtkComposerNodeLoopDataComposite implementation // ///////////////////////////////////////////////////////////////// dtkComposerNodeLoopDataComposite::dtkComposerNodeLoopDataComposite(dtkComposerNode *parent) : dtkComposerNodeLoop(parent), d(new dtkComposerNodeLoopDataCompositePrivate) { d->block_loop = this->addBlock("loop"); d->block_loop->setInteractive(false); d->block_loop->setHeightRatio(1); this->addInputProperty(d->block_loop->addInputProperty("from", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this)); this->addInputProperty(d->block_loop->addInputProperty("to", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this)); this->addInputProperty(d->block_loop->addInputProperty("step", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this)); this->addInputProperty(d->block_loop->addInputProperty("item", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, dtkComposerNodeProperty::AsLoopInput, this)); this->setColor(QColor("#2ABFFF")); this->setInputPropertyName("composite"); this->setTitle("Composite Data Loop"); this->setType("dtkComposerLoopDataComposite"); d->from_default = 0; d->to_default = 0; d->step_default = 1; d->from = -1; d->to = -1; d->step = -1; d->index = 0; d->item = NULL; d->composite = NULL; d->valid_input_composite = false; } dtkComposerNodeLoopDataComposite::~dtkComposerNodeLoopDataComposite(void) { delete d; d = NULL; } void dtkComposerNodeLoopDataComposite::layout(void) { dtkComposerNodeControl::layout(); QRectF node_rect = this->boundingRect(); qreal node_radius = this->nodeRadius(); int j; qreal offset = 23; dtkComposerNodeControlBlock *block = this->blocks().at(0); block->setRect(QRectF(node_rect.x(), node_rect.y() + offset, node_rect.width(), block->height())); j = 0; foreach(dtkComposerNodeProperty *property, block->inputProperties()) { property->setRect(QRectF(block->mapRectToParent(block->rect()).left() + node_radius, block->mapRectToParent(block->rect()).top() + node_radius * (4*j + 1), 2 * node_radius, 2 * node_radius )); if (property->name() == "item") { property->mirror(); j++; } j++; } j = 5; foreach(dtkComposerNodeProperty *property, block->outputProperties()) { property->setRect(QRectF(block->mapRectToParent(block->rect()).right() - node_radius * 3, block->mapRectToParent(block->rect()).top() + node_radius * (4*j + 1), 2 * node_radius, 2 * node_radius )); j++; } } void dtkComposerNodeLoopDataComposite::update(void) { #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_PRETTY_FUNCTION << this; #endif if (this->isRunning()) { return; } else { if (!this->dirty()) return; // -- Check dirty input value if (this->dirtyInputValue()) return; #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_GREEN << DTK_PRETTY_FUNCTION << "Dirty input value OK" << DTK_NO_COLOR; #endif // -- Check dirty inputs if (this->dtkComposerNode::dirtyUpstreamNodes()) return; // -- Mark dirty outputs this->dtkComposerNode::markDirtyDownstreamNodes(); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_GREEN << DTK_PRETTY_FUNCTION << "All output nodes are set to dirty" << DTK_NO_COLOR; #endif // -- Clean active input routes this->cleanInputActiveRoutes(); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "Input active routes cleaned" << DTK_NO_COLOR; #endif // -- Pull foreach(dtkComposerEdge *i_route, this->inputRoutes()) this->pull(i_route, i_route->destination()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "Pull done" << DTK_NO_COLOR; #endif // -- Set input composite and loop options foreach(dtkComposerEdge *i_route, this->inputActiveRoutes()) { if (i_route->destination() == this->inputProperty()) { dtkAbstractData *data = NULL; if(dtkAbstractData *dt = qobject_cast<dtkAbstractData *>(i_route->source()->node()->object())) { data = dt; } else if(dtkAbstractProcess *process = qobject_cast<dtkAbstractProcess *>(i_route->source()->node()->object())) { if(i_route->source()->node()->outputProperties().count() >= 1) data = process->output(i_route->source()->node()->number(i_route->source())); else data = process->output(); } if (data) { d->composite = qobject_cast<dtkAbstractDataComposite *>(data); if (!d->composite) { dtkDebug() << DTK_PRETTY_FUNCTION << "input data is not of dtkAbstractDataComposite* type."; return; } if (d->composite->count()) this->setObject((*d->composite)[0]); d->to_default = d->composite->count()-1; d->valid_input_composite = true; } else { dtkDebug() << DTK_PRETTY_FUNCTION << "input data is not defined"; return; } } else if (i_route->destination()->name() == "from") { d->from = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "from value =" << d->from << DTK_NO_COLOR; #endif } else if (i_route->destination()->name() == "to") { d->to = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "to value =" << d->to << DTK_NO_COLOR; #endif } else if (i_route->destination()->name() == "step") { d->step = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "step value =" << d->step << DTK_NO_COLOR; #endif } qDebug() << i_route; } if (!d->valid_input_composite) { dtkDebug() << DTK_PRETTY_FUNCTION << " input composite property is not connected."; return; } if ((d->from > d->to) && (d->from > d->to_default)) d->from = d->to_default; else if (d->from < 0) d->from = d->from_default; else if (d->to < d->from && d->to < 0) d->to = d->from_default; else if (d->to > d->to_default) d->to = d->to_default; if (d->step < 0 && (d->from < d->to)) d->step = d->step_default; d->index = d->from; // -- Running logics of conditional block this->setRunning(true); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_RED << "Loop initialization done" << DTK_NO_COLOR; #endif while(d->index <= d->to) { #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_RED << "Loop is running, index = " << d->index << DTK_NO_COLOR; #endif d->item = (*d->composite)[d->index]; this->run(); this->updatePassThroughVariables(); d->index += d->step; } // -- Clean active output routes this->cleanOutputActiveRoutes(); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "Output active routes cleaned" << DTK_NO_COLOR; #endif // -- Push foreach(dtkComposerEdge *o_route, this->outputRoutes()) this->push(o_route, o_route->source()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "Push done" << DTK_NO_COLOR; #endif // -- Forward this->setDirty(false); this->setRunning(false); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_BLUE << DTK_PRETTY_FUNCTION << "Forward done" << DTK_NO_COLOR; #endif foreach(dtkComposerEdge *o_route, this->outputRoutes()) o_route->destination()->node()->update(); } } void dtkComposerNodeLoopDataComposite::onEdgeConnected(dtkComposerEdge *edge) { if(true) edge->invalidate(); else ; // dtkComposerNodeLoop::onEdgeConnected(edge); } void dtkComposerNodeLoopDataComposite::pull(dtkComposerEdge *i_route, dtkComposerNodeProperty *property) { if (property->name() == "from" || property->name() == "to" || property->name() == "step") this->addInputActiveRoute(i_route); dtkComposerNodeLoop::pull(i_route, property); } QVariant dtkComposerNodeLoopDataComposite::value(dtkComposerNodeProperty *property) { return QVariant(); } <commit_msg>As property type checking is not yet implemented, composite node data loop will invalidate the edge but build the routes anyway.<commit_after>/* dtkComposerNodeLoopDataComposite.cpp --- * * Author: Thibaud Kloczko * Copyright (C) 2011 - Thibaud Kloczko, Inria. * Created: Wed Oct 12 16:02:18 2011 (+0200) * Version: $Id$ * Last-Updated: Fri Oct 14 16:28:35 2011 (+0200) * By: Julien Wintz * Update #: 143 */ /* Commentary: * */ /* Change log: * */ #include "dtkComposerNodeLoopDataComposite.h" #include <dtkComposer/dtkComposerEdge> #include <dtkComposer/dtkComposerNode> #include <dtkComposer/dtkComposerNodeControlBlock> #include <dtkComposer/dtkComposerNodeNumber> #include <dtkComposer/dtkComposerNodeProperty> #include <dtkCore/dtkAbstractData> #include <dtkCore/dtkAbstractDataComposite> #include <dtkCore/dtkAbstractProcess> #include <dtkCore/dtkGlobal> #include <dtkCore/dtkLog> #define DTK_DEBUG_COMPOSER_INTERACTION 1 #define DTK_DEBUG_COMPOSER_EVALUATION 1 // ///////////////////////////////////////////////////////////////// // dtkComposerNodeLoopDataCompositePrivate declaration // ///////////////////////////////////////////////////////////////// class dtkComposerNodeLoopDataCompositePrivate { public: dtkComposerNodeControlBlock *block_loop; public: dtkxarch_int from_default; dtkxarch_int to_default; dtkxarch_int step_default; dtkxarch_int from; dtkxarch_int to; dtkxarch_int step; dtkxarch_int index; dtkAbstractData *item; dtkAbstractDataComposite *composite; bool valid_input_composite; }; // ///////////////////////////////////////////////////////////////// // dtkComposerNodeLoopDataComposite implementation // ///////////////////////////////////////////////////////////////// dtkComposerNodeLoopDataComposite::dtkComposerNodeLoopDataComposite(dtkComposerNode *parent) : dtkComposerNodeLoop(parent), d(new dtkComposerNodeLoopDataCompositePrivate) { d->block_loop = this->addBlock("loop"); d->block_loop->setInteractive(false); d->block_loop->setHeightRatio(1); this->addInputProperty(d->block_loop->addInputProperty("from", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this)); this->addInputProperty(d->block_loop->addInputProperty("to", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this)); this->addInputProperty(d->block_loop->addInputProperty("step", dtkComposerNodeProperty::Input, dtkComposerNodeProperty::Single, dtkComposerNodeProperty::None, this)); this->addInputProperty(d->block_loop->addInputProperty("item", dtkComposerNodeProperty::Output, dtkComposerNodeProperty::Multiple, dtkComposerNodeProperty::AsLoopInput, this)); this->setColor(QColor("#2ABFFF")); this->setInputPropertyName("composite"); this->setTitle("Composite Data Loop"); this->setType("dtkComposerLoopDataComposite"); d->from_default = 0; d->to_default = 0; d->step_default = 1; d->from = -1; d->to = -1; d->step = -1; d->index = 0; d->item = NULL; d->composite = NULL; d->valid_input_composite = false; } dtkComposerNodeLoopDataComposite::~dtkComposerNodeLoopDataComposite(void) { delete d; d = NULL; } void dtkComposerNodeLoopDataComposite::layout(void) { dtkComposerNodeControl::layout(); QRectF node_rect = this->boundingRect(); qreal node_radius = this->nodeRadius(); int j; qreal offset = 23; dtkComposerNodeControlBlock *block = this->blocks().at(0); block->setRect(QRectF(node_rect.x(), node_rect.y() + offset, node_rect.width(), block->height())); j = 0; foreach(dtkComposerNodeProperty *property, block->inputProperties()) { property->setRect(QRectF(block->mapRectToParent(block->rect()).left() + node_radius, block->mapRectToParent(block->rect()).top() + node_radius * (4*j + 1), 2 * node_radius, 2 * node_radius )); if (property->name() == "item") { property->mirror(); j++; } j++; } j = 5; foreach(dtkComposerNodeProperty *property, block->outputProperties()) { property->setRect(QRectF(block->mapRectToParent(block->rect()).right() - node_radius * 3, block->mapRectToParent(block->rect()).top() + node_radius * (4*j + 1), 2 * node_radius, 2 * node_radius )); j++; } } void dtkComposerNodeLoopDataComposite::update(void) { #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_PRETTY_FUNCTION << this; #endif if (this->isRunning()) { return; } else { if (!this->dirty()) return; // -- Check dirty input value if (this->dirtyInputValue()) return; #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_GREEN << DTK_PRETTY_FUNCTION << "Dirty input value OK" << DTK_NO_COLOR; #endif // -- Check dirty inputs if (this->dtkComposerNode::dirtyUpstreamNodes()) return; // -- Mark dirty outputs this->dtkComposerNode::markDirtyDownstreamNodes(); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_GREEN << DTK_PRETTY_FUNCTION << "All output nodes are set to dirty" << DTK_NO_COLOR; #endif // -- Clean active input routes this->cleanInputActiveRoutes(); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "Input active routes cleaned" << DTK_NO_COLOR; #endif // -- Pull foreach(dtkComposerEdge *i_route, this->inputRoutes()) this->pull(i_route, i_route->destination()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "Pull done" << DTK_NO_COLOR; #endif // -- Set input composite and loop options foreach(dtkComposerEdge *i_route, this->inputActiveRoutes()) { if (i_route->destination() == this->inputProperty()) { dtkAbstractData *data = NULL; if(dtkAbstractData *dt = qobject_cast<dtkAbstractData *>(i_route->source()->node()->object())) { data = dt; } else if(dtkAbstractProcess *process = qobject_cast<dtkAbstractProcess *>(i_route->source()->node()->object())) { if(i_route->source()->node()->outputProperties().count() >= 1) data = process->output(i_route->source()->node()->number(i_route->source())); else data = process->output(); } if (data) { d->composite = qobject_cast<dtkAbstractDataComposite *>(data); if (!d->composite) { dtkDebug() << DTK_PRETTY_FUNCTION << "input data is not of dtkAbstractDataComposite* type."; return; } if (d->composite->count()) this->setObject((*d->composite)[0]); d->to_default = d->composite->count()-1; d->valid_input_composite = true; } else { dtkDebug() << DTK_PRETTY_FUNCTION << "input data is not defined"; return; } } else if (i_route->destination()->name() == "from") { d->from = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "from value =" << d->from << DTK_NO_COLOR; #endif } else if (i_route->destination()->name() == "to") { d->to = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "to value =" << d->to << DTK_NO_COLOR; #endif } else if (i_route->destination()->name() == "step") { d->step = (dtkxarch_int)(i_route->source()->node()->value(i_route->source()).toLongLong()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "step value =" << d->step << DTK_NO_COLOR; #endif } qDebug() << i_route; } if (!d->valid_input_composite) { dtkDebug() << DTK_PRETTY_FUNCTION << " input composite property is not connected."; return; } if ((d->from > d->to) && (d->from > d->to_default)) d->from = d->to_default; else if (d->from < 0) d->from = d->from_default; else if (d->to < d->from && d->to < 0) d->to = d->from_default; else if (d->to > d->to_default) d->to = d->to_default; if (d->step < 0 && (d->from < d->to)) d->step = d->step_default; d->index = d->from; // -- Running logics of conditional block this->setRunning(true); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_RED << "Loop initialization done" << DTK_NO_COLOR; #endif while(d->index <= d->to) { #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_RED << "Loop is running, index = " << d->index << DTK_NO_COLOR; #endif d->item = (*d->composite)[d->index]; this->run(); this->updatePassThroughVariables(); d->index += d->step; } // -- Clean active output routes this->cleanOutputActiveRoutes(); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "Output active routes cleaned" << DTK_NO_COLOR; #endif // -- Push foreach(dtkComposerEdge *o_route, this->outputRoutes()) this->push(o_route, o_route->source()); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_YELLOW << DTK_PRETTY_FUNCTION << "Push done" << DTK_NO_COLOR; #endif // -- Forward this->setDirty(false); this->setRunning(false); #if defined(DTK_DEBUG_COMPOSER_EVALUATION) qDebug() << DTK_COLOR_BG_BLUE << DTK_PRETTY_FUNCTION << "Forward done" << DTK_NO_COLOR; #endif foreach(dtkComposerEdge *o_route, this->outputRoutes()) o_route->destination()->node()->update(); } } void dtkComposerNodeLoopDataComposite::onEdgeConnected(dtkComposerEdge *edge) { if(true) edge->invalidate(); else ; // dtkComposerNodeLoop::onEdgeConnected(edge); dtkComposerNodeLoop::onEdgeConnected(edge); // TO BE REMOVED LATER ON } void dtkComposerNodeLoopDataComposite::pull(dtkComposerEdge *i_route, dtkComposerNodeProperty *property) { if (property->name() == "from" || property->name() == "to" || property->name() == "step") this->addInputActiveRoute(i_route); dtkComposerNodeLoop::pull(i_route, property); } QVariant dtkComposerNodeLoopDataComposite::value(dtkComposerNodeProperty *property) { return QVariant(); } <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "coverage_shared.hh" void Coverage_shared::receive_from_server() { // Read number of active clients std::vector<std::string> tmp; char* s = NULL; size_t si = 0; std::vector<int> clients; g_io_channel_flush(d_stdin,NULL); while(g_main_context_iteration(NULL,FALSE)); if (getline(&s,&si,d_stdout)<0) { status=false; return; } if (strlen(s)>2) { s[strlen(s)-2]='\0'; s++; } if (!string2vector(log,s,clients,0,INT_MAX,this)) { status=false; return; } // Read each client... for(unsigned i=0;i<clients.size();i++) { if (getline(&s,&si,d_stdout)<0) { status=false; return; } if (!status) { continue; } // Prepare the if (!child->set_instance(clients[i])) { status=false; continue; } std::string name,option; param_cut(std::string(s),name,option); std::vector<std::string> p; commalist(option,p); for(unsigned j=0;status&&(j<p.size());j++) { std::vector<std::string> at; param_cut(p[j],name,option); commalist(option,at); if (at.size()!=2) { status=false; continue; } int act=atoi(at[0].c_str()); std::vector<int> tags; if (!string2vector(log,at[1].c_str(),tags,0,INT_MAX,this)) { status=false; } else { // We should pass tags... child->execute(act); } } } } void Coverage_shared::communicate(int action) { if (!status) { return; } // First, send action fprintf(d_stdin,"(%i,)\n",action); receive_from_server(); } FACTORY_DEFAULT_CREATOR(Coverage, Coverage_shared, "shared") <commit_msg>call child->set_instance(0) at end of receive_from_server() at coverage_shared. If it's not done, current execution is appedned to end of the last received clients execution. That's bad.<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "coverage_shared.hh" void Coverage_shared::receive_from_server() { // Read number of active clients std::vector<std::string> tmp; char* s = NULL; size_t si = 0; std::vector<int> clients; g_io_channel_flush(d_stdin,NULL); while(g_main_context_iteration(NULL,FALSE)); if (getline(&s,&si,d_stdout)<0) { status=false; return; } if (strlen(s)>2) { s[strlen(s)-2]='\0'; s++; } if (!string2vector(log,s,clients,0,INT_MAX,this)) { status=false; return; } // Read each client... for(unsigned i=0;i<clients.size();i++) { if (getline(&s,&si,d_stdout)<0) { status=false; return; } if (!status) { continue; } // Prepare the if (!child->set_instance(clients[i])) { status=false; continue; } std::string name,option; param_cut(std::string(s),name,option); std::vector<std::string> p; commalist(option,p); for(unsigned j=0;status&&(j<p.size());j++) { std::vector<std::string> at; param_cut(p[j],name,option); commalist(option,at); if (at.size()!=2) { status=false; continue; } int act=atoi(at[0].c_str()); std::vector<int> tags; if (!string2vector(log,at[1].c_str(),tags,0,INT_MAX,this)) { status=false; } else { // We should pass tags... child->execute(act); } } } child->set_instance(0); } void Coverage_shared::communicate(int action) { if (!status) { return; } // First, send action fprintf(d_stdin,"(%i,)\n",action); receive_from_server(); } FACTORY_DEFAULT_CREATOR(Coverage, Coverage_shared, "shared") <|endoftext|>
<commit_before>// Copyright (c) 2016 Ansho Enigu #include "crypto/lamport.h" #include "crypto/ripemd160.h" #include "crypto/common.h" #include "uint256.h" bool LAMPORT::checksig(unsigned char data[10000], char sig[20][2][20], char rootkey[20], char merklewit[]) { char exmerklewit[8][20]; /*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*/ char pubkey[20][2][20]; bool merklecheckfin = false; //start converting merkle wit to exmerklewit and public key char merklebuffer[800]; //size of publickey is the max size of the buffer unsigned int i; for(i = 0; i < sizeof(merklewit); i++) { if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) /*test for partition beetween merkle segments*/ break; merklebuffer[i] = merklewit[i]; } memcpy(&pubkey, &merklebuffer, sizeof(merklebuffer)); int o = 0; int r = 0; //number of times we have reset o count for(; i < sizeof(merklewit); i++) { if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) { memcpy(&exmerklewit[r], &merklebuffer, sizeof(merklebuffer)); r++; i++; //get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle o = 0; } else { merklebuffer[o] = merklewit[i]; o++; } } //end decoding merkle wit format //start checking if new publickey is a part of the root key for(int i = 0; !merklecheckfin; i++) //to end if false we will use return to lower processing time { return false; } //end checking if new publickey is a part of the root key /* unsigned char* datapart; unsigned char[(160/LAMPORT::chuncksize)]* datahashs; for(int i = 0; i < (160/LAMPORT::chuncksize); i++) { for(int o = 0; o < chuncksizeinbyte; o++) { datapart[o] = data[(i * LAMPORT::chuncksize) + o]; } CRIPEMD160().Write(begin_ptr(datapart), datapart.size()).Finalize(begin_ptr(datahashs[i])); } */ return true; // if compleats all tests return true } char *** LAMPORT::createsig(unsigned char data[10000], uint512_t prikey, int sellectedpubkey) { /* hash of the message */ bool messhashb[160]; unsigned char messhash[20]; CRIPEMD160().Write(&data, 10000).Finalize(&messhash); /* creating true key from seed (the seed is used as the key by the user but it only is a form of compress key) */ unsigned char[20] vchHash unsigned char[64] prikeychar; memcpy(&prikeychar, &prikey, 64); CRIPEMD160().Write(&prikeychar, 64).Finalize(&vchHash); char temphash[20]; char ichar; for(int i =0; i < 320; i++) { memcpy(&ichar, &i, 1); CRIPEMD160().Write(&vchHash, sizeof(vchHash)).Write(&ichar, sizeof(ichar)).Finalize(&temphash); prikeys[i] = temphash; } /* the signing will happen under this */ char sig[20][2][20]; return &sig; } <commit_msg>Update lamport.cpp<commit_after>// Copyright (c) 2016 Ansho Enigu #include "crypto/lamport.h" #include "crypto/ripemd160.h" #include "crypto/common.h" #include "uint256.h" bool LAMPORT::checksig(unsigned char data[10000], char sig[20][2][20], char rootkey[20], char merklewit[]) { char exmerklewit[8][20]; /*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*/ char pubkey[20][2][20]; bool merklecheckfin = false; //start converting merkle wit to exmerklewit and public key char merklebuffer[800]; //size of publickey is the max size of the buffer unsigned int i; for(i = 0; i < sizeof(merklewit); i++) { if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) /*test for partition beetween merkle segments*/ break; merklebuffer[i] = merklewit[i]; } memcpy(&pubkey, &merklebuffer, sizeof(merklebuffer)); int o = 0; int r = 0; //number of times we have reset o count for(; i < sizeof(merklewit); i++) { if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) { memcpy(&exmerklewit[r], &merklebuffer, sizeof(merklebuffer)); r++; i++; //get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle o = 0; } else { merklebuffer[o] = merklewit[i]; o++; } } //end decoding merkle wit format //start checking if new publickey is a part of the root key for(int i = 0; !merklecheckfin; i++) //to end if false we will use return to lower processing time { return false; } //end checking if new publickey is a part of the root key /* unsigned char* datapart; unsigned char[(160/LAMPORT::chuncksize)]* datahashs; for(int i = 0; i < (160/LAMPORT::chuncksize); i++) { for(int o = 0; o < chuncksizeinbyte; o++) { datapart[o] = data[(i * LAMPORT::chuncksize) + o]; } CRIPEMD160().Write(begin_ptr(datapart), datapart.size()).Finalize(begin_ptr(datahashs[i])); } */ return true; // if compleats all tests return true } char *** LAMPORT::createsig(unsigned char data[10000], uint512_t prikey, int sellectedpubkey) { /* hash of the message */ bool messhashb[160]; unsigned char messhash[20]; CRIPEMD160().Write(&data, 10000).Finalize(&messhash); /* creating true key from seed (the seed is used as the key by the user but it only is a form of compress key) */ unsigned char vchHash[20]; unsigned char prikeychar[64]; memcpy(&prikeychar, &prikey, 64); CRIPEMD160().Write(&prikeychar, 64).Finalize(&vchHash); char temphash[20]; char ichar; for(int i =0; i < 320; i++) { memcpy(&ichar, &i, 1); CRIPEMD160().Write(&vchHash, sizeof(vchHash)).Write(&ichar, sizeof(ichar)).Finalize(&temphash); memcpy(&prikeys[i], &temphash, sizeof(temphash)); } /* the signing will happen under this */ char sig[20][2][20]; return &sig; } <|endoftext|>
<commit_before>#include <cmath> #include <string> #include <ros/ros.h> #include <dynamic_reconfigure/server.h> #include <tf/transform_broadcaster.h> #include <nav_msgs/Odometry.h> #include <std_msgs/Float64.h> #include <jaguar/diff_drive.h> #include <jaguar/JaguarConfig.h> using namespace can; using namespace jaguar; static ros::Subscriber sub_twist; static ros::Publisher pub_odom; static ros::Publisher pub_vleft, pub_vright; static DiffDriveSettings settings; static boost::shared_ptr<DiffDriveRobot> robot; static boost::shared_ptr<tf::TransformBroadcaster> pub_tf; static std::string frame_parent; static std::string frame_child; void callback_odom(double x, double y, double theta, double vx, double vy, double omega) { ros::Time now = ros::Time::now(); // odom TF Frame geometry_msgs::TransformStamped msg_tf; msg_tf.header.stamp = now; msg_tf.header.frame_id = frame_parent; msg_tf.child_frame_id = frame_child; msg_tf.transform.translation.x = x; msg_tf.transform.translation.y = y; msg_tf.transform.rotation = tf::createQuaternionMsgFromYaw(theta); pub_tf->sendTransform(msg_tf); // Odometry Message nav_msgs::Odometry msg_odom; msg_odom.header.stamp = now; msg_odom.header.frame_id = frame_parent; msg_odom.child_frame_id = frame_child; msg_odom.pose.pose.position.x = x; msg_odom.pose.pose.position.y = y; msg_odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(theta); msg_odom.twist.twist.linear.x = vx; msg_odom.twist.twist.linear.y = vy; msg_odom.twist.twist.angular.z = omega; pub_odom.publish(msg_odom); } void callback_speed(DiffDriveRobot::Side side, double speed) { std_msgs::Float64 msg; msg.data = speed; switch (side) { case DiffDriveRobot::kLeft: pub_vleft.publish(msg); break; case DiffDriveRobot::kRight: pub_vright.publish(msg); break; default: ROS_WARN_THROTTLE(10, "Invalid speed callback."); } } void callback_cmd(geometry_msgs::Twist const &twist) { if (twist.linear.y != 0.0 || twist.linear.z != 0 || twist.angular.x != 0.0 || twist.angular.y != 0) { ROS_WARN_THROTTLE(10.0, "Ignoring non-zero component of velocity command."); } robot->drive(twist.linear.x, twist.angular.z); } void callback_reconfigure(jaguar::JaguarConfig &config, uint32_t level) { // Speed Control Gains if (level & 1) { robot->speed_set_p(config.gain_p); ROS_INFO("Reconfigure, P = %f", config.gain_p); } if (level & 2) { robot->speed_set_i(config.gain_i); ROS_INFO("Reconfigure, I = %f", config.gain_i); } if (level & 4) { robot->speed_set_d(config.gain_d); ROS_INFO("Reconfigure, D = %f", config.gain_d); } if (level & 8) { robot->drive_brake(config.brake); ROS_INFO("Reconfigure, Braking = %d", config.brake); } if (level & 16) { if (0 < config.ticks_per_rev && config.ticks_per_rev <= std::numeric_limits<uint16_t>::max()) { robot->robot_set_encoders(config.ticks_per_rev); ROS_INFO("Reconfigure, Ticks/Rev = %d", config.ticks_per_rev); } else { ROS_WARN("Ticks/rev must be a positive 16-bit unsigned integer."); } } if (level & 32) { if (config.wheel_radius <= 0) { ROS_WARN("Wheel radius must be positive."); } else if (config.robot_radius <= 0) { ROS_WARN("Robot radius must be positive."); } else { robot->robot_set_radii(config.wheel_radius, config.robot_radius); ROS_INFO("Reconfigure, Wheel Radius = %f m and Robot Radius = %f m", config.wheel_radius, config.robot_radius ); } } if (level & 64) { robot->drive_raw(config.setpoint, config.setpoint); ROS_INFO("Reconfigure, Setpoint = %f", config.setpoint); } } int main(int argc, char **argv) { ros::init(argc, argv, "diff_drive_node"); ros::NodeHandle nh; int ticks_per_rev; ros::param::get("~port", settings.port); ros::param::get("~id_left", settings.id_left); ros::param::get("~id_right", settings.id_right); ros::param::get("~heartbeat", settings.heartbeat_ms); ros::param::get("~status", settings.status_ms); ros::param::get("~frame_parent", frame_parent); ros::param::get("~frame_child", frame_child); ros::param::get("~accel_max", settings.accel_max_mps2); settings.ticks_per_rev = static_cast<uint16_t>(ticks_per_rev); ROS_INFO("Port: %s", settings.port.c_str()); ROS_INFO("ID Left: %d", settings.id_left); ROS_INFO("ID Right: %d", settings.id_right); ROS_INFO("Heartbeat Rate: %d ms", settings.heartbeat_ms); ROS_INFO("Status Rate: %d ms", settings.status_ms); // TODO: Read this from a parameter. settings.brake = BrakeCoastSetting::kOverrideCoast; if (!(1 <= settings.id_left && settings.id_left <= 63) || !(1 <= settings.id_right && settings.id_right <= 63)) { ROS_FATAL("Invalid CAN device id. Must be in the range 1-63."); return 1; } else if (settings.heartbeat_ms <= 0 || settings.heartbeat_ms > 100) { ROS_FATAL("Heartbeat period invalid. Must be in the range 1-500 ms."); return 1; } else if (settings.status_ms <= 0 || settings.status_ms > std::numeric_limits<uint16_t>::max()) { ROS_FATAL("Status period invalid must be in the range 1-255 ms."); return 1; } else if (ticks_per_rev <= 0) { ROS_FATAL("Number of ticks per revolution must be positive"); return 1; } else if (settings.wheel_radius_m <= 0) { ROS_FATAL("Wheel radius must be positive."); return 1; } else if (settings.robot_radius_m <= 0) { ROS_FATAL("Robot radius must be positive."); return 1; } // This must be done first because the asynchronous encoder callbacks use // the transform broadcaster. sub_twist = nh.subscribe("cmd_vel", 1, &callback_cmd); pub_odom = nh.advertise<nav_msgs::Odometry>("odom", 100); pub_vleft = nh.advertise<std_msgs::Float64>("encoder_left", 100); pub_vright = nh.advertise<std_msgs::Float64>("encoder_right", 100); pub_tf = boost::make_shared<tf::TransformBroadcaster>(); dynamic_reconfigure::Server<jaguar::JaguarConfig> server; dynamic_reconfigure::Server<jaguar::JaguarConfig>::CallbackType f; f = boost::bind(&callback_reconfigure, _1, _2); server.setCallback(f); robot = boost::make_shared<DiffDriveRobot>(settings); robot->odom_attach(&callback_odom); robot->speed_attach(&callback_speed); // TODO: Read this heartbeat rate from a parameter. ros::Rate heartbeat_rate(50); while (ros::ok()) { robot->drive_spin(1 / 50.); robot->heartbeat(); ros::spinOnce(); heartbeat_rate.sleep(); } return 0; } <commit_msg>removed unused variable<commit_after>#include <cmath> #include <string> #include <ros/ros.h> #include <dynamic_reconfigure/server.h> #include <tf/transform_broadcaster.h> #include <nav_msgs/Odometry.h> #include <std_msgs/Float64.h> #include <jaguar/diff_drive.h> #include <jaguar/JaguarConfig.h> using namespace can; using namespace jaguar; static ros::Subscriber sub_twist; static ros::Publisher pub_odom; static ros::Publisher pub_vleft, pub_vright; static DiffDriveSettings settings; static boost::shared_ptr<DiffDriveRobot> robot; static boost::shared_ptr<tf::TransformBroadcaster> pub_tf; static std::string frame_parent; static std::string frame_child; void callback_odom(double x, double y, double theta, double vx, double vy, double omega) { ros::Time now = ros::Time::now(); // odom TF Frame geometry_msgs::TransformStamped msg_tf; msg_tf.header.stamp = now; msg_tf.header.frame_id = frame_parent; msg_tf.child_frame_id = frame_child; msg_tf.transform.translation.x = x; msg_tf.transform.translation.y = y; msg_tf.transform.rotation = tf::createQuaternionMsgFromYaw(theta); pub_tf->sendTransform(msg_tf); // Odometry Message nav_msgs::Odometry msg_odom; msg_odom.header.stamp = now; msg_odom.header.frame_id = frame_parent; msg_odom.child_frame_id = frame_child; msg_odom.pose.pose.position.x = x; msg_odom.pose.pose.position.y = y; msg_odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(theta); msg_odom.twist.twist.linear.x = vx; msg_odom.twist.twist.linear.y = vy; msg_odom.twist.twist.angular.z = omega; pub_odom.publish(msg_odom); } void callback_speed(DiffDriveRobot::Side side, double speed) { std_msgs::Float64 msg; msg.data = speed; switch (side) { case DiffDriveRobot::kLeft: pub_vleft.publish(msg); break; case DiffDriveRobot::kRight: pub_vright.publish(msg); break; default: ROS_WARN_THROTTLE(10, "Invalid speed callback."); } } void callback_cmd(geometry_msgs::Twist const &twist) { if (twist.linear.y != 0.0 || twist.linear.z != 0 || twist.angular.x != 0.0 || twist.angular.y != 0) { ROS_WARN_THROTTLE(10.0, "Ignoring non-zero component of velocity command."); } robot->drive(twist.linear.x, twist.angular.z); } void callback_reconfigure(jaguar::JaguarConfig &config, uint32_t level) { // Speed Control Gains if (level & 1) { robot->speed_set_p(config.gain_p); ROS_INFO("Reconfigure, P = %f", config.gain_p); } if (level & 2) { robot->speed_set_i(config.gain_i); ROS_INFO("Reconfigure, I = %f", config.gain_i); } if (level & 4) { robot->speed_set_d(config.gain_d); ROS_INFO("Reconfigure, D = %f", config.gain_d); } if (level & 8) { robot->drive_brake(config.brake); ROS_INFO("Reconfigure, Braking = %d", config.brake); } if (level & 16) { if (0 < config.ticks_per_rev && config.ticks_per_rev <= std::numeric_limits<uint16_t>::max()) { robot->robot_set_encoders(config.ticks_per_rev); ROS_INFO("Reconfigure, Ticks/Rev = %d", config.ticks_per_rev); } else { ROS_WARN("Ticks/rev must be a positive 16-bit unsigned integer."); } } if (level & 32) { if (config.wheel_radius <= 0) { ROS_WARN("Wheel radius must be positive."); } else if (config.robot_radius <= 0) { ROS_WARN("Robot radius must be positive."); } else { robot->robot_set_radii(config.wheel_radius, config.robot_radius); ROS_INFO("Reconfigure, Wheel Radius = %f m and Robot Radius = %f m", config.wheel_radius, config.robot_radius ); } } if (level & 64) { robot->drive_raw(config.setpoint, config.setpoint); ROS_INFO("Reconfigure, Setpoint = %f", config.setpoint); } } int main(int argc, char **argv) { ros::init(argc, argv, "diff_drive_node"); ros::NodeHandle nh; ros::param::get("~port", settings.port); ros::param::get("~id_left", settings.id_left); ros::param::get("~id_right", settings.id_right); ros::param::get("~heartbeat", settings.heartbeat_ms); ros::param::get("~status", settings.status_ms); ros::param::get("~frame_parent", frame_parent); ros::param::get("~frame_child", frame_child); ros::param::get("~accel_max", settings.accel_max_mps2); ROS_INFO("Port: %s", settings.port.c_str()); ROS_INFO("ID Left: %d", settings.id_left); ROS_INFO("ID Right: %d", settings.id_right); ROS_INFO("Heartbeat Rate: %d ms", settings.heartbeat_ms); ROS_INFO("Status Rate: %d ms", settings.status_ms); // TODO: Read this from a parameter. settings.brake = BrakeCoastSetting::kOverrideCoast; if (!(1 <= settings.id_left && settings.id_left <= 63) || !(1 <= settings.id_right && settings.id_right <= 63)) { ROS_FATAL("Invalid CAN device id. Must be in the range 1-63."); return 1; } else if (settings.heartbeat_ms <= 0 || settings.heartbeat_ms > 100) { ROS_FATAL("Heartbeat period invalid. Must be in the range 1-500 ms."); return 1; } else if (settings.status_ms <= 0 || settings.status_ms > std::numeric_limits<uint16_t>::max()) { ROS_FATAL("Status period invalid must be in the range 1-255 ms."); return 1; } else if (ticks_per_rev <= 0) { ROS_FATAL("Number of ticks per revolution must be positive"); return 1; } else if (settings.wheel_radius_m <= 0) { ROS_FATAL("Wheel radius must be positive."); return 1; } else if (settings.robot_radius_m <= 0) { ROS_FATAL("Robot radius must be positive."); return 1; } // This must be done first because the asynchronous encoder callbacks use // the transform broadcaster. sub_twist = nh.subscribe("cmd_vel", 1, &callback_cmd); pub_odom = nh.advertise<nav_msgs::Odometry>("odom", 100); pub_vleft = nh.advertise<std_msgs::Float64>("encoder_left", 100); pub_vright = nh.advertise<std_msgs::Float64>("encoder_right", 100); pub_tf = boost::make_shared<tf::TransformBroadcaster>(); dynamic_reconfigure::Server<jaguar::JaguarConfig> server; dynamic_reconfigure::Server<jaguar::JaguarConfig>::CallbackType f; f = boost::bind(&callback_reconfigure, _1, _2); server.setCallback(f); robot = boost::make_shared<DiffDriveRobot>(settings); robot->odom_attach(&callback_odom); robot->speed_attach(&callback_speed); // TODO: Read this heartbeat rate from a parameter. ros::Rate heartbeat_rate(50); while (ros::ok()) { robot->drive_spin(1 / 50.); robot->heartbeat(); ros::spinOnce(); heartbeat_rate.sleep(); } return 0; } <|endoftext|>
<commit_before>#ifndef _SNARKFRONT_COMPILE_QAP_HPP_ #define _SNARKFRONT_COMPILE_QAP_HPP_ #include <array> #include <cstdint> #include <fstream> #include <functional> #include <string> // snarklib #include <AuxSTL.hpp> #include <HugeSystem.hpp> #include <IndexSpace.hpp> #include <PPZK_randomness.hpp> #include <QAP_query.hpp> #include <QAP_system.hpp> #include <QAP_witness.hpp> #include <Rank1DSL.hpp> #include <Util.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // query ABCH // template <typename PAIRING> class QAP_query_ABCH { typedef typename PAIRING::Fr FR; typedef typename snarklib::QAP_QueryABC<snarklib::HugeSystem, FR> Q_ABC; typedef typename snarklib::QAP_QueryH<snarklib::HugeSystem, FR> Q_H; typedef typename snarklib::QAP_SystemPoint<snarklib::HugeSystem, FR> SYSPT; public: QAP_query_ABCH(const std::size_t numBlocks, const std::string& sysfile, const std::string& randfile) : m_numBlocks(numBlocks), m_hugeSystem(sysfile) { std::ifstream ifs(randfile); m_error = !ifs || !m_lagrangePoint.marshal_in(ifs) || !m_hugeSystem.loadIndex(); } // for g1_exp_count() and g2_exp_count() only QAP_query_ABCH(const std::string& sysfile) : m_numBlocks(0), m_hugeSystem(sysfile) { m_error = !m_hugeSystem.loadIndex(); } bool operator! () const { return m_error; } void A(const std::string& outfile) { writeFilesABC(outfile, Q_ABC::VecSelect::A); } void B(const std::string& outfile) { writeFilesABC(outfile, Q_ABC::VecSelect::B); } void C(const std::string& outfile) { writeFilesABC(outfile, Q_ABC::VecSelect::C); } void H(const std::string& outfile) { writeFilesH(outfile); } std::size_t g1_exp_count(const std::string& afile, const std::string& bfile, const std::string& cfile, const std::string& hfile) { return snarklib::g1_exp_count( m_hugeSystem.maxIndex(), // same as QAP numVariables() m_hugeSystem.numCircuitInputs(), // same as QAP numCircuitInputs() nonzeroCount(afile), nonzeroCount(bfile), nonzeroCount(cfile), nonzeroCount(hfile)); } std::size_t g2_exp_count(const std::string& bfile) { return snarklib::g2_exp_count( nonzeroCount(bfile)); } private: template <typename QUERY> void writeFiles(const std::string& outfile, std::function<QUERY (const SYSPT&)> func) { const SYSPT qap(m_hugeSystem, m_hugeSystem.numCircuitInputs(), m_lagrangePoint.point()); const auto Q = func(qap); auto space = snarklib::BlockVector<FR>::space(Q.vec()); space.blockPartition(std::array<size_t, 1>{m_numBlocks}); space.param(Q.nonzeroCount()); std::ofstream ofs(outfile); if (!ofs || !write_blockvector(outfile, space, Q.vec())) m_error = true; else space.marshal_out(ofs); } void writeFilesABC(const std::string& outfile, const unsigned int mask) { writeFiles<Q_ABC>( outfile, [&mask] (const SYSPT& qap) { return Q_ABC(qap, mask); }); } void writeFilesH(const std::string& outfile) { writeFiles<Q_H>( outfile, [] (const SYSPT& qap) { return Q_H(qap); }); } std::size_t nonzeroCount(const std::string& abchfile) { snarklib::IndexSpace<1> space; std::ifstream ifs(abchfile); return (!ifs || !space.marshal_in(ifs)) ? m_error = false : space.param()[0]; } const std::size_t m_numBlocks; snarklib::PPZK_LagrangePoint<FR> m_lagrangePoint; snarklib::HugeSystem<FR> m_hugeSystem; bool m_error; }; //////////////////////////////////////////////////////////////////////////////// // query K // template <typename PAIRING> class QAP_query_K { typedef typename PAIRING::Fr FR; typedef typename snarklib::QAP_SystemPoint<snarklib::HugeSystem, FR> SYSPT; public: QAP_query_K(const std::string& afile, const std::string& bfile, const std::string& cfile, const std::string& sysfile, const std::string& randfile) : m_afile(afile), m_bfile(bfile), m_cfile(cfile), m_hugeSystem(sysfile) { std::ifstream ifs(randfile); m_error = !ifs || !m_lagrangePoint.marshal_in(ifs) || !m_clearGreeks.marshal_in(ifs) || !m_hugeSystem.loadIndex(); } bool operator! () const { return m_error; } void K(const std::string& outfile, const std::size_t blocknum) { writeFiles(outfile, blocknum); } private: void writeFiles(const std::string& outfile, const std::size_t blocknum) { const SYSPT qap(m_hugeSystem, m_hugeSystem.numCircuitInputs(), m_lagrangePoint.point()); snarklib::QAP_QueryK<FR> Q(qap, m_clearGreeks.beta_rA(), m_clearGreeks.beta_rB(), m_clearGreeks.beta_rC()); std::size_t block = (-1 == blocknum) ? 0 : blocknum; bool b = true; while (b) { snarklib::BlockVector<FR> A, B, C; if (!snarklib::read_blockvector(m_afile, block, A) || !snarklib::read_blockvector(m_bfile, block, B) || !snarklib::read_blockvector(m_cfile, block, C)) { m_error = true; return; } const auto& space = A.space(); Q.accumVector(A, B, C); if (!snarklib::write_blockvector(outfile, block, space, Q.vec())) { m_error = true; return; } b = (-1 == blocknum) ? ++block < space.blockID()[0] : false; if (!b) { std::ofstream ofs(outfile); if (!ofs) m_error = true; else space.marshal_out(ofs); } } } const std::string m_afile, m_bfile, m_cfile; snarklib::PPZK_LagrangePoint<FR> m_lagrangePoint; snarklib::PPZK_BlindGreeks<FR, FR> m_clearGreeks; snarklib::HugeSystem<FR> m_hugeSystem; bool m_error; }; //////////////////////////////////////////////////////////////////////////////// // query IC // template <typename PAIRING> class QAP_query_IC { typedef typename PAIRING::Fr FR; typedef typename PAIRING::G1 G1; typedef typename PAIRING::G2 G2; typedef typename snarklib::QAP_SystemPoint<snarklib::HugeSystem, FR> SYSPT; public: QAP_query_IC(const std::string& afile, // side-effect: file is modified const std::string& sysfile, const std::string& randfile) : m_afile(afile), m_hugeSystem(sysfile) { std::ifstream ifs(randfile); m_error = !ifs || !m_lagrangePoint.marshal_in(ifs) || !m_hugeSystem.loadIndex(); } bool operator! () const { return m_error; } void IC(const std::string& outfile) { writeFiles(outfile); } private: void writeFiles(const std::string& outfile) { const SYSPT qap(m_hugeSystem, m_hugeSystem.numCircuitInputs(), m_lagrangePoint.point()); snarklib::QAP_QueryIC<FR> Q(qap); std::size_t block = 0; bool b = true; while (b) { snarklib::BlockVector<FR> A; if (!snarklib::read_blockvector(m_afile, block, A)) { m_error = true; return; } if (!Q.accumVector(A)) break; std::stringstream ss; ss << m_afile << block; std::ofstream ofs(ss.str()); if (!ofs) m_error = true; else A.marshal_out(ofs); // side-effect: write back to file b = ++block < A.space().blockID()[0]; } std::ofstream ofs(outfile); const auto space = snarklib::BlockVector<FR>::space(Q.vec()); if (!ofs || !snarklib::write_blockvector(outfile, space, Q.vec())) m_error = true; else space.marshal_out(ofs); } const std::string m_afile; snarklib::PPZK_LagrangePoint<FR> m_lagrangePoint; snarklib::HugeSystem<FR> m_hugeSystem; bool m_error; }; //////////////////////////////////////////////////////////////////////////////// // witness ABCH // template <typename PAIRING> class QAP_witness_ABCH { typedef typename PAIRING::Fr FR; typedef typename snarklib::QAP_SystemPoint<snarklib::HugeSystem, FR> SYSPT; public: QAP_witness_ABCH(const std::size_t numBlocks, const std::string& sysfile, const std::string& randfile, const std::string& witfile) : m_numBlocks(numBlocks), m_hugeSystem(sysfile) { std::ifstream ifsR(randfile), ifsW(witfile); m_error = !ifsR || !m_randomness.marshal_in(ifsR) || !ifsW || !m_witness.marshal_in(ifsW) || !m_hugeSystem.loadIndex(); } bool operator! () const { return m_error; } void writeFiles(const std::string& outfile) { const SYSPT qap(m_hugeSystem, m_hugeSystem.numCircuitInputs()); const snarklib::QAP_WitnessABCH<snarklib::HugeSystem, FR> ABCH(qap, m_witness, m_randomness.d1(), m_randomness.d2(), m_randomness.d3()); auto space = snarklib::BlockVector<FR>::space(ABCH.vec()); space.blockPartition(std::array<size_t, 1>{m_numBlocks}); if (! write_blockvector(outfile, space, ABCH.vec())) m_error = true; } private: const std::size_t m_numBlocks; snarklib::R1Witness<FR> m_witness; snarklib::PPZK_ProofRandomness<FR> m_randomness; snarklib::HugeSystem<FR> m_hugeSystem; bool m_error; }; } // namespace snarkfront #endif <commit_msg>constructor randomness arguments<commit_after>#ifndef _SNARKFRONT_COMPILE_QAP_HPP_ #define _SNARKFRONT_COMPILE_QAP_HPP_ #include <array> #include <cstdint> #include <fstream> #include <functional> #include <string> // snarklib #include <AuxSTL.hpp> #include <HugeSystem.hpp> #include <IndexSpace.hpp> #include <PPZK_randomness.hpp> #include <QAP_query.hpp> #include <QAP_system.hpp> #include <QAP_witness.hpp> #include <Rank1DSL.hpp> #include <Util.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // query ABCH // template <typename PAIRING> class QAP_query_ABCH { typedef typename PAIRING::Fr FR; typedef typename snarklib::QAP_QueryABC<snarklib::HugeSystem, FR> Q_ABC; typedef typename snarklib::QAP_QueryH<snarklib::HugeSystem, FR> Q_H; typedef typename snarklib::QAP_SystemPoint<snarklib::HugeSystem, FR> SYSPT; public: QAP_query_ABCH(const std::size_t numBlocks, const std::string& sysfile, const std::string& randfile) : m_numBlocks(numBlocks), m_hugeSystem(sysfile) { std::ifstream ifs(randfile); m_error = !ifs || !m_lagrangePoint.marshal_in(ifs) || !m_hugeSystem.loadIndex(); } QAP_query_ABCH(const std::size_t numBlocks, const std::string& sysfile, const snarklib::PPZK_LagrangePoint<FR>& lagrangeRand) : m_numBlocks(numBlocks), m_hugeSystem(sysfile), m_lagrangePoint(lagrangeRand) { m_error = !m_hugeSystem.loadIndex(); } // for g1_exp_count() and g2_exp_count() only QAP_query_ABCH(const std::string& sysfile) : m_numBlocks(0), m_hugeSystem(sysfile) { m_error = !m_hugeSystem.loadIndex(); } bool operator! () const { return m_error; } void A(const std::string& outfile) { writeFilesABC(outfile, Q_ABC::VecSelect::A); } void B(const std::string& outfile) { writeFilesABC(outfile, Q_ABC::VecSelect::B); } void C(const std::string& outfile) { writeFilesABC(outfile, Q_ABC::VecSelect::C); } void H(const std::string& outfile) { writeFilesH(outfile); } std::size_t g1_exp_count(const std::string& afile, const std::string& bfile, const std::string& cfile, const std::string& hfile) { return snarklib::g1_exp_count( m_hugeSystem.maxIndex(), // same as QAP numVariables() m_hugeSystem.numCircuitInputs(), // same as QAP numCircuitInputs() nonzeroCount(afile), nonzeroCount(bfile), nonzeroCount(cfile), nonzeroCount(hfile)); } std::size_t g2_exp_count(const std::string& bfile) { return snarklib::g2_exp_count( nonzeroCount(bfile)); } private: template <typename QUERY> void writeFiles(const std::string& outfile, std::function<QUERY (const SYSPT&)> func) { const SYSPT qap(m_hugeSystem, m_hugeSystem.numCircuitInputs(), m_lagrangePoint.point()); const auto Q = func(qap); auto space = snarklib::BlockVector<FR>::space(Q.vec()); space.blockPartition(std::array<size_t, 1>{m_numBlocks}); space.param(Q.nonzeroCount()); std::ofstream ofs(outfile); if (!ofs || !write_blockvector(outfile, space, Q.vec())) m_error = true; else space.marshal_out(ofs); } void writeFilesABC(const std::string& outfile, const unsigned int mask) { writeFiles<Q_ABC>( outfile, [&mask] (const SYSPT& qap) { return Q_ABC(qap, mask); }); } void writeFilesH(const std::string& outfile) { writeFiles<Q_H>( outfile, [] (const SYSPT& qap) { return Q_H(qap); }); } std::size_t nonzeroCount(const std::string& abchfile) { snarklib::IndexSpace<1> space; std::ifstream ifs(abchfile); return (!ifs || !space.marshal_in(ifs)) ? m_error = false : space.param()[0]; } const std::size_t m_numBlocks; snarklib::PPZK_LagrangePoint<FR> m_lagrangePoint; snarklib::HugeSystem<FR> m_hugeSystem; bool m_error; }; //////////////////////////////////////////////////////////////////////////////// // query K // template <typename PAIRING> class QAP_query_K { typedef typename PAIRING::Fr FR; typedef typename snarklib::QAP_SystemPoint<snarklib::HugeSystem, FR> SYSPT; public: QAP_query_K(const std::string& afile, const std::string& bfile, const std::string& cfile, const std::string& sysfile, const std::string& randfile) : m_afile(afile), m_bfile(bfile), m_cfile(cfile), m_hugeSystem(sysfile) { std::ifstream ifs(randfile); m_error = !ifs || !m_lagrangePoint.marshal_in(ifs) || !m_clearGreeks.marshal_in(ifs) || !m_hugeSystem.loadIndex(); } QAP_query_K(const std::string& afile, const std::string& bfile, const std::string& cfile, const std::string& sysfile, const snarklib::PPZK_LagrangePoint<FR>& lagrangeRand, const snarklib::PPZK_BlindGreeks<FR, FR>& greeksRand) : m_afile(afile), m_bfile(bfile), m_cfile(cfile), m_hugeSystem(sysfile), m_lagrangePoint(lagrangeRand), m_clearGreeks(greeksRand) { m_error = !m_hugeSystem.loadIndex(); } bool operator! () const { return m_error; } void K(const std::string& outfile, const std::size_t blocknum) { writeFiles(outfile, blocknum); } private: void writeFiles(const std::string& outfile, const std::size_t blocknum) { const SYSPT qap(m_hugeSystem, m_hugeSystem.numCircuitInputs(), m_lagrangePoint.point()); snarklib::QAP_QueryK<FR> Q(qap, m_clearGreeks.beta_rA(), m_clearGreeks.beta_rB(), m_clearGreeks.beta_rC()); std::size_t block = (-1 == blocknum) ? 0 : blocknum; bool b = true; while (b) { snarklib::BlockVector<FR> A, B, C; if (!snarklib::read_blockvector(m_afile, block, A) || !snarklib::read_blockvector(m_bfile, block, B) || !snarklib::read_blockvector(m_cfile, block, C)) { m_error = true; return; } const auto& space = A.space(); Q.accumVector(A, B, C); if (!snarklib::write_blockvector(outfile, block, space, Q.vec())) { m_error = true; return; } b = (-1 == blocknum) ? ++block < space.blockID()[0] : false; if (!b) { std::ofstream ofs(outfile); if (!ofs) m_error = true; else space.marshal_out(ofs); } } } const std::string m_afile, m_bfile, m_cfile; snarklib::PPZK_LagrangePoint<FR> m_lagrangePoint; snarklib::PPZK_BlindGreeks<FR, FR> m_clearGreeks; snarklib::HugeSystem<FR> m_hugeSystem; bool m_error; }; //////////////////////////////////////////////////////////////////////////////// // query IC // template <typename PAIRING> class QAP_query_IC { typedef typename PAIRING::Fr FR; typedef typename PAIRING::G1 G1; typedef typename PAIRING::G2 G2; typedef typename snarklib::QAP_SystemPoint<snarklib::HugeSystem, FR> SYSPT; public: QAP_query_IC(const std::string& afile, // side-effect: file is modified const std::string& sysfile, const std::string& randfile) : m_afile(afile), m_hugeSystem(sysfile) { std::ifstream ifs(randfile); m_error = !ifs || !m_lagrangePoint.marshal_in(ifs) || !m_hugeSystem.loadIndex(); } QAP_query_IC(const std::string& afile, // side-effect: file is modified const std::string& sysfile, const snarklib::PPZK_LagrangePoint<FR>& lagrangeRand) : m_afile(afile), m_hugeSystem(sysfile), m_lagrangePoint(lagrangeRand) { m_error = !m_hugeSystem.loadIndex(); } bool operator! () const { return m_error; } void IC(const std::string& outfile) { writeFiles(outfile); } private: void writeFiles(const std::string& outfile) { const SYSPT qap(m_hugeSystem, m_hugeSystem.numCircuitInputs(), m_lagrangePoint.point()); snarklib::QAP_QueryIC<FR> Q(qap); std::size_t block = 0; bool b = true; while (b) { snarklib::BlockVector<FR> A; if (!snarklib::read_blockvector(m_afile, block, A)) { m_error = true; return; } if (!Q.accumVector(A)) break; std::stringstream ss; ss << m_afile << block; std::ofstream ofs(ss.str()); if (!ofs) m_error = true; else A.marshal_out(ofs); // side-effect: write back to file b = ++block < A.space().blockID()[0]; } std::ofstream ofs(outfile); const auto space = snarklib::BlockVector<FR>::space(Q.vec()); if (!ofs || !snarklib::write_blockvector(outfile, space, Q.vec())) m_error = true; else space.marshal_out(ofs); } const std::string m_afile; snarklib::PPZK_LagrangePoint<FR> m_lagrangePoint; snarklib::HugeSystem<FR> m_hugeSystem; bool m_error; }; //////////////////////////////////////////////////////////////////////////////// // witness ABCH // template <typename PAIRING> class QAP_witness_ABCH { typedef typename PAIRING::Fr FR; typedef typename snarklib::QAP_SystemPoint<snarklib::HugeSystem, FR> SYSPT; public: QAP_witness_ABCH(const std::size_t numBlocks, const std::string& sysfile, const std::string& randfile, const std::string& witfile) : m_numBlocks(numBlocks), m_hugeSystem(sysfile) { std::ifstream ifsR(randfile), ifsW(witfile); m_error = !ifsR || !m_randomness.marshal_in(ifsR) || !ifsW || !m_witness.marshal_in(ifsW) || !m_hugeSystem.loadIndex(); } QAP_witness_ABCH(const std::size_t numBlocks, const std::string& sysfile, const snarklib::PPZK_ProofRandomness<FR>& proofRand, const std::string& witfile) : m_numBlocks(numBlocks), m_hugeSystem(sysfile), m_randomness(proofRand) { std::ifstream ifs(witfile); m_error = !ifs || !m_witness.marshal_in(ifs) || !m_hugeSystem.loadIndex(); } bool operator! () const { return m_error; } void writeFiles(const std::string& outfile) { const SYSPT qap(m_hugeSystem, m_hugeSystem.numCircuitInputs()); const snarklib::QAP_WitnessABCH<snarklib::HugeSystem, FR> ABCH(qap, m_witness, m_randomness.d1(), m_randomness.d2(), m_randomness.d3()); auto space = snarklib::BlockVector<FR>::space(ABCH.vec()); space.blockPartition(std::array<size_t, 1>{m_numBlocks}); if (! write_blockvector(outfile, space, ABCH.vec())) m_error = true; } private: const std::size_t m_numBlocks; snarklib::R1Witness<FR> m_witness; snarklib::PPZK_ProofRandomness<FR> m_randomness; snarklib::HugeSystem<FR> m_hugeSystem; bool m_error; }; } // namespace snarkfront #endif <|endoftext|>
<commit_before>/** * @file Connection.cpp * @brief * @author Travis Lane * @version 0.0.1 * @date 2016-01-05 */ #include "Connection.h" Connection::Connection(Bluetooth &new_bt, int id) : bt(new_bt) { this->id = id; } int Connection::write(int percent) { int rc = 0; StaticJsonBuffer<200> buffer; JsonObject& object = buffer.createObject(); if (!bt.connected()) { return -1; } object["id"] = this->id; object["throttle"] = percent; /* Don't pretty print, I deliminate on \n */ rc = object.printTo(bt); bt.write('\n'); return rc; } int Connection::read(int *out_percent) { int rc = 0; char buff[200]; StaticJsonBuffer<200> buffer; if (!bt.connected()) { return -1; } rc = bt.readBytesUntil('\n', buff, sizeof(buff)); if (rc <= 0) { return -1; } /* Set last char to NULL */ buff[rc] = '\0'; JsonObject& object = buffer.parseObject(buff); if (!object.success()) { return -1; } if (object["id"] != id) { /* The ID doesn't match... We should ignore this message */ return -1; } *out_percent = object["throttle"]; return rc; } <commit_msg>Change status codes for debugging<commit_after>/** * @file Connection.cpp * @brief * @author Travis Lane * @version 0.0.1 * @date 2016-01-05 */ #include "Connection.h" Connection::Connection(Bluetooth &new_bt, int id) : bt(new_bt) { this->id = id; } int Connection::write(int percent) { int rc = 0; StaticJsonBuffer<200> buffer; JsonObject& object = buffer.createObject(); if (!bt.connected()) { return -1; } object["id"] = this->id; object["throttle"] = percent; /* Don't pretty print, I deliminate on \n */ rc = object.printTo(bt); bt.write('\n'); return rc; } int Connection::read(int *out_percent) { int rc = 0; char buff[200]; StaticJsonBuffer<200> buffer; if (!bt.connected()) { return -1; } rc = bt.readBytesUntil('\n', buff, sizeof(buff)); if (rc <= 0) { return -2; } /* Set last char to NULL */ buff[rc] = '\0'; JsonObject& object = buffer.parseObject(buff); if (!object.success()) { return -3; } if (object["id"] != id) { /* The ID doesn't match... We should ignore this message */ return -4; } *out_percent = object["throttle"]; return rc; } <|endoftext|>
<commit_before>//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include <map> #include <memory> #include <string> #include <vector> #include "ngraph/pass/manager.hpp" #include "ngraph/runtime/executable.hpp" namespace ngraph { namespace runtime { class Backend; namespace hybrid { class HybridExecutable; } } // namespace runtime } // namespace ngraph class ngraph::runtime::hybrid::HybridExecutable : public runtime::Executable { public: HybridExecutable(const std::vector<std::shared_ptr<runtime::Backend>>& backend_list, const std::shared_ptr<Function>& func, bool enable_performance_collection = false, bool debug_enabled = false); bool call(const std::vector<std::shared_ptr<ngraph::runtime::Tensor>>& outputs, const std::vector<std::shared_ptr<ngraph::runtime::Tensor>>& inputs) override; template <typename T> std::shared_ptr<T> get_as() const { return std::dynamic_pointer_cast<T>(m_executable); } /// Allow overriding the configuration of the pass manager. If you overload this method /// you must define all passes. virtual void configure_passes(ngraph::pass::Manager& pass_manager); protected: std::shared_ptr<ngraph::Function> m_function; std::shared_ptr<Executable> m_executable; std::unordered_map<std::shared_ptr<ngraph::op::Parameter>, std::shared_ptr<ngraph::op::Result>> m_map_parameter_to_result; std::vector<std::shared_ptr<runtime::Backend>> m_backend_list; bool m_debug_enabled = false; }; <commit_msg>Add check to hybridexecutable::get_as. (#2998)<commit_after>//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include <map> #include <memory> #include <string> #include <vector> #include "ngraph/pass/manager.hpp" #include "ngraph/runtime/executable.hpp" namespace ngraph { namespace runtime { class Backend; namespace hybrid { class HybridExecutable; } } // namespace runtime } // namespace ngraph class ngraph::runtime::hybrid::HybridExecutable : public runtime::Executable { public: HybridExecutable(const std::vector<std::shared_ptr<runtime::Backend>>& backend_list, const std::shared_ptr<Function>& func, bool enable_performance_collection = false, bool debug_enabled = false); bool call(const std::vector<std::shared_ptr<ngraph::runtime::Tensor>>& outputs, const std::vector<std::shared_ptr<ngraph::runtime::Tensor>>& inputs) override; template <typename T> std::shared_ptr<T> get_as() const { if (auto exec = std::dynamic_pointer_cast<T>(m_executable)) { return exec; } else { throw ngraph::ngraph_error("Requested invalid ngraph::Executable subclass"); } } /// Allow overriding the configuration of the pass manager. If you overload this method /// you must define all passes. virtual void configure_passes(ngraph::pass::Manager& pass_manager); protected: std::shared_ptr<ngraph::Function> m_function; std::shared_ptr<Executable> m_executable; std::unordered_map<std::shared_ptr<ngraph::op::Parameter>, std::shared_ptr<ngraph::op::Result>> m_map_parameter_to_result; std::vector<std::shared_ptr<runtime::Backend>> m_backend_list; bool m_debug_enabled = false; }; <|endoftext|>
<commit_before>/* Copyright (c) 2018, 2019 Jouni Siren Author: Jouni Siren <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <string> #include <unistd.h> #include <gbwt/dynamic_gbwt.h> using namespace gbwt; //------------------------------------------------------------------------------ const std::string tool_name = "GBWT sequence remove"; void printUsage(int exit_code = EXIT_SUCCESS); //------------------------------------------------------------------------------ int main(int argc, char** argv) { if(argc < 3) { printUsage(); } int c = 0; std::string output; size_type chunk_size = DynamicGBWT::REMOVE_CHUNK_SIZE; bool range = false; while((c = getopt(argc, argv, "c:o:r")) != -1) { switch(c) { case 'c': chunk_size = std::max(1ul, std::stoul(optarg)); break; case 'o': output = optarg; break; case 'r': range = true; break; case '?': std::exit(EXIT_FAILURE); default: std::exit(EXIT_FAILURE); } } if(optind + 1 >= argc) { printUsage(EXIT_FAILURE); } std::string base_name = argv[optind]; optind++; if(output.empty()) { output = base_name; } std::vector<size_type> seq_ids; if(range) { if(argc != optind + 2) { printUsage(EXIT_FAILURE); } size_type start = std::stoul(argv[optind]); optind++; size_type stop = std::stoul(argv[optind]); optind++; if(stop < start) { printUsage(EXIT_FAILURE); } for(size_type seq_id = start; seq_id <= stop; seq_id++) { seq_ids.push_back(seq_id); } } else { while(optind < argc) { seq_ids.push_back(std::stoul(argv[optind])); optind++; } } Version::print(std::cout, tool_name); printHeader("Input"); std::cout << base_name << std::endl; printHeader("Output"); std::cout << output << std::endl; printHeader("Sequences"); std::cout << seq_ids.size() << std::endl; printHeader("Chunk size"); std::cout << chunk_size << std::endl; std::cout << std::endl; double start = readTimer(); DynamicGBWT index; if(!sdsl::load_from_file(index, base_name + DynamicGBWT::EXTENSION)) { std::cerr << "remove_seq: Cannot load the index from " << (base_name + DynamicGBWT::EXTENSION) << std::endl; std::exit(EXIT_FAILURE); } printStatistics(index, base_name); size_type total_length = index.remove(seq_ids, chunk_size); if(total_length > 0) { if(!sdsl::store_to_file(index, output + DynamicGBWT::EXTENSION)) { std::cerr << "remove_seq: Cannot write the index to " << (output + DynamicGBWT::EXTENSION) << std::endl; std::exit(EXIT_FAILURE); } printStatistics(index, output); } double seconds = readTimer() - start; std::cout << "Removed " << total_length << " nodes in " << seconds << " seconds (" << (total_length / seconds) << " nodes/second)" << std::endl; std::cout << "Memory usage " << inGigabytes(memoryUsage()) << " GB" << std::endl; std::cout << std::endl; return 0; } //------------------------------------------------------------------------------ void printUsage(int exit_code) { Version::print(std::cerr, tool_name); std::cerr << "Usage: remove_seq [options] base_name seq1 [seq2 ...]" << std::endl; std::cerr << std::endl; std::cerr << " -c N Build the RA in chunks of N sequences per thread (default: " << DynamicGBWT::REMOVE_CHUNK_SIZE << ")" << std::endl; std::cerr << " -o X Use X as the base name for output" << std::endl; std::cerr << " -r Remove a range of sequences (inclusive; requires 2 sequence ids)" << std::endl; std::cerr << std::endl; std::exit(exit_code); } //------------------------------------------------------------------------------ <commit_msg>Remove sequences by sample/contig in remove_seq<commit_after>/* Copyright (c) 2018, 2019 Jouni Siren Author: Jouni Siren <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <string> #include <unistd.h> #include <gbwt/dynamic_gbwt.h> using namespace gbwt; //------------------------------------------------------------------------------ const std::string tool_name = "GBWT sequence removal"; void printUsage(int exit_code = EXIT_SUCCESS); //------------------------------------------------------------------------------ int main(int argc, char** argv) { if(argc < 3) { printUsage(); } // Parse command line options. int c = 0; std::string output; size_type chunk_size = DynamicGBWT::REMOVE_CHUNK_SIZE; bool range = false, sample = false, contig = false; while((c = getopt(argc, argv, "c:o:rSC")) != -1) { switch(c) { case 'c': chunk_size = std::max(1ul, std::stoul(optarg)); break; case 'o': output = optarg; break; case 'r': range = true; break; case 'S': sample = true; break; case 'C': contig = true; break; case '?': std::exit(EXIT_FAILURE); default: std::exit(EXIT_FAILURE); } } // Check command line options. if(optind + 1 >= argc) { printUsage(EXIT_FAILURE); } if((range & sample) || (range & contig) || (sample & contig)) { std::cerr << "remove_seq: Options -r, -S, and -C are mutually exclusive" << std::endl; std::exit(EXIT_FAILURE); } std::string base_name = argv[optind]; optind++; std::string key; if(output.empty()) { output = base_name; } std::vector<size_type> seq_ids; if(range) { if(argc != optind + 2) { printUsage(EXIT_FAILURE); } size_type start = std::stoul(argv[optind]); optind++; size_type stop = std::stoul(argv[optind]); optind++; if(stop < start) { printUsage(EXIT_FAILURE); } for(size_type seq_id = start; seq_id <= stop; seq_id++) { seq_ids.push_back(seq_id); } } else if(sample || contig) { if(argc != optind + 1) { printUsage(EXIT_FAILURE); } key = argv[optind]; } else { while(optind < argc) { seq_ids.push_back(std::stoul(argv[optind])); optind++; } } // Initial output. Version::print(std::cout, tool_name); printHeader("Input"); std::cout << base_name << std::endl; printHeader("Output"); std::cout << output << std::endl; if(range) { printHeader("Range"); std::cout << range_type(seq_ids.front(), seq_ids.back()) << std::endl; } else if(sample) { printHeader("Sample"); std::cout << key << std::endl; } else if(contig) { printHeader("Contig"); std::cout << key << std::endl; } else { printHeader("Sequences"); std::cout << seq_ids.size() << std::endl; } printHeader("Chunk size"); std::cout << chunk_size << std::endl; std::cout << std::endl; double start = readTimer(); // Load index. DynamicGBWT index; if(!sdsl::load_from_file(index, base_name + DynamicGBWT::EXTENSION)) { std::cerr << "remove_seq: Cannot load the index from " << (base_name + DynamicGBWT::EXTENSION) << std::endl; std::exit(EXIT_FAILURE); } printStatistics(index, base_name); // Handle metadata. if(sample) { if(!(index.hasMetadata()) || !(index.metadata.hasSampleNames()) || !(index.metadata.hasPathNames())) { std::cerr << "remove_seq: Option -S requires sample and path names" << std::endl; std::exit(EXIT_FAILURE); } size_type sample_id = index.metadata.sample(key); seq_ids = index.metadata.removeSample(sample_id); if(seq_ids.empty()) { std::cerr << "remove_seq: No sequences for sample " << key << std::endl; std::exit(EXIT_FAILURE); } } else if(contig) { if(!(index.hasMetadata()) || !(index.metadata.hasContigNames()) || !(index.metadata.hasPathNames())) { std::cerr << "remove_seq: Option -C requires contig and path names" << std::endl; std::exit(EXIT_FAILURE); } size_type contig_id = index.metadata.contig(key); seq_ids = index.metadata.removeContig(contig_id); if(seq_ids.empty()) { std::cerr << "remove_seq: No sequences for contig " << key << std::endl; std::exit(EXIT_FAILURE); } } else { if(index.hasMetadata() && index.metadata.hasPathNames()) { std::cerr << "remove_seq: Removing arbitrary sequences would leave the metadata inconsistent" << std::endl; std::exit(EXIT_FAILURE); } } // Remove the sequences. size_type total_length = index.remove(seq_ids, chunk_size); if(total_length > 0) { if(!sdsl::store_to_file(index, output + DynamicGBWT::EXTENSION)) { std::cerr << "remove_seq: Cannot write the index to " << (output + DynamicGBWT::EXTENSION) << std::endl; std::exit(EXIT_FAILURE); } printStatistics(index, output); } double seconds = readTimer() - start; std::cout << "Removed " << total_length << " nodes in " << seconds << " seconds (" << (total_length / seconds) << " nodes/second)" << std::endl; std::cout << "Memory usage " << inGigabytes(memoryUsage()) << " GB" << std::endl; std::cout << std::endl; return 0; } //------------------------------------------------------------------------------ void printUsage(int exit_code) { Version::print(std::cerr, tool_name); std::cerr << "Usage: remove_seq [options] base_name seq1 [seq2 ...]" << std::endl; std::cerr << std::endl; std::cerr << " -c N Build the RA in chunks of N sequences per thread (default: " << DynamicGBWT::REMOVE_CHUNK_SIZE << ")" << std::endl; std::cerr << " -o X Use X as the base name for output" << std::endl; std::cerr << " -r Remove a range of sequences (inclusive; requires 2 sequence ids)" << std::endl; std::cerr << " -S Remove all sequences for the sample with name seq1 (cannot have seq2)" << std::endl; std::cerr << " -C Remove all sequences for the contig with name seq1 (cannot have seq2)" << std::endl; std::cerr << std::endl; std::exit(exit_code); } //------------------------------------------------------------------------------ <|endoftext|>
<commit_before>#include "ylikuutio_string.hpp" // Include standard headers #include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc. #include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp #include <iostream> // std::cout, std::cin, std::cerr #include <list> // std::list #include <sstream> // std::stringstream #include <string> // std::string #include <vector> // std::vector namespace string { bool check_and_report_if_some_string_matches(const char* file_base_pointer, char* file_data_pointer, std::vector<std::string> identifier_strings_vector) { for (std::string identifier_string : identifier_strings_vector) { const char* identifier_string_char = identifier_string.c_str(); if (std::strncmp(file_data_pointer, identifier_string_char, std::strlen(identifier_string_char)) == 0) { const char* identifier_string_char = identifier_string.c_str(); uint64_t offset = (uint64_t) file_data_pointer - (uint64_t) file_base_pointer; std::printf("%s found at file offset 0x%llu (memory address 0x%llu).\n", identifier_string_char, offset, (uint64_t) file_data_pointer); return true; } } return false; } void extract_string(char* dest_mem_pointer, char* &src_mem_pointer, char* char_end_string) { while (std::strncmp(src_mem_pointer, char_end_string, std::strlen(char_end_string)) != 0) { strncpy(dest_mem_pointer++, src_mem_pointer++, 1); } *dest_mem_pointer = '\0'; } void extract_string_with_several_endings(char* dest_mem_pointer, char*& src_mem_pointer, char* char_end_string) { // This function copies characters from `src_mem_pointer` until a character matches. while (true) { uint32_t n_of_ending_characters = std::strlen(char_end_string); char* end_char_pointer; end_char_pointer = char_end_string; // Check if current character is any of the ending characters. while (*end_char_pointer != '\0') { if (std::strncmp(src_mem_pointer, end_char_pointer, 1) == 0) { *dest_mem_pointer = '\0'; return; } end_char_pointer++; } // OK, current character is not any of the ending characters. // Copy it and advance the pointers accordingly. strncpy(dest_mem_pointer++, src_mem_pointer++, 1); } } int32_t extract_int32_t_value_from_string(char*& data_pointer, char* char_end_string, const char* description) { char char_number_buffer[1024]; // FIXME: risk of buffer overflow. char* dest_mem_pointer; dest_mem_pointer = char_number_buffer; string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string); uint32_t value = std::atoi(dest_mem_pointer); std::printf("%s: %d\n", description, value); return value; } float extract_float_value_from_string(char*& data_pointer, char* char_end_string, const char* description) { char char_number_buffer[1024]; // FIXME: risk of buffer overflow. char* dest_mem_pointer; dest_mem_pointer = char_number_buffer; string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string); float value = std::atof(dest_mem_pointer); std::printf("%s: %f\n", description, value); return value; } int32_t extract_unicode_value_from_string(const char*& unicode_char_pointer) { if (*unicode_char_pointer == '\0') { unicode_char_pointer++; std::cerr << "Error: Unicode can not begin with \\0!\n"; return 0xdfff; // invalid unicode! } if (*unicode_char_pointer != '&') { // it's just a character, so return its value, // and advance to the next character. return (int32_t) *unicode_char_pointer++; } if (*++unicode_char_pointer != '#') { // not valid format, must begin `"&#x"`. unicode_char_pointer++; std::cerr << "Error: Unicode string format not supported!\n"; return 0xdfff; // invalid unicode! } if (*++unicode_char_pointer != 'x') { // not valid format, must begin `"&#x"`. unicode_char_pointer++; std::cerr << "Error: Unicode string format not supported!\n"; return 0xdfff; // invalid unicode! } // valid format. std::string hex_string; // unicode string beginning with '&' while (*++unicode_char_pointer != ';') { if (*unicode_char_pointer == '\0') { std::cerr << "Error: Null character \\0 reached before end of Unicode string!\n"; return 0xdfff; // invalid unicode! } char current_char = *unicode_char_pointer; hex_string.append(unicode_char_pointer); } // Advance to the next character. unicode_char_pointer++; // convert hexadecimal string to signed integer. // http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer/1070499#1070499 uint32_t unicode_value; std::stringstream unicode_stringstream; unicode_stringstream << std::hex << hex_string; unicode_stringstream >> unicode_value; return unicode_value; } std::string convert_std_list_char_to_std_string(const std::list<char>& std_list_char) { std::string my_string; for (std::list<char>::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++) { my_string.push_back(*it); } return my_string; } std::string convert_std_list_char_to_std_string(const std::list<char>& std_list_char, uint32_t first_line_length, uint32_t line_length) { std::string my_string; uint32_t remaining_characters_on_this_line = first_line_length; for (std::list<char>::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++) { if (remaining_characters_on_this_line == 0) { my_string.push_back('\\'); my_string.push_back('n'); remaining_characters_on_this_line = line_length; } my_string.push_back(*it); remaining_characters_on_this_line--; } return my_string; } } <commit_msg>If `description` is `nullptr`, do not `printf` anything.<commit_after>#include "ylikuutio_string.hpp" // Include standard headers #include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc. #include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp #include <iostream> // std::cout, std::cin, std::cerr #include <list> // std::list #include <sstream> // std::stringstream #include <string> // std::string #include <vector> // std::vector namespace string { bool check_and_report_if_some_string_matches(const char* file_base_pointer, char* file_data_pointer, std::vector<std::string> identifier_strings_vector) { for (std::string identifier_string : identifier_strings_vector) { const char* identifier_string_char = identifier_string.c_str(); if (std::strncmp(file_data_pointer, identifier_string_char, std::strlen(identifier_string_char)) == 0) { const char* identifier_string_char = identifier_string.c_str(); uint64_t offset = (uint64_t) file_data_pointer - (uint64_t) file_base_pointer; std::printf("%s found at file offset 0x%llu (memory address 0x%llu).\n", identifier_string_char, offset, (uint64_t) file_data_pointer); return true; } } return false; } void extract_string(char* dest_mem_pointer, char* &src_mem_pointer, char* char_end_string) { while (std::strncmp(src_mem_pointer, char_end_string, std::strlen(char_end_string)) != 0) { strncpy(dest_mem_pointer++, src_mem_pointer++, 1); } *dest_mem_pointer = '\0'; } void extract_string_with_several_endings(char* dest_mem_pointer, char*& src_mem_pointer, char* char_end_string) { // This function copies characters from `src_mem_pointer` until a character matches. while (true) { uint32_t n_of_ending_characters = std::strlen(char_end_string); char* end_char_pointer; end_char_pointer = char_end_string; // Check if current character is any of the ending characters. while (*end_char_pointer != '\0') { if (std::strncmp(src_mem_pointer, end_char_pointer, 1) == 0) { *dest_mem_pointer = '\0'; return; } end_char_pointer++; } // OK, current character is not any of the ending characters. // Copy it and advance the pointers accordingly. strncpy(dest_mem_pointer++, src_mem_pointer++, 1); } } int32_t extract_int32_t_value_from_string(char*& data_pointer, char* char_end_string, const char* description) { char char_number_buffer[1024]; // FIXME: risk of buffer overflow. char* dest_mem_pointer; dest_mem_pointer = char_number_buffer; string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string); uint32_t value = std::atoi(dest_mem_pointer); if (description != nullptr) { std::printf("%s: %d\n", description, value); } return value; } float extract_float_value_from_string(char*& data_pointer, char* char_end_string, const char* description) { char char_number_buffer[1024]; // FIXME: risk of buffer overflow. char* dest_mem_pointer; dest_mem_pointer = char_number_buffer; string::extract_string_with_several_endings(dest_mem_pointer, ++data_pointer, char_end_string); float value = std::atof(dest_mem_pointer); if (description != nullptr) { std::printf("%s: %f\n", description, value); } return value; } int32_t extract_unicode_value_from_string(const char*& unicode_char_pointer) { if (*unicode_char_pointer == '\0') { unicode_char_pointer++; std::cerr << "Error: Unicode can not begin with \\0!\n"; return 0xdfff; // invalid unicode! } if (*unicode_char_pointer != '&') { // it's just a character, so return its value, // and advance to the next character. return (int32_t) *unicode_char_pointer++; } if (*++unicode_char_pointer != '#') { // not valid format, must begin `"&#x"`. unicode_char_pointer++; std::cerr << "Error: Unicode string format not supported!\n"; return 0xdfff; // invalid unicode! } if (*++unicode_char_pointer != 'x') { // not valid format, must begin `"&#x"`. unicode_char_pointer++; std::cerr << "Error: Unicode string format not supported!\n"; return 0xdfff; // invalid unicode! } // valid format. std::string hex_string; // unicode string beginning with '&' while (*++unicode_char_pointer != ';') { if (*unicode_char_pointer == '\0') { std::cerr << "Error: Null character \\0 reached before end of Unicode string!\n"; return 0xdfff; // invalid unicode! } char current_char = *unicode_char_pointer; hex_string.append(unicode_char_pointer); } // Advance to the next character. unicode_char_pointer++; // convert hexadecimal string to signed integer. // http://stackoverflow.com/questions/1070497/c-convert-hex-string-to-signed-integer/1070499#1070499 uint32_t unicode_value; std::stringstream unicode_stringstream; unicode_stringstream << std::hex << hex_string; unicode_stringstream >> unicode_value; return unicode_value; } std::string convert_std_list_char_to_std_string(const std::list<char>& std_list_char) { std::string my_string; for (std::list<char>::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++) { my_string.push_back(*it); } return my_string; } std::string convert_std_list_char_to_std_string(const std::list<char>& std_list_char, uint32_t first_line_length, uint32_t line_length) { std::string my_string; uint32_t remaining_characters_on_this_line = first_line_length; for (std::list<char>::const_iterator it = std_list_char.begin(); it != std_list_char.end(); it++) { if (remaining_characters_on_this_line == 0) { my_string.push_back('\\'); my_string.push_back('n'); remaining_characters_on_this_line = line_length; } my_string.push_back(*it); remaining_characters_on_this_line--; } return my_string; } } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/gtk_dnd_util.h" #include "base/logging.h" #include "base/pickle.h" #include "base/utf_string_conversions.h" #include "googleurl/src/gurl.h" static const int kBitsPerByte = 8; using WebKit::WebDragOperationsMask; using WebKit::WebDragOperation; using WebKit::WebDragOperationNone; using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationLink; using WebKit::WebDragOperationMove; namespace { void AddTargetToList(GtkTargetList* targets, int target_code) { switch (target_code) { case gtk_dnd_util::TEXT_PLAIN: gtk_target_list_add_text_targets(targets, gtk_dnd_util::TEXT_PLAIN); break; case gtk_dnd_util::TEXT_URI_LIST: gtk_target_list_add_uri_targets(targets, gtk_dnd_util::TEXT_URI_LIST); break; case gtk_dnd_util::TEXT_HTML: gtk_target_list_add( targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN), 0, gtk_dnd_util::TEXT_HTML); break; case gtk_dnd_util::NETSCAPE_URL: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL), 0, gtk_dnd_util::NETSCAPE_URL); break; case gtk_dnd_util::CHROME_TAB: case gtk_dnd_util::CHROME_BOOKMARK_ITEM: case gtk_dnd_util::CHROME_NAMED_URL: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(target_code), GTK_TARGET_SAME_APP, target_code); break; case gtk_dnd_util::DIRECT_SAVE_FILE: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::DIRECT_SAVE_FILE), 0, gtk_dnd_util::DIRECT_SAVE_FILE); break; default: NOTREACHED() << " Unexpected target code: " << target_code; } } } // namespace namespace gtk_dnd_util { GdkAtom GetAtomForTarget(int target) { switch (target) { case CHROME_TAB: static GdkAtom tab_atom = gdk_atom_intern( const_cast<char*>("application/x-chrome-tab"), false); return tab_atom; case TEXT_HTML: static GdkAtom html_atom = gdk_atom_intern( const_cast<char*>("text/html"), false); return html_atom; case CHROME_BOOKMARK_ITEM: static GdkAtom bookmark_atom = gdk_atom_intern( const_cast<char*>("application/x-chrome-bookmark-item"), false); return bookmark_atom; case TEXT_PLAIN: static GdkAtom text_atom = gdk_atom_intern( const_cast<char*>("text/plain;charset=utf-8"), false); return text_atom; case TEXT_URI_LIST: static GdkAtom uris_atom = gdk_atom_intern( const_cast<char*>("text/uri-list"), false); return uris_atom; case CHROME_NAMED_URL: static GdkAtom named_url = gdk_atom_intern( const_cast<char*>("application/x-chrome-named-url"), false); return named_url; case NETSCAPE_URL: static GdkAtom netscape_url = gdk_atom_intern( const_cast<char*>("_NETSCAPE_URL"), false); return netscape_url; case TEXT_PLAIN_NO_CHARSET: static GdkAtom text_no_charset_atom = gdk_atom_intern( const_cast<char*>("text/plain"), false); return text_no_charset_atom; case DIRECT_SAVE_FILE: static GdkAtom xds_atom = gdk_atom_intern( const_cast<char*>("XdndDirectSave0"), false); return xds_atom; default: NOTREACHED(); } return NULL; } GtkTargetList* GetTargetListFromCodeMask(int code_mask) { GtkTargetList* targets = gtk_target_list_new(NULL, 0); for (size_t i = 1; i < INVALID_TARGET; i = i << 1) { if (i == CHROME_WEBDROP_FILE_CONTENTS) continue; if (i & code_mask) AddTargetToList(targets, i); } return targets; } void SetSourceTargetListFromCodeMask(GtkWidget* source, int code_mask) { GtkTargetList* targets = GetTargetListFromCodeMask(code_mask); gtk_drag_source_set_target_list(source, targets); gtk_target_list_unref(targets); } void SetDestTargetList(GtkWidget* dest, const int* target_codes) { GtkTargetList* targets = gtk_target_list_new(NULL, 0); for (size_t i = 0; target_codes[i] != -1; ++i) { AddTargetToList(targets, target_codes[i]); } gtk_drag_dest_set_target_list(dest, targets); gtk_target_list_unref(targets); } void WriteURLWithName(GtkSelectionData* selection_data, const GURL& url, const string16& title, int type) { switch (type) { case TEXT_PLAIN: { gtk_selection_data_set_text(selection_data, url.spec().c_str(), url.spec().length()); break; } case TEXT_URI_LIST: { gchar* uri_array[2]; uri_array[0] = strdup(url.spec().c_str()); uri_array[1] = NULL; gtk_selection_data_set_uris(selection_data, uri_array); free(uri_array[0]); break; } case CHROME_NAMED_URL: { Pickle pickle; pickle.WriteString(UTF16ToUTF8(title)); pickle.WriteString(url.spec()); gtk_selection_data_set( selection_data, GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL), kBitsPerByte, reinterpret_cast<const guchar*>(pickle.data()), pickle.size()); break; } case NETSCAPE_URL: { // _NETSCAPE_URL format is URL + \n + title. std::string utf8_text = url.spec() + "\n" + UTF16ToUTF8(title); gtk_selection_data_set(selection_data, selection_data->target, kBitsPerByte, reinterpret_cast<const guchar*>(utf8_text.c_str()), utf8_text.length()); break; } default: { NOTREACHED(); break; } } } bool ExtractNamedURL(GtkSelectionData* selection_data, GURL* url, string16* title) { Pickle data(reinterpret_cast<char*>(selection_data->data), selection_data->length); void* iter = NULL; std::string title_utf8, url_utf8; if (!data.ReadString(&iter, &title_utf8) || !data.ReadString(&iter, &url_utf8)) { return false; } GURL gurl(url_utf8); if (!gurl.is_valid()) return false; *url = gurl; *title = UTF8ToUTF16(title_utf8); return true; } bool ExtractURIList(GtkSelectionData* selection_data, std::vector<GURL>* urls) { gchar** uris = gtk_selection_data_get_uris(selection_data); if (!uris) return false; for (size_t i = 0; uris[i] != NULL; ++i) { GURL url(uris[i]); if (url.is_valid()) urls->push_back(url); } g_strfreev(uris); return true; } GdkDragAction WebDragOpToGdkDragAction(WebDragOperationsMask op) { GdkDragAction action = static_cast<GdkDragAction>(0); if (op & WebDragOperationCopy) action = static_cast<GdkDragAction>(action | GDK_ACTION_COPY); if (op & WebDragOperationLink) action = static_cast<GdkDragAction>(action | GDK_ACTION_LINK); if (op & WebDragOperationMove) action = static_cast<GdkDragAction>(action | GDK_ACTION_MOVE); return action; } WebDragOperationsMask GdkDragActionToWebDragOp(GdkDragAction action) { WebDragOperationsMask op = WebDragOperationNone; if (action & GDK_ACTION_COPY) op = static_cast<WebDragOperationsMask>(op | WebDragOperationCopy); if (action & GDK_ACTION_LINK) op = static_cast<WebDragOperationsMask>(op | WebDragOperationLink); if (action & GDK_ACTION_MOVE) op = static_cast<WebDragOperationsMask>(op | WebDragOperationMove); return op; } } // namespace gtk_dnd_util <commit_msg>We DnD shouldn't provide text/html if it claims to provide text/text/plain;charset=utf-8.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/gtk_dnd_util.h" #include "base/logging.h" #include "base/pickle.h" #include "base/utf_string_conversions.h" #include "googleurl/src/gurl.h" static const int kBitsPerByte = 8; using WebKit::WebDragOperationsMask; using WebKit::WebDragOperation; using WebKit::WebDragOperationNone; using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationLink; using WebKit::WebDragOperationMove; namespace { void AddTargetToList(GtkTargetList* targets, int target_code) { switch (target_code) { case gtk_dnd_util::TEXT_PLAIN: gtk_target_list_add_text_targets(targets, gtk_dnd_util::TEXT_PLAIN); break; case gtk_dnd_util::TEXT_URI_LIST: gtk_target_list_add_uri_targets(targets, gtk_dnd_util::TEXT_URI_LIST); break; case gtk_dnd_util::TEXT_HTML: gtk_target_list_add( targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML), 0, gtk_dnd_util::TEXT_HTML); break; case gtk_dnd_util::NETSCAPE_URL: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL), 0, gtk_dnd_util::NETSCAPE_URL); break; case gtk_dnd_util::CHROME_TAB: case gtk_dnd_util::CHROME_BOOKMARK_ITEM: case gtk_dnd_util::CHROME_NAMED_URL: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(target_code), GTK_TARGET_SAME_APP, target_code); break; case gtk_dnd_util::DIRECT_SAVE_FILE: gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::DIRECT_SAVE_FILE), 0, gtk_dnd_util::DIRECT_SAVE_FILE); break; default: NOTREACHED() << " Unexpected target code: " << target_code; } } } // namespace namespace gtk_dnd_util { GdkAtom GetAtomForTarget(int target) { switch (target) { case CHROME_TAB: static GdkAtom tab_atom = gdk_atom_intern( const_cast<char*>("application/x-chrome-tab"), false); return tab_atom; case TEXT_HTML: static GdkAtom html_atom = gdk_atom_intern( const_cast<char*>("text/html"), false); return html_atom; case CHROME_BOOKMARK_ITEM: static GdkAtom bookmark_atom = gdk_atom_intern( const_cast<char*>("application/x-chrome-bookmark-item"), false); return bookmark_atom; case TEXT_PLAIN: static GdkAtom text_atom = gdk_atom_intern( const_cast<char*>("text/plain;charset=utf-8"), false); return text_atom; case TEXT_URI_LIST: static GdkAtom uris_atom = gdk_atom_intern( const_cast<char*>("text/uri-list"), false); return uris_atom; case CHROME_NAMED_URL: static GdkAtom named_url = gdk_atom_intern( const_cast<char*>("application/x-chrome-named-url"), false); return named_url; case NETSCAPE_URL: static GdkAtom netscape_url = gdk_atom_intern( const_cast<char*>("_NETSCAPE_URL"), false); return netscape_url; case TEXT_PLAIN_NO_CHARSET: static GdkAtom text_no_charset_atom = gdk_atom_intern( const_cast<char*>("text/plain"), false); return text_no_charset_atom; case DIRECT_SAVE_FILE: static GdkAtom xds_atom = gdk_atom_intern( const_cast<char*>("XdndDirectSave0"), false); return xds_atom; default: NOTREACHED(); } return NULL; } GtkTargetList* GetTargetListFromCodeMask(int code_mask) { GtkTargetList* targets = gtk_target_list_new(NULL, 0); for (size_t i = 1; i < INVALID_TARGET; i = i << 1) { if (i == CHROME_WEBDROP_FILE_CONTENTS) continue; if (i & code_mask) AddTargetToList(targets, i); } return targets; } void SetSourceTargetListFromCodeMask(GtkWidget* source, int code_mask) { GtkTargetList* targets = GetTargetListFromCodeMask(code_mask); gtk_drag_source_set_target_list(source, targets); gtk_target_list_unref(targets); } void SetDestTargetList(GtkWidget* dest, const int* target_codes) { GtkTargetList* targets = gtk_target_list_new(NULL, 0); for (size_t i = 0; target_codes[i] != -1; ++i) { AddTargetToList(targets, target_codes[i]); } gtk_drag_dest_set_target_list(dest, targets); gtk_target_list_unref(targets); } void WriteURLWithName(GtkSelectionData* selection_data, const GURL& url, const string16& title, int type) { switch (type) { case TEXT_PLAIN: { gtk_selection_data_set_text(selection_data, url.spec().c_str(), url.spec().length()); break; } case TEXT_URI_LIST: { gchar* uri_array[2]; uri_array[0] = strdup(url.spec().c_str()); uri_array[1] = NULL; gtk_selection_data_set_uris(selection_data, uri_array); free(uri_array[0]); break; } case CHROME_NAMED_URL: { Pickle pickle; pickle.WriteString(UTF16ToUTF8(title)); pickle.WriteString(url.spec()); gtk_selection_data_set( selection_data, GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL), kBitsPerByte, reinterpret_cast<const guchar*>(pickle.data()), pickle.size()); break; } case NETSCAPE_URL: { // _NETSCAPE_URL format is URL + \n + title. std::string utf8_text = url.spec() + "\n" + UTF16ToUTF8(title); gtk_selection_data_set(selection_data, selection_data->target, kBitsPerByte, reinterpret_cast<const guchar*>(utf8_text.c_str()), utf8_text.length()); break; } default: { NOTREACHED(); break; } } } bool ExtractNamedURL(GtkSelectionData* selection_data, GURL* url, string16* title) { Pickle data(reinterpret_cast<char*>(selection_data->data), selection_data->length); void* iter = NULL; std::string title_utf8, url_utf8; if (!data.ReadString(&iter, &title_utf8) || !data.ReadString(&iter, &url_utf8)) { return false; } GURL gurl(url_utf8); if (!gurl.is_valid()) return false; *url = gurl; *title = UTF8ToUTF16(title_utf8); return true; } bool ExtractURIList(GtkSelectionData* selection_data, std::vector<GURL>* urls) { gchar** uris = gtk_selection_data_get_uris(selection_data); if (!uris) return false; for (size_t i = 0; uris[i] != NULL; ++i) { GURL url(uris[i]); if (url.is_valid()) urls->push_back(url); } g_strfreev(uris); return true; } GdkDragAction WebDragOpToGdkDragAction(WebDragOperationsMask op) { GdkDragAction action = static_cast<GdkDragAction>(0); if (op & WebDragOperationCopy) action = static_cast<GdkDragAction>(action | GDK_ACTION_COPY); if (op & WebDragOperationLink) action = static_cast<GdkDragAction>(action | GDK_ACTION_LINK); if (op & WebDragOperationMove) action = static_cast<GdkDragAction>(action | GDK_ACTION_MOVE); return action; } WebDragOperationsMask GdkDragActionToWebDragOp(GdkDragAction action) { WebDragOperationsMask op = WebDragOperationNone; if (action & GDK_ACTION_COPY) op = static_cast<WebDragOperationsMask>(op | WebDragOperationCopy); if (action & GDK_ACTION_LINK) op = static_cast<WebDragOperationsMask>(op | WebDragOperationLink); if (action & GDK_ACTION_MOVE) op = static_cast<WebDragOperationsMask>(op | WebDragOperationMove); return op; } } // namespace gtk_dnd_util <|endoftext|>
<commit_before>#include "types.h" #include "amd64.h" #include "mmu.h" #include "cpu.hh" #include "kernel.hh" #include "bits.hh" #include "spinlock.h" #include "kalloc.hh" #include "queue.h" #include "condvar.h" #include "proc.hh" #include "vm.hh" #include <stddef.h> using namespace std; static pgmap* descend(pgmap *dir, u64 va, u64 flags, int create, int level) { atomic<pme_t> *entryp; pme_t entry; pgmap *next; retry: entryp = &dir->e[PX(level, va)]; entry = entryp->load(); if (entry & PTE_P) { next = (pgmap*) p2v(PTE_ADDR(entry)); } else { if (!create) return NULL; next = (pgmap*) kalloc(); if (!next) return NULL; memset(next, 0, PGSIZE); if (!cmpxch(entryp, entry, v2p(next) | PTE_P | PTE_W | flags)) { kfree((void*) next); goto retry; } } return next; } // Return the address of the PTE in page table pgdir // that corresponds to linear address va. If create!=0, // create any required page table pages. atomic<pme_t>* walkpgdir(pgmap *pml4, u64 va, int create) { auto pdp = descend(pml4, va, PTE_U, create, 3); if (pdp == NULL) return NULL; auto pd = descend(pdp, va, PTE_U, create, 2); if (pd == NULL) return NULL; auto pt = descend(pd, va, PTE_U, create, 1); if (pt == NULL) return NULL; return &pt->e[PX(0,va)]; } // Map from 0 to 128Gbytes starting at KBASE. void initpg(void) { extern char end[]; u64 va = KBASE; paddr pa = 0; while (va < (KBASE+(128ull<<30))) { auto pdp = descend(&kpml4, va, 0, 1, 3); auto pd = descend(pdp, va, 0, 1, 2); atomic<pme_t> *sp = &pd->e[PX(1,va)]; u64 flags = PTE_W | PTE_P | PTE_PS; // Set NX for non-code pages if (va >= (u64) end) flags |= PTE_NX; *sp = pa | flags; va = va + PGSIZE*512; pa += PGSIZE*512; } } // Set up kernel part of a page table. pgmap* setupkvm(void) { pgmap *pml4; int k; if((pml4 = (pgmap*)kalloc()) == 0) return 0; k = PX(3, KBASE); memset(&pml4->e[0], 0, 8*k); memmove(&pml4->e[k], &kpml4.e[k], 8*(512-k)); return pml4; } int setupkshared(pgmap *pml4, char *kshared) { for (u64 off = 0; off < KSHAREDSIZE; off+=4096) { atomic<pme_t> *pte = walkpgdir(pml4, (u64) (KSHARED+off), 1); if (pte == NULL) panic("setupkshared: oops"); *pte = v2p(kshared+off) | PTE_P | PTE_U | PTE_W; } return 0; } // Switch h/w page table register to the kernel-only page table, // for when no process is running. void switchkvm(void) { lcr3(v2p(&kpml4)); // switch to the kernel page table } // Switch TSS and h/w page table to correspond to process p. void switchuvm(struct proc *p) { u64 base = (u64) &mycpu()->ts; pushcli(); mycpu()->gdt[TSSSEG>>3] = (struct segdesc) SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A); mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base); mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE; mycpu()->ts.iomba = (u16)offsetof(struct taskstate, iopb); ltr(TSSSEG); if(p->vmap == 0 || p->vmap->pml4 == 0) panic("switchuvm: no vmap/pml4"); lcr3(v2p(p->vmap->pml4)); // switch to new address space popcli(); } static void freepm(pgmap *pm, int level) { int i; if (level != 0) { for (i = 0; i < 512; i++) { pme_t entry = pm->e[i]; if (entry & PTE_P) freepm((pgmap*) p2v(PTE_ADDR(entry)), level - 1); } } kfree(pm); } // Free a page table and all the physical memory pages // in the user part. void freevm(pgmap *pml4) { int k; int i; if(pml4 == 0) panic("freevm: no pgdir"); // Don't free kernel portion of the pml4 k = PX(3, KBASE); for (i = 0; i < k; i++) { pme_t entry = pml4->e[i]; if (entry & PTE_P) { freepm((pgmap*) p2v(PTE_ADDR(entry)), 2); } } kfree(pml4); } // Set up CPU's kernel segment descriptors. // Run once at boot time on each CPU. void inittls(void) { struct cpu *c; // Initialize cpu-local storage. c = &cpus[cpunum()]; writegs(KDSEG); writemsr(MSR_GS_BASE, (u64)&c->cpu); c->cpu = c; c->proc = NULL; c->kmem = &kmems[cpunum()]; } atomic<u64> tlbflush_req; void tlbflush() { u64 myreq = tlbflush_req++; pushcli(); // the caller may not hold any spinlock, because other CPUs might // be spinning waiting for that spinlock, with interrupts disabled, // so we will deadlock waiting for their TLB flush.. assert(mycpu()->ncli == 1); int myid = mycpu()->id; lcr3(rcr3()); popcli(); for (int i = 0; i < ncpu; i++) if (i != myid) lapic_tlbflush(i); for (int i = 0; i < ncpu; i++) if (i != myid) while (cpus[i].tlbflush_done < myreq) /* spin */ ; } <commit_msg>avoid pushcli/popcli<commit_after>#include "types.h" #include "amd64.h" #include "mmu.h" #include "cpu.hh" #include "kernel.hh" #include "bits.hh" #include "spinlock.h" #include "kalloc.hh" #include "queue.h" #include "condvar.h" #include "proc.hh" #include "vm.hh" #include <stddef.h> using namespace std; static pgmap* descend(pgmap *dir, u64 va, u64 flags, int create, int level) { atomic<pme_t> *entryp; pme_t entry; pgmap *next; retry: entryp = &dir->e[PX(level, va)]; entry = entryp->load(); if (entry & PTE_P) { next = (pgmap*) p2v(PTE_ADDR(entry)); } else { if (!create) return NULL; next = (pgmap*) kalloc(); if (!next) return NULL; memset(next, 0, PGSIZE); if (!cmpxch(entryp, entry, v2p(next) | PTE_P | PTE_W | flags)) { kfree((void*) next); goto retry; } } return next; } // Return the address of the PTE in page table pgdir // that corresponds to linear address va. If create!=0, // create any required page table pages. atomic<pme_t>* walkpgdir(pgmap *pml4, u64 va, int create) { auto pdp = descend(pml4, va, PTE_U, create, 3); if (pdp == NULL) return NULL; auto pd = descend(pdp, va, PTE_U, create, 2); if (pd == NULL) return NULL; auto pt = descend(pd, va, PTE_U, create, 1); if (pt == NULL) return NULL; return &pt->e[PX(0,va)]; } // Map from 0 to 128Gbytes starting at KBASE. void initpg(void) { extern char end[]; u64 va = KBASE; paddr pa = 0; while (va < (KBASE+(128ull<<30))) { auto pdp = descend(&kpml4, va, 0, 1, 3); auto pd = descend(pdp, va, 0, 1, 2); atomic<pme_t> *sp = &pd->e[PX(1,va)]; u64 flags = PTE_W | PTE_P | PTE_PS; // Set NX for non-code pages if (va >= (u64) end) flags |= PTE_NX; *sp = pa | flags; va = va + PGSIZE*512; pa += PGSIZE*512; } } // Set up kernel part of a page table. pgmap* setupkvm(void) { pgmap *pml4; int k; if((pml4 = (pgmap*)kalloc()) == 0) return 0; k = PX(3, KBASE); memset(&pml4->e[0], 0, 8*k); memmove(&pml4->e[k], &kpml4.e[k], 8*(512-k)); return pml4; } int setupkshared(pgmap *pml4, char *kshared) { for (u64 off = 0; off < KSHAREDSIZE; off+=4096) { atomic<pme_t> *pte = walkpgdir(pml4, (u64) (KSHARED+off), 1); if (pte == NULL) panic("setupkshared: oops"); *pte = v2p(kshared+off) | PTE_P | PTE_U | PTE_W; } return 0; } // Switch h/w page table register to the kernel-only page table, // for when no process is running. void switchkvm(void) { lcr3(v2p(&kpml4)); // switch to the kernel page table } // Switch TSS and h/w page table to correspond to process p. void switchuvm(struct proc *p) { u64 base = (u64) &mycpu()->ts; pushcli(); mycpu()->gdt[TSSSEG>>3] = (struct segdesc) SEGDESC(base, (sizeof(mycpu()->ts)-1), SEG_P|SEG_TSS64A); mycpu()->gdt[(TSSSEG>>3)+1] = (struct segdesc) SEGDESCHI(base); mycpu()->ts.rsp[0] = (u64) myproc()->kstack + KSTACKSIZE; mycpu()->ts.iomba = (u16)offsetof(struct taskstate, iopb); ltr(TSSSEG); if(p->vmap == 0 || p->vmap->pml4 == 0) panic("switchuvm: no vmap/pml4"); lcr3(v2p(p->vmap->pml4)); // switch to new address space popcli(); } static void freepm(pgmap *pm, int level) { int i; if (level != 0) { for (i = 0; i < 512; i++) { pme_t entry = pm->e[i]; if (entry & PTE_P) freepm((pgmap*) p2v(PTE_ADDR(entry)), level - 1); } } kfree(pm); } // Free a page table and all the physical memory pages // in the user part. void freevm(pgmap *pml4) { int k; int i; if(pml4 == 0) panic("freevm: no pgdir"); // Don't free kernel portion of the pml4 k = PX(3, KBASE); for (i = 0; i < k; i++) { pme_t entry = pml4->e[i]; if (entry & PTE_P) { freepm((pgmap*) p2v(PTE_ADDR(entry)), 2); } } kfree(pml4); } // Set up CPU's kernel segment descriptors. // Run once at boot time on each CPU. void inittls(void) { struct cpu *c; // Initialize cpu-local storage. c = &cpus[cpunum()]; writegs(KDSEG); writemsr(MSR_GS_BASE, (u64)&c->cpu); c->cpu = c; c->proc = NULL; c->kmem = &kmems[cpunum()]; } atomic<u64> tlbflush_req; void tlbflush() { u64 myreq = tlbflush_req++; // the caller may not hold any spinlock, because other CPUs might // be spinning waiting for that spinlock, with interrupts disabled, // so we will deadlock waiting for their TLB flush.. assert(mycpu()->ncli == 0); for (int i = 0; i < ncpu; i++) lapic_tlbflush(i); for (int i = 0; i < ncpu; i++) while (cpus[i].tlbflush_done < myreq) /* spin */ ; } <|endoftext|>
<commit_before> #include <iostream> #include <string> #include <thread> #include <mutex> #include <boost/program_options.hpp> #include "filter/compiler.h" #include "fileemitor.h" #include "version.h" #include "worker.h" namespace po = boost::program_options; std::mutex screenMutex; std::string recordSeparator = "\n"; void outDocument(const std::string &what) { std::lock_guard<std::mutex> screenLock(screenMutex); std::cout.write(what.data(), what.size()); std::cout << recordSeparator; } void updateSeparator(std::string &sep) { std::string res; bool esc = false; for(char c : sep) { if (esc) { switch(c) { case 'n': res += '\n'; break; case 't': res += '\t'; break; default: res += c; } esc = false; continue; } if (c == '\\') { esc = true; } else { res += c; } } sep = res; } void correctJobsNumber(u_int &jobs) { if (jobs < 1) { std::cerr << "hint: adjusting threads number to 1" << std::endl; jobs = 1; } else if (jobs > 10) { std::cerr << "hint: do not be so greedy. adjusting threads number to 10" << std::endl; jobs = 10; } } int main(int argc, const char * argv[]) { std::cout.sync_with_stdio(false); std::string condition; int limit = -1; u_int jobs = 1; std::string fields; bool printProcessingFile = false; bool countMode = false; bool disableParseLoop = false; bool displayVersionAndExit = false; std::string fieldSeparator = "\t"; po::options_description desc("Allowed options"); desc.add_options() ("input-file,f", po::value< std::vector<std::string> >(), "Input files") ("condition,c", po::value< std::string >(&condition), "Expression") ("limit,n", po::value< int >(&limit)->default_value(-1), "Maximum number of records (default -1 means no limit)") ("fields,l", po::value< std::string >(&fields), "Fields to output") ("print-file", po::bool_switch(&printProcessingFile), "Print name of processing file") ("jobs,j", po::value< u_int >(&jobs)->default_value(1), "Number of threads to run") ("count-only", po::bool_switch(&countMode), "Count of matched records, don't print them") ("record-separator", po::value<std::string>(&recordSeparator)->default_value("\\n"), "Record separator (\\n by default)") ("field-separator", po::value<std::string>(&fieldSeparator)->default_value("\\t"), "Field separator for TSV output (\\t by default)") ("disable-parse-loop", po::bool_switch(&disableParseLoop), "Disable experimental parsing mode (enabled by default)") ("help,h", "Show help message") ("version", po::bool_switch(&displayVersionAndExit), "Display version and exit") ; po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv). options(desc).positional(p).run(), vm); po::notify(vm); } catch(const boost::program_options::error &e) { std::cerr << "Sorry, I couldn't parse arguments: " << e.what() << std::endl; std::cerr << "Try --help" << std::endl; return 1; } if (vm.count("help")) { std::cout << desc << std::endl; return 0; } if (displayVersionAndExit) { std::cout << "aq version: " << avroqVersion() << std::endl; return 0; } updateSeparator(recordSeparator); updateSeparator(fieldSeparator); filter::Compiler filterCompiler; std::shared_ptr<filter::Filter> filter; if (!condition.empty()) { try { filter = filterCompiler.compile(condition); } catch(const filter::Compiler::CompileError &e) { std::cerr << "Condition complile failed: " << std::endl; std::cerr << e.what() << std::endl; return 1; } } if (vm.count("input-file")) { const auto &fileList = vm["input-file"].as< std::vector<std::string> >(); FileEmitor emitor(fileList, limit, outDocument); emitor.setFilter(filter); emitor.setTsvFieldList(fields, fieldSeparator); if (printProcessingFile) { emitor.enablePrintProcessingFile(); } if (countMode) { emitor.enableCountOnlyMode(); } if ( ! disableParseLoop ) { emitor.enableParseLoop(); } std::vector<std::thread> workers; correctJobsNumber(jobs); for(u_int i = 0; i < jobs; ++i) { // TODO: check for inadequate values workers.emplace_back( std::thread(Worker(emitor)) ); } for(auto &p : workers) { p.join(); } if (countMode) { std::cout << "Matched documents: " << emitor.getCountedDocuments() << std::endl; } if (emitor.getLastError().size() > 0) { std::cerr << emitor.getLastError() << std::endl; return 1; } } else { std::cerr << "No input files" << std::endl; return 1; } return 0; } <commit_msg>Increased threads limit to 16, for 16-x core systems<commit_after> #include <iostream> #include <string> #include <thread> #include <mutex> #include <boost/program_options.hpp> #include "filter/compiler.h" #include "fileemitor.h" #include "version.h" #include "worker.h" namespace po = boost::program_options; std::mutex screenMutex; std::string recordSeparator = "\n"; void outDocument(const std::string &what) { std::lock_guard<std::mutex> screenLock(screenMutex); std::cout.write(what.data(), what.size()); std::cout << recordSeparator; } void updateSeparator(std::string &sep) { std::string res; bool esc = false; for(char c : sep) { if (esc) { switch(c) { case 'n': res += '\n'; break; case 't': res += '\t'; break; default: res += c; } esc = false; continue; } if (c == '\\') { esc = true; } else { res += c; } } sep = res; } void correctJobsNumber(u_int &jobs) { if (jobs < 1) { std::cerr << "hint: adjusting threads number to 1" << std::endl; jobs = 1; } else if (jobs > 16) { std::cerr << "hint: do not be so greedy. adjusting threads number to 16" << std::endl; jobs = 16; } } int main(int argc, const char * argv[]) { std::cout.sync_with_stdio(false); std::string condition; int limit = -1; u_int jobs = 1; std::string fields; bool printProcessingFile = false; bool countMode = false; bool disableParseLoop = false; bool displayVersionAndExit = false; std::string fieldSeparator = "\t"; po::options_description desc("Allowed options"); desc.add_options() ("input-file,f", po::value< std::vector<std::string> >(), "Input files") ("condition,c", po::value< std::string >(&condition), "Expression") ("limit,n", po::value< int >(&limit)->default_value(-1), "Maximum number of records (default -1 means no limit)") ("fields,l", po::value< std::string >(&fields), "Fields to output") ("print-file", po::bool_switch(&printProcessingFile), "Print name of processing file") ("jobs,j", po::value< u_int >(&jobs)->default_value(1), "Number of threads to run") ("count-only", po::bool_switch(&countMode), "Count of matched records, don't print them") ("record-separator", po::value<std::string>(&recordSeparator)->default_value("\\n"), "Record separator (\\n by default)") ("field-separator", po::value<std::string>(&fieldSeparator)->default_value("\\t"), "Field separator for TSV output (\\t by default)") ("disable-parse-loop", po::bool_switch(&disableParseLoop), "Disable experimental parsing mode (enabled by default)") ("help,h", "Show help message") ("version", po::bool_switch(&displayVersionAndExit), "Display version and exit") ; po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; try { po::store(po::command_line_parser(argc, argv). options(desc).positional(p).run(), vm); po::notify(vm); } catch(const boost::program_options::error &e) { std::cerr << "Sorry, I couldn't parse arguments: " << e.what() << std::endl; std::cerr << "Try --help" << std::endl; return 1; } if (vm.count("help")) { std::cout << desc << std::endl; return 0; } if (displayVersionAndExit) { std::cout << "aq version: " << avroqVersion() << std::endl; return 0; } updateSeparator(recordSeparator); updateSeparator(fieldSeparator); filter::Compiler filterCompiler; std::shared_ptr<filter::Filter> filter; if (!condition.empty()) { try { filter = filterCompiler.compile(condition); } catch(const filter::Compiler::CompileError &e) { std::cerr << "Condition complile failed: " << std::endl; std::cerr << e.what() << std::endl; return 1; } } if (vm.count("input-file")) { const auto &fileList = vm["input-file"].as< std::vector<std::string> >(); FileEmitor emitor(fileList, limit, outDocument); emitor.setFilter(filter); emitor.setTsvFieldList(fields, fieldSeparator); if (printProcessingFile) { emitor.enablePrintProcessingFile(); } if (countMode) { emitor.enableCountOnlyMode(); } if ( ! disableParseLoop ) { emitor.enableParseLoop(); } std::vector<std::thread> workers; correctJobsNumber(jobs); for(u_int i = 0; i < jobs; ++i) { // TODO: check for inadequate values workers.emplace_back( std::thread(Worker(emitor)) ); } for(auto &p : workers) { p.join(); } if (countMode) { std::cout << "Matched documents: " << emitor.getCountedDocuments() << std::endl; } if (emitor.getLastError().size() > 0) { std::cerr << emitor.getLastError() << std::endl; return 1; } } else { std::cerr << "No input files" << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>// Copyright 2016 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= // FinishedNodes returns a 1-D tensor listing the nodes that are finished // accumulating. #include "tensorflow/contrib/tensor_forest/core/ops/tree_utils.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/random/simple_philox.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/util/work_sharder.h" namespace tensorflow { using shape_inference::Dimension; using shape_inference::InferenceContext; using shape_inference::Shape; using std::placeholders::_1; using std::placeholders::_2; using tensorforest::CheckTensorBounds; using tensorforest::Sum; using tensorforest::BestSplitDominatesClassificationBootstrap; using tensorforest::BestSplitDominatesClassificationChebyshev; using tensorforest::BestSplitDominatesClassificationHoeffding; using tensorforest::BestSplitDominatesRegression; namespace { struct EvaluateParams { Tensor leaves; Tensor node_to_accumulator; Tensor accumulator_sums; Tensor birth_epochs; int current_epoch; int32 num_split_after_samples; int32 min_split_samples; bool need_random; int64 random_seed; std::function<bool(int, random::SimplePhilox*)> dominate_method; }; void Evaluate(const EvaluateParams& params, mutex* mutex, int32 start, int32 end, std::vector<int32>* final_finished_leaves, std::vector<int32>* final_stale) { const auto leaves = params.leaves.unaligned_flat<int32>(); const auto node_map = params.node_to_accumulator.unaligned_flat<int32>(); const auto sums = params.accumulator_sums.tensor<float, 2>(); const auto start_epochs = params.birth_epochs.unaligned_flat<int32>(); const int32 num_accumulators = static_cast<int32>(params.accumulator_sums.shape().dim_size(0)); std::vector<int32> finished_leaves; std::vector<int32> stale; std::unique_ptr<random::SimplePhilox> simple_philox; random::PhiloxRandom rnd_gen(params.random_seed); if (params.need_random) { simple_philox.reset(new random::SimplePhilox(&rnd_gen)); } for (int32 i = start; i < end; i++) { const int32 leaf = internal::SubtleMustCopy(leaves(i)); if (leaf == -1) { continue; } if (!FastBoundsCheck(leaf, node_map.size())) { LOG(ERROR) << "leaf " << leaf << " not in valid range."; } const int32 accumulator = internal::SubtleMustCopy(node_map(leaf)); if (accumulator < 0) { continue; } if (!FastBoundsCheck(accumulator, num_accumulators)) { LOG(ERROR) << "accumulator " << accumulator << " not in valid range."; } // The first column holds the number of samples seen. // For classification, this should be the sum of the other columns. int32 count = sums(accumulator, 0); if (params.current_epoch > start_epochs(leaf) + 1) { if (count >= params.min_split_samples) { finished_leaves.push_back(leaf); } else { stale.push_back(leaf); } continue; } if (count >= params.num_split_after_samples) { finished_leaves.push_back(leaf); continue; } if (count < params.min_split_samples) { continue; } bool finished = params.dominate_method(accumulator, simple_philox.get()); if (finished) { finished_leaves.push_back(leaf); } } mutex_lock m(*mutex); final_finished_leaves->insert(final_finished_leaves->end(), finished_leaves.begin(), finished_leaves.end()); final_stale->insert(final_stale->end(), stale.begin(), stale.end()); } } // namespace REGISTER_OP("FinishedNodes") .Attr("regression: bool = false") .Attr("num_split_after_samples: int") .Attr("min_split_samples: int") .Attr("dominate_fraction: float = 0.99") // TODO(thomaswc): Test out bootstrap on several datasets, confirm it // works well, make it the default. .Attr( "dominate_method:" " {'none', 'hoeffding', 'bootstrap', 'chebyshev'} = 'hoeffding'") .Attr("random_seed: int = 0") .Input("leaves: int32") .Input("node_to_accumulator: int32") .Input("split_sums: float") .Input("split_squares: float") .Input("accumulator_sums: float") .Input("accumulator_squares: float") .Input("birth_epochs: int32") .Input("current_epoch: int32") .Output("finished: int32") .Output("stale: int32") .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->Vector(InferenceContext::kUnknownDim)); c->set_output(1, c->Vector(InferenceContext::kUnknownDim)); return Status::OK(); }) .Doc(R"doc( Determines which of the given leaf nodes are done accumulating. leaves:= A 1-d int32 tensor. Lists the nodes that are currently leaves. node_to_accumulator: If the i-th node is fertile, `node_to_accumulator[i]` is it's accumulator slot. Otherwise, `node_to_accumulator[i]` is -1. split_sums:= a 3-d tensor where `split_sums[a][s]` summarizes the training labels for examples that fall into the fertile node associated with accumulator slot s and have then taken the *left* branch of candidate split s. For a classification problem, `split_sums[a][s][c]` is the count of such examples with class c and for regression problems, `split_sums[a][s]` is the sum of the regression labels for such examples. split_squares: Same as split_sums, but it contains the sum of the squares of the regression labels. Only used for regression. For classification problems, pass a dummy tensor into this. accumulator_sums: For classification, `accumulator_sums[a][c]` records how many training examples have class c and have ended up in the fertile node associated with accumulator slot a. It has the total sum in entry 0 for convenience. For regression, it is the same except it contains the sum of the input labels that have been seen, and entry 0 contains the number of training examples that have been seen. accumulator_squares: Same as accumulator_sums, but it contains the sum of the squares of the regression labels. Only used for regression. For classification problems, pass a dummy tensor into this. birth_epochs:= A 1-d int32 tensor. `birth_epochs[i]` contains the epoch the i-th node was created in. current_epoch:= A 1-d int32 tensor with shape (1). `current_epoch[0]` stores the current epoch number. finished:= A 1-d int32 tensor containing the indices of the finished nodes. Nodes are finished if they have received at least num_split_after_samples samples, or if they have received min_split_samples and the best scoring split is sufficiently greater than the next best split. stale:= A 1-d int32 tensor containing the fertile nodes that were created two or more epochs ago. )doc"); class FinishedNodes : public OpKernel { public: explicit FinishedNodes(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr( "regression", &regression_)); OP_REQUIRES_OK(context, context->GetAttr( "num_split_after_samples", &num_split_after_samples_)); OP_REQUIRES_OK(context, context->GetAttr( "min_split_samples", &min_split_samples_)); OP_REQUIRES_OK(context, context->GetAttr( "dominate_fraction", &dominate_fraction_)); OP_REQUIRES_OK(context, context->GetAttr("dominate_method", &dominate_method_)); OP_REQUIRES_OK(context, context->GetAttr("random_seed", &random_seed_)); } void Compute(OpKernelContext* context) override { const Tensor& leaf_tensor = context->input(0); const Tensor& node_to_accumulator = context->input(1); const Tensor& split_sums = context->input(2); const Tensor& split_squares = context->input(3); const Tensor& accumulator_sums = context->input(4); const Tensor& accumulator_squares = context->input(5); const Tensor& birth_epochs = context->input(6); const Tensor& current_epoch = context->input(7); OP_REQUIRES(context, leaf_tensor.shape().dims() == 1, errors::InvalidArgument( "leaf_tensor should be one-dimensional")); OP_REQUIRES(context, node_to_accumulator.shape().dims() == 1, errors::InvalidArgument( "node_to_accumulator should be one-dimensional")); OP_REQUIRES(context, split_sums.shape().dims() == 3, errors::InvalidArgument( "split_sums should be three-dimensional")); OP_REQUIRES(context, accumulator_sums.shape().dims() == 2, errors::InvalidArgument( "accumulator_sums should be two-dimensional")); OP_REQUIRES(context, birth_epochs.shape().dims() == 1, errors::InvalidArgument( "birth_epochs should be one-dimensional")); OP_REQUIRES( context, birth_epochs.shape().dim_size(0) == node_to_accumulator.shape().dim_size(0), errors::InvalidArgument( "birth_epochs and node_to_accumulator should be the same size.")); // Check tensor bounds. if (!CheckTensorBounds(context, leaf_tensor)) return; if (!CheckTensorBounds(context, node_to_accumulator)) return; if (!CheckTensorBounds(context, split_sums)) return; if (!CheckTensorBounds(context, split_squares)) return; if (!CheckTensorBounds(context, accumulator_sums)) return; if (!CheckTensorBounds(context, accumulator_squares)) return; if (!CheckTensorBounds(context, birth_epochs)) return; if (!CheckTensorBounds(context, current_epoch)) return; const int32 epoch = current_epoch.unaligned_flat<int32>()(0); const int32 num_leaves = static_cast<int32>( leaf_tensor.shape().dim_size(0)); auto worker_threads = context->device()->tensorflow_cpu_worker_threads(); int num_threads = worker_threads->num_threads; EvaluateParams params; params.leaves = leaf_tensor; params.node_to_accumulator = node_to_accumulator; params.accumulator_sums = accumulator_sums; params.birth_epochs = birth_epochs; params.current_epoch = epoch; params.min_split_samples = min_split_samples_; params.num_split_after_samples = num_split_after_samples_; params.need_random = false; if (regression_) { params.dominate_method = std::bind(&BestSplitDominatesRegression, accumulator_sums, accumulator_squares, split_sums, split_squares, _1); } else { if (dominate_method_ == "none") { params.dominate_method = [](int, random::SimplePhilox*) { return false; }; } else if (dominate_method_ == "hoeffding") { params.dominate_method = std::bind(&BestSplitDominatesClassificationHoeffding, accumulator_sums, split_sums, _1, dominate_fraction_); } else if (dominate_method_ == "chebyshev") { params.dominate_method = std::bind(&BestSplitDominatesClassificationChebyshev, accumulator_sums, split_sums, _1, dominate_fraction_); } else if (dominate_method_ == "bootstrap") { params.need_random = true; params.random_seed = random_seed_; if (params.random_seed == 0) { params.random_seed = static_cast<uint64>(Env::Default()->NowMicros()); } params.dominate_method = std::bind(&BestSplitDominatesClassificationBootstrap, accumulator_sums, split_sums, _1, dominate_fraction_, _2); } else { LOG(FATAL) << "Unknown dominate method " << dominate_method_; } } std::vector<int32> finished_leaves; std::vector<int32> stale; mutex m; // Require at least 100 leaves per thread. I guess that's about 800 cost // per unit. This isn't well defined. const int64 costPerUnit = 800; auto work = [&params, &finished_leaves, &stale, &m, num_leaves](int64 start, int64 end) { CHECK(start <= end); CHECK(end <= num_leaves); Evaluate(params, &m, static_cast<int32>(start), static_cast<int32>(end), &finished_leaves, &stale); }; Shard(num_threads, worker_threads->workers, num_leaves, costPerUnit, work); // Copy to output. Tensor* output_finished = nullptr; TensorShape finished_shape; finished_shape.AddDim(finished_leaves.size()); OP_REQUIRES_OK(context, context->allocate_output(0, finished_shape, &output_finished)); auto out_finished = output_finished->unaligned_flat<int32>(); std::copy(finished_leaves.begin(), finished_leaves.end(), out_finished.data()); Tensor* output_stale = nullptr; TensorShape stale_shape; stale_shape.AddDim(stale.size()); OP_REQUIRES_OK(context, context->allocate_output(1, stale_shape, &output_stale)); auto out_stale = output_stale->unaligned_flat<int32>(); std::copy(stale.begin(), stale.end(), out_stale.data()); } private: bool regression_; int32 num_split_after_samples_; int32 min_split_samples_; float dominate_fraction_; string dominate_method_; int32 random_seed_; }; REGISTER_KERNEL_BUILDER(Name("FinishedNodes").Device(DEVICE_CPU), FinishedNodes); } // namespace tensorflow <commit_msg>Change default dominate_method to bootsrap. Change: 137959663<commit_after>// Copyright 2016 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= // FinishedNodes returns a 1-D tensor listing the nodes that are finished // accumulating. #include "tensorflow/contrib/tensor_forest/core/ops/tree_utils.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/random/simple_philox.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/util/work_sharder.h" namespace tensorflow { using shape_inference::Dimension; using shape_inference::InferenceContext; using shape_inference::Shape; using std::placeholders::_1; using std::placeholders::_2; using tensorforest::CheckTensorBounds; using tensorforest::Sum; using tensorforest::BestSplitDominatesClassificationBootstrap; using tensorforest::BestSplitDominatesClassificationChebyshev; using tensorforest::BestSplitDominatesClassificationHoeffding; using tensorforest::BestSplitDominatesRegression; namespace { struct EvaluateParams { Tensor leaves; Tensor node_to_accumulator; Tensor accumulator_sums; Tensor birth_epochs; int current_epoch; int32 num_split_after_samples; int32 min_split_samples; bool need_random; int64 random_seed; std::function<bool(int, random::SimplePhilox*)> dominate_method; }; void Evaluate(const EvaluateParams& params, mutex* mutex, int32 start, int32 end, std::vector<int32>* final_finished_leaves, std::vector<int32>* final_stale) { const auto leaves = params.leaves.unaligned_flat<int32>(); const auto node_map = params.node_to_accumulator.unaligned_flat<int32>(); const auto sums = params.accumulator_sums.tensor<float, 2>(); const auto start_epochs = params.birth_epochs.unaligned_flat<int32>(); const int32 num_accumulators = static_cast<int32>(params.accumulator_sums.shape().dim_size(0)); std::vector<int32> finished_leaves; std::vector<int32> stale; std::unique_ptr<random::SimplePhilox> simple_philox; random::PhiloxRandom rnd_gen(params.random_seed); if (params.need_random) { simple_philox.reset(new random::SimplePhilox(&rnd_gen)); } for (int32 i = start; i < end; i++) { const int32 leaf = internal::SubtleMustCopy(leaves(i)); if (leaf == -1) { continue; } if (!FastBoundsCheck(leaf, node_map.size())) { LOG(ERROR) << "leaf " << leaf << " not in valid range."; } const int32 accumulator = internal::SubtleMustCopy(node_map(leaf)); if (accumulator < 0) { continue; } if (!FastBoundsCheck(accumulator, num_accumulators)) { LOG(ERROR) << "accumulator " << accumulator << " not in valid range."; } // The first column holds the number of samples seen. // For classification, this should be the sum of the other columns. int32 count = sums(accumulator, 0); if (params.current_epoch > start_epochs(leaf) + 1) { if (count >= params.min_split_samples) { finished_leaves.push_back(leaf); } else { stale.push_back(leaf); } continue; } if (count >= params.num_split_after_samples) { finished_leaves.push_back(leaf); continue; } if (count < params.min_split_samples) { continue; } bool finished = params.dominate_method(accumulator, simple_philox.get()); if (finished) { finished_leaves.push_back(leaf); } } mutex_lock m(*mutex); final_finished_leaves->insert(final_finished_leaves->end(), finished_leaves.begin(), finished_leaves.end()); final_stale->insert(final_stale->end(), stale.begin(), stale.end()); } } // namespace REGISTER_OP("FinishedNodes") .Attr("regression: bool = false") .Attr("num_split_after_samples: int") .Attr("min_split_samples: int") .Attr("dominate_fraction: float = 0.99") .Attr( "dominate_method:" " {'none', 'hoeffding', 'bootstrap', 'chebyshev'} = 'bootstrap'") .Attr("random_seed: int = 0") .Input("leaves: int32") .Input("node_to_accumulator: int32") .Input("split_sums: float") .Input("split_squares: float") .Input("accumulator_sums: float") .Input("accumulator_squares: float") .Input("birth_epochs: int32") .Input("current_epoch: int32") .Output("finished: int32") .Output("stale: int32") .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->Vector(InferenceContext::kUnknownDim)); c->set_output(1, c->Vector(InferenceContext::kUnknownDim)); return Status::OK(); }) .Doc(R"doc( Determines which of the given leaf nodes are done accumulating. leaves:= A 1-d int32 tensor. Lists the nodes that are currently leaves. node_to_accumulator: If the i-th node is fertile, `node_to_accumulator[i]` is it's accumulator slot. Otherwise, `node_to_accumulator[i]` is -1. split_sums:= a 3-d tensor where `split_sums[a][s]` summarizes the training labels for examples that fall into the fertile node associated with accumulator slot s and have then taken the *left* branch of candidate split s. For a classification problem, `split_sums[a][s][c]` is the count of such examples with class c and for regression problems, `split_sums[a][s]` is the sum of the regression labels for such examples. split_squares: Same as split_sums, but it contains the sum of the squares of the regression labels. Only used for regression. For classification problems, pass a dummy tensor into this. accumulator_sums: For classification, `accumulator_sums[a][c]` records how many training examples have class c and have ended up in the fertile node associated with accumulator slot a. It has the total sum in entry 0 for convenience. For regression, it is the same except it contains the sum of the input labels that have been seen, and entry 0 contains the number of training examples that have been seen. accumulator_squares: Same as accumulator_sums, but it contains the sum of the squares of the regression labels. Only used for regression. For classification problems, pass a dummy tensor into this. birth_epochs:= A 1-d int32 tensor. `birth_epochs[i]` contains the epoch the i-th node was created in. current_epoch:= A 1-d int32 tensor with shape (1). `current_epoch[0]` stores the current epoch number. finished:= A 1-d int32 tensor containing the indices of the finished nodes. Nodes are finished if they have received at least num_split_after_samples samples, or if they have received min_split_samples and the best scoring split is sufficiently greater than the next best split. stale:= A 1-d int32 tensor containing the fertile nodes that were created two or more epochs ago. )doc"); class FinishedNodes : public OpKernel { public: explicit FinishedNodes(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr( "regression", &regression_)); OP_REQUIRES_OK(context, context->GetAttr( "num_split_after_samples", &num_split_after_samples_)); OP_REQUIRES_OK(context, context->GetAttr( "min_split_samples", &min_split_samples_)); OP_REQUIRES_OK(context, context->GetAttr( "dominate_fraction", &dominate_fraction_)); OP_REQUIRES_OK(context, context->GetAttr("dominate_method", &dominate_method_)); OP_REQUIRES_OK(context, context->GetAttr("random_seed", &random_seed_)); } void Compute(OpKernelContext* context) override { const Tensor& leaf_tensor = context->input(0); const Tensor& node_to_accumulator = context->input(1); const Tensor& split_sums = context->input(2); const Tensor& split_squares = context->input(3); const Tensor& accumulator_sums = context->input(4); const Tensor& accumulator_squares = context->input(5); const Tensor& birth_epochs = context->input(6); const Tensor& current_epoch = context->input(7); OP_REQUIRES(context, leaf_tensor.shape().dims() == 1, errors::InvalidArgument( "leaf_tensor should be one-dimensional")); OP_REQUIRES(context, node_to_accumulator.shape().dims() == 1, errors::InvalidArgument( "node_to_accumulator should be one-dimensional")); OP_REQUIRES(context, split_sums.shape().dims() == 3, errors::InvalidArgument( "split_sums should be three-dimensional")); OP_REQUIRES(context, accumulator_sums.shape().dims() == 2, errors::InvalidArgument( "accumulator_sums should be two-dimensional")); OP_REQUIRES(context, birth_epochs.shape().dims() == 1, errors::InvalidArgument( "birth_epochs should be one-dimensional")); OP_REQUIRES( context, birth_epochs.shape().dim_size(0) == node_to_accumulator.shape().dim_size(0), errors::InvalidArgument( "birth_epochs and node_to_accumulator should be the same size.")); // Check tensor bounds. if (!CheckTensorBounds(context, leaf_tensor)) return; if (!CheckTensorBounds(context, node_to_accumulator)) return; if (!CheckTensorBounds(context, split_sums)) return; if (!CheckTensorBounds(context, split_squares)) return; if (!CheckTensorBounds(context, accumulator_sums)) return; if (!CheckTensorBounds(context, accumulator_squares)) return; if (!CheckTensorBounds(context, birth_epochs)) return; if (!CheckTensorBounds(context, current_epoch)) return; const int32 epoch = current_epoch.unaligned_flat<int32>()(0); const int32 num_leaves = static_cast<int32>( leaf_tensor.shape().dim_size(0)); auto worker_threads = context->device()->tensorflow_cpu_worker_threads(); int num_threads = worker_threads->num_threads; EvaluateParams params; params.leaves = leaf_tensor; params.node_to_accumulator = node_to_accumulator; params.accumulator_sums = accumulator_sums; params.birth_epochs = birth_epochs; params.current_epoch = epoch; params.min_split_samples = min_split_samples_; params.num_split_after_samples = num_split_after_samples_; params.need_random = false; if (regression_) { params.dominate_method = std::bind(&BestSplitDominatesRegression, accumulator_sums, accumulator_squares, split_sums, split_squares, _1); } else { if (dominate_method_ == "none") { params.dominate_method = [](int, random::SimplePhilox*) { return false; }; } else if (dominate_method_ == "hoeffding") { params.dominate_method = std::bind(&BestSplitDominatesClassificationHoeffding, accumulator_sums, split_sums, _1, dominate_fraction_); } else if (dominate_method_ == "chebyshev") { params.dominate_method = std::bind(&BestSplitDominatesClassificationChebyshev, accumulator_sums, split_sums, _1, dominate_fraction_); } else if (dominate_method_ == "bootstrap") { params.need_random = true; params.random_seed = random_seed_; if (params.random_seed == 0) { params.random_seed = static_cast<uint64>(Env::Default()->NowMicros()); } params.dominate_method = std::bind(&BestSplitDominatesClassificationBootstrap, accumulator_sums, split_sums, _1, dominate_fraction_, _2); } else { LOG(FATAL) << "Unknown dominate method " << dominate_method_; } } std::vector<int32> finished_leaves; std::vector<int32> stale; mutex m; // Require at least 100 leaves per thread. I guess that's about 800 cost // per unit. This isn't well defined. const int64 costPerUnit = 800; auto work = [&params, &finished_leaves, &stale, &m, num_leaves](int64 start, int64 end) { CHECK(start <= end); CHECK(end <= num_leaves); Evaluate(params, &m, static_cast<int32>(start), static_cast<int32>(end), &finished_leaves, &stale); }; Shard(num_threads, worker_threads->workers, num_leaves, costPerUnit, work); // Copy to output. Tensor* output_finished = nullptr; TensorShape finished_shape; finished_shape.AddDim(finished_leaves.size()); OP_REQUIRES_OK(context, context->allocate_output(0, finished_shape, &output_finished)); auto out_finished = output_finished->unaligned_flat<int32>(); std::copy(finished_leaves.begin(), finished_leaves.end(), out_finished.data()); Tensor* output_stale = nullptr; TensorShape stale_shape; stale_shape.AddDim(stale.size()); OP_REQUIRES_OK(context, context->allocate_output(1, stale_shape, &output_stale)); auto out_stale = output_stale->unaligned_flat<int32>(); std::copy(stale.begin(), stale.end(), out_stale.data()); } private: bool regression_; int32 num_split_after_samples_; int32 min_split_samples_; float dominate_fraction_; string dominate_method_; int32 random_seed_; }; REGISTER_KERNEL_BUILDER(Name("FinishedNodes").Device(DEVICE_CPU), FinishedNodes); } // namespace tensorflow <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/platform_thread.h" #include <dlfcn.h> #include <errno.h> #include <sched.h> #if defined(OS_MACOSX) #include <mach/mach.h> #include <sys/resource.h> #include <algorithm> #endif #if defined(OS_LINUX) #include <sys/prctl.h> #include <sys/syscall.h> #include <unistd.h> #endif #include "base/logging.h" #include "base/safe_strerror_posix.h" #if defined(OS_MACOSX) namespace base { void InitThreading(); } // namespace base #endif static void* ThreadFunc(void* closure) { PlatformThread::Delegate* delegate = static_cast<PlatformThread::Delegate*>(closure); delegate->ThreadMain(); return NULL; } // static PlatformThreadId PlatformThread::CurrentId() { // Pthreads doesn't have the concept of a thread ID, so we have to reach down // into the kernel. #if defined(OS_MACOSX) return mach_thread_self(); #elif defined(OS_LINUX) return syscall(__NR_gettid); #elif defined(OS_FREEBSD) // TODO(BSD): find a better thread ID return reinterpret_cast<int64>(pthread_self()); #endif } // static void PlatformThread::YieldCurrentThread() { sched_yield(); } // static void PlatformThread::Sleep(int duration_ms) { struct timespec sleep_time, remaining; // Contains the portion of duration_ms >= 1 sec. sleep_time.tv_sec = duration_ms / 1000; duration_ms -= sleep_time.tv_sec * 1000; // Contains the portion of duration_ms < 1 sec. sleep_time.tv_nsec = duration_ms * 1000 * 1000; // nanoseconds. while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR) sleep_time = remaining; } // Linux SetName is currently disabled, as we need to distinguish between // helper threads (where it's ok to make this call) and the main thread // (where making this call renames our process, causing tools like killall // to stop working). #if 0 && defined(OS_LINUX) // static void PlatformThread::SetName(const char* name) { // http://0pointer.de/blog/projects/name-your-threads.html // glibc recently added support for pthread_setname_np, but it's not // commonly available yet. So test for it at runtime. int (*dynamic_pthread_setname_np)(pthread_t, const char*); *reinterpret_cast<void**>(&dynamic_pthread_setname_np) = dlsym(RTLD_DEFAULT, "pthread_setname_np"); if (dynamic_pthread_setname_np) { // This limit comes from glibc, which gets it from the kernel // (TASK_COMM_LEN). const int kMaxNameLength = 15; std::string shortened_name = std::string(name).substr(0, kMaxNameLength); int err = dynamic_pthread_setname_np(pthread_self(), shortened_name.c_str()); if (err < 0) LOG(ERROR) << "pthread_setname_np: " << safe_strerror(err); } else { // Implementing this function without glibc is simple enough. (We // don't do the name length clipping as above because it will be // truncated by the callee (see TASK_COMM_LEN above).) int err = prctl(PR_SET_NAME, name); if (err < 0) PLOG(ERROR) << "prctl(PR_SET_NAME)"; } } #elif defined(OS_MACOSX) // Mac is implemented in platform_thread_mac.mm. #else // static void PlatformThread::SetName(const char* name) { // Leave it unimplemented. // (This should be relatively simple to implement for the BSDs; I // just don't have one handy to test the code on.) } #endif // defined(OS_LINUX) namespace { bool CreateThread(size_t stack_size, bool joinable, PlatformThread::Delegate* delegate, PlatformThreadHandle* thread_handle) { #if defined(OS_MACOSX) base::InitThreading(); #endif // OS_MACOSX bool success = false; pthread_attr_t attributes; pthread_attr_init(&attributes); // Pthreads are joinable by default, so only specify the detached attribute if // the thread should be non-joinable. if (!joinable) { pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); } #if defined(OS_MACOSX) // The Mac OS X default for a pthread stack size is 512kB. // Libc-594.1.4/pthreads/pthread.c's pthread_attr_init uses // DEFAULT_STACK_SIZE for this purpose. // // 512kB isn't quite generous enough for some deeply recursive threads that // otherwise request the default stack size by specifying 0. Here, adopt // glibc's behavior as on Linux, which is to use the current stack size // limit (ulimit -s) as the default stack size. See // glibc-2.11.1/nptl/nptl-init.c's __pthread_initialize_minimal_internal. To // avoid setting the limit below the Mac OS X default or the minimum usable // stack size, these values are also considered. If any of these values // can't be determined, or if stack size is unlimited (ulimit -s unlimited), // stack_size is left at 0 to get the system default. // // Mac OS X normally only applies ulimit -s to the main thread stack. On // contemporary OS X and Linux systems alike, this value is generally 8MB // or in that neighborhood. if (stack_size == 0) { size_t default_stack_size; struct rlimit stack_rlimit; if (pthread_attr_getstacksize(&attributes, &default_stack_size) == 0 && getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 && stack_rlimit.rlim_cur != RLIM_INFINITY) { stack_size = std::max(std::max(default_stack_size, static_cast<size_t>(PTHREAD_STACK_MIN)), static_cast<size_t>(stack_rlimit.rlim_cur)); } } #endif // OS_MACOSX if (stack_size > 0) pthread_attr_setstacksize(&attributes, stack_size); success = !pthread_create(thread_handle, &attributes, ThreadFunc, delegate); pthread_attr_destroy(&attributes); return success; } } // anonymous namespace // static bool PlatformThread::Create(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle) { return CreateThread(stack_size, true /* joinable thread */, delegate, thread_handle); } // static bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) { PlatformThreadHandle unused; bool result = CreateThread(stack_size, false /* non-joinable thread */, delegate, &unused); return result; } // static void PlatformThread::Join(PlatformThreadHandle thread_handle) { pthread_join(thread_handle, NULL); } <commit_msg>NaCl bringup of base.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/platform_thread.h" #include <errno.h> #include <sched.h> #if defined(OS_MACOSX) #include <mach/mach.h> #include <sys/resource.h> #include <algorithm> #endif #if defined(OS_LINUX) #include <dlfcn.h> #include <sys/prctl.h> #include <sys/syscall.h> #include <unistd.h> #endif #if defined(OS_NACL) #include <sys/nacl_syscalls.h> #endif #include "base/logging.h" #include "base/safe_strerror_posix.h" #if defined(OS_MACOSX) namespace base { void InitThreading(); } // namespace base #endif static void* ThreadFunc(void* closure) { PlatformThread::Delegate* delegate = static_cast<PlatformThread::Delegate*>(closure); delegate->ThreadMain(); return NULL; } // static PlatformThreadId PlatformThread::CurrentId() { // Pthreads doesn't have the concept of a thread ID, so we have to reach down // into the kernel. #if defined(OS_MACOSX) return mach_thread_self(); #elif defined(OS_LINUX) return syscall(__NR_gettid); #elif defined(OS_FREEBSD) // TODO(BSD): find a better thread ID return reinterpret_cast<int64>(pthread_self()); #elif defined(OS_NACL) return pthread_self(); #endif } // static void PlatformThread::YieldCurrentThread() { sched_yield(); } // static void PlatformThread::Sleep(int duration_ms) { struct timespec sleep_time, remaining; // Contains the portion of duration_ms >= 1 sec. sleep_time.tv_sec = duration_ms / 1000; duration_ms -= sleep_time.tv_sec * 1000; // Contains the portion of duration_ms < 1 sec. sleep_time.tv_nsec = duration_ms * 1000 * 1000; // nanoseconds. while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR) sleep_time = remaining; } // Linux SetName is currently disabled, as we need to distinguish between // helper threads (where it's ok to make this call) and the main thread // (where making this call renames our process, causing tools like killall // to stop working). #if 0 && defined(OS_LINUX) // static void PlatformThread::SetName(const char* name) { // http://0pointer.de/blog/projects/name-your-threads.html // glibc recently added support for pthread_setname_np, but it's not // commonly available yet. So test for it at runtime. int (*dynamic_pthread_setname_np)(pthread_t, const char*); *reinterpret_cast<void**>(&dynamic_pthread_setname_np) = dlsym(RTLD_DEFAULT, "pthread_setname_np"); if (dynamic_pthread_setname_np) { // This limit comes from glibc, which gets it from the kernel // (TASK_COMM_LEN). const int kMaxNameLength = 15; std::string shortened_name = std::string(name).substr(0, kMaxNameLength); int err = dynamic_pthread_setname_np(pthread_self(), shortened_name.c_str()); if (err < 0) LOG(ERROR) << "pthread_setname_np: " << safe_strerror(err); } else { // Implementing this function without glibc is simple enough. (We // don't do the name length clipping as above because it will be // truncated by the callee (see TASK_COMM_LEN above).) int err = prctl(PR_SET_NAME, name); if (err < 0) PLOG(ERROR) << "prctl(PR_SET_NAME)"; } } #elif defined(OS_MACOSX) // Mac is implemented in platform_thread_mac.mm. #else // static void PlatformThread::SetName(const char* name) { // Leave it unimplemented. // (This should be relatively simple to implement for the BSDs; I // just don't have one handy to test the code on.) } #endif // defined(OS_LINUX) namespace { bool CreateThread(size_t stack_size, bool joinable, PlatformThread::Delegate* delegate, PlatformThreadHandle* thread_handle) { #if defined(OS_MACOSX) base::InitThreading(); #endif // OS_MACOSX bool success = false; pthread_attr_t attributes; pthread_attr_init(&attributes); // Pthreads are joinable by default, so only specify the detached attribute if // the thread should be non-joinable. if (!joinable) { pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); } #if defined(OS_MACOSX) // The Mac OS X default for a pthread stack size is 512kB. // Libc-594.1.4/pthreads/pthread.c's pthread_attr_init uses // DEFAULT_STACK_SIZE for this purpose. // // 512kB isn't quite generous enough for some deeply recursive threads that // otherwise request the default stack size by specifying 0. Here, adopt // glibc's behavior as on Linux, which is to use the current stack size // limit (ulimit -s) as the default stack size. See // glibc-2.11.1/nptl/nptl-init.c's __pthread_initialize_minimal_internal. To // avoid setting the limit below the Mac OS X default or the minimum usable // stack size, these values are also considered. If any of these values // can't be determined, or if stack size is unlimited (ulimit -s unlimited), // stack_size is left at 0 to get the system default. // // Mac OS X normally only applies ulimit -s to the main thread stack. On // contemporary OS X and Linux systems alike, this value is generally 8MB // or in that neighborhood. if (stack_size == 0) { size_t default_stack_size; struct rlimit stack_rlimit; if (pthread_attr_getstacksize(&attributes, &default_stack_size) == 0 && getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 && stack_rlimit.rlim_cur != RLIM_INFINITY) { stack_size = std::max(std::max(default_stack_size, static_cast<size_t>(PTHREAD_STACK_MIN)), static_cast<size_t>(stack_rlimit.rlim_cur)); } } #endif // OS_MACOSX if (stack_size > 0) pthread_attr_setstacksize(&attributes, stack_size); success = !pthread_create(thread_handle, &attributes, ThreadFunc, delegate); pthread_attr_destroy(&attributes); return success; } } // anonymous namespace // static bool PlatformThread::Create(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle) { return CreateThread(stack_size, true /* joinable thread */, delegate, thread_handle); } // static bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) { PlatformThreadHandle unused; bool result = CreateThread(stack_size, false /* non-joinable thread */, delegate, &unused); return result; } // static void PlatformThread::Join(PlatformThreadHandle thread_handle) { pthread_join(thread_handle, NULL); } <|endoftext|>
<commit_before><commit_msg>Fix ProcessUtilTest.FDRemapping hang on x86_64 by counting open fds in child process nondestructively BUG=25270 TEST=base_unittests --gtest_filter=ProcessUtilTest.FDRemapping on x86_64 linux<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sbjsmeth.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 14:22:32 $ * * 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 _SB_SBJSMETH_HXX #define _SB_SBJSMETH_HXX #ifndef _SB_SBMETH_HXX #include <basic/sbmeth.hxx> #endif // Basic-Modul fuer JavaScript-Sourcen. // Alle Basic-spezifischen Methoden muessen virtuell ueberladen und deaktiviert // werden. Die Unterscheidung von normalen Modulen erfolgt uebr RTTI. class SbJScriptMethod : public SbMethod { public: SbJScriptMethod( const String&, SbxDataType, SbModule* ); virtual ~SbJScriptMethod(); SBX_DECL_PERSIST_NODATA(SBXCR_SBX,SBXID_JSCRIPTMETH,2); TYPEINFO(); }; #ifndef __SB_SBJSCRIPTMETHODREF_HXX #define __SB_SBJSCRIPTMETHODREF_HXX SV_DECL_IMPL_REF(SbJScriptMethod) #endif #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.88); FILE MERGED 2008/04/01 10:48:42 thb 1.5.88.2: #i85898# Stripping all external header guards 2008/03/28 16:07:28 rt 1.5.88.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: sbjsmeth.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SB_SBJSMETH_HXX #define _SB_SBJSMETH_HXX #include <basic/sbmeth.hxx> // Basic-Modul fuer JavaScript-Sourcen. // Alle Basic-spezifischen Methoden muessen virtuell ueberladen und deaktiviert // werden. Die Unterscheidung von normalen Modulen erfolgt uebr RTTI. class SbJScriptMethod : public SbMethod { public: SbJScriptMethod( const String&, SbxDataType, SbModule* ); virtual ~SbJScriptMethod(); SBX_DECL_PERSIST_NODATA(SBXCR_SBX,SBXID_JSCRIPTMETH,2); TYPEINFO(); }; #ifndef __SB_SBJSCRIPTMETHODREF_HXX #define __SB_SBJSCRIPTMETHODREF_HXX SV_DECL_IMPL_REF(SbJScriptMethod) #endif #endif <|endoftext|>
<commit_before>// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fdiagnostics-show-option -verify %s // C++98 [basic.lookup.classref]p1: // In a class member access expression (5.2.5), if the . or -> token is // immediately followed by an identifier followed by a <, the identifier must // be looked up to determine whether the < is the beginning of a template // argument list (14.2) or a less-than operator. The identifier is first // looked up in the class of the object expression. If the identifier is not // found, it is then looked up in the context of the entire postfix-expression // and shall name a class or function template. If the lookup in the class of // the object expression finds a template, the name is also looked up in the // context of the entire postfix-expression and // -- if the name is not found, the name found in the class of the object // expression is used, otherwise // -- if the name is found in the context of the entire postfix-expression // and does not name a class template, the name found in the class of the // object expression is used, otherwise // -- if the name found is a class template, it must refer to the same // entity as the one found in the class of the object expression, // otherwise the program is ill-formed. // From PR 7247 template<typename T> struct set{}; struct Value { template<typename T> void set(T value) {} void resolves_to_same() { Value v; v.set<double>(3.2); } }; void resolves_to_different() { { Value v; // The fact that the next line is a warning rather than an error is an // extension. v.set<double>(3.2); } { int set; // Non-template. Value v; v.set<double>(3.2); } } namespace rdar9915664 { struct A { template<typename T> void a(); }; struct B : A { }; struct C : A { }; struct D : B, C { A &getA() { return static_cast<B&>(*this); } void test_a() { getA().a<int>(); } }; } namespace PR11856 { template<typename T> T end(T); template <typename T> void Foo() { T it1; if (it1->end < it1->end) { } } template<typename T> T *end(T*); class X { }; template <typename T> void Foo2() { T it1; if (it1->end < it1->end) { } X *x; if (x->end < 7) { // expected-error{{no member named 'end' in 'PR11856::X'}} } } } <commit_msg>We don't need a lengthy quote from the wrong standard.<commit_after>// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fdiagnostics-show-option -verify %s template<typename T> struct set{}; struct Value { template<typename T> void set(T value) {} void resolves_to_same() { Value v; v.set<double>(3.2); } }; void resolves_to_different() { { Value v; // The fact that the next line is a warning rather than an error is an // extension. v.set<double>(3.2); } { int set; // Non-template. Value v; v.set<double>(3.2); } } namespace rdar9915664 { struct A { template<typename T> void a(); }; struct B : A { }; struct C : A { }; struct D : B, C { A &getA() { return static_cast<B&>(*this); } void test_a() { getA().a<int>(); } }; } namespace PR11856 { template<typename T> T end(T); template <typename T> void Foo() { T it1; if (it1->end < it1->end) { } } template<typename T> T *end(T*); class X { }; template <typename T> void Foo2() { T it1; if (it1->end < it1->end) { } X *x; if (x->end < 7) { // expected-error{{no member named 'end' in 'PR11856::X'}} } } } <|endoftext|>
<commit_before><commit_msg>IMPALA-1735: ExpandRmReservation only check parent pools with limit<commit_after><|endoftext|>
<commit_before>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <dariadb.h> #include <utils/fs.h> #include <storage/page_manager.h> #include <ctime> #include <limits> #include <cmath> #include <chrono> #include <thread> #include <atomic> #include <cassert> class BenchCallback :public dariadb::storage::Cursor::Callback { public: void call(dariadb::storage::Chunk_Ptr &) { count++; } size_t count; }; const std::string storagePath = "benchStorage/"; const size_t chunks_count = 1024; const size_t chunks_size = 1024; int main(int argc, char *argv[]) { (void)argc; (void)argv; { dariadb::Time t = 0; dariadb::Meas first; first.id = 1; first.time = t; dariadb::storage::Chunk_Ptr ch = std::make_shared<dariadb::storage::Chunk>(chunks_size, first); for (int i = 0;; i++, t++) { first.flag = dariadb::Flag(i); first.time = t; first.value = dariadb::Value(i); if (!ch->append(first)) { break; } } if (dariadb::utils::fs::path_exists(storagePath)) { dariadb::utils::fs::rm(storagePath); } dariadb::storage::PageManager::start(dariadb::storage::PageManager::Params(storagePath, dariadb::storage::MODE::SINGLE, chunks_count, chunks_size)); auto start = clock(); for (size_t i = 0; i < chunks_count; ++i) { dariadb::storage::PageManager::instance()->append(ch); ch->maxTime += dariadb::Time(chunks_size); ch->minTime += dariadb::Time(chunks_size); } auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "insert : " << elapsed << std::endl; BenchCallback*clbk = new BenchCallback; start = clock(); dariadb::Time to_t = chunks_size; for (size_t i = 1; i < chunks_count; i++) { auto cursor = dariadb::storage::PageManager::instance()->chunksByIterval(dariadb::IdArray{}, 0, to_t, 0); cursor->readAll(clbk); cursor = nullptr; to_t *= 2; } elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "readAll : " << elapsed << std::endl; delete clbk; dariadb::storage::PageManager::stop(); if (dariadb::utils::fs::path_exists(storagePath)) { dariadb::utils::fs::rm(storagePath); } ch = nullptr; } } <commit_msg>page_benchmark: read benchmarks.<commit_after>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <dariadb.h> #include <utils/fs.h> #include <storage/page_manager.h> #include <ctime> #include <limits> #include <cmath> #include <chrono> #include <thread> #include <atomic> #include <cassert> #include <random> class BenchCallback :public dariadb::storage::Cursor::Callback { public: void call(dariadb::storage::Chunk_Ptr &) { count++; } size_t count; }; const std::string storagePath = "benchStorage/"; const size_t chunks_count = 1024; const size_t chunks_size = 1024; int main(int argc, char *argv[]) { (void)argc; (void)argv; { dariadb::Time t = 0; dariadb::Meas first; first.id = 1; first.time = t; dariadb::storage::Chunk_Ptr ch = std::make_shared<dariadb::storage::Chunk>(chunks_size, first); for (int i = 0;; i++, t++) { first.flag = dariadb::Flag(i); first.time = t; first.value = dariadb::Value(i); if (!ch->append(first)) { break; } } if (dariadb::utils::fs::path_exists(storagePath)) { dariadb::utils::fs::rm(storagePath); } dariadb::storage::PageManager::start(dariadb::storage::PageManager::Params(storagePath, dariadb::storage::MODE::SINGLE, chunks_count, chunks_size)); auto start = clock(); for (size_t i = 0; i < chunks_count; ++i) { dariadb::storage::PageManager::instance()->append(ch); ch->maxTime += dariadb::Time(chunks_size); ch->minTime += dariadb::Time(chunks_size); } auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "insert : " << elapsed << std::endl; dariadb::storage::PageManager::instance()->flush(); std::random_device r; std::default_random_engine e1(r()); std::uniform_int_distribution<dariadb::Id> uniform_dist(dariadb::storage::PageManager::instance()->minTime(), dariadb::storage::PageManager::instance()->maxTime()); BenchCallback*clbk = new BenchCallback; start = clock(); for (size_t i = 0; i < size_t(100); i++) { auto time_point1 = uniform_dist(e1); auto time_point2 = uniform_dist(e1); auto from=std::min(time_point1,time_point2); auto to=std::max(time_point1,time_point2); auto cursor = dariadb::storage::PageManager::instance()->chunksByIterval(dariadb::IdArray{}, from, to, 0); cursor->readAll(clbk); cursor = nullptr; } elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "interval: " << elapsed << std::endl; start = clock(); for (size_t i = 0; i < size_t(100); i++) { auto time_point = uniform_dist(e1); dariadb::storage::PageManager::instance()->chunksBeforeTimePoint(dariadb::IdArray{}, 0,time_point); } elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "timePoint: " << elapsed << std::endl; delete clbk; dariadb::storage::PageManager::stop(); if (dariadb::utils::fs::path_exists(storagePath)) { dariadb::utils::fs::rm(storagePath); } ch = nullptr; } } <|endoftext|>
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Header: FGTrimAxis.cpp Author: Tony Peden Date started: 7/3/00 --------- Copyright (C) 1999 Anthony K. Peden ([email protected]) --------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. HISTORY -------------------------------------------------------------------------------- 7/3/00 TP Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include <string> #include <stdlib.h> #include "FGFDMExec.h" #include "FGAtmosphere.h" #include "FGInitialCondition.h" #include "FGTrimAxis.h" #include "FGAircraft.h" static const char *IdSrc = "$Header: /cvsroot/jsbsim/JSBSim/Attic/FGTrimAxis.cpp,v 1.10 2000/11/01 11:38:09 jsb Exp $"; static const char *IdHdr = ID_TRIMAXIS; /*****************************************************************************/ FGTrimAxis::FGTrimAxis(FGFDMExec* fdex, FGInitialCondition* ic, Accel acc, Control ctrl, float ff) { fdmex=fdex; fgic=ic; accel=acc; control=ctrl; tolerance=ff; solver_eps=tolerance; max_iterations=10; control_value=0; its_to_stable_value=0; total_iterations=0; total_stability_iterations=0; accel_convert=1.0; control_convert=1.0; accel_value=0; switch(control) { case tThrottle: control_min=0; control_max=1; control_value=0.5; break; case tBeta: control_min=-30*DEGTORAD; control_max=30*DEGTORAD; control_convert=RADTODEG; break; case tAlpha: control_min=fdmex->GetAircraft()->GetAlphaCLMin(); control_max=fdmex->GetAircraft()->GetAlphaCLMax(); if(control_max <= control_min) { control_max=20*DEGTORAD; control_min=-5*DEGTORAD; } control_value= (control_min+control_max)/2; control_convert=RADTODEG; solver_eps=tolerance/100; break; case tPitchTrim: case tElevator: case tRollTrim: case tAileron: case tYawTrim: case tRudder: control_min=-1; control_max=1; accel_convert=RADTODEG; solver_eps=tolerance/100; break; case tAltAGL: control_min=0; control_max=30; control_value=fdmex->GetPosition()->GetDistanceAGL(); solver_eps=tolerance/100; break; case tTheta: control_min=fdmex->GetRotation()->Gettht() - 5*DEGTORAD; control_max=fdmex->GetRotation()->Gettht() + 5*DEGTORAD; accel_convert=RADTODEG; break; case tPhi: control_min=fdmex->GetRotation()->Getphi() - 5*DEGTORAD; control_max=fdmex->GetRotation()->Getphi() + 5*DEGTORAD; accel_convert=RADTODEG; break; case tGamma: solver_eps=tolerance/100; control_min=-80*DEGTORAD; control_max=80*DEGTORAD; control_convert=RADTODEG; break; } } /*****************************************************************************/ FGTrimAxis::~FGTrimAxis() {} /*****************************************************************************/ void FGTrimAxis::getAccel(void) { switch(accel) { case tUdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(1); break; case tVdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(2); break; case tWdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(3); break; case tQdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(2);break; case tPdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(1); break; case tRdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(3); break; } } /*****************************************************************************/ //Accels are not settable void FGTrimAxis::getControl(void) { switch(control) { case tThrottle: control_value=fdmex->GetFCS()->GetThrottleCmd(0); break; case tBeta: control_value=fdmex->GetTranslation()->Getalpha(); break; case tAlpha: control_value=fdmex->GetTranslation()->Getbeta(); break; case tPitchTrim: control_value=fdmex->GetFCS() -> GetPitchTrimCmd(); break; case tElevator: control_value=fdmex->GetFCS() -> GetDeCmd(); break; case tRollTrim: case tAileron: control_value=fdmex->GetFCS() -> GetDaCmd(); break; case tYawTrim: case tRudder: control_value=fdmex->GetFCS() -> GetDrCmd(); break; case tAltAGL: control_value=fdmex->GetPosition()->GetDistanceAGL();break; case tTheta: control_value=fdmex->GetRotation()->Gettht(); break; case tPhi: control_value=fdmex->GetRotation()->Getphi(); break; case tGamma: control_value=fdmex->GetPosition()->GetGamma();break; } } /*****************************************************************************/ void FGTrimAxis::setControl(void) { switch(control) { case tThrottle: setThrottlesPct(); break; case tBeta: fgic->SetBetaRadIC(control_value); break; case tAlpha: fgic->SetAlphaRadIC(control_value); break; case tPitchTrim: fdmex->GetFCS() -> SetPitchTrimCmd(control_value); break; case tElevator: fdmex-> GetFCS() -> SetDeCmd(control_value); break; case tRollTrim: case tAileron: fdmex-> GetFCS() -> SetDaCmd(control_value); break; case tYawTrim: case tRudder: fdmex-> GetFCS() -> SetDrCmd(control_value); break; case tAltAGL: fgic->SetAltitudeAGLFtIC(control_value); break; case tTheta: fgic->SetPitchAngleRadIC(control_value); break; case tPhi: fgic->SetRollAngleRadIC(control_value); break; case tGamma: fgic->SetFlightPathAngleRadIC(control_value); break; } } /*****************************************************************************/ // the aircraft center of rotation is no longer the cg once the gear // contact the ground so the altitude needs to be changed when pitch // and roll angle are adjusted. Instead of attempting to calculate the // new center of rotation, pick a gear unit as a reference and use its // location vector to calculate the new height change. i.e. new altitude = // earth z component of that vector (which is in body axes ) void FGTrimAxis::SetThetaOnGround(float ff) { int center,i,ref; // favor an off-center unit so that the same one can be used for both // pitch and roll. An on-center unit is used (for pitch)if that's all // that's in contact with the ground. i=0; ref=-1; center=-1; while( (ref < 0) && (i < fdmex->GetAircraft()->GetNumGearUnits()) ) { if(fdmex->GetAircraft()->GetGearUnit(i)->GetWOW()) { if(fabs(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(2)) > 0.01) ref=i; else center=i; } i++; } if((ref < 0) && (center >= 0)) { ref=center; } cout << "SetThetaOnGround ref gear: " << ref << endl; if(ref >= 0) { float sp=fdmex->GetRotation()->GetSinphi(); float cp=fdmex->GetRotation()->GetCosphi(); float lx=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(1); float ly=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(2); float lz=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(3); float hagl = -1*lx*sin(ff) + ly*sp*cos(ff) + lz*cp*cos(ff); fgic->SetAltitudeAGLFtIC(hagl); cout << "SetThetaOnGround new alt: " << hagl << endl; } fgic->SetPitchAngleRadIC(ff); cout << "SetThetaOnGround new theta: " << ff << endl; } /*****************************************************************************/ bool FGTrimAxis::initTheta(void) { int i,N,iAft, iForward; float zAft,zForward,zDiff,theta; bool level; float saveAlt; saveAlt=fgic->GetAltitudeAGLFtIC(); fgic->SetAltitudeAGLFtIC(100); N=fdmex->GetAircraft()->GetNumGearUnits(); //find the first wheel unit forward of the cg //the list is short so a simple linear search is fine for( i=0; i<N; i++ ) { if(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(1) > 0 ) { iForward=i; break; } } //now find the first wheel unit aft of the cg for( i=0; i<N; i++ ) { if(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(1) < 0 ) { iAft=i; break; } } cout << "iForward: " << iForward << endl; cout << "iAft: " << iAft << endl; // now adjust theta till the wheels are the same distance from the ground zAft=fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear()(3); zForward=fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear()(3); zDiff = zForward - zAft; level=false; theta=fgic->GetPitchAngleDegIC(); while(!level && (i < 100)) { theta+=2.0*zDiff; fgic->SetPitchAngleDegIC(theta); fdmex->RunIC(fgic); zAft=fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear()(3); zForward=fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear()(3); zDiff = zForward - zAft; //cout << endl << theta << " " << zDiff << endl; //cout << "0: " << fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear() << endl; //cout << "1: " << fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear() << endl; if(fabs(zDiff ) < 0.1) level=true; i++; } //cout << i << endl; cout << "Initial Theta: " << fdmex->GetRotation()->Gettht()*RADTODEG << endl; control_min=(theta+5)*DEGTORAD; control_max=(theta-5)*DEGTORAD; fgic->SetAltitudeAGLFtIC(saveAlt); if(i < 100) return true; else return false; } /*****************************************************************************/ void FGTrimAxis::SetPhiOnGround(float ff) { int i,ref; i=0; ref=-1; //must have an off-center unit here while( (ref < 0) && (i < fdmex->GetAircraft()->GetNumGearUnits()) ) { if( (fdmex->GetAircraft()->GetGearUnit(i)->GetWOW()) && (fabs(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(2)) > 0.01)) ref=i; i++; } if(ref >= 0) { float st=fdmex->GetRotation()->GetSintht(); float ct=fdmex->GetRotation()->GetCostht(); float lx=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(1); float ly=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(2); float lz=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(3); float hagl = -1*lx*st + ly*sin(ff)*ct + lz*cos(ff)*ct; fgic->SetAltitudeAGLFtIC(hagl); } fgic->SetRollAngleRadIC(ff); } /*****************************************************************************/ void FGTrimAxis::Run(void) { float last_accel_value; int i; setControl(); //cout << "FGTrimAxis::Run: " << control_value << endl; i=0; bool stable=false; while(!stable) { i++; last_accel_value=accel_value; fdmex->RunIC(fgic); getAccel(); if(i > 1) { if((fabs(last_accel_value - accel_value) < tolerance) || (i >= 100) ) stable=true; } } its_to_stable_value=i; total_stability_iterations+=its_to_stable_value; total_iterations++; } /*****************************************************************************/ void FGTrimAxis::setThrottlesPct(void) { float tMin,tMax; for(unsigned i=0;i<fdmex->GetAircraft()->GetNumEngines();i++) { tMin=fdmex->GetAircraft()->GetEngine(i)->GetThrottleMin(); tMax=fdmex->GetAircraft()->GetEngine(i)->GetThrottleMax(); //cout << "setThrottlespct: " << i << ", " << control_min << ", " << control_max << ", " << control_value; fdmex -> GetFCS() -> SetThrottleCmd(i,tMin+control_value*(tMax-tMin)); } } /*****************************************************************************/ void FGTrimAxis::AxisReport(void) { char out[80]; sprintf(out," %20s: %6.2f %5s: %9.2e Tolerance: %3.0e\n", GetControlName().c_str(), GetControl()*control_convert, GetAccelName().c_str(), GetAccel(), GetTolerance()); cout << out; } /*****************************************************************************/ float FGTrimAxis::GetAvgStability( void ) { if(total_iterations > 0) { return float(total_stability_iterations)/float(total_iterations); } return 0; } <commit_msg>AKP Cleanup<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Header: FGTrimAxis.cpp Author: Tony Peden Date started: 7/3/00 --------- Copyright (C) 1999 Anthony K. Peden ([email protected]) --------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. HISTORY -------------------------------------------------------------------------------- 7/3/00 TP Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include <string> #include <stdlib.h> #include "FGFDMExec.h" #include "FGAtmosphere.h" #include "FGInitialCondition.h" #include "FGTrimAxis.h" #include "FGAircraft.h" static const char *IdSrc = "$Header: /cvsroot/jsbsim/JSBSim/Attic/FGTrimAxis.cpp,v 1.11 2000/11/01 12:14:48 jsb Exp $"; static const char *IdHdr = ID_TRIMAXIS; /*****************************************************************************/ FGTrimAxis::FGTrimAxis(FGFDMExec* fdex, FGInitialCondition* ic, Accel acc, Control ctrl, float ff) { fdmex=fdex; fgic=ic; accel=acc; control=ctrl; tolerance=ff; solver_eps=tolerance; max_iterations=10; control_value=0; its_to_stable_value=0; total_iterations=0; total_stability_iterations=0; accel_convert=1.0; control_convert=1.0; accel_value=0; switch(control) { case tThrottle: control_min=0; control_max=1; control_value=0.5; break; case tBeta: control_min=-30*DEGTORAD; control_max=30*DEGTORAD; control_convert=RADTODEG; break; case tAlpha: control_min=fdmex->GetAircraft()->GetAlphaCLMin(); control_max=fdmex->GetAircraft()->GetAlphaCLMax(); if(control_max <= control_min) { control_max=20*DEGTORAD; control_min=-5*DEGTORAD; } control_value= (control_min+control_max)/2; control_convert=RADTODEG; solver_eps=tolerance/100; break; case tPitchTrim: case tElevator: case tRollTrim: case tAileron: case tYawTrim: case tRudder: control_min=-1; control_max=1; accel_convert=RADTODEG; solver_eps=tolerance/100; break; case tAltAGL: control_min=0; control_max=30; control_value=fdmex->GetPosition()->GetDistanceAGL(); solver_eps=tolerance/100; break; case tTheta: control_min=fdmex->GetRotation()->Gettht() - 5*DEGTORAD; control_max=fdmex->GetRotation()->Gettht() + 5*DEGTORAD; accel_convert=RADTODEG; break; case tPhi: control_min=fdmex->GetRotation()->Getphi() - 5*DEGTORAD; control_max=fdmex->GetRotation()->Getphi() + 5*DEGTORAD; accel_convert=RADTODEG; break; case tGamma: solver_eps=tolerance/100; control_min=-80*DEGTORAD; control_max=80*DEGTORAD; control_convert=RADTODEG; break; } } /*****************************************************************************/ FGTrimAxis::~FGTrimAxis() {} /*****************************************************************************/ void FGTrimAxis::getAccel(void) { switch(accel) { case tUdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(1); break; case tVdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(2); break; case tWdot: accel_value=fdmex -> GetTranslation()->GetUVWdot()(3); break; case tQdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(2);break; case tPdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(1); break; case tRdot: accel_value=fdmex -> GetRotation()->GetPQRdot()(3); break; } } /*****************************************************************************/ //Accels are not settable void FGTrimAxis::getControl(void) { switch(control) { case tThrottle: control_value=fdmex->GetFCS()->GetThrottleCmd(0); break; case tBeta: control_value=fdmex->GetTranslation()->Getalpha(); break; case tAlpha: control_value=fdmex->GetTranslation()->Getbeta(); break; case tPitchTrim: control_value=fdmex->GetFCS() -> GetPitchTrimCmd(); break; case tElevator: control_value=fdmex->GetFCS() -> GetDeCmd(); break; case tRollTrim: case tAileron: control_value=fdmex->GetFCS() -> GetDaCmd(); break; case tYawTrim: case tRudder: control_value=fdmex->GetFCS() -> GetDrCmd(); break; case tAltAGL: control_value=fdmex->GetPosition()->GetDistanceAGL();break; case tTheta: control_value=fdmex->GetRotation()->Gettht(); break; case tPhi: control_value=fdmex->GetRotation()->Getphi(); break; case tGamma: control_value=fdmex->GetPosition()->GetGamma();break; } } /*****************************************************************************/ void FGTrimAxis::setControl(void) { switch(control) { case tThrottle: setThrottlesPct(); break; case tBeta: fgic->SetBetaRadIC(control_value); break; case tAlpha: fgic->SetAlphaRadIC(control_value); break; case tPitchTrim: fdmex->GetFCS() -> SetPitchTrimCmd(control_value); break; case tElevator: fdmex-> GetFCS() -> SetDeCmd(control_value); break; case tRollTrim: case tAileron: fdmex-> GetFCS() -> SetDaCmd(control_value); break; case tYawTrim: case tRudder: fdmex-> GetFCS() -> SetDrCmd(control_value); break; case tAltAGL: fgic->SetAltitudeAGLFtIC(control_value); break; case tTheta: fgic->SetPitchAngleRadIC(control_value); break; case tPhi: fgic->SetRollAngleRadIC(control_value); break; case tGamma: fgic->SetFlightPathAngleRadIC(control_value); break; } } /*****************************************************************************/ // the aircraft center of rotation is no longer the cg once the gear // contact the ground so the altitude needs to be changed when pitch // and roll angle are adjusted. Instead of attempting to calculate the // new center of rotation, pick a gear unit as a reference and use its // location vector to calculate the new height change. i.e. new altitude = // earth z component of that vector (which is in body axes ) void FGTrimAxis::SetThetaOnGround(float ff) { int center,i,ref; // favor an off-center unit so that the same one can be used for both // pitch and roll. An on-center unit is used (for pitch)if that's all // that's in contact with the ground. i=0; ref=-1; center=-1; while( (ref < 0) && (i < fdmex->GetAircraft()->GetNumGearUnits()) ) { if(fdmex->GetAircraft()->GetGearUnit(i)->GetWOW()) { if(fabs(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(2)) > 0.01) ref=i; else center=i; } i++; } if((ref < 0) && (center >= 0)) { ref=center; } cout << "SetThetaOnGround ref gear: " << ref << endl; if(ref >= 0) { float sp=fdmex->GetRotation()->GetSinphi(); float cp=fdmex->GetRotation()->GetCosphi(); float lx=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(1); float ly=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(2); float lz=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(3); float hagl = -1*lx*sin(ff) + ly*sp*cos(ff) + lz*cp*cos(ff); fgic->SetAltitudeAGLFtIC(hagl); cout << "SetThetaOnGround new alt: " << hagl << endl; } fgic->SetPitchAngleRadIC(ff); cout << "SetThetaOnGround new theta: " << ff << endl; } /*****************************************************************************/ bool FGTrimAxis::initTheta(void) { int i,N,iAft, iForward; float zAft,zForward,zDiff,theta; bool level; float saveAlt; saveAlt=fgic->GetAltitudeAGLFtIC(); fgic->SetAltitudeAGLFtIC(100); N=fdmex->GetAircraft()->GetNumGearUnits(); //find the first wheel unit forward of the cg //the list is short so a simple linear search is fine for( i=0; i<N; i++ ) { if(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(1) > 0 ) { iForward=i; break; } } //now find the first wheel unit aft of the cg for( i=0; i<N; i++ ) { if(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(1) < 0 ) { iAft=i; break; } } // now adjust theta till the wheels are the same distance from the ground zAft=fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear()(3); zForward=fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear()(3); zDiff = zForward - zAft; level=false; theta=fgic->GetPitchAngleDegIC(); while(!level && (i < 100)) { theta+=2.0*zDiff; fgic->SetPitchAngleDegIC(theta); fdmex->RunIC(fgic); zAft=fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear()(3); zForward=fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear()(3); zDiff = zForward - zAft; //cout << endl << theta << " " << zDiff << endl; //cout << "0: " << fdmex->GetAircraft()->GetGearUnit(0)->GetLocalGear() << endl; //cout << "1: " << fdmex->GetAircraft()->GetGearUnit(1)->GetLocalGear() << endl; if(fabs(zDiff ) < 0.1) level=true; i++; } //cout << i << endl; cout << " Initial Theta: " << fdmex->GetRotation()->Gettht()*RADTODEG << endl; control_min=(theta+5)*DEGTORAD; control_max=(theta-5)*DEGTORAD; fgic->SetAltitudeAGLFtIC(saveAlt); if(i < 100) return true; else return false; } /*****************************************************************************/ void FGTrimAxis::SetPhiOnGround(float ff) { int i,ref; i=0; ref=-1; //must have an off-center unit here while( (ref < 0) && (i < fdmex->GetAircraft()->GetNumGearUnits()) ) { if( (fdmex->GetAircraft()->GetGearUnit(i)->GetWOW()) && (fabs(fdmex->GetAircraft()->GetGearUnit(i)->GetBodyLocation()(2)) > 0.01)) ref=i; i++; } if(ref >= 0) { float st=fdmex->GetRotation()->GetSintht(); float ct=fdmex->GetRotation()->GetCostht(); float lx=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(1); float ly=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(2); float lz=fdmex->GetAircraft()->GetGearUnit(ref)->GetBodyLocation()(3); float hagl = -1*lx*st + ly*sin(ff)*ct + lz*cos(ff)*ct; fgic->SetAltitudeAGLFtIC(hagl); } fgic->SetRollAngleRadIC(ff); } /*****************************************************************************/ void FGTrimAxis::Run(void) { float last_accel_value; int i; setControl(); //cout << "FGTrimAxis::Run: " << control_value << endl; i=0; bool stable=false; while(!stable) { i++; last_accel_value=accel_value; fdmex->RunIC(fgic); getAccel(); if(i > 1) { if((fabs(last_accel_value - accel_value) < tolerance) || (i >= 100) ) stable=true; } } its_to_stable_value=i; total_stability_iterations+=its_to_stable_value; total_iterations++; } /*****************************************************************************/ void FGTrimAxis::setThrottlesPct(void) { float tMin,tMax; for(unsigned i=0;i<fdmex->GetAircraft()->GetNumEngines();i++) { tMin=fdmex->GetAircraft()->GetEngine(i)->GetThrottleMin(); tMax=fdmex->GetAircraft()->GetEngine(i)->GetThrottleMax(); //cout << "setThrottlespct: " << i << ", " << control_min << ", " << control_max << ", " << control_value; fdmex -> GetFCS() -> SetThrottleCmd(i,tMin+control_value*(tMax-tMin)); } } /*****************************************************************************/ void FGTrimAxis::AxisReport(void) { char out[80]; sprintf(out," %20s: %6.2f %5s: %9.2e Tolerance: %3.0e\n", GetControlName().c_str(), GetControl()*control_convert, GetAccelName().c_str(), GetAccel(), GetTolerance()); cout << out; } /*****************************************************************************/ float FGTrimAxis::GetAvgStability( void ) { if(total_iterations > 0) { return float(total_stability_iterations)/float(total_iterations); } return 0; } <|endoftext|>
<commit_before>#include "types.h" #include "mmu.h" #include "kernel.hh" #include "amd64.h" #include "cpu.hh" #include "traps.h" #include "queue.h" #include "spinlock.h" #include "condvar.h" #include "proc.hh" #include "kmtrace.hh" #include "bits.hh" #include "kalloc.hh" #include "apic.hh" #include "kstream.hh" extern "C" void __uaccess_end(void); struct intdesc idt[256] __attribute__((aligned(16))); // boot.S extern u64 trapentry[]; u64 sysentry_c(u64 a0, u64 a1, u64 a2, u64 a3, u64 a4, u64 a5, u64 num) { sti(); if(myproc()->killed) { mtstart(trap, myproc()); exit(); } trapframe *tf = (trapframe*) (myproc()->kstack + KSTACKSIZE - sizeof(*tf)); myproc()->tf = tf; u64 r = syscall(a0, a1, a2, a3, a4, a5, num); if(myproc()->killed) { mtstart(trap, myproc()); exit(); } return r; } int do_pagefault(struct trapframe *tf) { uptr addr = rcr2(); if (myproc()->uaccess_) { if (addr >= USERTOP) panic("do_pagefault: %lx", addr); sti(); if(pagefault(myproc()->vmap, addr, tf->err) >= 0){ #if MTRACE mtstop(myproc()); if (myproc()->mtrace_stacks.curr >= 0) mtresume(myproc()); #endif return 0; } cprintf("pagefault: failed in kernel\n"); tf->rax = -1; tf->rip = (u64)__uaccess_end; return 0; } else if (tf->err & FEC_U) { sti(); if(pagefault(myproc()->vmap, addr, tf->err) >= 0){ #if MTRACE mtstop(myproc()); if (myproc()->mtrace_stacks.curr >= 0) mtresume(myproc()); #endif return 0; } uerr.println("pagefault: failed in user"); cli(); } return -1; } void trap(struct trapframe *tf) { if (tf->trapno == T_NMI) { // The only locks that we can acquire during NMI are ones // we acquire only during NMI. if (sampintr(tf)) return; panic("NMI"); } #if MTRACE if (myproc()->mtrace_stacks.curr >= 0) mtpause(myproc()); mtstart(trap, myproc()); // XXX mt_ascope ascope("trap:%d", tf->trapno); #endif switch(tf->trapno){ case T_IRQ0 + IRQ_TIMER: if (mycpu()->timer_printpc) { cprintf("cpu%d: proc %s rip %lx rsp %lx cs %x\n", mycpu()->id, myproc() ? myproc()->name : "(none)", tf->rip, tf->rsp, tf->cs); if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) { uptr pc[10]; getcallerpcs((void *) tf->rbp, pc, NELEM(pc)); for (int i = 0; i < 10 && pc[i]; i++) cprintf("cpu%d: %lx\n", mycpu()->id, pc[i]); } mycpu()->timer_printpc = 0; } if (mycpu()->id == 0) timerintr(); lapiceoi(); break; case T_IRQ0 + IRQ_IDE: ideintr(); lapiceoi(); piceoi(); break; case T_IRQ0 + IRQ_IDE+1: // Bochs generates spurious IDE1 interrupts. break; case T_IRQ0 + IRQ_KBD: kbdintr(); lapiceoi(); piceoi(); break; case T_IRQ0 + IRQ_COM2: case T_IRQ0 + IRQ_COM1: uartintr(); lapiceoi(); piceoi(); break; case T_IRQ0 + 7: case T_IRQ0 + IRQ_SPURIOUS: cprintf("cpu%d: spurious interrupt at %x:%lx\n", mycpu()->id, tf->cs, tf->rip); lapiceoi(); break; case T_IRQ0 + IRQ_ERROR: cprintf("cpu%d: lapic error?\n", mycpu()->id); lapiceoi(); break; case T_TLBFLUSH: { lapiceoi(); u64 nreq = tlbflush_req.load(); lcr3(rcr3()); mycpu()->tlbflush_done = nreq; break; } case T_SAMPCONF: lapiceoi(); sampconf(); break; default: if (tf->trapno == T_IRQ0+e1000irq) { e1000intr(); lapiceoi(); piceoi(); break; } if (tf->trapno == T_PGFLT && do_pagefault(tf) == 0) return; if (myproc() == 0 || (tf->cs&3) == 0) kerneltrap(tf); // In user space, assume process misbehaved. uerr.println("pid ", myproc()->pid, ' ', myproc()->name, ": trap ", (u64)tf->trapno, " err ", (u32)tf->err, " on cpu ", myid(), " rip ", shex(tf->rip), " rsp ", shex(tf->rsp), " addr ", shex(rcr2()), "--kill proc"); myproc()->killed = 1; } // Force process exit if it has been killed and is in user space. // (If it is still executing in the kernel, let it keep running // until it gets to the regular system call return.) if(myproc() && myproc()->killed && (tf->cs&3) == 0x3) exit(); // Force process to give up CPU on clock tick. // If interrupts were on while locks held, would need to check nlock. if(myproc() && myproc()->get_state() == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER) yield(); // Check if the process has been killed since we yielded if(myproc() && myproc()->killed && (tf->cs&3) == 0x3) exit(); #if MTRACE mtstop(myproc()); if (myproc()->mtrace_stacks.curr >= 0) mtresume(myproc()); #endif } void inittrap(void) { u64 entry; u8 bits; int i; bits = INT_P | SEG_INTR64; // present, interrupt gate for(i=0; i<256; i++) { entry = trapentry[i]; idt[i] = INTDESC(KCSEG, entry, bits); } } void initnmi(void) { void *nmistackbase = ksalloc(slab_stack); mycpu()->ts.ist[1] = (u64) nmistackbase + KSTACKSIZE; if (mycpu()->id == 0) idt[T_NMI].ist = 1; } void initseg(void) { volatile struct desctr dtr; struct cpu *c; dtr.limit = sizeof(idt) - 1; dtr.base = (u64)idt; lidt((void *)&dtr.limit); // TLS might not be ready c = &cpus[myid()]; // Load per-CPU GDT memmove(c->gdt, bootgdt, sizeof(bootgdt)); dtr.limit = sizeof(c->gdt) - 1; dtr.base = (u64)c->gdt; lgdt((void *)&dtr.limit); // When executing a syscall instruction the CPU sets the SS selector // to (star >> 32) + 8 and the CS selector to (star >> 32). // When executing a sysret instruction the CPU sets the SS selector // to (star >> 48) + 8 and the CS selector to (star >> 48) + 16. u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32); writemsr(MSR_STAR, star); writemsr(MSR_LSTAR, (u64)&sysentry); writemsr(MSR_SFMASK, FL_TF | FL_IF); } // Pushcli/popcli are like cli/sti except that they are matched: // it takes two popcli to undo two pushcli. Also, if interrupts // are off, then pushcli, popcli leaves them off. void pushcli(void) { u64 rflags; rflags = readrflags(); cli(); if(mycpu()->ncli++ == 0) mycpu()->intena = rflags & FL_IF; } void popcli(void) { if(readrflags()&FL_IF) panic("popcli - interruptible"); if(--mycpu()->ncli < 0) panic("popcli"); if(mycpu()->ncli == 0 && mycpu()->intena) sti(); } // Record the current call stack in pcs[] by following the %rbp chain. void getcallerpcs(void *v, uptr pcs[], int n) { uptr *rbp; int i; rbp = (uptr*)v; for(i = 0; i < n; i++){ if(rbp == 0 || rbp < (uptr*)KBASE || rbp == (uptr*)(~0UL) || (rbp >= (uptr*)KBASEEND && rbp < (uptr*)KCODE)) break; pcs[i] = rbp[1]; // saved %rip rbp = (uptr*)rbp[0]; // saved %rbp } for(; i < n; i++) pcs[i] = 0; } <commit_msg>Subtract one from PCs recorded by getcallerpcs<commit_after>#include "types.h" #include "mmu.h" #include "kernel.hh" #include "amd64.h" #include "cpu.hh" #include "traps.h" #include "queue.h" #include "spinlock.h" #include "condvar.h" #include "proc.hh" #include "kmtrace.hh" #include "bits.hh" #include "kalloc.hh" #include "apic.hh" #include "kstream.hh" extern "C" void __uaccess_end(void); struct intdesc idt[256] __attribute__((aligned(16))); // boot.S extern u64 trapentry[]; u64 sysentry_c(u64 a0, u64 a1, u64 a2, u64 a3, u64 a4, u64 a5, u64 num) { sti(); if(myproc()->killed) { mtstart(trap, myproc()); exit(); } trapframe *tf = (trapframe*) (myproc()->kstack + KSTACKSIZE - sizeof(*tf)); myproc()->tf = tf; u64 r = syscall(a0, a1, a2, a3, a4, a5, num); if(myproc()->killed) { mtstart(trap, myproc()); exit(); } return r; } int do_pagefault(struct trapframe *tf) { uptr addr = rcr2(); if (myproc()->uaccess_) { if (addr >= USERTOP) panic("do_pagefault: %lx", addr); sti(); if(pagefault(myproc()->vmap, addr, tf->err) >= 0){ #if MTRACE mtstop(myproc()); if (myproc()->mtrace_stacks.curr >= 0) mtresume(myproc()); #endif return 0; } cprintf("pagefault: failed in kernel\n"); tf->rax = -1; tf->rip = (u64)__uaccess_end; return 0; } else if (tf->err & FEC_U) { sti(); if(pagefault(myproc()->vmap, addr, tf->err) >= 0){ #if MTRACE mtstop(myproc()); if (myproc()->mtrace_stacks.curr >= 0) mtresume(myproc()); #endif return 0; } uerr.println("pagefault: failed in user"); cli(); } return -1; } void trap(struct trapframe *tf) { if (tf->trapno == T_NMI) { // The only locks that we can acquire during NMI are ones // we acquire only during NMI. if (sampintr(tf)) return; panic("NMI"); } #if MTRACE if (myproc()->mtrace_stacks.curr >= 0) mtpause(myproc()); mtstart(trap, myproc()); // XXX mt_ascope ascope("trap:%d", tf->trapno); #endif switch(tf->trapno){ case T_IRQ0 + IRQ_TIMER: if (mycpu()->timer_printpc) { cprintf("cpu%d: proc %s rip %lx rsp %lx cs %x\n", mycpu()->id, myproc() ? myproc()->name : "(none)", tf->rip, tf->rsp, tf->cs); if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) { uptr pc[10]; getcallerpcs((void *) tf->rbp, pc, NELEM(pc)); for (int i = 0; i < 10 && pc[i]; i++) cprintf("cpu%d: %lx\n", mycpu()->id, pc[i]); } mycpu()->timer_printpc = 0; } if (mycpu()->id == 0) timerintr(); lapiceoi(); break; case T_IRQ0 + IRQ_IDE: ideintr(); lapiceoi(); piceoi(); break; case T_IRQ0 + IRQ_IDE+1: // Bochs generates spurious IDE1 interrupts. break; case T_IRQ0 + IRQ_KBD: kbdintr(); lapiceoi(); piceoi(); break; case T_IRQ0 + IRQ_COM2: case T_IRQ0 + IRQ_COM1: uartintr(); lapiceoi(); piceoi(); break; case T_IRQ0 + 7: case T_IRQ0 + IRQ_SPURIOUS: cprintf("cpu%d: spurious interrupt at %x:%lx\n", mycpu()->id, tf->cs, tf->rip); lapiceoi(); break; case T_IRQ0 + IRQ_ERROR: cprintf("cpu%d: lapic error?\n", mycpu()->id); lapiceoi(); break; case T_TLBFLUSH: { lapiceoi(); u64 nreq = tlbflush_req.load(); lcr3(rcr3()); mycpu()->tlbflush_done = nreq; break; } case T_SAMPCONF: lapiceoi(); sampconf(); break; default: if (tf->trapno == T_IRQ0+e1000irq) { e1000intr(); lapiceoi(); piceoi(); break; } if (tf->trapno == T_PGFLT && do_pagefault(tf) == 0) return; if (myproc() == 0 || (tf->cs&3) == 0) kerneltrap(tf); // In user space, assume process misbehaved. uerr.println("pid ", myproc()->pid, ' ', myproc()->name, ": trap ", (u64)tf->trapno, " err ", (u32)tf->err, " on cpu ", myid(), " rip ", shex(tf->rip), " rsp ", shex(tf->rsp), " addr ", shex(rcr2()), "--kill proc"); myproc()->killed = 1; } // Force process exit if it has been killed and is in user space. // (If it is still executing in the kernel, let it keep running // until it gets to the regular system call return.) if(myproc() && myproc()->killed && (tf->cs&3) == 0x3) exit(); // Force process to give up CPU on clock tick. // If interrupts were on while locks held, would need to check nlock. if(myproc() && myproc()->get_state() == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER) yield(); // Check if the process has been killed since we yielded if(myproc() && myproc()->killed && (tf->cs&3) == 0x3) exit(); #if MTRACE mtstop(myproc()); if (myproc()->mtrace_stacks.curr >= 0) mtresume(myproc()); #endif } void inittrap(void) { u64 entry; u8 bits; int i; bits = INT_P | SEG_INTR64; // present, interrupt gate for(i=0; i<256; i++) { entry = trapentry[i]; idt[i] = INTDESC(KCSEG, entry, bits); } } void initnmi(void) { void *nmistackbase = ksalloc(slab_stack); mycpu()->ts.ist[1] = (u64) nmistackbase + KSTACKSIZE; if (mycpu()->id == 0) idt[T_NMI].ist = 1; } void initseg(void) { volatile struct desctr dtr; struct cpu *c; dtr.limit = sizeof(idt) - 1; dtr.base = (u64)idt; lidt((void *)&dtr.limit); // TLS might not be ready c = &cpus[myid()]; // Load per-CPU GDT memmove(c->gdt, bootgdt, sizeof(bootgdt)); dtr.limit = sizeof(c->gdt) - 1; dtr.base = (u64)c->gdt; lgdt((void *)&dtr.limit); // When executing a syscall instruction the CPU sets the SS selector // to (star >> 32) + 8 and the CS selector to (star >> 32). // When executing a sysret instruction the CPU sets the SS selector // to (star >> 48) + 8 and the CS selector to (star >> 48) + 16. u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32); writemsr(MSR_STAR, star); writemsr(MSR_LSTAR, (u64)&sysentry); writemsr(MSR_SFMASK, FL_TF | FL_IF); } // Pushcli/popcli are like cli/sti except that they are matched: // it takes two popcli to undo two pushcli. Also, if interrupts // are off, then pushcli, popcli leaves them off. void pushcli(void) { u64 rflags; rflags = readrflags(); cli(); if(mycpu()->ncli++ == 0) mycpu()->intena = rflags & FL_IF; } void popcli(void) { if(readrflags()&FL_IF) panic("popcli - interruptible"); if(--mycpu()->ncli < 0) panic("popcli"); if(mycpu()->ncli == 0 && mycpu()->intena) sti(); } // Record the current call stack in pcs[] by following the %rbp chain. void getcallerpcs(void *v, uptr pcs[], int n) { uptr *rbp; int i; rbp = (uptr*)v; for(i = 0; i < n; i++){ if(rbp == 0 || rbp < (uptr*)KBASE || rbp == (uptr*)(~0UL) || (rbp >= (uptr*)KBASEEND && rbp < (uptr*)KCODE)) break; pcs[i] = rbp[1] - 1; // saved %rip; - 1 so it points to the call // instruction rbp = (uptr*)rbp[0]; // saved %rbp } for(; i < n; i++) pcs[i] = 0; } <|endoftext|>
<commit_before>// File: ebdpConfigFile.cpp // Date: 9/27/2017 // Auth: K. Loux // Desc: Configuration file object. // Local headers #include "ebdpConfigFile.h" void EBDPConfigFile::BuildConfigItems() { AddConfigItem(_T("OBS_DATA_FILE"), config.dataFileName); AddConfigItem(_T("OUTPUT_FILE"), config.outputFileName); AddConfigItem(_T("COUNTRY"), config.countryFilter); AddConfigItem(_T("STATE"), config.stateFilter); AddConfigItem(_T("COUNTY"), config.countyFilter); AddConfigItem(_T("LOCATION"), config.locationFilter); AddConfigItem(_T("LIST_TYPE"), config.listType); AddConfigItem(_T("SCORE_RARITIES"), config.generateRarityScores); AddConfigItem(_T("SPECIES_COUNT_ONLY"), config.speciesCountOnly); AddConfigItem(_T("INCLUDE_PARTIAL_IDS"), config.includePartialIDs); AddConfigItem(_T("PHOTO_FILE"), config.photoFileName); AddConfigItem(_T("SHOW_PHOTO_NEEDS"), config.showOnlyPhotoNeeds); AddConfigItem(_T("YEAR"), config.yearFilter); AddConfigItem(_T("MONTH"), config.monthFilter); AddConfigItem(_T("WEEK"), config.weekFilter); AddConfigItem(_T("DAY"), config.dayFilter); AddConfigItem(_T("SORT_FIRST"), config.primarySort); AddConfigItem(_T("SORT_SECOND"), config.secondarySort); AddConfigItem(_T("SHOW_UNIQUE_OBS"), config.uniqueObservations); AddConfigItem(_T("CALENDAR"), config.generateTargetCalendar); AddConfigItem(_T("TARGET_AREA"), config.targetNeedArea); AddConfigItem(_T("TOP_COUNT"), config.topBirdCount); AddConfigItem(_T("FREQUENCY_FILES"), config.frequencyFilePath); AddConfigItem(_T("TARGET_INFO_FILE_NAME"), config.targetInfoFileName); AddConfigItem(_T("RECENT_PERIOD"), config.recentObservationPeriod); AddConfigItem(_T("GOOGLE_MAPS_KEY"), config.googleMapsAPIKey); AddConfigItem(_T("HOME_LOCATION"), config.homeLocation); AddConfigItem(_T("EBIRD_API_KEY"), config.eBirdApiKey); AddConfigItem(_T("FIND_MAX_NEEDS"), config.findMaxNeedsLocations); AddConfigItem(_T("KML_LIBRARY"), config.kmlLibraryPath); AddConfigItem(_T("OAUTH_CLIENT_ID"), config.oAuthClientId); AddConfigItem(_T("OAUTH_CLIENT_SECRET"), config.oAuthClientSecret); AddConfigItem(_T("DATASET"), config.eBirdDatasetPath); } void EBDPConfigFile::AssignDefaults() { config.listType = EBDPConfig::ListType::Life; config.speciesCountOnly = false; config.includePartialIDs = false; config.yearFilter = 0; config.monthFilter = 0; config.weekFilter = 0; config.dayFilter = 0; config.primarySort = EBDPConfig::SortBy::None; config.secondarySort = EBDPConfig::SortBy::None; config.uniqueObservations = EBDPConfig::UniquenessType::None; config.targetNeedArea = EBDPConfig::TargetNeedArea::None; config.generateTargetCalendar = false; config.generateRarityScores = false; config.topBirdCount = 20; config.recentObservationPeriod = 15; config.showOnlyPhotoNeeds = false; config.findMaxNeedsLocations = false; } bool EBDPConfigFile::ConfigIsOK() { bool configurationOK(true); if (!GeneralConfigIsOK()) configurationOK = false; if (!FrequencyHarvestConfigIsOK()) configurationOK = false; if (!TargetCalendarConfigIsOK()) configurationOK = false; if (!FindMaxNeedsConfigIsOK()) configurationOK = false; if (!RaritiesConfigIsOK()) configurationOK = false; return configurationOK; } bool EBDPConfigFile::FrequencyHarvestConfigIsOK() { bool configurationOK(true); if (!config.eBirdDatasetPath.empty() && config.frequencyFilePath.empty()) { Cerr << GetKey(config.eBirdDatasetPath) << " requires " << GetKey(config.frequencyFilePath) << '\n'; configurationOK = false; } return configurationOK; } bool EBDPConfigFile::TargetCalendarConfigIsOK() { if (!config.generateTargetCalendar) return true; bool configurationOK(true); if (config.frequencyFilePath.empty()) { Cerr << "Must specify " << GetKey(config.frequencyFilePath) << " when using " << GetKey(config.generateTargetCalendar) << '\n'; configurationOK = false; } if (config.eBirdApiKey.empty()) { Cerr << "Must specify " << GetKey(config.eBirdApiKey) << " when using " << GetKey(config.generateTargetCalendar) << '\n'; configurationOK = false; } if (config.uniqueObservations != EBDPConfig::UniquenessType::None) { Cerr << "Cannot specify both " << GetKey(config.generateTargetCalendar) << " and " << GetKey(config.uniqueObservations) << '\n'; configurationOK = false; } return configurationOK; } bool EBDPConfigFile::FindMaxNeedsConfigIsOK() { if (!config.findMaxNeedsLocations) return true; bool configurationOK(true); if (config.oAuthClientId.empty() || config.oAuthClientSecret.empty()) { Cerr << GetKey(config.findMaxNeedsLocations) << " requires " << GetKey(config.oAuthClientId) << " and " << GetKey(config.oAuthClientSecret) << '\n'; configurationOK = false; } if (config.kmlLibraryPath.empty()) { Cerr << GetKey(config.findMaxNeedsLocations) << " requires " << GetKey(config.kmlLibraryPath) << '\n'; configurationOK = false; } if (config.eBirdApiKey.empty()) { Cerr << GetKey(config.findMaxNeedsLocations) << " requires " << GetKey(config.eBirdApiKey) << '\n'; configurationOK = false; } if (config.frequencyFilePath.empty()) { Cerr << "Must specify " << GetKey(config.frequencyFilePath) << " when using " << GetKey(config.findMaxNeedsLocations) << '\n'; configurationOK = false; } return configurationOK; } bool EBDPConfigFile::GeneralConfigIsOK() { bool configurationOK(true); if (config.dataFileName.empty()) { Cerr << "Must specify '" << GetKey(config.dataFileName) << "'\n"; configurationOK = false; } if (!config.countryFilter.empty() && config.countryFilter.length() != 2) { Cerr << "Country (" << GetKey(config.countryFilter) << ") must be specified using 2-digit abbreviation\n"; configurationOK = false; } if (!config.stateFilter.empty() && (config.stateFilter.length() < 2 || config.stateFilter.length() > 3)) { Cerr << "State/providence (" << GetKey(config.stateFilter) << ") must be specified using 2- or 3-digit abbreviation\n"; configurationOK = false; } if (config.dayFilter > 31) { Cerr << "Day (" << GetKey(config.dayFilter) << ") must be in the range 0 - 31\n"; configurationOK = false; } if (config.monthFilter > 12) { Cerr << "Month (" << GetKey(config.monthFilter) << ") must be in the range 0 - 12\n"; configurationOK = false; } if (config.weekFilter > 53) { Cerr << "Week (" << GetKey(config.weekFilter) << ") must be in the range 0 - 53\n"; configurationOK = false; } if (config.recentObservationPeriod < 1 || config.recentObservationPeriod > 30) { Cerr << GetKey(config.recentObservationPeriod) << " must be between 1 and 30\n"; configurationOK = false; } /*if (!config.googleMapsAPIKey.empty() && config.homeLocation.empty()) { Cerr << "Must specify " << GetKey(config.homeLocation) << " when using " << GetKey(config.googleMapsAPIKey) << '\n'; configurationOK = false; }*/ if (config.uniqueObservations != EBDPConfig::UniquenessType::None && !config.countryFilter.empty()) { Cerr << "Cannot specify both " << GetKey(config.countryFilter) << " and " << GetKey(config.uniqueObservations) << '\n'; configurationOK = false; } if (config.showOnlyPhotoNeeds && config.photoFileName.empty()) { Cerr << "Must specify " << GetKey(config.photoFileName) << " when using " << GetKey(config.showOnlyPhotoNeeds) << '\n'; configurationOK = false; } return configurationOK; } bool EBDPConfigFile::RaritiesConfigIsOK() { if (!config.generateRarityScores) return true; bool configurationOK(true); if (config.frequencyFilePath.empty()) { Cerr << "Must specify " << GetKey(config.frequencyFilePath) << " when using " << GetKey(config.generateRarityScores) << '\n'; configurationOK = false; } if (config.eBirdApiKey.empty()) { Cerr << "Must specify " << GetKey(config.eBirdApiKey) << " when using " << GetKey(config.generateRarityScores) << '\n'; configurationOK = false; } if (config.generateTargetCalendar) { Cerr << "Cannot specify both " << GetKey(config.generateRarityScores) << " and " << GetKey(config.generateTargetCalendar) << '\n'; configurationOK = false; } if (config.uniqueObservations != EBDPConfig::UniquenessType::None) { Cerr << "Cannot specify both " << GetKey(config.generateRarityScores) << " and " << GetKey(config.uniqueObservations) << '\n'; configurationOK = false; } return configurationOK; } <commit_msg>Fixed indentation that was generating compiler warning<commit_after>// File: ebdpConfigFile.cpp // Date: 9/27/2017 // Auth: K. Loux // Desc: Configuration file object. // Local headers #include "ebdpConfigFile.h" void EBDPConfigFile::BuildConfigItems() { AddConfigItem(_T("OBS_DATA_FILE"), config.dataFileName); AddConfigItem(_T("OUTPUT_FILE"), config.outputFileName); AddConfigItem(_T("COUNTRY"), config.countryFilter); AddConfigItem(_T("STATE"), config.stateFilter); AddConfigItem(_T("COUNTY"), config.countyFilter); AddConfigItem(_T("LOCATION"), config.locationFilter); AddConfigItem(_T("LIST_TYPE"), config.listType); AddConfigItem(_T("SCORE_RARITIES"), config.generateRarityScores); AddConfigItem(_T("SPECIES_COUNT_ONLY"), config.speciesCountOnly); AddConfigItem(_T("INCLUDE_PARTIAL_IDS"), config.includePartialIDs); AddConfigItem(_T("PHOTO_FILE"), config.photoFileName); AddConfigItem(_T("SHOW_PHOTO_NEEDS"), config.showOnlyPhotoNeeds); AddConfigItem(_T("YEAR"), config.yearFilter); AddConfigItem(_T("MONTH"), config.monthFilter); AddConfigItem(_T("WEEK"), config.weekFilter); AddConfigItem(_T("DAY"), config.dayFilter); AddConfigItem(_T("SORT_FIRST"), config.primarySort); AddConfigItem(_T("SORT_SECOND"), config.secondarySort); AddConfigItem(_T("SHOW_UNIQUE_OBS"), config.uniqueObservations); AddConfigItem(_T("CALENDAR"), config.generateTargetCalendar); AddConfigItem(_T("TARGET_AREA"), config.targetNeedArea); AddConfigItem(_T("TOP_COUNT"), config.topBirdCount); AddConfigItem(_T("FREQUENCY_FILES"), config.frequencyFilePath); AddConfigItem(_T("TARGET_INFO_FILE_NAME"), config.targetInfoFileName); AddConfigItem(_T("RECENT_PERIOD"), config.recentObservationPeriod); AddConfigItem(_T("GOOGLE_MAPS_KEY"), config.googleMapsAPIKey); AddConfigItem(_T("HOME_LOCATION"), config.homeLocation); AddConfigItem(_T("EBIRD_API_KEY"), config.eBirdApiKey); AddConfigItem(_T("FIND_MAX_NEEDS"), config.findMaxNeedsLocations); AddConfigItem(_T("KML_LIBRARY"), config.kmlLibraryPath); AddConfigItem(_T("OAUTH_CLIENT_ID"), config.oAuthClientId); AddConfigItem(_T("OAUTH_CLIENT_SECRET"), config.oAuthClientSecret); AddConfigItem(_T("DATASET"), config.eBirdDatasetPath); } void EBDPConfigFile::AssignDefaults() { config.listType = EBDPConfig::ListType::Life; config.speciesCountOnly = false; config.includePartialIDs = false; config.yearFilter = 0; config.monthFilter = 0; config.weekFilter = 0; config.dayFilter = 0; config.primarySort = EBDPConfig::SortBy::None; config.secondarySort = EBDPConfig::SortBy::None; config.uniqueObservations = EBDPConfig::UniquenessType::None; config.targetNeedArea = EBDPConfig::TargetNeedArea::None; config.generateTargetCalendar = false; config.generateRarityScores = false; config.topBirdCount = 20; config.recentObservationPeriod = 15; config.showOnlyPhotoNeeds = false; config.findMaxNeedsLocations = false; } bool EBDPConfigFile::ConfigIsOK() { bool configurationOK(true); if (!GeneralConfigIsOK()) configurationOK = false; if (!FrequencyHarvestConfigIsOK()) configurationOK = false; if (!TargetCalendarConfigIsOK()) configurationOK = false; if (!FindMaxNeedsConfigIsOK()) configurationOK = false; if (!RaritiesConfigIsOK()) configurationOK = false; return configurationOK; } bool EBDPConfigFile::FrequencyHarvestConfigIsOK() { bool configurationOK(true); if (!config.eBirdDatasetPath.empty() && config.frequencyFilePath.empty()) { Cerr << GetKey(config.eBirdDatasetPath) << " requires " << GetKey(config.frequencyFilePath) << '\n'; configurationOK = false; } return configurationOK; } bool EBDPConfigFile::TargetCalendarConfigIsOK() { if (!config.generateTargetCalendar) return true; bool configurationOK(true); if (config.frequencyFilePath.empty()) { Cerr << "Must specify " << GetKey(config.frequencyFilePath) << " when using " << GetKey(config.generateTargetCalendar) << '\n'; configurationOK = false; } if (config.eBirdApiKey.empty()) { Cerr << "Must specify " << GetKey(config.eBirdApiKey) << " when using " << GetKey(config.generateTargetCalendar) << '\n'; configurationOK = false; } if (config.uniqueObservations != EBDPConfig::UniquenessType::None) { Cerr << "Cannot specify both " << GetKey(config.generateTargetCalendar) << " and " << GetKey(config.uniqueObservations) << '\n'; configurationOK = false; } return configurationOK; } bool EBDPConfigFile::FindMaxNeedsConfigIsOK() { if (!config.findMaxNeedsLocations) return true; bool configurationOK(true); if (config.oAuthClientId.empty() || config.oAuthClientSecret.empty()) { Cerr << GetKey(config.findMaxNeedsLocations) << " requires " << GetKey(config.oAuthClientId) << " and " << GetKey(config.oAuthClientSecret) << '\n'; configurationOK = false; } if (config.kmlLibraryPath.empty()) { Cerr << GetKey(config.findMaxNeedsLocations) << " requires " << GetKey(config.kmlLibraryPath) << '\n'; configurationOK = false; } if (config.eBirdApiKey.empty()) { Cerr << GetKey(config.findMaxNeedsLocations) << " requires " << GetKey(config.eBirdApiKey) << '\n'; configurationOK = false; } if (config.frequencyFilePath.empty()) { Cerr << "Must specify " << GetKey(config.frequencyFilePath) << " when using " << GetKey(config.findMaxNeedsLocations) << '\n'; configurationOK = false; } return configurationOK; } bool EBDPConfigFile::GeneralConfigIsOK() { bool configurationOK(true); if (config.dataFileName.empty()) { Cerr << "Must specify '" << GetKey(config.dataFileName) << "'\n"; configurationOK = false; } if (!config.countryFilter.empty() && config.countryFilter.length() != 2) { Cerr << "Country (" << GetKey(config.countryFilter) << ") must be specified using 2-digit abbreviation\n"; configurationOK = false; } if (!config.stateFilter.empty() && (config.stateFilter.length() < 2 || config.stateFilter.length() > 3)) { Cerr << "State/providence (" << GetKey(config.stateFilter) << ") must be specified using 2- or 3-digit abbreviation\n"; configurationOK = false; } if (config.dayFilter > 31) { Cerr << "Day (" << GetKey(config.dayFilter) << ") must be in the range 0 - 31\n"; configurationOK = false; } if (config.monthFilter > 12) { Cerr << "Month (" << GetKey(config.monthFilter) << ") must be in the range 0 - 12\n"; configurationOK = false; } if (config.weekFilter > 53) { Cerr << "Week (" << GetKey(config.weekFilter) << ") must be in the range 0 - 53\n"; configurationOK = false; } if (config.recentObservationPeriod < 1 || config.recentObservationPeriod > 30) { Cerr << GetKey(config.recentObservationPeriod) << " must be between 1 and 30\n"; configurationOK = false; } /*if (!config.googleMapsAPIKey.empty() && config.homeLocation.empty()) { Cerr << "Must specify " << GetKey(config.homeLocation) << " when using " << GetKey(config.googleMapsAPIKey) << '\n'; configurationOK = false; }*/ if (config.uniqueObservations != EBDPConfig::UniquenessType::None && !config.countryFilter.empty()) { Cerr << "Cannot specify both " << GetKey(config.countryFilter) << " and " << GetKey(config.uniqueObservations) << '\n'; configurationOK = false; } if (config.showOnlyPhotoNeeds && config.photoFileName.empty()) { Cerr << "Must specify " << GetKey(config.photoFileName) << " when using " << GetKey(config.showOnlyPhotoNeeds) << '\n'; configurationOK = false; } return configurationOK; } bool EBDPConfigFile::RaritiesConfigIsOK() { if (!config.generateRarityScores) return true; bool configurationOK(true); if (config.frequencyFilePath.empty()) { Cerr << "Must specify " << GetKey(config.frequencyFilePath) << " when using " << GetKey(config.generateRarityScores) << '\n'; configurationOK = false; } if (config.eBirdApiKey.empty()) { Cerr << "Must specify " << GetKey(config.eBirdApiKey) << " when using " << GetKey(config.generateRarityScores) << '\n'; configurationOK = false; } if (config.generateTargetCalendar) { Cerr << "Cannot specify both " << GetKey(config.generateRarityScores) << " and " << GetKey(config.generateTargetCalendar) << '\n'; configurationOK = false; } if (config.uniqueObservations != EBDPConfig::UniquenessType::None) { Cerr << "Cannot specify both " << GetKey(config.generateRarityScores) << " and " << GetKey(config.uniqueObservations) << '\n'; configurationOK = false; } return configurationOK; } <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file multi_sensor_sigma_point_update_policy.hpp * \date August 2015 * \author Jan Issac ([email protected]) */ #ifndef FL__FILTER__GAUSSIAN__MULTI_SENSOR_SIGMA_POINT_UPDATE_POLICY_HPP #define FL__FILTER__GAUSSIAN__MULTI_SENSOR_SIGMA_POINT_UPDATE_POLICY_HPP #include <Eigen/Dense> #include <fl/util/meta.hpp> #include <fl/util/types.hpp> #include <fl/util/traits.hpp> #include <fl/util/descriptor.hpp> #include <fl/model/observation/joint_observation_model_iid.hpp> #include <fl/filter/gaussian/transform/point_set.hpp> #include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp> namespace fl { // Forward declarations template <typename...> class MultiSensorSigmaPointUpdatePolicy; /** * \internal */ template < typename SigmaPointQuadrature, typename NonJoinObservationModel > class MultiSensorSigmaPointUpdatePolicy< SigmaPointQuadrature, NonJoinObservationModel> { static_assert( std::is_base_of< internal::JointObservationModelIidType, NonJoinObservationModel >::value, "\n\n\n" "====================================================================\n" "= Static Assert: You are using the wrong observation model type =\n" "====================================================================\n" " Observation model type must be a JointObservationModel<...>. \n" " For single observation model, use the regular Gaussian filter \n" " or the regular SigmaPointUpdatePolicy if you are specifying \n" " the update policy explicitly fo the GaussianFilter. \n" "====================================================================\n" ); }; template < typename SigmaPointQuadrature, typename MultipleOfLocalObsrvModel > class MultiSensorSigmaPointUpdatePolicy< SigmaPointQuadrature, JointObservationModel<MultipleOfLocalObsrvModel>> : public MultiSensorSigmaPointUpdatePolicy< SigmaPointQuadrature, NonAdditive<JointObservationModel<MultipleOfLocalObsrvModel>>> { }; template < typename SigmaPointQuadrature, typename MultipleOfLocalObsrvModel > class MultiSensorSigmaPointUpdatePolicy< SigmaPointQuadrature, NonAdditive<JointObservationModel<MultipleOfLocalObsrvModel>>> : public Descriptor { public: typedef JointObservationModel<MultipleOfLocalObsrvModel> JointModel; typedef typename MultipleOfLocalObsrvModel::Type LocalModel; typedef typename JointModel::State State; typedef typename JointModel::Obsrv Obsrv; typedef typename JointModel::Noise Noise; enum : signed int { NumberOfPoints = SigmaPointQuadrature::number_of_points( JoinSizes< SizeOf<State>::Value, SizeOf<Noise>::Value >::Size) }; typedef PointSet<State, NumberOfPoints> StatePointSet; typedef PointSet<Noise, NumberOfPoints> NoisePointSet; typedef PointSet<Obsrv, NumberOfPoints> ObsrvPointSet; template < typename Belief > void operator()(const JointModel& obsrv_function, const SigmaPointQuadrature& quadrature, const Belief& prior_belief, const Obsrv& obsrv, Belief& posterior_belief) { // static_assert() is non-additive INIT_PROFILING noise_distr_.dimension(obsrv_function.noise_dimension()); auto&& h = [&](const State& x, const Noise& w) { return obsrv_function.observation(x, w); }; quadrature.propergate_gaussian(h, prior_belief, noise_distr_, X, Y, Z); MEASURE("Integrate"); auto&& mu_y = Z.center(); auto&& mu_x = X.center(); auto&& Z_c = Z.points(); auto&& X_c = X.points(); auto&& W = X.covariance_weights_vector(); auto cov_xx = (X_c * W.asDiagonal() * X_c.transpose()).eval(); auto cov_xx_inv = (cov_xx.inverse()).eval(); auto innovation = (obsrv - mu_y).eval(); auto C = cov_xx_inv; auto D = mu_x; D.setZero(); const int dim_Z_i = obsrv_function.local_obsrv_model().obsrv_dimension(); const int obsrv_count = obsrv_function.count_local_models(); MEASURE("Preparation"); // for (int i = 0; i < obsrv_count; ++i) // { // auto Z_i = Z_c.middleRows(i * dim_Z_i, dim_Z_i).eval(); // auto cov_xy_i = (X_c * W.asDiagonal() * Z_i.transpose()).eval(); // auto cov_yy_i = (Z_i * W.asDiagonal() * Z_i.transpose()).eval(); // auto innov_i = innovation.middleRows(i * dim_Z_i, dim_Z_i).eval(); // auto A_i = (cov_xy_i.transpose() * cov_xx_inv).eval(); // auto cov_yy_i_inv_given_x = // (cov_yy_i - cov_xy_i.transpose() * cov_xx_inv * cov_xy_i) // .inverse(); // auto T = (A_i.transpose() * cov_yy_i_inv_given_x).eval(); // C += T * A_i; // D += T * innov_i; // } auto Z_0 = Z_c.middleRows(0 * dim_Z_i, dim_Z_i).eval(); auto cov_xy_0 = (X_c * W.asDiagonal() * Z_0.transpose()).eval(); auto cov_yy_0 = (Z_0 * W.asDiagonal() * Z_0.transpose()).eval(); auto innov_0 = innovation.middleRows(0 * dim_Z_i, dim_Z_i).eval(); auto A_0 = (cov_xy_0.transpose() * cov_xx_inv).eval(); auto cov_yy_i_inv_given_x = (cov_yy_0 - cov_xy_0.transpose() * cov_xx_inv * cov_xy_0) .inverse(); auto T0 = (A_0.transpose() * cov_yy_i_inv_given_x).eval(); MEASURE("Debugging temp preparation"); for (int i = 0; i < obsrv_count; ++i) { auto Z_i = Z_c.middleRows(i * dim_Z_i, dim_Z_i).eval(); } MEASURE("auto Z_i = ..."); for (int i = 0; i < obsrv_count; ++i) { auto cov_xy_i = (X_c * W.asDiagonal() * Z_0.transpose()).eval(); } MEASURE("auto cov_xy_i = ..."); for (int i = 0; i < obsrv_count; ++i) { auto cov_yy_i = (Z_0 * W.asDiagonal() * Z_0.transpose()).eval(); } MEASURE("auto cov_yy_i = ..."); for (int i = 0; i < obsrv_count; ++i){ auto innov_i = innovation.middleRows(i * dim_Z_i, dim_Z_i).eval(); } MEASURE("auto innov_i = ..."); for (int i = 0; i < obsrv_count; ++i){ auto A_i = (cov_xy_0.transpose() * cov_xx_inv).eval(); } MEASURE("auto A_i = ..."); for (int i = 0; i < obsrv_count; ++i){ auto cov_yy_i_inv_given_x = (cov_yy_0 - cov_xy_0.transpose() * cov_xx_inv * cov_xy_0) .inverse(); } MEASURE("auto cov_yy_i_inv_given_x = ..."); for (int i = 0; i < obsrv_count; ++i){ auto T = (A_0.transpose() * cov_yy_i_inv_given_x).eval(); } MEASURE("auto T = ..."); for (int i = 0; i < obsrv_count; ++i){ C += T0 * A_0; } MEASURE("auto C = ..."); for (int i = 0; i < obsrv_count; ++i){ D += T0 * innov_0; } MEASURE("auto D = ..."); posterior_belief.covariance(C.inverse()); MEASURE("posterior_belief.covariance(C.inverse())"); posterior_belief.mean(mu_x + posterior_belief.covariance() * D); MEASURE("posterior_belief.mean(mu_x + posterior_belief.covariance() * D)"); std::cout << "==================================================================" << std::endl; } virtual std::string name() const { return "MultiSensorSigmaPointUpdatePolicy<" + this->list_arguments( "SigmaPointQuadrature", "NonAdditive<ObservationFunction>") + ">"; } virtual std::string description() const { return "Multi-Sensor Sigma Point based filter update policy " "for joint observation model of multiple local observation " "models with non-additive noise."; } protected: StatePointSet X; NoisePointSet Y; ObsrvPointSet Z; Gaussian<Noise> noise_distr_; }; } #endif <commit_msg>Updated MultiSensor update policy. Minor factoriztion and :lipstick:<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file multi_sensor_sigma_point_update_policy.hpp * \date August 2015 * \author Jan Issac ([email protected]) */ #ifndef FL__FILTER__GAUSSIAN__MULTI_SENSOR_SIGMA_POINT_UPDATE_POLICY_HPP #define FL__FILTER__GAUSSIAN__MULTI_SENSOR_SIGMA_POINT_UPDATE_POLICY_HPP #include <Eigen/Dense> #include <fl/util/meta.hpp> #include <fl/util/types.hpp> #include <fl/util/traits.hpp> #include <fl/util/descriptor.hpp> #include <fl/model/observation/joint_observation_model_iid.hpp> #include <fl/filter/gaussian/transform/point_set.hpp> #include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp> namespace fl { // Forward declarations template <typename...> class MultiSensorSigmaPointUpdatePolicy; /** * \internal */ template < typename SigmaPointQuadrature, typename NonJoinObservationModel > class MultiSensorSigmaPointUpdatePolicy< SigmaPointQuadrature, NonJoinObservationModel> { static_assert( std::is_base_of< internal::JointObservationModelIidType, NonJoinObservationModel >::value, "\n\n\n" "====================================================================\n" "= Static Assert: You are using the wrong observation model type =\n" "====================================================================\n" " Observation model type must be a JointObservationModel<...>. \n" " For single observation model, use the regular Gaussian filter \n" " or the regular SigmaPointUpdatePolicy if you are specifying \n" " the update policy explicitly fo the GaussianFilter. \n" "====================================================================\n" ); }; template < typename SigmaPointQuadrature, typename MultipleOfLocalObsrvModel > class MultiSensorSigmaPointUpdatePolicy< SigmaPointQuadrature, JointObservationModel<MultipleOfLocalObsrvModel>> : public MultiSensorSigmaPointUpdatePolicy< SigmaPointQuadrature, NonAdditive<JointObservationModel<MultipleOfLocalObsrvModel>>> { }; template < typename SigmaPointQuadrature, typename MultipleOfLocalObsrvModel > class MultiSensorSigmaPointUpdatePolicy< SigmaPointQuadrature, NonAdditive<JointObservationModel<MultipleOfLocalObsrvModel>>> : public Descriptor { public: typedef JointObservationModel<MultipleOfLocalObsrvModel> JointModel; typedef typename MultipleOfLocalObsrvModel::Type LocalModel; typedef typename JointModel::State State; typedef typename JointModel::Obsrv Obsrv; typedef typename JointModel::Noise Noise; typedef typename Traits<JointModel>::LocalObsrv LocalObsrv; typedef typename Traits<JointModel>::LocalNoise LocalObsrvNoise; enum : signed int { NumberOfPoints = SigmaPointQuadrature::number_of_points( JoinSizes< SizeOf<State>::Value, SizeOf<LocalObsrvNoise>::Value >::Size) }; typedef PointSet<State, NumberOfPoints> StatePointSet; typedef PointSet<LocalObsrv, NumberOfPoints> LocalObsrvPointSet; typedef PointSet<LocalObsrvNoise, NumberOfPoints> LocalNoisePointSet; template < typename Belief > void operator()(JointModel& obsrv_function, const SigmaPointQuadrature& quadrature, const Belief& prior_belief, const Obsrv& y, Belief& posterior_belief) { quadrature.transform_to_points(prior_belief, noise_distr_, p_X, p_Q); auto& model = obsrv_function.local_obsrv_model(); auto&& h = [&](const State& x, const LocalObsrvNoise& w) { return model.observation(x, w); }; auto&& mu_x = p_X.center(); auto&& X = p_X.points(); auto c_xx = cov(X, X); auto c_xx_inv = c_xx.inverse().eval(); auto C = c_xx_inv; auto D = State(); D.setZero(mu_x.size()); const int sensors = obsrv_function.count_local_models(); for (int i = 0; i < sensors; ++i) { model.id(i); quadrature.propergate_points(h, p_X, p_Q, p_Y); auto mu_y = p_Y.center(); auto Y = p_Y.points(); auto c_yy = cov(Y, Y); auto c_xy = cov(X, Y); auto c_yx = c_xy.transpose(); auto A_i = (c_yx * c_xx_inv).eval(); auto c_yy_given_x_inv = (c_yy - c_yx * c_xx_inv * c_xy).inverse(); auto T = (A_i.transpose() * c_yy_given_x_inv).eval(); C += T * A_i; D += T * (y.middleRows(i * mu_y.size(), mu_y.size()) - mu_y); } posterior_belief.covariance(C.inverse()); posterior_belief.mean(mu_x + posterior_belief.covariance() * D); } virtual std::string name() const { return "MultiSensorSigmaPointUpdatePolicy<" + this->list_arguments( "SigmaPointQuadrature", "NonAdditive<ObservationFunction>") + ">"; } virtual std::string description() const { return "Multi-Sensor Sigma Point based filter update policy " "for joint observation model of multiple local observation " "models with non-additive noise."; } private: template <typename A, typename B> auto cov(const A& a, const B& b) -> decltype((a * b.transpose()).eval()) { auto&& W = p_X.covariance_weights_vector().asDiagonal(); auto c = (a * W * b.transpose()).eval(); return c; } protected: StatePointSet p_X; LocalNoisePointSet p_Q; LocalObsrvPointSet p_Y; Gaussian<LocalObsrvNoise> noise_distr_; }; } #endif <|endoftext|>
<commit_before>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // BloopIRInterface.h // // Purpose: // A derivation of the IR interface for the ISA (disassembler) class // of bloop. // // Note: many stubs still exist. // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** #ifndef BloopIRInterface_h #define BloopIRInterface_h //************************* System Include Files **************************** #include <list> #include <set> //*************************** User Include Files **************************** // OpenAnalysis headers. // Use OA_IRHANDLETYPE_SZ64: size of bfd_vma/Addr #include <OpenAnalysis/Utils/DGraph.h> #include <OpenAnalysis/Interface/IRInterface.h> #include <lib/ISA/ISA.h> #include <lib/binutils/Instruction.h> #include <lib/binutils/Procedure.h> #include <lib/support/String.h> #include <lib/support/Assertion.h> //*************************** Forward Declarations *************************** class BloopIRStmtIterator: public IRStmtIterator { public: BloopIRStmtIterator (Procedure &_p) : pii(_p) { }; ~BloopIRStmtIterator () {}; StmtHandle Current () { return (StmtHandle)(pii.Current()); }; bool IsValid () { return pii.IsValid(); }; void operator++ () { ++pii; }; private: ProcedureInstructionIterator pii; }; class BloopIRUseDefIterator: public IRUseDefIterator { public: BloopIRUseDefIterator (Instruction *insn, int uses_or_defs); BloopIRUseDefIterator () { BriefAssertion (0); } ~BloopIRUseDefIterator () {}; LeafHandle Current () { return 0; }; bool IsValid () { return false; }; void operator++ () { }; private: }; //*************************** Forward Declarations *************************** class BloopIRInterface : public IRInterface { public: BloopIRInterface (Procedure *_p); BloopIRInterface () { BriefAssertion(0); } ~BloopIRInterface () {} //------------------------------ // General - all statement types //------------------------------ IRStmtType GetStmtType (StmtHandle); StmtLabel GetLabel (StmtHandle); //------------------------------ // For procedures, compound statements. //------------------------------ IRStmtIterator *ProcBody(ProcHandle h) { BriefAssertion(false); return NULL; } IRStmtIterator *GetFirstInCompound (StmtHandle h); //------------------------------ // Loops //------------------------------ IRStmtIterator *LoopBody(StmtHandle h); StmtHandle LoopHeader (StmtHandle h); bool LoopIterationsDefinedAtEntry (StmtHandle h); ExprHandle GetLoopCondition (StmtHandle h); StmtHandle GetLoopIncrement (StmtHandle h); //------------------------------ // invariant: a two-way conditional or a multi-way conditional MUST provide // provided either a target, or a target label //------------------------------ //------------------------------ // Structured two-way conditionals //------------------------------ IRStmtIterator *TrueBody (StmtHandle h); IRStmtIterator *ElseBody (StmtHandle h); //------------------------------ // Structured multiway conditionals //------------------------------ int NumMultiCases (StmtHandle h); // condition for multi body ExprHandle GetSMultiCondition (StmtHandle h, int bodyIndex); // multi-way beginning expression ExprHandle GetMultiExpr (StmtHandle h); IRStmtIterator *MultiBody (StmtHandle h, int bodyIndex); bool IsBreakImplied (StmtHandle multicond); IRStmtIterator *GetMultiCatchall (StmtHandle h); //------------------------------ // Unstructured two-way conditionals: //------------------------------ // two-way branch, loop continue StmtLabel GetTargetLabel (StmtHandle h, int n); ExprHandle GetCondition (StmtHandle h); //------------------------------ // Unstructured multi-way conditionals //------------------------------ int NumUMultiTargets (StmtHandle h); StmtLabel GetUMultiTargetLabel (StmtHandle h, int targetIndex); StmtLabel GetUMultiCatchallLabel (StmtHandle h); ExprHandle GetUMultiCondition (StmtHandle h, int targetIndex); //------------------------------ // Special //------------------------------ bool ParallelWithSuccessor(StmtHandle h) { return false; } // Given an unstructured branch/jump statement, return the number // of delay slots. int NumberOfDelaySlots(StmtHandle h); //------------------------------ // Obtain uses and defs //------------------------------ IRProcCallIterator *GetProcCalls(StmtHandle h) { BriefAssertion(false); return NULL; } IRUseDefIterator *GetUses (StmtHandle h); IRUseDefIterator *GetDefs (StmtHandle h); //------------------------------ // Symbol Handles //------------------------------ SymHandle GetProcSymHandle(ProcHandle h) { return (SymHandle)0; } SymHandle GetSymHandle (LeafHandle vh) { return (SymHandle)0; } const char *GetSymNameFromSymHandle (SymHandle sh) { return "<no-sym>"; } //------------------------------ // Debugging //------------------------------ void PrintLeaf (LeafHandle vh, ostream & os) { }; void Dump (StmtHandle stmt, ostream& os); private: Procedure *proc; std::set<Addr> branchTargetSet; }; #endif // BloopIRInterface_h <commit_msg>Coordinate with updates to IRInterface<commit_after>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // BloopIRInterface.h // // Purpose: // A derivation of the IR interface for the ISA (disassembler) class // of bloop. // // Note: many stubs still exist. // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** #ifndef BloopIRInterface_h #define BloopIRInterface_h //************************* System Include Files **************************** #include <list> #include <set> //*************************** User Include Files **************************** // OpenAnalysis headers. // Use OA_IRHANDLETYPE_SZ64: size of bfd_vma/Addr #include <OpenAnalysis/Utils/DGraph.h> #include <OpenAnalysis/Interface/IRInterface.h> #include <lib/ISA/ISA.h> #include <lib/binutils/Instruction.h> #include <lib/binutils/Procedure.h> #include <lib/support/String.h> #include <lib/support/Assertion.h> //*************************** Forward Declarations *************************** class BloopIRStmtIterator: public IRStmtIterator { public: BloopIRStmtIterator (Procedure &_p) : pii(_p) { } ~BloopIRStmtIterator () { } StmtHandle Current () { return (StmtHandle)(pii.Current()); } bool IsValid () { return pii.IsValid(); } void operator++ () { ++pii; } void Reset() { pii.Reset(); } private: ProcedureInstructionIterator pii; }; class BloopIRUseDefIterator: public IRUseDefIterator { public: BloopIRUseDefIterator (Instruction *insn, int uses_or_defs); BloopIRUseDefIterator () { BriefAssertion (0); } ~BloopIRUseDefIterator () { } LeafHandle Current () { return 0; } bool IsValid () { return false; } void operator++ () { } void Reset() { } private: }; //*************************** Forward Declarations *************************** class BloopIRInterface : public IRInterface { public: BloopIRInterface (Procedure *_p); BloopIRInterface () { BriefAssertion(0); } ~BloopIRInterface () { } //-------------------------------------------------------- // Procedures and call sites //-------------------------------------------------------- IRProcType GetProcType(ProcHandle h) { BriefAssertion(0); return ProcType_ILLEGAL; } IRStmtIterator *ProcBody(ProcHandle h) { BriefAssertion(0); return NULL; } IRCallsiteIterator *GetCallsites(StmtHandle h) { BriefAssertion(0); return NULL; } IRCallsiteParamIterator *GetCallsiteParams(ExprHandle h) { BriefAssertion(0); return NULL; } bool IsParamProcRef(ExprHandle h) { BriefAssertion(0); return false; } virtual bool IsCallThruProcParam(ExprHandle h) { BriefAssertion(0); return false; } //-------------------------------------------------------- // Statements: General //-------------------------------------------------------- IRStmtType GetStmtType (StmtHandle); StmtLabel GetLabel (StmtHandle); IRStmtIterator *GetFirstInCompound (StmtHandle h); //-------------------------------------------------------- // Loops //-------------------------------------------------------- IRStmtIterator *LoopBody(StmtHandle h); StmtHandle LoopHeader (StmtHandle h); bool LoopIterationsDefinedAtEntry (StmtHandle h); ExprHandle GetLoopCondition (StmtHandle h); StmtHandle GetLoopIncrement (StmtHandle h); //-------------------------------------------------------- // invariant: a two-way conditional or a multi-way conditional MUST provide // provided either a target, or a target label //-------------------------------------------------------- //-------------------------------------------------------- // Structured two-way conditionals //-------------------------------------------------------- IRStmtIterator *TrueBody (StmtHandle h); IRStmtIterator *ElseBody (StmtHandle h); //-------------------------------------------------------- // Structured multiway conditionals //-------------------------------------------------------- int NumMultiCases (StmtHandle h); // condition for multi body ExprHandle GetSMultiCondition (StmtHandle h, int bodyIndex); // multi-way beginning expression ExprHandle GetMultiExpr (StmtHandle h); IRStmtIterator *MultiBody (StmtHandle h, int bodyIndex); bool IsBreakImplied (StmtHandle multicond); IRStmtIterator *GetMultiCatchall (StmtHandle h); //-------------------------------------------------------- // Unstructured two-way conditionals: //-------------------------------------------------------- // two-way branch, loop continue StmtLabel GetTargetLabel (StmtHandle h, int n); ExprHandle GetCondition (StmtHandle h); //-------------------------------------------------------- // Unstructured multi-way conditionals //-------------------------------------------------------- int NumUMultiTargets (StmtHandle h); StmtLabel GetUMultiTargetLabel (StmtHandle h, int targetIndex); StmtLabel GetUMultiCatchallLabel (StmtHandle h); ExprHandle GetUMultiCondition (StmtHandle h, int targetIndex); //-------------------------------------------------------- // Special //-------------------------------------------------------- bool ParallelWithSuccessor(StmtHandle h) { return false; } // Given an unstructured branch/jump statement, return the number // of delay slots. int NumberOfDelaySlots(StmtHandle h); //-------------------------------------------------------- // Obtain uses and defs //-------------------------------------------------------- IRUseDefIterator *GetUses (StmtHandle h); IRUseDefIterator *GetDefs (StmtHandle h); //-------------------------------------------------------- // Symbol Handles //-------------------------------------------------------- SymHandle GetProcSymHandle(ProcHandle h) { BriefAssertion(0); return (SymHandle)0; } SymHandle GetSymHandle (LeafHandle vh) { return (SymHandle)0; } const char *GetSymNameFromSymHandle (SymHandle sh) { return "<no-sym>"; } //-------------------------------------------------------- // Debugging //-------------------------------------------------------- void PrintLeaf (LeafHandle vh, ostream & os) { }; void Dump (StmtHandle stmt, ostream& os); private: Procedure *proc; std::set<Addr> branchTargetSet; }; #endif // BloopIRInterface_h <|endoftext|>
<commit_before>//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #else // g++ nem fordit a stanard include-ok nelkul :-/ #include <string.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: // Neptun: //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y, z; Vector(float x0, float y0, float z0) { x = x0; y = y0; z = z0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y, z + v.z); } Vector operator*(float f) { return Vector(x * f, y * f, z * f); } }; class Matrix { public: float m[4][4]; void Clear() { memset(&m[0][0], 0, sizeof(m)); } void LoadIdentify() { Clear(); m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1; } Vector operator*(const Vector& v) { float Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3]; float Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3]; float Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3]; float h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3]; return Vector(Xh/h, Yh/h, Zh/h); } }; enum { NOOP = 0, SCALE, ROTATE, SHIFT }; int trans_state = NOOP; // csak mert math.ht nemszabad ;-/ # define M_PI 3.14159265358979323846 const Vector* points[2][7]; Matrix* transs[4]; void onInitialization( ) { points[0][0] = new Vector(160, 20, 0); points[0][1] = new Vector(250, 80, 0); points[0][2] = new Vector(270, 20, 0); points[0][3] = new Vector(360, 80, 0); points[0][4] = new Vector(390, 20, 0); points[0][5] = new Vector(470, 80, 0); points[0][6] = new Vector(490, 20, 0); points[1][0] = new Vector(160, 120, 0); points[1][1] = new Vector(250, 180, 0); points[1][2] = new Vector(270, 120, 0); points[1][3] = new Vector(360, 180, 0); points[1][4] = new Vector(390, 120, 0); points[1][5] = new Vector(470, 180, 0); points[1][6] = new Vector(490, 120, 0); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 */ transs[NOOP] = new Matrix(); transs[NOOP]->LoadIdentify(); /* * 0.5 0 0 0 * 0 0.5 0 0 * 0 0 0.5 0 * 0 0 0 1 */ transs[SCALE] = new Matrix(); transs[SCALE]->LoadIdentify(); transs[SCALE]->m[0][0] = 0.5; transs[SCALE]->m[1][1] = 0.5; transs[SCALE]->m[2][2] = 0.5; /* * cos sin 0 0 * -sin cos 0 0 * 0 0 1 0 * 0 0 0 1 */ float angle = M_PI/4; transs[ROTATE] = new Matrix(); transs[ROTATE]->LoadIdentify(); transs[ROTATE]->m[0][0] = cosf(angle); transs[ROTATE]->m[0][1] = -sinf(angle); transs[ROTATE]->m[1][0] = sinf(angle); transs[ROTATE]->m[1][1] = cosf(angle); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * px py pz 1 */ transs[SHIFT] = new Matrix(); transs[SHIFT]->LoadIdentify(); transs[SHIFT]->m[1][3] = 100; gluOrtho2D(0., 500., 0., 500.); } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); for (int i = 0; i < ARRAY_SIZE(points); i++) { glBegin(GL_LINE_STRIP); for (int j = 0; j < ARRAY_SIZE(points[i]); j++) { Vector v = *transs[trans_state] * *points[i][j]; glVertex2d(v.x, v.y); } glEnd(); } // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle( ) { } void onKeyboard(unsigned char key, int x, int y) { if (key == 's') trans_state = (trans_state + 1) % 4; onDisplay(); } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; } <commit_msg>nev neptunkod<commit_after>//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #else // g++ nem fordit a stanard include-ok nelkul :-/ #include <string.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: Vajna Miklos // Neptun: AYU9RZ //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y, z; Vector(float x0, float y0, float z0) { x = x0; y = y0; z = z0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y, z + v.z); } Vector operator*(float f) { return Vector(x * f, y * f, z * f); } }; class Matrix { public: float m[4][4]; void Clear() { memset(&m[0][0], 0, sizeof(m)); } void LoadIdentify() { Clear(); m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1; } Vector operator*(const Vector& v) { float Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3]; float Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3]; float Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3]; float h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3]; return Vector(Xh/h, Yh/h, Zh/h); } }; enum { NOOP = 0, SCALE, ROTATE, SHIFT }; int trans_state = NOOP; // csak mert math.ht nemszabad ;-/ # define M_PI 3.14159265358979323846 const Vector* points[2][7]; Matrix* transs[4]; void onInitialization( ) { points[0][0] = new Vector(160, 20, 0); points[0][1] = new Vector(250, 80, 0); points[0][2] = new Vector(270, 20, 0); points[0][3] = new Vector(360, 80, 0); points[0][4] = new Vector(390, 20, 0); points[0][5] = new Vector(470, 80, 0); points[0][6] = new Vector(490, 20, 0); points[1][0] = new Vector(160, 120, 0); points[1][1] = new Vector(250, 180, 0); points[1][2] = new Vector(270, 120, 0); points[1][3] = new Vector(360, 180, 0); points[1][4] = new Vector(390, 120, 0); points[1][5] = new Vector(470, 180, 0); points[1][6] = new Vector(490, 120, 0); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 */ transs[NOOP] = new Matrix(); transs[NOOP]->LoadIdentify(); /* * 0.5 0 0 0 * 0 0.5 0 0 * 0 0 0.5 0 * 0 0 0 1 */ transs[SCALE] = new Matrix(); transs[SCALE]->LoadIdentify(); transs[SCALE]->m[0][0] = 0.5; transs[SCALE]->m[1][1] = 0.5; transs[SCALE]->m[2][2] = 0.5; /* * cos sin 0 0 * -sin cos 0 0 * 0 0 1 0 * 0 0 0 1 */ float angle = M_PI/4; transs[ROTATE] = new Matrix(); transs[ROTATE]->LoadIdentify(); transs[ROTATE]->m[0][0] = cosf(angle); transs[ROTATE]->m[0][1] = -sinf(angle); transs[ROTATE]->m[1][0] = sinf(angle); transs[ROTATE]->m[1][1] = cosf(angle); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * px py pz 1 */ transs[SHIFT] = new Matrix(); transs[SHIFT]->LoadIdentify(); transs[SHIFT]->m[1][3] = 100; gluOrtho2D(0., 500., 0., 500.); } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); for (int i = 0; i < ARRAY_SIZE(points); i++) { glBegin(GL_LINE_STRIP); for (int j = 0; j < ARRAY_SIZE(points[i]); j++) { Vector v = *transs[trans_state] * *points[i][j]; glVertex2d(v.x, v.y); } glEnd(); } // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle( ) { } void onKeyboard(unsigned char key, int x, int y) { if (key == 's') trans_state = (trans_state + 1) % 4; onDisplay(); } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * expand/include.cpp * - include!/include_str!/include_bytes! support */ #include <synext_macro.hpp> #include <synext.hpp> // for Expand_BareExpr #include <parse/common.hpp> #include <parse/parseerror.hpp> // for GET_CHECK_TOK #include <parse/ttstream.hpp> #include <parse/lex.hpp> // Lexer (new files) #include <ast/expr.hpp> #include <ast/crate.hpp> namespace { ::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod) { auto n = Parse_ExprVal(lex); ASSERT_BUG(sp, n, "No expression returned"); Expand_BareExpr(crate, mod, n); auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n); if( !string_np ) { ERROR(sp, E0000, "include! requires a string literal - got " << *n); } return mv$( string_np->m_value ); } ::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path) { DEBUG(base_path << ", " << path); // Absolute if( path[0] == '/' || path[0] == '\\' ) { return path; } // Windows absolute else if( isalnum(path[0]) && path[1] == ':' && (path[2] == '/' || path[2] == '\\') ) { return path; } else if( base_path.size() == 0 ) { return path; } else if( base_path.back() == '/' || base_path.back() == '\\' ) { return base_path + path; } else { auto slash = ::std::min( base_path.find_last_of('/'), base_path.find_last_of('\\') ); if( slash == ::std::string::npos ) { return path; } else { slash += 1; ::std::string rv; rv.reserve( slash + path.size() ); rv.append( base_path.begin(), base_path.begin() + slash ); rv.append( path.begin(), path.end() ); return rv; } } } }; class CIncludeExpander: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override { Token tok; auto lex = TTStream(sp, ParseState(crate.m_edition), tt); auto path = get_string(sp, lex, crate, mod); GET_CHECK_TOK(tok, lex, TOK_EOF); ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path)); crate.m_extra_files.push_back(file_path); try { ParseState ps(crate.m_edition); ps.module = &mod; return box$( Lexer(file_path, ps) ); } catch(::std::runtime_error& e) { ERROR(sp, E0000, e.what()); } } }; class CIncludeBytesExpander: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override { Token tok; auto lex = TTStream(sp, ParseState(crate.m_edition), tt); auto path = get_string(sp, lex, crate, mod); GET_CHECK_TOK(tok, lex, TOK_EOF); ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path)); crate.m_extra_files.push_back(file_path); ::std::ifstream is(file_path); if( !is.good() ) { ERROR(sp, E0000, "Cannot open file " << file_path << " for include_bytes!"); } ::std::stringstream ss; ss << is.rdbuf(); ::std::vector<TokenTree> toks; toks.push_back(Token(TOK_BYTESTRING, mv$(ss.str()))); return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) ); } }; class CIncludeStrExpander: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override { Token tok; auto lex = TTStream(sp, ParseState(crate.m_edition), tt); auto path = get_string(sp, lex, crate, mod); GET_CHECK_TOK(tok, lex, TOK_EOF); ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path)); crate.m_extra_files.push_back(file_path); ::std::ifstream is(file_path); if( !is.good() ) { ERROR(sp, E0000, "Cannot open file " << file_path << " for include_str!"); } ::std::stringstream ss; ss << is.rdbuf(); ::std::vector<TokenTree> toks; toks.push_back(Token(TOK_STRING, mv$(ss.str()))); return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) ); } }; // TODO: include_str! and include_bytes! STATIC_MACRO("include", CIncludeExpander); STATIC_MACRO("include_bytes", CIncludeBytesExpander); STATIC_MACRO("include_str", CIncludeStrExpander); <commit_msg>Expand include - Relative path logic<commit_after>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * expand/include.cpp * - include!/include_str!/include_bytes! support */ #include <synext_macro.hpp> #include <synext.hpp> // for Expand_BareExpr #include <parse/common.hpp> #include <parse/parseerror.hpp> // for GET_CHECK_TOK #include <parse/ttstream.hpp> #include <parse/lex.hpp> // Lexer (new files) #include <ast/expr.hpp> #include <ast/crate.hpp> namespace { ::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod) { auto n = Parse_ExprVal(lex); ASSERT_BUG(sp, n, "No expression returned"); Expand_BareExpr(crate, mod, n); auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n); if( !string_np ) { ERROR(sp, E0000, "include! requires a string literal - got " << *n); } return mv$( string_np->m_value ); } ::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path) { DEBUG(base_path << ", " << path); // Absolute if( path[0] == '/' || path[0] == '\\' ) { return path; } // Windows absolute else if( isalnum(path[0]) && path[1] == ':' && (path[2] == '/' || path[2] == '\\') ) { return path; } else if( base_path.size() == 0 ) { return path; } else if( base_path.back() == '/' || base_path.back() == '\\' ) { return base_path + path; } else { auto slash_fwd = base_path.find_last_of('/'); auto slash_back = base_path.find_last_of('\\'); auto slash = slash_fwd == std::string::npos ? slash_back : slash_back == std::string::npos ? slash_fwd : std::max(slash_fwd, slash_back) ; if( slash == ::std::string::npos ) { return path; } else { DEBUG("> slash = " << slash); slash += 1; ::std::string rv; rv.reserve( slash + path.size() ); rv.append( base_path.begin(), base_path.begin() + slash ); rv.append( path.begin(), path.end() ); return rv; } } } }; class CIncludeExpander: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override { Token tok; auto lex = TTStream(sp, ParseState(crate.m_edition), tt); auto path = get_string(sp, lex, crate, mod); GET_CHECK_TOK(tok, lex, TOK_EOF); ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path)); crate.m_extra_files.push_back(file_path); try { ParseState ps(crate.m_edition); ps.module = &mod; return box$( Lexer(file_path, ps) ); } catch(::std::runtime_error& e) { ERROR(sp, E0000, e.what()); } } }; class CIncludeBytesExpander: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override { Token tok; auto lex = TTStream(sp, ParseState(crate.m_edition), tt); auto path = get_string(sp, lex, crate, mod); GET_CHECK_TOK(tok, lex, TOK_EOF); ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path)); crate.m_extra_files.push_back(file_path); ::std::ifstream is(file_path); if( !is.good() ) { ERROR(sp, E0000, "Cannot open file " << file_path << " for include_bytes!"); } ::std::stringstream ss; ss << is.rdbuf(); ::std::vector<TokenTree> toks; toks.push_back(Token(TOK_BYTESTRING, mv$(ss.str()))); return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) ); } }; class CIncludeStrExpander: public ExpandProcMacro { ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override { Token tok; auto lex = TTStream(sp, ParseState(crate.m_edition), tt); auto path = get_string(sp, lex, crate, mod); GET_CHECK_TOK(tok, lex, TOK_EOF); ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path)); crate.m_extra_files.push_back(file_path); ::std::ifstream is(file_path); if( !is.good() ) { ERROR(sp, E0000, "Cannot open file " << file_path << " for include_str!"); } ::std::stringstream ss; ss << is.rdbuf(); ::std::vector<TokenTree> toks; toks.push_back(Token(TOK_STRING, mv$(ss.str()))); return box$( TTStreamO(sp, ParseState(crate.m_edition), TokenTree(Ident::Hygiene::new_scope(), mv$(toks))) ); } }; // TODO: include_str! and include_bytes! STATIC_MACRO("include", CIncludeExpander); STATIC_MACRO("include_bytes", CIncludeBytesExpander); STATIC_MACRO("include_str", CIncludeStrExpander); <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fclaw2d_global.h> #include <fclaw2d_regrid.h> #include <fclaw2d_ghost_fill.h> #include <fclaw_timer.h> #include <fclaw2d_forestclaw.h> #include <fclaw2d_partition.h> #include <fclaw2d_exchange.h> #include <fclaw2d_vtable.h> #include <fclaw2d_clawpatch.h> #ifdef __cplusplus extern "C" { #if 0 } #endif #endif /* This is also called from fclaw2d_initialize, so is not made static */ void cb_fclaw2d_regrid_tag4refinement(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_vtable_t vt; int refine_patch, maxlevel, level; const amr_options_t* gparms; int domain_init = *((int*) user); vt = fclaw2d_get_vtable(domain); gparms = get_domain_parms(domain); maxlevel = gparms->maxlevel; level = this_patch->level; if (level < maxlevel) { refine_patch = vt.regrid_tag4refinement(domain,this_patch,this_block_idx, this_patch_idx, domain_init); if (refine_patch == 1) { fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx); } } } /* Tag family for coarsening */ static void cb_regrid_tag4coarsening(fclaw2d_domain_t *domain, fclaw2d_patch_t *fine_patches, int blockno, int fine0_patchno, void *user) { const amr_options_t *gparms = get_domain_parms(domain); fclaw2d_vtable_t vt; vt = fclaw2d_get_vtable(domain); int minlevel = gparms->minlevel; int level = fine_patches[0].level; if (level > minlevel) { int family_coarsened = 1; family_coarsened = vt.regrid_tag4coarsening(domain,&fine_patches[0], blockno, fine0_patchno); if (family_coarsened == 1) { for (int igrid = 0; igrid < NumSiblings; igrid++) { int fine_patchno = fine0_patchno + igrid; fclaw2d_patch_mark_coarsen(domain,blockno, fine_patchno); } } } } /* ---------------------------------------------------------------- Public interface -------------------------------------------------------------- */ void cb_fclaw2d_regrid_repopulate(fclaw2d_domain_t * old_domain, fclaw2d_patch_t * old_patch, fclaw2d_domain_t * new_domain, fclaw2d_patch_t * new_patch, fclaw2d_patch_relation_t newsize, int blockno, int old_patchno, int new_patchno, void *user) { fclaw2d_vtable_t vt; vt = fclaw2d_get_vtable(new_domain); int domain_init = *((int*) user); fclaw2d_domain_data_t *ddata_old = fclaw2d_domain_get_data (old_domain); fclaw2d_domain_data_t *ddata_new = fclaw2d_domain_get_data (new_domain); fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE; if (newsize == FCLAW2D_PATCH_SAMESIZE) { new_patch->user = old_patch->user; old_patch->user = NULL; ++ddata_old->count_delete_clawpatch; ++ddata_new->count_set_clawpatch; #if 0 fclaw2d_clawpatch_initialize_after_regrid(new_domain, new_patch, blockno, new_patchno); #endif } else if (newsize == FCLAW2D_PATCH_HALFSIZE) { fclaw2d_patch_t *fine_siblings = new_patch; fclaw2d_patch_t *coarse_patch = old_patch; for (int i = 0; i < NumSiblings; i++) { fclaw2d_patch_t *fine_patch = &fine_siblings[i]; int fine_patchno = new_patchno + i; fclaw2d_patch_data_new(new_domain,fine_patch); fclaw2d_clawpatch_build(new_domain,fine_patch,blockno, fine_patchno,(void*) &build_mode); if (domain_init) { vt.patch_initialize(new_domain,fine_patch,blockno,fine_patchno); } } if (!domain_init) { int coarse_patchno = old_patchno; int fine_patchno = new_patchno; vt.regrid_interpolate2fine(new_domain,coarse_patch,fine_siblings, blockno,coarse_patchno,fine_patchno); } fclaw2d_patch_data_delete(old_domain,coarse_patch); } else if (newsize == FCLAW2D_PATCH_DOUBLESIZE) { if (domain_init) { fclaw_debugf("fclaw2d_regrid.cpp (repopulate): We shouldn't end up here\n"); exit(0); } /* Old grids are the finer grids; new grid is the coarsened grid */ fclaw2d_patch_t *fine_siblings = old_patch; int fine_patchno = old_patchno; fclaw2d_patch_t *coarse_patch = new_patch; int coarse_patchno = new_patchno; fclaw2d_patch_data_new(new_domain,coarse_patch); /* Area (and possibly other things) should be averaged to coarse grid. */ fclaw2d_clawpatch_build_from_fine(new_domain,fine_siblings,coarse_patch, blockno,coarse_patchno,fine_patchno, build_mode); /* Average the solution. Does this need to be customizable? */ vt.regrid_average2coarse(new_domain,fine_siblings,coarse_patch, blockno,coarse_patchno, fine_patchno); for(int i = 0; i < 4; i++) { fclaw2d_patch_t* fine_patch = &fine_siblings[i]; fclaw2d_patch_data_delete(old_domain,fine_patch); } } else { fclaw_global_essentialf("cb_adapt_domain : newsize not recognized\n"); exit(1); } } /* ---------------------------------------------------------------- Public interface -------------------------------------------------------------- */ void fclaw2d_regrid(fclaw2d_domain_t **domain) { fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID]); fclaw_global_infof("Regridding domain\n"); /* First determine which families should be coarsened. */ fclaw2d_domain_iterate_families(*domain, cb_regrid_tag4coarsening, (void*) NULL); int domain_init = 0; fclaw2d_domain_iterate_patches(*domain, cb_fclaw2d_regrid_tag4refinement, (void *) &domain_init); /* Rebuild domain if necessary */ /* Will return be NULL if no refining was done */ fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain); fclaw_bool have_new_refinement = new_domain != NULL; /* Domain data may go out of scope now. */ ddata = NULL; if (have_new_refinement) { fclaw_global_infof(" -- Have new refinement\n"); /* allocate memory for user patch data and user domain data in the new domain; copy data from the old to new the domain. */ fclaw2d_domain_setup(*domain, new_domain); ddata = fclaw2d_domain_get_data(new_domain); /* Average to new coarse grids and interpolate to new fine grids */ fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); fclaw2d_domain_iterate_adapted(*domain, new_domain, cb_fclaw2d_regrid_repopulate, (void *) &domain_init); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); /* free memory associated with old domain */ fclaw2d_domain_reset(domain); *domain = new_domain; new_domain = NULL; /* Repartition for load balancing. Second arg (mode) for vtk output */ fclaw2d_partition_domain(domain, -1); /* Need a new timer */ ddata = fclaw2d_domain_get_data(*domain); /* Set up ghost patches. No parallel communication is done here */ fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]); fclaw2d_exchange_setup(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]); /* Update ghost cells. This is needed because we have new coarse or fine patches without valid ghost cells. Time_interp = 0, since we only only regrid when all levels are time synchronized. */ int minlevel = (*domain)->global_minlevel; int maxlevel = (*domain)->global_maxlevel; int time_interp = 0; double sync_time = fclaw2d_domain_get_time(*domain); fclaw2d_ghost_update(*domain, minlevel, maxlevel, sync_time, time_interp, FCLAW2D_TIMER_REGRID); } else { #if 0 /* We updated all the ghost cells when leaving advance, so don't need to do it here */ /* Set up ghost patches. No parallel communication is done here */ fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]); fclaw2d_exchange_setup(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]); #endif } /* Stop timer */ ddata = fclaw2d_domain_get_data(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID]); /* Count calls to this function */ ++ddata->count_amr_regrid; } #ifdef __cplusplus #if 0 { #endif } #endif <commit_msg>Adding timer around grid adaption<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fclaw2d_global.h> #include <fclaw2d_regrid.h> #include <fclaw2d_ghost_fill.h> #include <fclaw_timer.h> #include <fclaw2d_forestclaw.h> #include <fclaw2d_partition.h> #include <fclaw2d_exchange.h> #include <fclaw2d_vtable.h> #include <fclaw2d_clawpatch.h> #ifdef __cplusplus extern "C" { #if 0 } #endif #endif /* This is also called from fclaw2d_initialize, so is not made static */ void cb_fclaw2d_regrid_tag4refinement(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_vtable_t vt; int refine_patch, maxlevel, level; const amr_options_t* gparms; int domain_init = *((int*) user); vt = fclaw2d_get_vtable(domain); gparms = get_domain_parms(domain); maxlevel = gparms->maxlevel; level = this_patch->level; if (level < maxlevel) { refine_patch = vt.regrid_tag4refinement(domain,this_patch,this_block_idx, this_patch_idx, domain_init); if (refine_patch == 1) { fclaw2d_patch_mark_refine(domain, this_block_idx, this_patch_idx); } } } /* Tag family for coarsening */ static void cb_regrid_tag4coarsening(fclaw2d_domain_t *domain, fclaw2d_patch_t *fine_patches, int blockno, int fine0_patchno, void *user) { const amr_options_t *gparms = get_domain_parms(domain); fclaw2d_vtable_t vt; vt = fclaw2d_get_vtable(domain); int minlevel = gparms->minlevel; int level = fine_patches[0].level; if (level > minlevel) { int family_coarsened = 1; family_coarsened = vt.regrid_tag4coarsening(domain,&fine_patches[0], blockno, fine0_patchno); if (family_coarsened == 1) { for (int igrid = 0; igrid < NumSiblings; igrid++) { int fine_patchno = fine0_patchno + igrid; fclaw2d_patch_mark_coarsen(domain,blockno, fine_patchno); } } } } /* ---------------------------------------------------------------- Public interface -------------------------------------------------------------- */ void cb_fclaw2d_regrid_repopulate(fclaw2d_domain_t * old_domain, fclaw2d_patch_t * old_patch, fclaw2d_domain_t * new_domain, fclaw2d_patch_t * new_patch, fclaw2d_patch_relation_t newsize, int blockno, int old_patchno, int new_patchno, void *user) { fclaw2d_vtable_t vt; vt = fclaw2d_get_vtable(new_domain); int domain_init = *((int*) user); fclaw2d_domain_data_t *ddata_old = fclaw2d_domain_get_data (old_domain); fclaw2d_domain_data_t *ddata_new = fclaw2d_domain_get_data (new_domain); fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE; if (newsize == FCLAW2D_PATCH_SAMESIZE) { new_patch->user = old_patch->user; old_patch->user = NULL; ++ddata_old->count_delete_clawpatch; ++ddata_new->count_set_clawpatch; #if 0 fclaw2d_clawpatch_initialize_after_regrid(new_domain, new_patch, blockno, new_patchno); #endif } else if (newsize == FCLAW2D_PATCH_HALFSIZE) { fclaw2d_patch_t *fine_siblings = new_patch; fclaw2d_patch_t *coarse_patch = old_patch; for (int i = 0; i < NumSiblings; i++) { fclaw2d_patch_t *fine_patch = &fine_siblings[i]; int fine_patchno = new_patchno + i; fclaw2d_patch_data_new(new_domain,fine_patch); fclaw2d_clawpatch_build(new_domain,fine_patch,blockno, fine_patchno,(void*) &build_mode); if (domain_init) { vt.patch_initialize(new_domain,fine_patch,blockno,fine_patchno); } } if (!domain_init) { int coarse_patchno = old_patchno; int fine_patchno = new_patchno; vt.regrid_interpolate2fine(new_domain,coarse_patch,fine_siblings, blockno,coarse_patchno,fine_patchno); } fclaw2d_patch_data_delete(old_domain,coarse_patch); } else if (newsize == FCLAW2D_PATCH_DOUBLESIZE) { if (domain_init) { fclaw_debugf("fclaw2d_regrid.cpp (repopulate): We shouldn't end up here\n"); exit(0); } /* Old grids are the finer grids; new grid is the coarsened grid */ fclaw2d_patch_t *fine_siblings = old_patch; int fine_patchno = old_patchno; fclaw2d_patch_t *coarse_patch = new_patch; int coarse_patchno = new_patchno; fclaw2d_patch_data_new(new_domain,coarse_patch); /* Area (and possibly other things) should be averaged to coarse grid. */ fclaw2d_clawpatch_build_from_fine(new_domain,fine_siblings,coarse_patch, blockno,coarse_patchno,fine_patchno, build_mode); /* Average the solution. Does this need to be customizable? */ vt.regrid_average2coarse(new_domain,fine_siblings,coarse_patch, blockno,coarse_patchno, fine_patchno); for(int i = 0; i < 4; i++) { fclaw2d_patch_t* fine_patch = &fine_siblings[i]; fclaw2d_patch_data_delete(old_domain,fine_patch); } } else { fclaw_global_essentialf("cb_adapt_domain : newsize not recognized\n"); exit(1); } } /* ---------------------------------------------------------------- Public interface -------------------------------------------------------------- */ void fclaw2d_regrid(fclaw2d_domain_t **domain) { fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain); fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID]); fclaw_global_infof("Regridding domain\n"); /* First determine which families should be coarsened. */ fclaw2d_domain_iterate_families(*domain, cb_regrid_tag4coarsening, (void*) NULL); int domain_init = 0; fclaw2d_domain_iterate_patches(*domain, cb_fclaw2d_regrid_tag4refinement, (void *) &domain_init); /* Rebuild domain if necessary */ /* Will return be NULL if no refining was done */ fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_EXTRA4]); fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_EXTRA4]); fclaw_bool have_new_refinement = new_domain != NULL; /* Domain data may go out of scope now. */ ddata = NULL; if (have_new_refinement) { fclaw_global_essentialf("-----> We should not be here\n"); exit(0); fclaw_global_infof(" -- Have new refinement\n"); /* allocate memory for user patch data and user domain data in the new domain; copy data from the old to new the domain. */ fclaw2d_domain_setup(*domain, new_domain); ddata = fclaw2d_domain_get_data(new_domain); /* Average to new coarse grids and interpolate to new fine grids */ fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); fclaw2d_domain_iterate_adapted(*domain, new_domain, cb_fclaw2d_regrid_repopulate, (void *) &domain_init); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDREGRID]); /* free memory associated with old domain */ fclaw2d_domain_reset(domain); *domain = new_domain; new_domain = NULL; /* Repartition for load balancing. Second arg (mode) for vtk output */ fclaw2d_partition_domain(domain, -1); /* Need a new timer */ ddata = fclaw2d_domain_get_data(*domain); /* Set up ghost patches. No parallel communication is done here */ fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]); fclaw2d_exchange_setup(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]); /* Update ghost cells. This is needed because we have new coarse or fine patches without valid ghost cells. Time_interp = 0, since we only only regrid when all levels are time synchronized. */ int minlevel = (*domain)->global_minlevel; int maxlevel = (*domain)->global_maxlevel; int time_interp = 0; double sync_time = fclaw2d_domain_get_time(*domain); fclaw2d_ghost_update(*domain, minlevel, maxlevel, sync_time, time_interp, FCLAW2D_TIMER_REGRID); } else { #if 0 /* We updated all the ghost cells when leaving advance, so don't need to do it here */ /* Set up ghost patches. No parallel communication is done here */ fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]); fclaw2d_exchange_setup(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_BUILDGHOST]); #endif } /* Stop timer */ ddata = fclaw2d_domain_get_data(*domain); fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID]); /* Count calls to this function */ ++ddata->count_amr_regrid; } #ifdef __cplusplus #if 0 { #endif } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <algorithm> #include <stdlib.h> #include <dali/public-api/dali-core.h> #include <dali-test-suite-utils.h> using namespace Dali; void utc_dali_resource_image_startup(void) { test_return_value = TET_UNDEF; } void utc_dali_resource_image_cleanup(void) { test_return_value = TET_PASS; } static const char* gTestImageFilename = "icon_wrt.png"; namespace { void LoadBitmapResource(TestPlatformAbstraction& platform) { Integration::ResourceRequest* request = platform.GetRequest(); Integration::Bitmap* bitmap = Integration::Bitmap::New( Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD ); Integration::ResourcePointer resource(bitmap); bitmap->GetPackedPixelsProfile()->ReserveBuffer(Pixel::RGBA8888, 80, 80, 80, 80); if(request) { platform.SetResourceLoaded(request->GetId(), request->GetType()->id, resource); } } } // namespace // 1.1 int UtcDaliResourceImageNew01(void) { TestApplication application; tet_infoline("UtcDaliResourceImageNew01 - ResourceImage::New(const std::string&)"); // invoke default handle constructor ResourceImage image; DALI_TEST_CHECK( !image ); // initialise handle image = ResourceImage::New(gTestImageFilename); DALI_TEST_CHECK( image ); END_TEST; } // 1.2 int UtcDaliResourceImageNew02(void) { TestApplication application; tet_infoline("UtcDaliREsourceImageNew02 - ResourceImage New( const std::string& url, ImageDimensions size, FittingMode scalingMode, SamplingMode samplingMode, bool orientationCorrection = true )"); // invoke default handle constructor ResourceImage image; DALI_TEST_CHECK( !image ); // initialise handle image = ResourceImage::New(gTestImageFilename, ImageDimensions( 128, 256 ), FittingMode::FIT_HEIGHT ); DALI_TEST_CHECK( image ); END_TEST; } // 1.7 int UtcDaliResourceImageDownCast(void) { TestApplication application; tet_infoline("Testing Dali::ResourceImage::DownCast()"); ResourceImage image = ResourceImage::New(gTestImageFilename); BaseHandle object(image); ResourceImage image2 = ResourceImage::DownCast(object); DALI_TEST_CHECK(image2); ResourceImage image3 = DownCast< ResourceImage >(object); DALI_TEST_CHECK(image3); BaseHandle unInitializedObject; ResourceImage image4 = ResourceImage::DownCast(unInitializedObject); DALI_TEST_CHECK(!image4); ResourceImage image5 = DownCast< ResourceImage >(unInitializedObject); DALI_TEST_CHECK(!image5); Image image6 = ResourceImage::New(gTestImageFilename); ResourceImage image7 = ResourceImage::DownCast(image6); DALI_TEST_CHECK(image7); END_TEST; } // 1.8 int UtcDaliResourceImageGetImageSize(void) { TestApplication application; TestPlatformAbstraction& platform = application.GetPlatform(); tet_infoline("UtcDaliResourceImageGetImageSize - ResourceImage::GetImageSize()"); Vector2 testSize(8.0f, 16.0f); platform.SetClosestImageSize(testSize); const ImageDimensions size = ResourceImage::GetImageSize(gTestImageFilename); DALI_TEST_CHECK( application.GetPlatform().GetTrace().FindMethod("GetClosestImageSize")); DALI_TEST_EQUALS( Vector2( size.GetX(), size.GetY() ), testSize, TEST_LOCATION); END_TEST; } // 1.9 int UtcDaliResourceImageGetUrl(void) { TestApplication application; tet_infoline("UtcDaliResourceImageGetFilename - ResourceImage::GetUrl()"); // invoke default handle constructor ResourceImage image; DALI_TEST_CHECK( !image ); // initialise handle image = ResourceImage::New(gTestImageFilename); DALI_TEST_EQUALS( image.GetUrl(), gTestImageFilename, TEST_LOCATION); END_TEST; } // 1.10 int UtcDaliResourceImageGetLoadingState01(void) { TestApplication application; tet_infoline("UtcDaliResourceImageGetLoadingState01"); ResourceImage image = ResourceImage::New(gTestImageFilename); DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed); // simulate load success PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 ); image.Reload(); // Test state == ResourceLoadingSucceeded DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded); END_TEST; } // 1.11 int UtcDaliResourceImageGetLoadingState02(void) { TestApplication application; tet_infoline("UtcDaliResourceImageGetLoadingState02"); // invoke default handle constructor ResourceImage image; DALI_TEST_CHECK( !image ); // initialise handle image = ResourceImage::New(gTestImageFilename); // Test state == ResourceLoadingFailed DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed); PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 ); image.Reload(); // Test state == ResourceLoadingFailed DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded); END_TEST; } static bool SignalLoadFlag = false; static void SignalLoadHandler(ResourceImage image) { tet_infoline("Received image load finished signal"); SignalLoadFlag = true; } // 1.13 int UtcDaliResourceImageSignalLoadingFinished(void) { TestApplication application; tet_infoline("UtcDaliResourceImageSignalLoadingFinished"); SignalLoadFlag = false; PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 ); ResourceImage image = ResourceImage::New(gTestImageFilename); image.LoadingFinishedSignal().Connect( SignalLoadHandler ); image.Reload(); application.SendNotification(); application.Render(16); Integration::ResourceRequest* request = application.GetPlatform().GetRequest(); if(request) { application.GetPlatform().SetResourceLoaded(request->GetId(), request->GetType()->id, Integration::ResourcePointer(Integration::Bitmap::New(Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD))); } application.Render(16); application.SendNotification(); DALI_TEST_CHECK( SignalLoadFlag == true ); END_TEST; } <commit_msg>(GCC 6.2) Remove unused functions from automated tests<commit_after>/* * Copyright (c) 2017 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <algorithm> #include <stdlib.h> #include <dali/public-api/dali-core.h> #include <dali-test-suite-utils.h> using namespace Dali; void utc_dali_resource_image_startup(void) { test_return_value = TET_UNDEF; } void utc_dali_resource_image_cleanup(void) { test_return_value = TET_PASS; } namespace { const char* gTestImageFilename = "icon_wrt.png"; } // unnamed namespace // 1.1 int UtcDaliResourceImageNew01(void) { TestApplication application; tet_infoline("UtcDaliResourceImageNew01 - ResourceImage::New(const std::string&)"); // invoke default handle constructor ResourceImage image; DALI_TEST_CHECK( !image ); // initialise handle image = ResourceImage::New(gTestImageFilename); DALI_TEST_CHECK( image ); END_TEST; } // 1.2 int UtcDaliResourceImageNew02(void) { TestApplication application; tet_infoline("UtcDaliREsourceImageNew02 - ResourceImage New( const std::string& url, ImageDimensions size, FittingMode scalingMode, SamplingMode samplingMode, bool orientationCorrection = true )"); // invoke default handle constructor ResourceImage image; DALI_TEST_CHECK( !image ); // initialise handle image = ResourceImage::New(gTestImageFilename, ImageDimensions( 128, 256 ), FittingMode::FIT_HEIGHT ); DALI_TEST_CHECK( image ); END_TEST; } // 1.7 int UtcDaliResourceImageDownCast(void) { TestApplication application; tet_infoline("Testing Dali::ResourceImage::DownCast()"); ResourceImage image = ResourceImage::New(gTestImageFilename); BaseHandle object(image); ResourceImage image2 = ResourceImage::DownCast(object); DALI_TEST_CHECK(image2); ResourceImage image3 = DownCast< ResourceImage >(object); DALI_TEST_CHECK(image3); BaseHandle unInitializedObject; ResourceImage image4 = ResourceImage::DownCast(unInitializedObject); DALI_TEST_CHECK(!image4); ResourceImage image5 = DownCast< ResourceImage >(unInitializedObject); DALI_TEST_CHECK(!image5); Image image6 = ResourceImage::New(gTestImageFilename); ResourceImage image7 = ResourceImage::DownCast(image6); DALI_TEST_CHECK(image7); END_TEST; } // 1.8 int UtcDaliResourceImageGetImageSize(void) { TestApplication application; TestPlatformAbstraction& platform = application.GetPlatform(); tet_infoline("UtcDaliResourceImageGetImageSize - ResourceImage::GetImageSize()"); Vector2 testSize(8.0f, 16.0f); platform.SetClosestImageSize(testSize); const ImageDimensions size = ResourceImage::GetImageSize(gTestImageFilename); DALI_TEST_CHECK( application.GetPlatform().GetTrace().FindMethod("GetClosestImageSize")); DALI_TEST_EQUALS( Vector2( size.GetX(), size.GetY() ), testSize, TEST_LOCATION); END_TEST; } // 1.9 int UtcDaliResourceImageGetUrl(void) { TestApplication application; tet_infoline("UtcDaliResourceImageGetFilename - ResourceImage::GetUrl()"); // invoke default handle constructor ResourceImage image; DALI_TEST_CHECK( !image ); // initialise handle image = ResourceImage::New(gTestImageFilename); DALI_TEST_EQUALS( image.GetUrl(), gTestImageFilename, TEST_LOCATION); END_TEST; } // 1.10 int UtcDaliResourceImageGetLoadingState01(void) { TestApplication application; tet_infoline("UtcDaliResourceImageGetLoadingState01"); ResourceImage image = ResourceImage::New(gTestImageFilename); DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed); // simulate load success PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 ); image.Reload(); // Test state == ResourceLoadingSucceeded DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded); END_TEST; } // 1.11 int UtcDaliResourceImageGetLoadingState02(void) { TestApplication application; tet_infoline("UtcDaliResourceImageGetLoadingState02"); // invoke default handle constructor ResourceImage image; DALI_TEST_CHECK( !image ); // initialise handle image = ResourceImage::New(gTestImageFilename); // Test state == ResourceLoadingFailed DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingFailed); PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 ); image.Reload(); // Test state == ResourceLoadingFailed DALI_TEST_CHECK(image.GetLoadingState() == ResourceLoadingSucceeded); END_TEST; } static bool SignalLoadFlag = false; static void SignalLoadHandler(ResourceImage image) { tet_infoline("Received image load finished signal"); SignalLoadFlag = true; } // 1.13 int UtcDaliResourceImageSignalLoadingFinished(void) { TestApplication application; tet_infoline("UtcDaliResourceImageSignalLoadingFinished"); SignalLoadFlag = false; PrepareResourceImage( application, 100u, 100u, Pixel::RGBA8888 ); ResourceImage image = ResourceImage::New(gTestImageFilename); image.LoadingFinishedSignal().Connect( SignalLoadHandler ); image.Reload(); application.SendNotification(); application.Render(16); Integration::ResourceRequest* request = application.GetPlatform().GetRequest(); if(request) { application.GetPlatform().SetResourceLoaded(request->GetId(), request->GetType()->id, Integration::ResourcePointer(Integration::Bitmap::New(Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_DISCARD))); } application.Render(16); application.SendNotification(); DALI_TEST_CHECK( SignalLoadFlag == true ); END_TEST; } <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CFunctionDB.cpp,v $ // $Revision: 1.83 $ // $Name: $ // $Author: aekamal $ // $Date: 2009/06/12 19:58:24 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CFunctionDB * * Created for Copasi by Stefan Hoops * (C) Stefan Hoops 2001 */ #include <algorithm> #include "copasi.h" #include "CFunctionDB.h" #include "CFunction.h" #include "FunctionDB.xml.h" #include "utilities/CCopasiException.h" #include "report/CCopasiObjectReference.h" #include "report/CKeyFactory.h" #include "xml/CCopasiXML.h" #include "model/CModel.h" CFunctionDB::CFunctionDB(const std::string & name, const CCopasiContainer * pParent): CCopasiContainer(name, pParent, "FunctionDB"), mFilename(), mLoadedFunctions("Functions", this) { initObjects(); CONSTRUCTOR_TRACE; } CFunctionDB::~CFunctionDB() { cleanup(); DESTRUCTOR_TRACE; } void CFunctionDB::cleanup() {mLoadedFunctions.cleanup();} void CFunctionDB::initObjects() { addObjectReference("File", mFilename); } bool CFunctionDB::load() { CCopasiXML XML; XML.setFunctionList(&mLoadedFunctions); std::stringstream DB; DB.str(FunctionDBxml); if (DB.fail()) return false; if (!XML.load(DB, "")) return false; return true; } C_INT32 CFunctionDB::load(CReadConfig &configbuffer) { CFunction Function; CFunction * pFunction = NULL; C_INT32 Size = 0; C_INT32 Fail = 0; configbuffer.getVariable("TotalUDKinetics", "C_INT32", &Size, CReadConfig::LOOP); for (C_INT32 i = 0; i < Size; i++) { Function.load(configbuffer); switch (Function.getType()) { case CEvaluationTree::Function: pFunction = new CFunction(Function); break; case CEvaluationTree::MassAction: pFunction = new CMassAction(Function); break; case CEvaluationTree::PreDefined: case CEvaluationTree::UserDefined: pFunction = new CKinFunction(Function, &configbuffer); break; default: fatalError(); } pFunction->compile(); if (!mLoadedFunctions.add(pFunction, true)) { pdelete(pFunction); // We ignore: // CCopasiVector (2): Object '%s' allready exists. if ((MCCopasiVector + 2) != CCopasiMessage::peekLastMessage().getNumber()) return Fail = 1; // Remove the ignored meesage. CCopasiMessage::getLastMessage(); } } return Fail; } void CFunctionDB::setFilename(const std::string & filename) {mFilename = filename;} std::string CFunctionDB::getFilename() const {return mFilename;} #ifdef FFFF CFunction * CFunctionDB::dBLoad(const std::string & functionName) { CFunction Function("NoName", &mLoadedFunctions); CFunction * pFunction = NULL; if (mFilename == "") return NULL; CReadConfig inbuf(mFilename); while (functionName != Function.getObjectName()) { Function.cleanup(); Function.load(inbuf); } switch (Function.getType()) { case CFunction::Base: pFunction = new CFunction(Function); break; case CFunction::MassAction: pFunction = new CMassAction(Function.isReversible()); break; case CFunction::PreDefined: case CFunction::UserDefined: pFunction = new CKinFunction(Function, &inbuf); break; case CFunction::Expression: fatalError(); //disabled //pFunction = new CUDFunction(Function); break; default: fatalError(); } if (!mLoadedFunctions.add(pFunction)) { pdelete(pFunction); // We ignore: // CCopasiVector (2): Object '%s' allready exists. if ((MCCopasiVector + 2) != CCopasiMessage::getLastMessage().getNumber()) pFunction = mLoadedFunctions[Function.getObjectName()]; } return pFunction; } #endif // FFFF #ifdef FFFF CEvaluationTree * CFunctionDB::createFunction(const std::string & name, const CEvaluationTree::Type & type) { if (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX) return NULL; //CFunction * pFunction = new CFunction(name); CEvaluationTree * pFunction = NULL; switch (type) { case CEvaluationTree::Base: pFunction = new CFunction(name); break; case CEvaluationTree::MassAction: pFunction = new CMassAction(name); break; case CEvaluationTree::PreDefinedKineticLaw: case CEvaluationTree::UserDefinedKineticLaw: pFunction = new CKinFunction(name); break; default: fatalError(); } if (!mLoadedFunctions.add(pFunction, true)) { delete pFunction; return NULL; } return pFunction; } #endif // FFFF bool CFunctionDB::add(CEvaluationTree * pFunction, const bool & adopt) {return mLoadedFunctions.add(pFunction, adopt);} void CFunctionDB::addAndAdaptName(CEvaluationTree * pFunction) { if (!pFunction) return; std::string basename = pFunction->getObjectName(); std::string name = basename; //CFunction* pFunc; //CCopasiVectorN<CEvaluationTree>& FunctionList //= this->loadedFunctions(); int i = 0; while (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX) { i++; std::ostringstream ss; ss << "_" << i; name = basename + ss.str(); } pFunction->setObjectName(name); this->add(pFunction, true); } bool CFunctionDB::removeFunction(unsigned C_INT32 index) { if (index == C_INVALID_INDEX) return false; mLoadedFunctions.CCopasiVector<CEvaluationTree>::remove(index); return true; } bool CFunctionDB::removeFunction(const std::string &key) { CEvaluationTree* func = dynamic_cast< CEvaluationTree * >(CCopasiRootContainer::getKeyFactory()->get(key)); if (!func) return false; unsigned C_INT32 index = mLoadedFunctions.CCopasiVector<CEvaluationTree>::getIndex(func); if (index == C_INVALID_INDEX) return false; mLoadedFunctions.CCopasiVector<CEvaluationTree>::remove(index); return true; } CEvaluationTree * CFunctionDB::findFunction(const std::string & functionName) { unsigned C_INT32 index = mLoadedFunctions.getIndex(functionName); if (index != C_INVALID_INDEX) return mLoadedFunctions[index]; else return NULL; } CEvaluationTree * CFunctionDB::findLoadFunction(const std::string & functionName) { unsigned C_INT32 i; for (i = 0; i < mLoadedFunctions.size(); i++) if (functionName == mLoadedFunctions[i]->getObjectName()) return mLoadedFunctions[i]; return NULL; } CCopasiVectorN < CEvaluationTree > & CFunctionDB::loadedFunctions() {return mLoadedFunctions;} std::vector<CFunction*> CFunctionDB::suitableFunctions(const unsigned C_INT32 noSubstrates, const unsigned C_INT32 noProducts, const TriLogic reversibility) { std::vector<CFunction*> ret; CFunction *pFunction; unsigned C_INT32 i, imax = mLoadedFunctions.size(); for (i = 0; i < imax; i++) { pFunction = dynamic_cast<CFunction *>(mLoadedFunctions[i]); if (!pFunction) continue; if (pFunction->isSuitable(noSubstrates, noProducts, reversibility)) ret.push_back(pFunction); } //always add constant flux it is is missing if (reversibility == TriTrue) { if ((noSubstrates > 0) || (noProducts > 0)) //constant flux was not yet added { pFunction = dynamic_cast<CFunction*>(findFunction("Constant flux (reversible)")); if (!pFunction) fatalError(); ret.push_back(pFunction); } } else //irreversible { if (noSubstrates > 0) //constant flux was not yet added { pFunction = dynamic_cast<CFunction*>(findFunction("Constant flux (irreversible)")); if (!pFunction) fatalError(); ret.push_back(pFunction); } } return ret; } bool CFunctionDB::appendDependentFunctions(std::set< const CCopasiObject * > candidates, std::set< const CCopasiObject * > & dependentFunctions) const { size_t Size = dependentFunctions.size(); CCopasiVectorN< CEvaluationTree >::const_iterator it = mLoadedFunctions.begin(); CCopasiVectorN< CEvaluationTree >::const_iterator end = mLoadedFunctions.end(); for (; it != end; ++it) if (candidates.find(*it) == candidates.end() && (*it)->dependsOn(candidates)) dependentFunctions.insert((*it)); return Size < dependentFunctions.size(); } std::set<std::string> CFunctionDB::listDependentTrees(const std::string & name) const { std::set<std::string> List; CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin(); CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end(); for (; it != end; ++it) if ((*it)->dependsOnTree(name)) List.insert((*it)->getObjectName()); return List; } std::vector< CEvaluationTree * > CFunctionDB::getUsedFunctions(const CModel* pModel) const { std::vector< CEvaluationTree * > UsedFunctions; CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin(); CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end(); for (; it != end; ++it) { // :TODO: Bug 719 // This will have to be modified as soon as the optimization problem stores its on expression if ((*it)->getType() == CEvaluationTree::Expression) { UsedFunctions.push_back(*it); continue; } std::set< const CCopasiObject * > Function; Function.insert(*it); std::set< const CCopasiObject * > Reactions; std::set< const CCopasiObject * > Metabolites; std::set< const CCopasiObject * > Values; std::set< const CCopasiObject * > Compartments; std::set< const CCopasiObject * > Events; pModel->appendDependentModelObjects(Function, Reactions, Metabolites, Compartments, Values, Events); if (Reactions.size() != 0) { UsedFunctions.push_back(*it); continue; } if (Metabolites.size() != 0) { UsedFunctions.push_back(*it); continue; } if (Values.size() != 0) { UsedFunctions.push_back(*it); continue; } if (Compartments.size() != 0) { UsedFunctions.push_back(*it); continue; } if (Events.size() != 0) { UsedFunctions.push_back(*it); continue; } } CEvaluationTree::completeEvaluationTreeList(UsedFunctions); return UsedFunctions; } <commit_msg>Removed obsolete code.<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CFunctionDB.cpp,v $ // $Revision: 1.84 $ // $Name: $ // $Author: shoops $ // $Date: 2009/10/26 22:08:51 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CFunctionDB * * Created for Copasi by Stefan Hoops * (C) Stefan Hoops 2001 */ #include <algorithm> #include "copasi.h" #include "CFunctionDB.h" #include "CFunction.h" #include "FunctionDB.xml.h" #include "utilities/CCopasiException.h" #include "report/CCopasiObjectReference.h" #include "report/CKeyFactory.h" #include "xml/CCopasiXML.h" #include "model/CModel.h" CFunctionDB::CFunctionDB(const std::string & name, const CCopasiContainer * pParent): CCopasiContainer(name, pParent, "FunctionDB"), mFilename(), mLoadedFunctions("Functions", this) { initObjects(); CONSTRUCTOR_TRACE; } CFunctionDB::~CFunctionDB() { cleanup(); DESTRUCTOR_TRACE; } void CFunctionDB::cleanup() {mLoadedFunctions.cleanup();} void CFunctionDB::initObjects() { addObjectReference("File", mFilename); } bool CFunctionDB::load() { CCopasiXML XML; XML.setFunctionList(&mLoadedFunctions); std::stringstream DB; DB.str(FunctionDBxml); if (DB.fail()) return false; if (!XML.load(DB, "")) return false; return true; } C_INT32 CFunctionDB::load(CReadConfig &configbuffer) { CFunction Function; CFunction * pFunction = NULL; C_INT32 Size = 0; C_INT32 Fail = 0; configbuffer.getVariable("TotalUDKinetics", "C_INT32", &Size, CReadConfig::LOOP); for (C_INT32 i = 0; i < Size; i++) { Function.load(configbuffer); switch (Function.getType()) { case CEvaluationTree::Function: pFunction = new CFunction(Function); break; case CEvaluationTree::MassAction: pFunction = new CMassAction(Function); break; case CEvaluationTree::PreDefined: case CEvaluationTree::UserDefined: pFunction = new CKinFunction(Function, &configbuffer); break; default: fatalError(); } pFunction->compile(); if (!mLoadedFunctions.add(pFunction, true)) { pdelete(pFunction); // We ignore: // CCopasiVector (2): Object '%s' allready exists. if ((MCCopasiVector + 2) != CCopasiMessage::peekLastMessage().getNumber()) return Fail = 1; // Remove the ignored meesage. CCopasiMessage::getLastMessage(); } } return Fail; } void CFunctionDB::setFilename(const std::string & filename) {mFilename = filename;} std::string CFunctionDB::getFilename() const {return mFilename;} #ifdef FFFF CFunction * CFunctionDB::dBLoad(const std::string & functionName) { CFunction Function("NoName", &mLoadedFunctions); CFunction * pFunction = NULL; if (mFilename == "") return NULL; CReadConfig inbuf(mFilename); while (functionName != Function.getObjectName()) { Function.cleanup(); Function.load(inbuf); } switch (Function.getType()) { case CFunction::Base: pFunction = new CFunction(Function); break; case CFunction::MassAction: pFunction = new CMassAction(Function.isReversible()); break; case CFunction::PreDefined: case CFunction::UserDefined: pFunction = new CKinFunction(Function, &inbuf); break; case CFunction::Expression: fatalError(); //disabled //pFunction = new CUDFunction(Function); break; default: fatalError(); } if (!mLoadedFunctions.add(pFunction)) { pdelete(pFunction); // We ignore: // CCopasiVector (2): Object '%s' allready exists. if ((MCCopasiVector + 2) != CCopasiMessage::getLastMessage().getNumber()) pFunction = mLoadedFunctions[Function.getObjectName()]; } return pFunction; } #endif // FFFF #ifdef FFFF CEvaluationTree * CFunctionDB::createFunction(const std::string & name, const CEvaluationTree::Type & type) { if (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX) return NULL; //CFunction * pFunction = new CFunction(name); CEvaluationTree * pFunction = NULL; switch (type) { case CEvaluationTree::Base: pFunction = new CFunction(name); break; case CEvaluationTree::MassAction: pFunction = new CMassAction(name); break; case CEvaluationTree::PreDefinedKineticLaw: case CEvaluationTree::UserDefinedKineticLaw: pFunction = new CKinFunction(name); break; default: fatalError(); } if (!mLoadedFunctions.add(pFunction, true)) { delete pFunction; return NULL; } return pFunction; } #endif // FFFF bool CFunctionDB::add(CEvaluationTree * pFunction, const bool & adopt) {return mLoadedFunctions.add(pFunction, adopt);} void CFunctionDB::addAndAdaptName(CEvaluationTree * pFunction) { if (!pFunction) return; std::string basename = pFunction->getObjectName(); std::string name = basename; //CFunction* pFunc; //CCopasiVectorN<CEvaluationTree>& FunctionList //= this->loadedFunctions(); int i = 0; while (mLoadedFunctions.getIndex(name) != C_INVALID_INDEX) { i++; std::ostringstream ss; ss << "_" << i; name = basename + ss.str(); } pFunction->setObjectName(name); this->add(pFunction, true); } bool CFunctionDB::removeFunction(unsigned C_INT32 index) { if (index == C_INVALID_INDEX) return false; mLoadedFunctions.CCopasiVector<CEvaluationTree>::remove(index); return true; } bool CFunctionDB::removeFunction(const std::string &key) { CEvaluationTree* func = dynamic_cast< CEvaluationTree * >(CCopasiRootContainer::getKeyFactory()->get(key)); if (!func) return false; unsigned C_INT32 index = mLoadedFunctions.CCopasiVector<CEvaluationTree>::getIndex(func); if (index == C_INVALID_INDEX) return false; mLoadedFunctions.CCopasiVector<CEvaluationTree>::remove(index); return true; } CEvaluationTree * CFunctionDB::findFunction(const std::string & functionName) { unsigned C_INT32 index = mLoadedFunctions.getIndex(functionName); if (index != C_INVALID_INDEX) return mLoadedFunctions[index]; else return NULL; } CEvaluationTree * CFunctionDB::findLoadFunction(const std::string & functionName) { unsigned C_INT32 i; for (i = 0; i < mLoadedFunctions.size(); i++) if (functionName == mLoadedFunctions[i]->getObjectName()) return mLoadedFunctions[i]; return NULL; } CCopasiVectorN < CEvaluationTree > & CFunctionDB::loadedFunctions() {return mLoadedFunctions;} std::vector<CFunction*> CFunctionDB::suitableFunctions(const unsigned C_INT32 noSubstrates, const unsigned C_INT32 noProducts, const TriLogic reversibility) { std::vector<CFunction*> ret; CFunction *pFunction; unsigned C_INT32 i, imax = mLoadedFunctions.size(); for (i = 0; i < imax; i++) { pFunction = dynamic_cast<CFunction *>(mLoadedFunctions[i]); if (!pFunction) continue; if (pFunction->isSuitable(noSubstrates, noProducts, reversibility)) ret.push_back(pFunction); } //always add constant flux it is is missing if (reversibility == TriTrue) { if ((noSubstrates > 0) || (noProducts > 0)) //constant flux was not yet added { pFunction = dynamic_cast<CFunction*>(findFunction("Constant flux (reversible)")); if (!pFunction) fatalError(); ret.push_back(pFunction); } } else //irreversible { if (noSubstrates > 0) //constant flux was not yet added { pFunction = dynamic_cast<CFunction*>(findFunction("Constant flux (irreversible)")); if (!pFunction) fatalError(); ret.push_back(pFunction); } } return ret; } bool CFunctionDB::appendDependentFunctions(std::set< const CCopasiObject * > candidates, std::set< const CCopasiObject * > & dependentFunctions) const { size_t Size = dependentFunctions.size(); CCopasiVectorN< CEvaluationTree >::const_iterator it = mLoadedFunctions.begin(); CCopasiVectorN< CEvaluationTree >::const_iterator end = mLoadedFunctions.end(); for (; it != end; ++it) if (candidates.find(*it) == candidates.end() && (*it)->dependsOn(candidates)) dependentFunctions.insert((*it)); return Size < dependentFunctions.size(); } std::set<std::string> CFunctionDB::listDependentTrees(const std::string & name) const { std::set<std::string> List; CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin(); CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end(); for (; it != end; ++it) if ((*it)->dependsOnTree(name)) List.insert((*it)->getObjectName()); return List; } std::vector< CEvaluationTree * > CFunctionDB::getUsedFunctions(const CModel* pModel) const { std::vector< CEvaluationTree * > UsedFunctions; CCopasiVectorN < CEvaluationTree >::const_iterator it = mLoadedFunctions.begin(); CCopasiVectorN < CEvaluationTree >::const_iterator end = mLoadedFunctions.end(); for (; it != end; ++it) { std::set< const CCopasiObject * > Function; Function.insert(*it); std::set< const CCopasiObject * > Reactions; std::set< const CCopasiObject * > Metabolites; std::set< const CCopasiObject * > Values; std::set< const CCopasiObject * > Compartments; std::set< const CCopasiObject * > Events; pModel->appendDependentModelObjects(Function, Reactions, Metabolites, Compartments, Values, Events); if (Reactions.size() != 0) { UsedFunctions.push_back(*it); continue; } if (Metabolites.size() != 0) { UsedFunctions.push_back(*it); continue; } if (Values.size() != 0) { UsedFunctions.push_back(*it); continue; } if (Compartments.size() != 0) { UsedFunctions.push_back(*it); continue; } if (Events.size() != 0) { UsedFunctions.push_back(*it); continue; } } CEvaluationTree::completeEvaluationTreeList(UsedFunctions); return UsedFunctions; } <|endoftext|>
<commit_before>#include "src/fillers.h" #include "src/utils.h" /* ***** */ void gfx_flatFill(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type) { const gfx_Vertex *v0 = &t->vertices[0]; const gfx_Vertex *v1 = &t->vertices[1]; const gfx_Vertex *v2 = &t->vertices[2]; double invDy, dxLeft, dxRight, xLeft, xRight; double y, yDir = 1; // variables used if depth test is enabled float startInvZ, endInvZ, invZ0, invZ1, invZ2, invY02; if(type == FLAT_BOTTOM) { invDy = 1.f / (v2->position.y - v0->position.y); } else { invDy = 1.f / (v0->position.y - v2->position.y); yDir = -1; } dxLeft = (v2->position.x - v0->position.x) * invDy; dxRight = (v1->position.x - v0->position.x) * invDy; xLeft = v0->position.x; xRight = xLeft; // skip the unnecessary divisions if there's no depth testing if(buffer->drawOpts.depthFunc != DF_ALWAYS) { invZ0 = 1.f / v0->position.z; invZ1 = 1.f / v1->position.z; invZ2 = 1.f / v2->position.z; invY02 = 1.f / (v0->position.y - v2->position.y); } for(y = v0->position.y; ; y += yDir) { if(type == FLAT_TOP && y < v2->position.y) break; else if(type == FLAT_BOTTOM && y > v2->position.y) { // to avoid pixel wide gaps, render extra line at the junction between two final points if(buffer->drawOpts.depthFunc != DF_ALWAYS) gfx_drawLine(xLeft-dxLeft, y, 1.f/startInvZ, xRight-dxRight, y, 1.f/endInvZ, t->color, buffer); else gfx_drawLine(xLeft-dxLeft, y, 0.f, xRight-dxRight, y, 0.f, t->color, buffer); break; } // interpolate 1/z only if depth testing is enabled if(buffer->drawOpts.depthFunc != DF_ALWAYS) { float r1 = (v0->position.y - y) * invY02; startInvZ = LERP(invZ0, invZ2, r1); endInvZ = LERP(invZ0, invZ1, r1); gfx_drawLine(xLeft, y, 1.f/startInvZ, xRight, y, 1.f/endInvZ, t->color, buffer); } else gfx_drawLine(xLeft, y, 0.f, xRight, y, 0.f, t->color, buffer); xLeft += dxLeft; xRight += dxRight; } } /* ***** */ void gfx_perspectiveTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type) { const gfx_Vertex *v0 = &t->vertices[0]; const gfx_Vertex *v1 = &t->vertices[1]; const gfx_Vertex *v2 = &t->vertices[2]; double x, y, invDy, dxLeft, dxRight, yDir = 1; int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0; int texW = t->texture->width - 1; int texH = t->texture->height - 1; int texArea = texW * texH; float startX = v0->position.x; float endX = startX; float invZ0, invZ1, invZ2, invY02 = 1.f; int finished = 0; if(type == FLAT_BOTTOM) { invDy = 1.f / (v2->position.y - v0->position.y); } else { invDy = 1.f / (v0->position.y - v2->position.y); yDir = -1; } dxLeft = (v2->position.x - v0->position.x) * invDy; dxRight = (v1->position.x - v0->position.x) * invDy; invZ0 = 1.f / v0->position.z; invZ1 = 1.f / v1->position.z; invZ2 = 1.f / v2->position.z; invY02 = 1.f / (v0->position.y - v2->position.y); for(y = v0->position.y; ; y += yDir) { float startInvZ, endInvZ, r1, invLineLength = 0.f; float startU = texW, startV = texH, endU = texW, endV = texH; if(type == FLAT_BOTTOM && y > v2->position.y) { // in final iteration draw extra scanline to avoid pixel wide gaps startX -= dxLeft; endX -= dxRight; y = v2->position.y; finished = 1; } else if ( type == FLAT_TOP && y < v2->position.y) break; r1 = (v0->position.y - y) * invY02; startInvZ = LERP(invZ0, invZ2, r1); endInvZ = LERP(invZ0, invZ1, r1); startU *= LERP(v0->uv.u * invZ0, v2->uv.u * invZ2, r1); startV *= LERP(v0->uv.v * invZ0, v2->uv.v * invZ2, r1); endU *= LERP(v0->uv.u * invZ0, v1->uv.u * invZ1, r1); endV *= LERP(v0->uv.v * invZ0, v1->uv.v * invZ1, r1); if(startX != endX) invLineLength = 1.f / (endX - startX); for(x = startX; x <= endX; ++x) { // interpolate 1/z for each pixel in the scanline float r = (x - startX) * invLineLength; float lerpInvZ = LERP(startInvZ, endInvZ, r); float z = 1.f/lerpInvZ; float u = z * LERP(startU, endU, r); float v = z * LERP(startV, endV, r); // fetch texture data with a texArea modulus for proper effect in case u or v are > 1 unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea]; if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey)) { // DF_ALWAYS = no depth test if(buffer->drawOpts.depthFunc == DF_ALWAYS) gfx_drawPixel(x, y, pixel, buffer); else gfx_drawPixelWithDepth(x, y, lerpInvZ, pixel, buffer); } } startX += dxLeft; endX += dxRight; if(finished) break; } } /* ***** */ void gfx_affineTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type) { const gfx_Vertex *v0 = &t->vertices[0]; const gfx_Vertex *v1 = &t->vertices[1]; const gfx_Vertex *v2 = &t->vertices[2]; double x, y, invDy, dxLeft, dxRight, yDir = 1; int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0; float duLeft, dvLeft, duRight, dvRight; float startU, startV, invDx, du, dv, startX, endX; float texW = t->texture->width - 1; float texH = t->texture->height - 1; int texArea = texW * texH; // variables used only if depth test is enabled float invZ0, invZ1, invZ2, invY02 = 1.f; int finished = 0; if(type == FLAT_BOTTOM) { invDy = 1.f / (v2->position.y - v0->position.y); } else { invDy = 1.f / (v0->position.y - v2->position.y); yDir = -1; } dxLeft = (v2->position.x - v0->position.x) * invDy; dxRight = (v1->position.x - v0->position.x) * invDy; duLeft = texW * (v2->uv.u - v0->uv.u) * invDy; dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy; duRight = texW * (v1->uv.u - v0->uv.u) * invDy; dvRight = texH * (v1->uv.v - v0->uv.v) * invDy; startU = texW * v0->uv.u; startV = texH * v0->uv.v; // With triangles the texture gradients (u,v slopes over the triangle surface) // are guaranteed to be constant, so we need to calculate du and dv only once. invDx = 1.f / (dxRight - dxLeft); du = (duRight - duLeft) * invDx; dv = (dvRight - dvLeft) * invDx; startX = v0->position.x; endX = startX; // skip the unnecessary divisions if there's no depth testing if(buffer->drawOpts.depthFunc != DF_ALWAYS) { invZ0 = 1.f / v0->position.z; invZ1 = 1.f / v1->position.z; invZ2 = 1.f / v2->position.z; invY02 = 1.f / (v0->position.y - v2->position.y); } for(y = v0->position.y; ; y += yDir) { float u = startU; float v = startV; // variables used only if depth test is enabled float startInvZ, endInvZ, invLineLength = 0.f; if(type == FLAT_BOTTOM && y > v2->position.y) { // in final iteration draw extra scanline to avoid pixel wide gaps u -= duLeft; v -= dvLeft; startX -= dxLeft; endX -= dxRight; finished = 1; } else if ( type == FLAT_TOP && y < v2->position.y) break; // interpolate 1/z only if depth testing is enabled if(buffer->drawOpts.depthFunc != DF_ALWAYS) { float r1 = (v0->position.y - y) * invY02; startInvZ = LERP(invZ0, invZ2, r1); endInvZ = LERP(invZ0, invZ1, r1); if(startX != endX) invLineLength = 1.f / (endX - startX); } for(x = startX; x <= endX; ++x) { // fetch texture data with a texArea modulus for proper effect in case u or v are > 1 unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea]; if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey)) { // DF_ALWAYS = no depth test if(buffer->drawOpts.depthFunc == DF_ALWAYS) gfx_drawPixel(x, y, pixel, buffer); else { float r = (x - startX) * invLineLength; float lerpInvZ = LERP(startInvZ, endInvZ, r); gfx_drawPixelWithDepth(x, y, lerpInvZ, pixel, buffer); } } u += du; v += dv; } startX += dxLeft; endX += dxRight; startU += duLeft; startV += dvLeft; if(finished) break; } } <commit_msg>slightly tighter scanline gap handling for triangle rendering<commit_after>#include "src/fillers.h" #include "src/utils.h" /* ***** */ void gfx_flatFill(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type) { const gfx_Vertex *v0 = &t->vertices[0]; const gfx_Vertex *v1 = &t->vertices[1]; const gfx_Vertex *v2 = &t->vertices[2]; double y, invDy, dxLeft, dxRight, xLeft, xRight; int currLine, numScanlines, yDir = 1; // variables used if depth test is enabled float startInvZ, endInvZ, invZ0, invZ1, invZ2, invY02; if(type == FLAT_BOTTOM) { invDy = 1.0 / (v2->position.y - v0->position.y); numScanlines = ceil(v2->position.y) - ceil(v0->position.y); } else { invDy = 1.0 / (v0->position.y - v2->position.y); yDir = -1; numScanlines = ceil(v0->position.y) - ceil(v2->position.y); } dxLeft = (v2->position.x - v0->position.x) * invDy; dxRight = (v1->position.x - v0->position.x) * invDy; xLeft = v0->position.x; xRight = xLeft; // skip the unnecessary divisions if there's no depth testing if(buffer->drawOpts.depthFunc != DF_ALWAYS) { invZ0 = 1.f / v0->position.z; invZ1 = 1.f / v1->position.z; invZ2 = 1.f / v2->position.z; invY02 = 1.f / (v0->position.y - v2->position.y); } for(currLine = 0, y = v0->position.y; currLine <= numScanlines; y += yDir) { // interpolate 1/z only if depth testing is enabled if(buffer->drawOpts.depthFunc != DF_ALWAYS) { float r1 = (v0->position.y - y) * invY02; startInvZ = LERP(invZ0, invZ2, r1); endInvZ = LERP(invZ0, invZ1, r1); gfx_drawLine(xLeft, y, 1.f/startInvZ, xRight, y, 1.f/endInvZ, t->color, buffer); } else gfx_drawLine(xLeft, y, 0.f, xRight, y, 0.f, t->color, buffer); xLeft += dxLeft; xRight += dxRight; if(++currLine == numScanlines) { xLeft -= dxLeft; xRight -= dxRight; } } } /* ***** */ void gfx_perspectiveTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type) { const gfx_Vertex *v0 = &t->vertices[0]; const gfx_Vertex *v1 = &t->vertices[1]; const gfx_Vertex *v2 = &t->vertices[2]; double x, y, invDy, dxLeft, dxRight, yDir = 1; int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0; int texW = t->texture->width - 1; int texH = t->texture->height - 1; int texArea = texW * texH; float startX = v0->position.x; float endX = startX; float invZ0, invZ1, invZ2, invY02 = 1.f; int currLine, numScanlines; if(type == FLAT_BOTTOM) { invDy = 1.0 / (v2->position.y - v0->position.y); numScanlines = ceil(v2->position.y) - ceil(v0->position.y); } else { invDy = 1.0 / (v0->position.y - v2->position.y); numScanlines = ceil(v0->position.y) - ceil(v2->position.y); yDir = -1; } dxLeft = (v2->position.x - v0->position.x) * invDy; dxRight = (v1->position.x - v0->position.x) * invDy; invZ0 = 1.f / v0->position.z; invZ1 = 1.f / v1->position.z; invZ2 = 1.f / v2->position.z; invY02 = 1.f / (v0->position.y - v2->position.y); for(currLine = 0, y = v0->position.y; currLine <= numScanlines; y += yDir) { float startInvZ, endInvZ, r1, invLineLength = 0.f; float startU = texW, startV = texH, endU = texW, endV = texH; r1 = (v0->position.y - y) * invY02; startInvZ = LERP(invZ0, invZ2, r1); endInvZ = LERP(invZ0, invZ1, r1); startU *= LERP(v0->uv.u * invZ0, v2->uv.u * invZ2, r1); startV *= LERP(v0->uv.v * invZ0, v2->uv.v * invZ2, r1); endU *= LERP(v0->uv.u * invZ0, v1->uv.u * invZ1, r1); endV *= LERP(v0->uv.v * invZ0, v1->uv.v * invZ1, r1); if(startX != endX) invLineLength = 1.f / (endX - startX); for(x = startX; x <= endX; ++x) { // interpolate 1/z for each pixel in the scanline float r = (x - startX) * invLineLength; float lerpInvZ = LERP(startInvZ, endInvZ, r); float z = 1.f/lerpInvZ; float u = z * LERP(startU, endU, r); float v = z * LERP(startV, endV, r); // fetch texture data with a texArea modulus for proper effect in case u or v are > 1 unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea]; if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey)) { // DF_ALWAYS = no depth test if(buffer->drawOpts.depthFunc == DF_ALWAYS) gfx_drawPixel(x, y, pixel, buffer); else gfx_drawPixelWithDepth(x, y, lerpInvZ, pixel, buffer); } } startX += dxLeft; endX += dxRight; if(++currLine == numScanlines) { startX -= dxLeft; endX -= dxRight; } } } /* ***** */ void gfx_affineTextureMap(const gfx_Triangle *t, gfx_drawBuffer *buffer, enum TriangleType type) { const gfx_Vertex *v0 = &t->vertices[0]; const gfx_Vertex *v1 = &t->vertices[1]; const gfx_Vertex *v2 = &t->vertices[2]; double x, y, invDy, dxLeft, dxRight, yDir = 1; int useColorKey = buffer->drawOpts.colorKey != -1 ? 1 : 0; float duLeft, dvLeft, duRight, dvRight; float startU, startV, invDx, du, dv, startX, endX; float texW = t->texture->width - 1; float texH = t->texture->height - 1; int texArea = texW * texH; // variables used only if depth test is enabled float invZ0, invZ1, invZ2, invY02 = 1.f; int currLine, numScanlines; if(type == FLAT_BOTTOM) { invDy = 1.f / (v2->position.y - v0->position.y); numScanlines = ceil(v2->position.y) - ceil(v0->position.y); } else { invDy = 1.f / (v0->position.y - v2->position.y); numScanlines = ceil(v0->position.y) - ceil(v2->position.y); yDir = -1; } dxLeft = (v2->position.x - v0->position.x) * invDy; dxRight = (v1->position.x - v0->position.x) * invDy; duLeft = texW * (v2->uv.u - v0->uv.u) * invDy; dvLeft = texH * (v2->uv.v - v0->uv.v) * invDy; duRight = texW * (v1->uv.u - v0->uv.u) * invDy; dvRight = texH * (v1->uv.v - v0->uv.v) * invDy; startU = texW * v0->uv.u; startV = texH * v0->uv.v; // With triangles the texture gradients (u,v slopes over the triangle surface) // are guaranteed to be constant, so we need to calculate du and dv only once. invDx = 1.f / (dxRight - dxLeft); du = (duRight - duLeft) * invDx; dv = (dvRight - dvLeft) * invDx; startX = v0->position.x; endX = startX; // skip the unnecessary divisions if there's no depth testing if(buffer->drawOpts.depthFunc != DF_ALWAYS) { invZ0 = 1.f / v0->position.z; invZ1 = 1.f / v1->position.z; invZ2 = 1.f / v2->position.z; invY02 = 1.f / (v0->position.y - v2->position.y); } for(currLine = 0, y = v0->position.y; currLine <= numScanlines ; y += yDir) { float u = startU; float v = startV; // variables used only if depth test is enabled float startInvZ, endInvZ, invLineLength = 0.f; // interpolate 1/z only if depth testing is enabled if(buffer->drawOpts.depthFunc != DF_ALWAYS) { float r1 = (v0->position.y - y) * invY02; startInvZ = LERP(invZ0, invZ2, r1); endInvZ = LERP(invZ0, invZ1, r1); if(startX != endX) invLineLength = 1.f / (endX - startX); } for(x = startX; x <= endX; ++x) { // fetch texture data with a texArea modulus for proper effect in case u or v are > 1 unsigned char pixel = t->texture->data[((int)u + ((int)v * t->texture->height)) % texArea]; if(!useColorKey || (useColorKey && pixel != (unsigned char)buffer->drawOpts.colorKey)) { // DF_ALWAYS = no depth test if(buffer->drawOpts.depthFunc == DF_ALWAYS) gfx_drawPixel(x, y, pixel, buffer); else { float r = (x - startX) * invLineLength; float lerpInvZ = LERP(startInvZ, endInvZ, r); gfx_drawPixelWithDepth(x, y, lerpInvZ, pixel, buffer); } } u += du; v += dv; } startX += dxLeft; endX += dxRight; startU += duLeft; startV += dvLeft; if(++currLine == numScanlines) { startX -= dxLeft; endX -= dxRight; startU -= duLeft; startV -= dvLeft; } } } <|endoftext|>
<commit_before>#include "bbprojectmanager.hpp" #include "bbprojectmanagerplugin.hpp" #include "bbprojectmanagerconstants.hpp" #include <coreplugin/icore.h> #include <coreplugin/icontext.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/command.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/coreconstants.h> #include <coreplugin/mimedatabase.h> #include <QAction> #include <QMessageBox> #include <QMainWindow> #include <QMenu> #include <QtPlugin> namespace BoostBuildProjectManager { namespace Internal { BoostBuildPlugin::BoostBuildPlugin() { // Create your members } BoostBuildPlugin::~BoostBuildPlugin() { // Unregister objects from the plugin manager's object pool // Delete members } bool BoostBuildPlugin::initialize(QStringList const& arguments, QString* errorString) { Q_UNUSED(arguments) // Register objects in the plugin manager's object pool // Load settings // Add actions to menus // Connect to other plugins' signals // In the initialize function, a plugin can be sure that the plugins it // depends on have initialized their members. QLatin1String const mimeTypes(":boostbuildproject/BoostBuildProjectManager.mimetypes.xml"); if (!Core::MimeDatabase::addMimeTypes(mimeTypes, errorString)) return false; addAutoReleasedObject(new ProjectManager); return true; } void BoostBuildPlugin::extensionsInitialized() { // Retrieve objects from the plugin manager's object pool // In the extensionsInitialized function, a plugin can be sure that all // plugins that depend on it are completely initialized. } ExtensionSystem::IPlugin::ShutdownFlag BoostBuildPlugin::aboutToShutdown() { // Save settings // Disconnect from signals that are not needed during shutdown // Hide UI (if you add UI that is not in the main window directly) return SynchronousShutdown; } }} <commit_msg>Add BuildConfigurationFactory and BuildStepFactory to auto-released objects<commit_after>#include "bbbuildconfiguration.hpp" #include "bbbuildstep.hpp" #include "bbprojectmanager.hpp" #include "bbprojectmanagerplugin.hpp" #include "bbprojectmanagerconstants.hpp" #include <coreplugin/icore.h> #include <coreplugin/icontext.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/command.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/coreconstants.h> #include <coreplugin/mimedatabase.h> #include <QAction> #include <QMessageBox> #include <QMainWindow> #include <QMenu> #include <QtPlugin> namespace BoostBuildProjectManager { namespace Internal { BoostBuildPlugin::BoostBuildPlugin() { // Create your members } BoostBuildPlugin::~BoostBuildPlugin() { // Unregister objects from the plugin manager's object pool // Delete members } bool BoostBuildPlugin::initialize(QStringList const& arguments, QString* errorString) { Q_UNUSED(arguments) // Register objects in the plugin manager's object pool // Load settings // Add actions to menus // Connect to other plugins' signals // In the initialize function, a plugin can be sure that the plugins it // depends on have initialized their members. QLatin1String const mimeTypes(":boostbuildproject/BoostBuildProjectManager.mimetypes.xml"); if (!Core::MimeDatabase::addMimeTypes(mimeTypes, errorString)) return false; addAutoReleasedObject(new BuildConfigurationFactory); addAutoReleasedObject(new BuildStepFactory); //TODO addAutoReleasedObject(new RunConfigurationFactory); addAutoReleasedObject(new ProjectManager); return true; } void BoostBuildPlugin::extensionsInitialized() { // Retrieve objects from the plugin manager's object pool // In the extensionsInitialized function, a plugin can be sure that all // plugins that depend on it are completely initialized. } ExtensionSystem::IPlugin::ShutdownFlag BoostBuildPlugin::aboutToShutdown() { // Save settings // Disconnect from signals that are not needed during shutdown // Hide UI (if you add UI that is not in the main window directly) return SynchronousShutdown; } }} <|endoftext|>
<commit_before>/* * FastRPC -- Fast RPC library compatible with XML-RPC * Copyright (C) 2005-7 Seznam.cz, a.s. * * 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 * * Seznam.cz, a.s. * Radlicka 2, Praha 5, 15000, Czech Republic * http://www.seznam.cz, mailto:[email protected] * * FILE $Id: frpcserverproxy.cc,v 1.11 2011-02-18 10:37:45 skeleton-golem Exp $ * * DESCRIPTION * * AUTHOR * Miroslav Talasek <[email protected]> * * HISTORY * */ #include <sstream> #include <memory> #include <stdarg.h> #include "frpcserverproxy.h" #include <frpc.h> #include <frpctreebuilder.h> #include <frpctreefeeder.h> #include <memory> #include <frpcfault.h> #include <frpcresponseerror.h> #include <frpcstruct.h> #include <frpcstring.h> #include <frpcint.h> #include <frpcbool.h> namespace { FRPC::Pool_t localPool; int getTimeout(const FRPC::Struct_t &config, const std::string &name, int defaultValue) { // get key from config and check for existence const FRPC::Value_t *val(config.get(name)); if (!val) return defaultValue; // OK return FRPC::Int(*val); } FRPC::ProtocolVersion_t parseProtocolVersion(const FRPC::Struct_t &config, const std::string &name) { std::string strver (FRPC::String(config.get(name, FRPC::String_t::FRPC_EMPTY))); // empty/undefined => current version if (strver.empty()) return FRPC::ProtocolVersion_t(); // parse input std::istringstream is(strver); int major, minor; is >> major >> minor; // OK return FRPC::ProtocolVersion_t(major, minor); } FRPC::ServerProxy_t::Config_t configFromStruct(const FRPC::Struct_t &s) { FRPC::ServerProxy_t::Config_t config; config.proxyUrl = FRPC::String(s.get("proxyUrl", FRPC::String_t::FRPC_EMPTY)); config.readTimeout = getTimeout(s, "readTimeout", 10000); config.writeTimeout = getTimeout(s, "writeTimeout", 1000); config.useBinary = FRPC::Int(s.get("transferMode", FRPC::Int_t::FRPC_ZERO)); config.useHTTP10 = FRPC::Bool(s.get("useHTTP10", FRPC::Bool_t::FRPC_FALSE)); config.protocolVersion = parseProtocolVersion(s, "protocolVersion"); config.connectTimeout = getTimeout(s, "connectTimeout", 10000); config.keepAlive = FRPC::Bool(s.get("keepAlive", FRPC::Bool_t::FRPC_FALSE)); return config; } } namespace FRPC { class ServerProxyImpl_t { public: ServerProxyImpl_t(const std::string &server, const ServerProxy_t::Config_t &config) : url(server, config.proxyUrl), io(-1, config.readTimeout, config.writeTimeout, -1 ,-1), rpcTransferMode(config.useBinary), useHTTP10(config.useHTTP10), serverSupportedProtocols(HTTPClient_t::XML_RPC), protocolVersion(config.protocolVersion), connector(new SimpleConnectorIPv6_t(url, config.connectTimeout, config.keepAlive)) {} /** Set new read timeout */ void setReadTimeout(int timeout) { io.setReadTimeout(timeout); } /** Set new write timeout */ void setWriteTimeout(int timeout) { io.setWriteTimeout(timeout); } /** Set new connect timeout */ void setConnectTimeout(int timeout) { connector->setTimeout(timeout); } const URL_t& getURL() { return url; } /** Create marshaller. */ Marshaller_t* createMarshaller(HTTPClient_t &client); /** Call method. */ Value_t& call(Pool_t &pool, const std::string &methodName, const Array_t &params); void call(DataBuilder_t &builder, const std::string &methodName, const Array_t &params); /** Call method with variable number of arguments. */ Value_t& call(Pool_t &pool, const char *methodName, va_list args); private: URL_t url; HTTPIO_t io; unsigned int rpcTransferMode; bool useHTTP10; unsigned int serverSupportedProtocols; ProtocolVersion_t protocolVersion; std::auto_ptr<Connector_t> connector; }; Marshaller_t* ServerProxyImpl_t::createMarshaller(HTTPClient_t &client) { Marshaller_t *marshaller; switch (rpcTransferMode) { case ServerProxy_t::Config_t::ON_SUPPORT: { if (serverSupportedProtocols & HTTPClient_t::BINARY_RPC) { //using BINARY_RPC marshaller= Marshaller_t::create(Marshaller_t::BINARY_RPC, client,protocolVersion); client.prepare(HTTPClient_t::BINARY_RPC); } else { //using XML_RPC marshaller = Marshaller_t::create (Marshaller_t::XML_RPC,client, protocolVersion); client.prepare(HTTPClient_t::XML_RPC); } } break; case ServerProxy_t::Config_t::NEVER: { // never using BINARY_RPC marshaller= Marshaller_t::create(Marshaller_t::XML_RPC, client,protocolVersion); client.prepare(HTTPClient_t::XML_RPC); } break; case ServerProxy_t::Config_t::ALWAYS: { //using BINARY_RPC always marshaller= Marshaller_t::create(Marshaller_t::BINARY_RPC, client,protocolVersion); client.prepare(HTTPClient_t::BINARY_RPC); } break; case ServerProxy_t::Config_t::ON_SUPPORT_ON_KEEP_ALIVE: default: { if ((serverSupportedProtocols & HTTPClient_t::XML_RPC) || connector->getKeepAlive() == false || io.socket() != -1) { //using XML_RPC marshaller= Marshaller_t::create (Marshaller_t::XML_RPC,client, protocolVersion); client.prepare(HTTPClient_t::XML_RPC); } else { //using BINARY_RPC marshaller= Marshaller_t::create (Marshaller_t::BINARY_RPC, client,protocolVersion); client.prepare(HTTPClient_t::BINARY_RPC); } } break; } // OK return marshaller; } ServerProxy_t::ServerProxy_t(const std::string &server, const Config_t &config) : sp(new ServerProxyImpl_t(server, config)) {} ServerProxy_t::ServerProxy_t(const std::string &server, const Struct_t &config) : sp(new ServerProxyImpl_t(server, configFromStruct(config))) {} ServerProxy_t::~ServerProxy_t() { // get rid of implementation } Value_t& ServerProxyImpl_t::call(Pool_t &pool, const std::string &methodName, const Array_t &params) { HTTPClient_t client(io, url, connector.get(), useHTTP10); TreeBuilder_t builder(pool); std::auto_ptr<Marshaller_t>marshaller(createMarshaller(client)); TreeFeeder_t feeder(*marshaller); try { marshaller->packMethodCall(methodName.c_str()); for (Array_t::const_iterator iparams = params.begin(), eparams = params.end(); iparams != eparams; ++iparams) { feeder.feedValue(**iparams); } marshaller->flush(); } catch (const ResponseError_t &e) {} client.readResponse(builder); serverSupportedProtocols = client.getSupportedProtocols(); protocolVersion = client.getProtocolVersion(); if (&(builder.getUnMarshaledData()) == 0) throw Fault_t(builder.getUnMarshaledErrorNumber(), builder.getUnMarshaledErrorMessage()); // OK, return unmarshalled data return builder.getUnMarshaledData(); } void ServerProxyImpl_t::call(DataBuilder_t &builder, const std::string &methodName, const Array_t &params) { HTTPClient_t client(io, url, connector.get(), useHTTP10); std::auto_ptr<Marshaller_t>marshaller(createMarshaller(client)); TreeFeeder_t feeder(*marshaller); try { marshaller->packMethodCall(methodName.c_str()); for (Array_t::const_iterator iparams = params.begin(), eparams = params.end(); iparams != eparams; ++iparams) { feeder.feedValue(**iparams); } marshaller->flush(); } catch (const ResponseError_t &e) {} client.readResponse(builder); serverSupportedProtocols = client.getSupportedProtocols(); protocolVersion = client.getProtocolVersion(); } Value_t& ServerProxy_t::call(Pool_t &pool, const std::string &methodName, const Array_t &params) { return sp->call(pool, methodName, params); } Value_t& ServerProxyImpl_t::call(Pool_t &pool, const char *methodName, va_list args) { HTTPClient_t client(io, url, connector.get(), useHTTP10); TreeBuilder_t builder(pool); std::auto_ptr<Marshaller_t>marshaller(createMarshaller(client)); TreeFeeder_t feeder(*marshaller); try { marshaller->packMethodCall(methodName); // marshall all passed values until null pointer while (const Value_t *value = va_arg(args, Value_t*)) feeder.feedValue(*value); marshaller->flush(); } catch (const ResponseError_t &e) {} client.readResponse(builder); serverSupportedProtocols = client.getSupportedProtocols(); protocolVersion = client.getProtocolVersion(); if(&(builder.getUnMarshaledData()) == 0) throw Fault_t(builder.getUnMarshaledErrorNumber(), builder.getUnMarshaledErrorMessage()); // OK, return unmarshalled data return builder.getUnMarshaledData(); } namespace { /** Hold va_list and destroy it (via va_end) on destruction. */ struct VaListHolder_t { VaListHolder_t(va_list &args) : args(args) {} ~VaListHolder_t() { va_end(args); } va_list &args; }; } Value_t& ServerProxy_t::call(Pool_t &pool, const char *methodName, ...) { // get variadic arguments va_list args; va_start(args, methodName); VaListHolder_t argsHolder(args); // use implementation return sp->call(pool, methodName, args); } void ServerProxy_t::call(DataBuilder_t &builder, const std::string &methodName, const Array_t &params) { sp->call(builder, methodName, params); } void ServerProxy_t::setReadTimeout(int timeout) { sp->setReadTimeout(timeout); } void ServerProxy_t::setWriteTimeout(int timeout) { sp->setWriteTimeout(timeout); } void ServerProxy_t::setConnectTimeout(int timeout) { sp->setConnectTimeout(timeout); } const URL_t& ServerProxy_t::getURL() { return sp->getURL(); } } // namespace FRPC <commit_msg>ServerProxy_t supports unix:// schema<commit_after>/* * FastRPC -- Fast RPC library compatible with XML-RPC * Copyright (C) 2005-7 Seznam.cz, a.s. * * 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 * * Seznam.cz, a.s. * Radlicka 2, Praha 5, 15000, Czech Republic * http://www.seznam.cz, mailto:[email protected] * * FILE $Id: frpcserverproxy.cc,v 1.11 2011-02-18 10:37:45 skeleton-golem Exp $ * * DESCRIPTION * * AUTHOR * Miroslav Talasek <[email protected]> * * HISTORY * */ #include <sstream> #include <memory> #include <stdarg.h> #include "frpcserverproxy.h" #include <frpc.h> #include <frpctreebuilder.h> #include <frpctreefeeder.h> #include <memory> #include <frpcfault.h> #include <frpcresponseerror.h> #include <frpcstruct.h> #include <frpcstring.h> #include <frpcint.h> #include <frpcbool.h> namespace { FRPC::Pool_t localPool; int getTimeout(const FRPC::Struct_t &config, const std::string &name, int defaultValue) { // get key from config and check for existence const FRPC::Value_t *val(config.get(name)); if (!val) return defaultValue; // OK return FRPC::Int(*val); } FRPC::ProtocolVersion_t parseProtocolVersion(const FRPC::Struct_t &config, const std::string &name) { std::string strver (FRPC::String(config.get(name, FRPC::String_t::FRPC_EMPTY))); // empty/undefined => current version if (strver.empty()) return FRPC::ProtocolVersion_t(); // parse input std::istringstream is(strver); int major, minor; is >> major >> minor; // OK return FRPC::ProtocolVersion_t(major, minor); } FRPC::ServerProxy_t::Config_t configFromStruct(const FRPC::Struct_t &s) { FRPC::ServerProxy_t::Config_t config; config.proxyUrl = FRPC::String(s.get("proxyUrl", FRPC::String_t::FRPC_EMPTY)); config.readTimeout = getTimeout(s, "readTimeout", 10000); config.writeTimeout = getTimeout(s, "writeTimeout", 1000); config.useBinary = FRPC::Int(s.get("transferMode", FRPC::Int_t::FRPC_ZERO)); config.useHTTP10 = FRPC::Bool(s.get("useHTTP10", FRPC::Bool_t::FRPC_FALSE)); config.protocolVersion = parseProtocolVersion(s, "protocolVersion"); config.connectTimeout = getTimeout(s, "connectTimeout", 10000); config.keepAlive = FRPC::Bool(s.get("keepAlive", FRPC::Bool_t::FRPC_FALSE)); return config; } FRPC::Connector_t* makeConnector( const FRPC::URL_t &url, const unsigned &connectTimeout, const bool &keepAlive) { if (url.isUnix()) { return new FRPC::SimpleConnectorUnix_t( url, connectTimeout, keepAlive); } return new FRPC::SimpleConnectorIPv6_t(url, connectTimeout, keepAlive); } } namespace FRPC { class ServerProxyImpl_t { public: ServerProxyImpl_t(const std::string &server, const ServerProxy_t::Config_t &config) : url(server, config.proxyUrl), io(-1, config.readTimeout, config.writeTimeout, -1 ,-1), rpcTransferMode(config.useBinary), useHTTP10(config.useHTTP10), serverSupportedProtocols(HTTPClient_t::XML_RPC), protocolVersion(config.protocolVersion), connector(makeConnector(url, config.connectTimeout, config.keepAlive)) {} /** Set new read timeout */ void setReadTimeout(int timeout) { io.setReadTimeout(timeout); } /** Set new write timeout */ void setWriteTimeout(int timeout) { io.setWriteTimeout(timeout); } /** Set new connect timeout */ void setConnectTimeout(int timeout) { connector->setTimeout(timeout); } const URL_t& getURL() { return url; } /** Create marshaller. */ Marshaller_t* createMarshaller(HTTPClient_t &client); /** Call method. */ Value_t& call(Pool_t &pool, const std::string &methodName, const Array_t &params); void call(DataBuilder_t &builder, const std::string &methodName, const Array_t &params); /** Call method with variable number of arguments. */ Value_t& call(Pool_t &pool, const char *methodName, va_list args); private: URL_t url; HTTPIO_t io; unsigned int rpcTransferMode; bool useHTTP10; unsigned int serverSupportedProtocols; ProtocolVersion_t protocolVersion; std::auto_ptr<Connector_t> connector; }; Marshaller_t* ServerProxyImpl_t::createMarshaller(HTTPClient_t &client) { Marshaller_t *marshaller; switch (rpcTransferMode) { case ServerProxy_t::Config_t::ON_SUPPORT: { if (serverSupportedProtocols & HTTPClient_t::BINARY_RPC) { //using BINARY_RPC marshaller= Marshaller_t::create(Marshaller_t::BINARY_RPC, client,protocolVersion); client.prepare(HTTPClient_t::BINARY_RPC); } else { //using XML_RPC marshaller = Marshaller_t::create (Marshaller_t::XML_RPC,client, protocolVersion); client.prepare(HTTPClient_t::XML_RPC); } } break; case ServerProxy_t::Config_t::NEVER: { // never using BINARY_RPC marshaller= Marshaller_t::create(Marshaller_t::XML_RPC, client,protocolVersion); client.prepare(HTTPClient_t::XML_RPC); } break; case ServerProxy_t::Config_t::ALWAYS: { //using BINARY_RPC always marshaller= Marshaller_t::create(Marshaller_t::BINARY_RPC, client,protocolVersion); client.prepare(HTTPClient_t::BINARY_RPC); } break; case ServerProxy_t::Config_t::ON_SUPPORT_ON_KEEP_ALIVE: default: { if ((serverSupportedProtocols & HTTPClient_t::XML_RPC) || connector->getKeepAlive() == false || io.socket() != -1) { //using XML_RPC marshaller= Marshaller_t::create (Marshaller_t::XML_RPC,client, protocolVersion); client.prepare(HTTPClient_t::XML_RPC); } else { //using BINARY_RPC marshaller= Marshaller_t::create (Marshaller_t::BINARY_RPC, client,protocolVersion); client.prepare(HTTPClient_t::BINARY_RPC); } } break; } // OK return marshaller; } ServerProxy_t::ServerProxy_t(const std::string &server, const Config_t &config) : sp(new ServerProxyImpl_t(server, config)) {} ServerProxy_t::ServerProxy_t(const std::string &server, const Struct_t &config) : sp(new ServerProxyImpl_t(server, configFromStruct(config))) {} ServerProxy_t::~ServerProxy_t() { // get rid of implementation } Value_t& ServerProxyImpl_t::call(Pool_t &pool, const std::string &methodName, const Array_t &params) { HTTPClient_t client(io, url, connector.get(), useHTTP10); TreeBuilder_t builder(pool); std::auto_ptr<Marshaller_t>marshaller(createMarshaller(client)); TreeFeeder_t feeder(*marshaller); try { marshaller->packMethodCall(methodName.c_str()); for (Array_t::const_iterator iparams = params.begin(), eparams = params.end(); iparams != eparams; ++iparams) { feeder.feedValue(**iparams); } marshaller->flush(); } catch (const ResponseError_t &e) {} client.readResponse(builder); serverSupportedProtocols = client.getSupportedProtocols(); protocolVersion = client.getProtocolVersion(); if (&(builder.getUnMarshaledData()) == 0) throw Fault_t(builder.getUnMarshaledErrorNumber(), builder.getUnMarshaledErrorMessage()); // OK, return unmarshalled data return builder.getUnMarshaledData(); } void ServerProxyImpl_t::call(DataBuilder_t &builder, const std::string &methodName, const Array_t &params) { HTTPClient_t client(io, url, connector.get(), useHTTP10); std::auto_ptr<Marshaller_t>marshaller(createMarshaller(client)); TreeFeeder_t feeder(*marshaller); try { marshaller->packMethodCall(methodName.c_str()); for (Array_t::const_iterator iparams = params.begin(), eparams = params.end(); iparams != eparams; ++iparams) { feeder.feedValue(**iparams); } marshaller->flush(); } catch (const ResponseError_t &e) {} client.readResponse(builder); serverSupportedProtocols = client.getSupportedProtocols(); protocolVersion = client.getProtocolVersion(); } Value_t& ServerProxy_t::call(Pool_t &pool, const std::string &methodName, const Array_t &params) { return sp->call(pool, methodName, params); } Value_t& ServerProxyImpl_t::call(Pool_t &pool, const char *methodName, va_list args) { HTTPClient_t client(io, url, connector.get(), useHTTP10); TreeBuilder_t builder(pool); std::auto_ptr<Marshaller_t>marshaller(createMarshaller(client)); TreeFeeder_t feeder(*marshaller); try { marshaller->packMethodCall(methodName); // marshall all passed values until null pointer while (const Value_t *value = va_arg(args, Value_t*)) feeder.feedValue(*value); marshaller->flush(); } catch (const ResponseError_t &e) {} client.readResponse(builder); serverSupportedProtocols = client.getSupportedProtocols(); protocolVersion = client.getProtocolVersion(); if(&(builder.getUnMarshaledData()) == 0) throw Fault_t(builder.getUnMarshaledErrorNumber(), builder.getUnMarshaledErrorMessage()); // OK, return unmarshalled data return builder.getUnMarshaledData(); } namespace { /** Hold va_list and destroy it (via va_end) on destruction. */ struct VaListHolder_t { VaListHolder_t(va_list &args) : args(args) {} ~VaListHolder_t() { va_end(args); } va_list &args; }; } Value_t& ServerProxy_t::call(Pool_t &pool, const char *methodName, ...) { // get variadic arguments va_list args; va_start(args, methodName); VaListHolder_t argsHolder(args); // use implementation return sp->call(pool, methodName, args); } void ServerProxy_t::call(DataBuilder_t &builder, const std::string &methodName, const Array_t &params) { sp->call(builder, methodName, params); } void ServerProxy_t::setReadTimeout(int timeout) { sp->setReadTimeout(timeout); } void ServerProxy_t::setWriteTimeout(int timeout) { sp->setWriteTimeout(timeout); } void ServerProxy_t::setConnectTimeout(int timeout) { sp->setConnectTimeout(timeout); } const URL_t& ServerProxy_t::getURL() { return sp->getURL(); } } // namespace FRPC <|endoftext|>
<commit_before><commit_msg>refactored code to select reference camera<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AGroup.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: vg $ $Date: 2007-03-26 13:56:48 $ * * 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_connectivity.hxx" #ifndef _CONNECTIVITY_ADO_GROUP_HXX_ #include "ado/AGroup.hxx" #endif #ifndef _CONNECTIVITY_ADO_USERS_HXX_ #include "ado/AUsers.hxx" #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_ #include "ado/AConnection.hxx" #endif #ifndef CONNECTIVITY_CONNECTION_HXX #include "TConnection.hxx" #endif using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace com::sun::star::sdbcx; // ------------------------------------------------------------------------- void WpADOGroup::Create() { HRESULT hr = -1; ADOGroup* pGroup = NULL; hr = CoCreateInstance(ADOS::CLSID_ADOGROUP_25, NULL, CLSCTX_INPROC_SERVER, ADOS::IID_ADOGROUP_25, (void**)&pGroup ); if( !FAILED( hr ) ) { operator=( pGroup ); pGroup->Release(); } } // ------------------------------------------------------------------------- OAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, ADOGroup* _pGroup) : OGroup_ADO(_bCase),m_pCatalog(_pParent) { construct(); if(_pGroup) m_aGroup = WpADOGroup(_pGroup); else m_aGroup.Create(); } // ------------------------------------------------------------------------- OAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, const ::rtl::OUString& _Name) : OGroup_ADO(_Name,_bCase),m_pCatalog(_pParent) { construct(); m_aGroup.Create(); m_aGroup.put_Name(_Name); } // ------------------------------------------------------------------------- void OAdoGroup::refreshUsers() { TStringVector aVector; WpADOUsers aUsers = m_aGroup.get_Users(); aUsers.fillElementNames(aVector); if(m_pUsers) m_pUsers->reFill(aVector); else m_pUsers = new OUsers(m_pCatalog,m_aMutex,aVector,aUsers,isCaseSensitive()); } //-------------------------------------------------------------------------- Sequence< sal_Int8 > OAdoGroup::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OAdoGroup::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OGroup_ADO::getSomething(rId); } // ------------------------------------------------------------------------- void OAdoGroup::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception) { if(m_aGroup.IsValid()) { switch(nHandle) { case PROPERTY_ID_NAME: { ::rtl::OUString aVal; rValue >>= aVal; m_aGroup.put_Name(aVal); } break; } } } // ------------------------------------------------------------------------- void OAdoGroup::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const { if(m_aGroup.IsValid()) { switch(nHandle) { case PROPERTY_ID_NAME: rValue <<= m_aGroup.get_Name(); break; } } } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OAdoGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException) { return MapRight(m_aGroup.GetPermissions(objName,MapObjectType(objType))); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OAdoGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException) { RightsEnum eNum = m_aGroup.GetPermissions(objName,MapObjectType(objType)); if(eNum & adRightWithGrant) return MapRight(eNum); return 0; } // ------------------------------------------------------------------------- void SAL_CALL OAdoGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException) { m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessGrant,Map2Right(objPrivileges)); } // ------------------------------------------------------------------------- void SAL_CALL OAdoGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException) { m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessDeny,Map2Right(objPrivileges)); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoGroup::acquire() throw() { OGroup_ADO::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoGroup::release() throw() { OGroup_ADO::release(); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS changefileheader (1.19.144); FILE MERGED 2008/04/01 15:08:35 thb 1.19.144.3: #i85898# Stripping all external header guards 2008/04/01 10:52:49 thb 1.19.144.2: #i85898# Stripping all external header guards 2008/03/28 15:23:26 rt 1.19.144.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: AGroup.cxx,v $ * $Revision: 1.20 $ * * 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_connectivity.hxx" #ifndef _CONNECTIVITY_ADO_GROUP_HXX_ #include "ado/AGroup.hxx" #endif #include "ado/AUsers.hxx" #include <cppuhelper/typeprovider.hxx> #include <comphelper/sequence.hxx> #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_ #include "ado/AConnection.hxx" #endif #include "TConnection.hxx" using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace com::sun::star::sdbcx; // ------------------------------------------------------------------------- void WpADOGroup::Create() { HRESULT hr = -1; ADOGroup* pGroup = NULL; hr = CoCreateInstance(ADOS::CLSID_ADOGROUP_25, NULL, CLSCTX_INPROC_SERVER, ADOS::IID_ADOGROUP_25, (void**)&pGroup ); if( !FAILED( hr ) ) { operator=( pGroup ); pGroup->Release(); } } // ------------------------------------------------------------------------- OAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, ADOGroup* _pGroup) : OGroup_ADO(_bCase),m_pCatalog(_pParent) { construct(); if(_pGroup) m_aGroup = WpADOGroup(_pGroup); else m_aGroup.Create(); } // ------------------------------------------------------------------------- OAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, const ::rtl::OUString& _Name) : OGroup_ADO(_Name,_bCase),m_pCatalog(_pParent) { construct(); m_aGroup.Create(); m_aGroup.put_Name(_Name); } // ------------------------------------------------------------------------- void OAdoGroup::refreshUsers() { TStringVector aVector; WpADOUsers aUsers = m_aGroup.get_Users(); aUsers.fillElementNames(aVector); if(m_pUsers) m_pUsers->reFill(aVector); else m_pUsers = new OUsers(m_pCatalog,m_aMutex,aVector,aUsers,isCaseSensitive()); } //-------------------------------------------------------------------------- Sequence< sal_Int8 > OAdoGroup::getUnoTunnelImplementationId() { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } // com::sun::star::lang::XUnoTunnel //------------------------------------------------------------------ sal_Int64 OAdoGroup::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException) { return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) ) ? reinterpret_cast< sal_Int64 >( this ) : OGroup_ADO::getSomething(rId); } // ------------------------------------------------------------------------- void OAdoGroup::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception) { if(m_aGroup.IsValid()) { switch(nHandle) { case PROPERTY_ID_NAME: { ::rtl::OUString aVal; rValue >>= aVal; m_aGroup.put_Name(aVal); } break; } } } // ------------------------------------------------------------------------- void OAdoGroup::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const { if(m_aGroup.IsValid()) { switch(nHandle) { case PROPERTY_ID_NAME: rValue <<= m_aGroup.get_Name(); break; } } } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OAdoGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException) { return MapRight(m_aGroup.GetPermissions(objName,MapObjectType(objType))); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OAdoGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException) { RightsEnum eNum = m_aGroup.GetPermissions(objName,MapObjectType(objType)); if(eNum & adRightWithGrant) return MapRight(eNum); return 0; } // ------------------------------------------------------------------------- void SAL_CALL OAdoGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException) { m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessGrant,Map2Right(objPrivileges)); } // ------------------------------------------------------------------------- void SAL_CALL OAdoGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException) { m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessDeny,Map2Right(objPrivileges)); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoGroup::acquire() throw() { OGroup_ADO::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL OAdoGroup::release() throw() { OGroup_ADO::release(); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS impress2 (1.1.2); FILE ADDED 2004/02/13 12:14:08 af 1.1.2.1: #i22705# Initial revision.<commit_after><|endoftext|>
<commit_before><commit_msg>integration-quickbrown-casemapping: Added tests for Hungarian strings.<commit_after><|endoftext|>
<commit_before><commit_msg>Prediction: use simple-version of move_sequence_predictor<commit_after><|endoftext|>
<commit_before>// 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 __STOUT_WINDOWS_OS_HPP__ #define __STOUT_WINDOWS_OS_HPP__ #include <direct.h> #include <io.h> #include <sys/utime.h> #include <list> #include <map> #include <set> #include <string> #include <stout/duration.hpp> #include <stout/none.hpp> #include <stout/nothing.hpp> #include <stout/option.hpp> #include <stout/path.hpp> #include <stout/try.hpp> #include <stout/windows.hpp> #include <stout/os/raw/environment.hpp> namespace os { /* // Sets the value associated with the specified key in the set of // environment variables. inline void setenv(const std::string& key, const std::string& value, bool overwrite = true) { UNIMPLEMENTED; } // Unsets the value associated with the specified key in the set of // environment variables. inline void unsetenv(const std::string& key) { UNIMPLEMENTED; } // Executes a command by calling "/bin/sh -c <command>", and returns // after the command has been completed. Returns 0 if succeeds, and // return -1 on error (e.g., fork/exec/waitpid failed). This function // is async signal safe. We return int instead of returning a Try // because Try involves 'new', which is not async signal safe. inline int system(const std::string& command) { UNIMPLEMENTED; } // This function is a portable version of execvpe ('p' means searching // executable from PATH and 'e' means setting environments). We add // this function because it is not available on all systems. // // NOTE: This function is not thread safe. It is supposed to be used // only after fork (when there is only one thread). This function is // async signal safe. inline int execvpe(const char* file, char** argv, char** envp) { UNIMPLEMENTED; } inline Try<Nothing> chown( uid_t uid, gid_t gid, const std::string& path, bool recursive) { UNIMPLEMENTED; } inline Try<Nothing> chmod(const std::string& path, int mode) { UNIMPLEMENTED; } inline Try<Nothing> chroot(const std::string& directory) { UNIMPLEMENTED; } inline Try<Nothing> mknod( const std::string& path, mode_t mode, dev_t dev) { UNIMPLEMENTED; } inline Result<uid_t> getuid(const Option<std::string>& user = None()) { UNIMPLEMENTED; } inline Result<gid_t> getgid(const Option<std::string>& user = None()) { UNIMPLEMENTED; } inline Try<Nothing> su(const std::string& user) { UNIMPLEMENTED; } inline Result<std::string> user(Option<uid_t> uid = None()) { UNIMPLEMENTED; } // Suspends execution for the given duration. inline Try<Nothing> sleep(const Duration& duration) { UNIMPLEMENTED; } // Returns the list of files that match the given (shell) pattern. inline Try<std::list<std::string>> glob(const std::string& pattern) { UNIMPLEMENTED; } // Returns the total number of cpus (cores). inline Try<long> cpus() { UNIMPLEMENTED; } // Returns load struct with average system loads for the last // 1, 5 and 15 minutes respectively. // Load values should be interpreted as usual average loads from // uptime(1). inline Try<Load> loadavg() { UNIMPLEMENTED; } // Returns the total size of main and free memory. inline Try<Memory> memory() { UNIMPLEMENTED; } // Return the system information. inline Try<UTSInfo> uname() { UNIMPLEMENTED; } inline Try<std::list<Process>> processes() { UNIMPLEMENTED; } // Overload of os::pids for filtering by groups and sessions. // A group / session id of 0 will fitler on the group / session ID // of the calling process. inline Try<std::set<pid_t>> pids(Option<pid_t> group, Option<pid_t> session) { UNIMPLEMENTED; } */ } // namespace os { #endif // __STOUT_WINDOWS_OS_HPP__ <commit_msg>Windows: Added `stout/os/read.hpp` include to `windows/os.hpp`.<commit_after>// 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 __STOUT_WINDOWS_OS_HPP__ #define __STOUT_WINDOWS_OS_HPP__ #include <direct.h> #include <io.h> #include <sys/utime.h> #include <list> #include <map> #include <set> #include <string> #include <stout/duration.hpp> #include <stout/none.hpp> #include <stout/nothing.hpp> #include <stout/option.hpp> #include <stout/path.hpp> #include <stout/try.hpp> #include <stout/windows.hpp> #include <stout/os/os.hpp> #include <stout/os/read.hpp> #include <stout/os/raw/environment.hpp> namespace os { /* // Sets the value associated with the specified key in the set of // environment variables. inline void setenv(const std::string& key, const std::string& value, bool overwrite = true) { UNIMPLEMENTED; } // Unsets the value associated with the specified key in the set of // environment variables. inline void unsetenv(const std::string& key) { UNIMPLEMENTED; } // Executes a command by calling "/bin/sh -c <command>", and returns // after the command has been completed. Returns 0 if succeeds, and // return -1 on error (e.g., fork/exec/waitpid failed). This function // is async signal safe. We return int instead of returning a Try // because Try involves 'new', which is not async signal safe. inline int system(const std::string& command) { UNIMPLEMENTED; } // This function is a portable version of execvpe ('p' means searching // executable from PATH and 'e' means setting environments). We add // this function because it is not available on all systems. // // NOTE: This function is not thread safe. It is supposed to be used // only after fork (when there is only one thread). This function is // async signal safe. inline int execvpe(const char* file, char** argv, char** envp) { UNIMPLEMENTED; } inline Try<Nothing> chown( uid_t uid, gid_t gid, const std::string& path, bool recursive) { UNIMPLEMENTED; } inline Try<Nothing> chmod(const std::string& path, int mode) { UNIMPLEMENTED; } inline Try<Nothing> chroot(const std::string& directory) { UNIMPLEMENTED; } inline Try<Nothing> mknod( const std::string& path, mode_t mode, dev_t dev) { UNIMPLEMENTED; } inline Result<uid_t> getuid(const Option<std::string>& user = None()) { UNIMPLEMENTED; } inline Result<gid_t> getgid(const Option<std::string>& user = None()) { UNIMPLEMENTED; } inline Try<Nothing> su(const std::string& user) { UNIMPLEMENTED; } inline Result<std::string> user(Option<uid_t> uid = None()) { UNIMPLEMENTED; } // Suspends execution for the given duration. inline Try<Nothing> sleep(const Duration& duration) { UNIMPLEMENTED; } // Returns the list of files that match the given (shell) pattern. inline Try<std::list<std::string>> glob(const std::string& pattern) { UNIMPLEMENTED; } // Returns the total number of cpus (cores). inline Try<long> cpus() { UNIMPLEMENTED; } // Returns load struct with average system loads for the last // 1, 5 and 15 minutes respectively. // Load values should be interpreted as usual average loads from // uptime(1). inline Try<Load> loadavg() { UNIMPLEMENTED; } // Returns the total size of main and free memory. inline Try<Memory> memory() { UNIMPLEMENTED; } // Return the system information. inline Try<UTSInfo> uname() { UNIMPLEMENTED; } inline Try<std::list<Process>> processes() { UNIMPLEMENTED; } // Overload of os::pids for filtering by groups and sessions. // A group / session id of 0 will fitler on the group / session ID // of the calling process. inline Try<std::set<pid_t>> pids(Option<pid_t> group, Option<pid_t> session) { UNIMPLEMENTED; } */ } // namespace os { #endif // __STOUT_WINDOWS_OS_HPP__ <|endoftext|>
<commit_before>/** \file map_ddc_and_rvk_to_ixtheo_notations.cc * \brief Map certain DDC and RVK categories to ixTheo notations and add them to field 652a. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2015, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <iterator> #include <memory> #include <unordered_map> #include <cctype> #include <cstdlib> #include "MarcUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " [--verbose] marc_input marc_output ddc_to_ixtheo_notations_map " << "rvk_to_ixtheo_notations_map\n"; std::exit(EXIT_FAILURE); } /** \class IxTheoMapper * \brief Maps from a DDC or RVK hierarchy entry to an IxTheo notation. */ class IxTheoMapper { std::string from_hierarchy_; std::string to_ix_theo_notation_; std::vector<std::string> exclusions_; public: explicit IxTheoMapper(const std::vector<std::string> &map_file_line); /** \brief Returns an IxTheo notation if we can match "hierarchy_classification". O/w we return the empty string. */ std::string map(const std::string &hierarchy_classification) const; }; IxTheoMapper::IxTheoMapper(const std::vector<std::string> &map_file_line) { if (map_file_line.size() < 2) throw std::runtime_error("in IxTheoMapper::IxTheoMapper: need at least 2 elements in \"map_file_line\"!"); from_hierarchy_ = map_file_line[0]; to_ix_theo_notation_ = map_file_line[1]; std::copy(map_file_line.begin() + 2, map_file_line.end(), std::back_inserter(exclusions_)); } std::string IxTheoMapper::map(const std::string &hierarchy_classification) const { if (not StringUtil::StartsWith(hierarchy_classification, from_hierarchy_)) return ""; for (const auto &exclusion : exclusions_) { if (StringUtil::StartsWith(hierarchy_classification, exclusion)) return ""; } return to_ix_theo_notation_; } void LoadCSVFile(const bool verbose, const std::string &filename, std::vector<IxTheoMapper> * const mappers) { DSVReader csv_reader(filename); std::vector<std::string> csv_values; while (csv_reader.readLine(&csv_values)) mappers->emplace_back(csv_values); if (verbose) std::cerr << "Read " << mappers->size() << " mappings from \"" << filename << "\".\n"; } void UpdateIxTheoNotations(const std::vector<IxTheoMapper> &mappers, const std::vector<std::string> &orig_values, std::string * const ixtheo_notations_list) { std::vector<std::string> ixtheo_notations_vector; StringUtil::Split(*ixtheo_notations_list, ':', &ixtheo_notations_vector); std::set<std::string> previously_assigned_notations(std::make_move_iterator(ixtheo_notations_vector.begin()), std::make_move_iterator(ixtheo_notations_vector.end())); for (const auto &mapper : mappers) { for (const auto &orig_value : orig_values) { const std::string mapped_value(mapper.map(orig_value)); if (not mapped_value.empty() and previously_assigned_notations.find(mapped_value) == previously_assigned_notations.end()) { if (not ixtheo_notations_list->empty()) *ixtheo_notations_list += ':'; *ixtheo_notations_list += mapped_value; previously_assigned_notations.insert(mapped_value); } } } } void ProcessRecords(const bool verbose, const std::shared_ptr<FILE> &input, const std::shared_ptr<FILE> &output, const std::vector<IxTheoMapper> &ddc_to_ixtheo_notation_mappers, const std::vector<IxTheoMapper> &/*rvk_to_ixtheo_notation_mappers*/) { unsigned count(0), records_with_ixtheo_notations(0), records_with_new_notations(0), skipped_group_count(0); while (MarcUtil::Record record = MarcUtil::Record(input.get())) { ++count; const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); if (dir_entries[0].getTag() != "001") Error("First field is not \"001\"!"); std::string ixtheo_notations_list(record.extractFirstSubfield("652", 'a')); if (not ixtheo_notations_list.empty()) { ++records_with_ixtheo_notations; record.write(output.get()); continue; } std::vector<std::string> ddc_values; if (record.extractSubfield("082", 'a', &ddc_values) == 0) { record.write(output.get()); continue; } if (std::find(ddc_values.cbegin(), ddc_values.cend(), "K") != ddc_values.cend() or std::find(ddc_values.cbegin(), ddc_values.cend(), "B") != ddc_values.cend()) { ++skipped_group_count; continue; } // Many DDCs have superfluous backslashes which are non-standard and need to be removed before further // processing can take place: for (auto &ddc_value : ddc_values) StringUtil::RemoveChars("/", &ddc_value); UpdateIxTheoNotations(ddc_to_ixtheo_notation_mappers, ddc_values, &ixtheo_notations_list); if (verbose and not ixtheo_notations_list.empty()) { const std::vector<std::string> &fields(record.getFields()); std::cout << fields[0] << ": " << StringUtil::Join(ddc_values, ',') << " -> " << ixtheo_notations_list << '\n'; } /* std::vector<std::string> rvk_values; int _084_index(record.getFieldIndex("084")); if (_084_index != -1) { const std::vector<std::string> &fields(record.getFields()); while (_084_index < static_cast<ssize_t>(dir_entries.size()) and dir_entries[_084_index].getTag() == "084") { const Subfields subfields(fields[_084_index]); if (subfields.hasSubfieldWithValue('2', "rvk")) rvk_values.emplace_back(subfields.getFirstSubfieldValue('a')); ++_084_index; } } UpdateIxTheoNotations(rvk_to_ixtheo_notation_mappers, rvk_values, &ixtheo_notations_list); */ if (not ixtheo_notations_list.empty()) { ++records_with_new_notations; record.insertField("652", " ""\x1F""a" + ixtheo_notations_list); } record.write(output.get()); } if (verbose) { std::cerr << "Read " << count << " records.\n"; std::cerr << records_with_ixtheo_notations << " records had Ixtheo notations.\n"; std::cerr << records_with_new_notations << " records received new Ixtheo notations.\n"; std::cerr << skipped_group_count << " records where skipped because they were in a group that we are not interested in.\n"; } } int main(int argc, char **argv) { progname = argv[0]; if (argc != 5 and argc != 6) Usage(); bool verbose(false); if (argc == 6) { if (std::strcmp(argv[1], "--verbose") != 0) Usage(); verbose = true; } const std::string marc_input_filename(argv[verbose ? 2 : 1]); std::shared_ptr<FILE> marc_input(std::fopen(marc_input_filename.c_str(), "rbm"), std::fclose); if (marc_input == nullptr) Error("can't open \"" + marc_input_filename + "\" for reading!"); const std::string marc_output_filename(argv[verbose ? 3 : 2]); std::shared_ptr<FILE> marc_output(std::fopen(marc_output_filename.c_str(), "wb"), std::fclose); if (marc_output == nullptr) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { std::vector<IxTheoMapper> ddc_to_ixtheo_notation_mappers; LoadCSVFile(verbose, argv[verbose ? 4 : 3], &ddc_to_ixtheo_notation_mappers); std::vector<IxTheoMapper> rvk_to_ixtheo_notation_mappers; // LoadCSVFile(verbose, argv[verbose ? 5 : 4], &rvk_to_ixtheo_notation_mappers); ProcessRecords(verbose, marc_input, marc_output, ddc_to_ixtheo_notation_mappers, rvk_to_ixtheo_notation_mappers); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Added a comment.<commit_after>/** \file map_ddc_and_rvk_to_ixtheo_notations.cc * \brief Map certain DDC and RVK categories to ixTheo notations and add them to field 652a. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2015, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <iterator> #include <memory> #include <unordered_map> #include <cctype> #include <cstdlib> #include "MarcUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" void Usage() { std::cerr << "Usage: " << progname << " [--verbose] marc_input marc_output ddc_to_ixtheo_notations_map " << "rvk_to_ixtheo_notations_map\n"; std::exit(EXIT_FAILURE); } /** \class IxTheoMapper * \brief Maps from a DDC or RVK hierarchy entry to an IxTheo notation. */ class IxTheoMapper { std::string from_hierarchy_; std::string to_ix_theo_notation_; std::vector<std::string> exclusions_; public: explicit IxTheoMapper(const std::vector<std::string> &map_file_line); /** \brief Returns an IxTheo notation if we can match "hierarchy_classification". O/w we return the empty string. */ std::string map(const std::string &hierarchy_classification) const; }; IxTheoMapper::IxTheoMapper(const std::vector<std::string> &map_file_line) { if (map_file_line.size() < 2) throw std::runtime_error("in IxTheoMapper::IxTheoMapper: need at least 2 elements in \"map_file_line\"!"); from_hierarchy_ = map_file_line[0]; to_ix_theo_notation_ = map_file_line[1]; std::copy(map_file_line.begin() + 2, map_file_line.end(), std::back_inserter(exclusions_)); } std::string IxTheoMapper::map(const std::string &hierarchy_classification) const { if (not StringUtil::StartsWith(hierarchy_classification, from_hierarchy_)) return ""; for (const auto &exclusion : exclusions_) { if (StringUtil::StartsWith(hierarchy_classification, exclusion)) return ""; } return to_ix_theo_notation_; } void LoadCSVFile(const bool verbose, const std::string &filename, std::vector<IxTheoMapper> * const mappers) { DSVReader csv_reader(filename); std::vector<std::string> csv_values; while (csv_reader.readLine(&csv_values)) mappers->emplace_back(csv_values); if (verbose) std::cerr << "Read " << mappers->size() << " mappings from \"" << filename << "\".\n"; } void UpdateIxTheoNotations(const std::vector<IxTheoMapper> &mappers, const std::vector<std::string> &orig_values, std::string * const ixtheo_notations_list) { std::vector<std::string> ixtheo_notations_vector; StringUtil::Split(*ixtheo_notations_list, ':', &ixtheo_notations_vector); std::set<std::string> previously_assigned_notations(std::make_move_iterator(ixtheo_notations_vector.begin()), std::make_move_iterator(ixtheo_notations_vector.end())); for (const auto &mapper : mappers) { for (const auto &orig_value : orig_values) { const std::string mapped_value(mapper.map(orig_value)); if (not mapped_value.empty() and previously_assigned_notations.find(mapped_value) == previously_assigned_notations.end()) { if (not ixtheo_notations_list->empty()) *ixtheo_notations_list += ':'; *ixtheo_notations_list += mapped_value; previously_assigned_notations.insert(mapped_value); } } } } void ProcessRecords(const bool verbose, const std::shared_ptr<FILE> &input, const std::shared_ptr<FILE> &output, const std::vector<IxTheoMapper> &ddc_to_ixtheo_notation_mappers, const std::vector<IxTheoMapper> &/*rvk_to_ixtheo_notation_mappers*/) { unsigned count(0), records_with_ixtheo_notations(0), records_with_new_notations(0), skipped_group_count(0); while (MarcUtil::Record record = MarcUtil::Record(input.get())) { ++count; const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); if (dir_entries[0].getTag() != "001") Error("First field is not \"001\"!"); std::string ixtheo_notations_list(record.extractFirstSubfield("652", 'a')); if (not ixtheo_notations_list.empty()) { ++records_with_ixtheo_notations; record.write(output.get()); continue; } std::vector<std::string> ddc_values; if (record.extractSubfield("082", 'a', &ddc_values) == 0) { record.write(output.get()); continue; } // "K" stands for children's literature and "B" stands for fiction, both of which we don't want to // import into IxTheo; if (std::find(ddc_values.cbegin(), ddc_values.cend(), "K") != ddc_values.cend() or std::find(ddc_values.cbegin(), ddc_values.cend(), "B") != ddc_values.cend()) { ++skipped_group_count; continue; } // Many DDCs have superfluous backslashes which are non-standard and need to be removed before further // processing can take place: for (auto &ddc_value : ddc_values) StringUtil::RemoveChars("/", &ddc_value); UpdateIxTheoNotations(ddc_to_ixtheo_notation_mappers, ddc_values, &ixtheo_notations_list); if (verbose and not ixtheo_notations_list.empty()) { const std::vector<std::string> &fields(record.getFields()); std::cout << fields[0] << ": " << StringUtil::Join(ddc_values, ',') << " -> " << ixtheo_notations_list << '\n'; } /* std::vector<std::string> rvk_values; int _084_index(record.getFieldIndex("084")); if (_084_index != -1) { const std::vector<std::string> &fields(record.getFields()); while (_084_index < static_cast<ssize_t>(dir_entries.size()) and dir_entries[_084_index].getTag() == "084") { const Subfields subfields(fields[_084_index]); if (subfields.hasSubfieldWithValue('2', "rvk")) rvk_values.emplace_back(subfields.getFirstSubfieldValue('a')); ++_084_index; } } UpdateIxTheoNotations(rvk_to_ixtheo_notation_mappers, rvk_values, &ixtheo_notations_list); */ if (not ixtheo_notations_list.empty()) { ++records_with_new_notations; record.insertField("652", " ""\x1F""a" + ixtheo_notations_list); } record.write(output.get()); } if (verbose) { std::cerr << "Read " << count << " records.\n"; std::cerr << records_with_ixtheo_notations << " records had Ixtheo notations.\n"; std::cerr << records_with_new_notations << " records received new Ixtheo notations.\n"; std::cerr << skipped_group_count << " records where skipped because they were in a group that we are not interested in.\n"; } } int main(int argc, char **argv) { progname = argv[0]; if (argc != 5 and argc != 6) Usage(); bool verbose(false); if (argc == 6) { if (std::strcmp(argv[1], "--verbose") != 0) Usage(); verbose = true; } const std::string marc_input_filename(argv[verbose ? 2 : 1]); std::shared_ptr<FILE> marc_input(std::fopen(marc_input_filename.c_str(), "rbm"), std::fclose); if (marc_input == nullptr) Error("can't open \"" + marc_input_filename + "\" for reading!"); const std::string marc_output_filename(argv[verbose ? 3 : 2]); std::shared_ptr<FILE> marc_output(std::fopen(marc_output_filename.c_str(), "wb"), std::fclose); if (marc_output == nullptr) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { std::vector<IxTheoMapper> ddc_to_ixtheo_notation_mappers; LoadCSVFile(verbose, argv[verbose ? 4 : 3], &ddc_to_ixtheo_notation_mappers); std::vector<IxTheoMapper> rvk_to_ixtheo_notation_mappers; // LoadCSVFile(verbose, argv[verbose ? 5 : 4], &rvk_to_ixtheo_notation_mappers); ProcessRecords(verbose, marc_input, marc_output, ddc_to_ixtheo_notation_mappers, rvk_to_ixtheo_notation_mappers); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>// This class #include <Internal/ParticleClasses/ParticleEmitter.hpp> //#include <FluidManager.hpp> // Included for the sake of particle data. Kinda silly, really #include <Internal/PhysicsModuleImplementation.hpp> // 3rd parties using namespace DirectX; using namespace physx; namespace DoremiEngine { namespace Physics { ParticleEmitter::ParticleEmitter(ParticleEmitterData p_data, InternalPhysicsUtils& p_utils) : m_this(p_data), m_utils(p_utils), m_timeSinceLast(0) { m_nextIndex = 0; m_particleSystem = m_utils.m_physics->createParticleSystem(PARTICLE_MAX_COUNT); m_particleSystem->setMaxMotionDistance(PARTICLE_MAX_MOTION_DISTANCE); m_particleSystem->setParticleReadDataFlag(PxParticleReadDataFlag::eVELOCITY_BUFFER, true); m_utils.m_worldScene->addActor(*m_particleSystem); // Might be necessary to set flag to collide with dynamics // m_particleSystem->setParticleBaseFlag(PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS, true); m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); // Should not be here } ParticleEmitter::~ParticleEmitter() {} void ParticleEmitter::SetPosition(XMFLOAT3 p_position) { m_this.m_position = p_position; } void ParticleEmitter::SetDirection(XMFLOAT4 p_direction) { m_this.m_direction = p_direction; } void ParticleEmitter::SetGravity(bool p_gravity) { m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, p_gravity); } void ParticleEmitter::GetPositions(vector<XMFLOAT3>& o_positions) { // This is a bit harder than it really ought to be... PxParticleReadData* readData = m_particleSystem->lockParticleReadData(); PxStrideIterator<const PxVec3> positions = readData->positionBuffer; PxStrideIterator<const PxVec3> velocities = readData->velocityBuffer; PxStrideIterator<const PxParticleFlags> flags = readData->flagsBuffer; vector<XMFLOAT3> velocitiesVector; vector<int> indicesOfParticlesToBeReleased; uint32_t numParticles = readData->validParticleRange; for(uint32_t i = 0; i < numParticles; i++) { // Check if particles are supposed to be removed XMFLOAT3 position = XMFLOAT3(positions[i].x, positions[i].y, positions[i].z); XMFLOAT3 velocity = XMFLOAT3(velocities[i].x, velocities[i].y, velocities[i].z); XMVECTOR velVec = XMLoadFloat3(&velocity); velVec = XMVector3Normalize(velVec); XMStoreFloat3(&velocity, velVec); // TODOJB Remove normalization once it's fixed in CastRay if(flags[i] & (PxParticleFlag::eCOLLISION_WITH_DRAIN)) // | PxParticleFlag::eVALID)) { /// Particle should be removed // Add index to release list indicesOfParticlesToBeReleased.push_back(i); // Find out which actor it collided with using ray tracing (seriously. It was this easy...) m_drainsHit.push_back(m_utils.m_rayCastManager->CastRay(position, velocity, 5)); // Zero might turn up buggy } else if(flags[i] & PxParticleFlag::eVALID) { o_positions.push_back(position); } } readData->unlock(); if(indicesOfParticlesToBeReleased.size() != 0) { PxStrideIterator<const PxU32> inicesPX(reinterpret_cast<PxU32*>(&indicesOfParticlesToBeReleased[0])); m_particleSystem->releaseParticles(indicesOfParticlesToBeReleased.size(), inicesPX); } } vector<int> ParticleEmitter::GetDrainsHit() { return m_drainsHit; } void ParticleEmitter::SetData(ParticleEmitterData p_data) { m_this = p_data; } void ParticleEmitter::UpdateParticleLifeTimeAndRemoveExpired(float p_dt) { // Get particle indexData PxParticleReadData* t_particleData = m_particleSystem->lockParticleReadData(); PX_ASSERT(t_particleData); std::vector<PxU32> t_indicesToRemove; PxU32 newvalidRange = 0; // Kolla om vi har ngra particlar som r valid annars ondigt att ens brja uppdatera if (t_particleData->validParticleRange > 0) { for (PxU32 i = 0; i <= (t_particleData->validParticleRange - 1) >> 5; i++) { for (PxU32 j = t_particleData->validParticleBitmap[i]; j; j &= j - 1) { // TODOXX super unsafe. I am not sure what i am doing here. I was following a tutorial and a function they used was missing. This seems to be what they did essentially but WARNING!! unsigned long b; _BitScanForward(&b, j); PxU32 t_index = (i << 5 | b); if (m_particlesLifeTime[t_index] = -p_dt < 0.0) { m_particlesLifeTime[t_index] = 0; t_indicesToRemove.push_back(t_index); } } } t_particleData->unlock(); PxStrideIterator<const PxU32> t_indexData(&t_indicesToRemove[0]); m_particleSystem->releaseParticles(static_cast<PxU32>(t_indicesToRemove.size()), t_indexData); // TODOLH om vi skaffar indexPool kr m_indexpool->freeIndices(indices.size(), indexData); } else { // Do nothing } } void ParticleEmitter::Update(float p_dt) { m_drainsHit.clear(); if(m_this.m_active) { // Update time since last particle wave was spawned m_timeSinceLast += p_dt; if(m_timeSinceLast > m_this.m_emissionRate) { m_timeSinceLast = 0; vector<XMFLOAT3> velocities; vector<XMFLOAT3> positions; vector<int> indices; /// Time for more particles! /// These particles will be spawned in a sort of grid (atm) for(int x = -m_this.m_density; x < m_this.m_density * 2 - 1; x++) { for(int y = -m_this.m_density; y < m_this.m_density * 2; y++) { // Calculate angles in local space float xAngle = (x / m_this.m_density) * m_this.m_emissionAreaDimensions.x; float yAngle = (y / m_this.m_density) * m_this.m_emissionAreaDimensions.y; // Define standard target in local space XMVECTOR particleVelocityVec = XMLoadFloat3(&XMFLOAT3(0, 0, 1)); XMMATRIX rotMatLocal = XMMatrixRotationRollPitchYaw(xAngle, yAngle, 0); particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatLocal); // Move velocity vector into world space XMMATRIX rotMatWorld = XMMatrixRotationQuaternion(XMLoadFloat4(&m_this.m_direction)); particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatWorld); // Multiply with pressure particleVelocityVec *= m_this.m_launchPressure; // Store in vector XMFLOAT3 velocity; XMStoreFloat3(&velocity, particleVelocityVec); velocities.push_back(velocity); // Add position (only emitts from the center of the emitter atm float launchOffset = 0.1f; XMVECTOR positionVec = XMLoadFloat3(&m_this.m_position); positionVec += launchOffset * particleVelocityVec; XMFLOAT3 position; XMStoreFloat3(&position, positionVec); positions.push_back(position); // Add index (silly way just to make it work atm) indices.push_back(m_nextIndex); // Set the lifetime of this particle TODOLH maybe add support for particles without lifetime. Some kind of bool. Hopefully we dont have to do this. Seems hard at first glance m_particlesLifeTime[m_nextIndex] = m_lifeTime; m_nextIndex++; } } if(positions.size() > 0 && !(m_nextIndex > PARTICLE_MAX_COUNT)) // no point doing things if there's no new particles { // Cast into PhysX datatypes PxVec3* positionsPX = reinterpret_cast<PxVec3*>(&positions[0]); PxVec3* velocitiesPX = reinterpret_cast<PxVec3*>(&velocities[0]); PxU32* indicesPX = reinterpret_cast<PxU32*>(&indices[0]); // Create the particles PxParticleCreationData newParticlesData; newParticlesData.numParticles = positions.size(); newParticlesData.positionBuffer = PxStrideIterator<const PxVec3>(positionsPX); newParticlesData.velocityBuffer = PxStrideIterator<const PxVec3>(velocitiesPX); newParticlesData.indexBuffer = PxStrideIterator<const PxU32>(indicesPX); m_particleSystem->createParticles(newParticlesData); } else { // No new particles. Do nothing } } } } } }<commit_msg>Added support for Particle Lifetime<commit_after>// This class #include <Internal/ParticleClasses/ParticleEmitter.hpp> //#include <FluidManager.hpp> // Included for the sake of particle data. Kinda silly, really #include <Internal/PhysicsModuleImplementation.hpp> // 3rd parties using namespace DirectX; using namespace physx; namespace DoremiEngine { namespace Physics { ParticleEmitter::ParticleEmitter(ParticleEmitterData p_data, InternalPhysicsUtils& p_utils) : m_this(p_data), m_utils(p_utils), m_timeSinceLast(0) { m_nextIndex = 0; m_particleSystem = m_utils.m_physics->createParticleSystem(PARTICLE_MAX_COUNT); m_particleSystem->setMaxMotionDistance(PARTICLE_MAX_MOTION_DISTANCE); m_particleSystem->setParticleReadDataFlag(PxParticleReadDataFlag::eVELOCITY_BUFFER, true); m_utils.m_worldScene->addActor(*m_particleSystem); // Might be necessary to set flag to collide with dynamics // m_particleSystem->setParticleBaseFlag(PxParticleBaseFlag::eCOLLISION_WITH_DYNAMIC_ACTORS, true); m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); // Should not be here } ParticleEmitter::~ParticleEmitter() {} void ParticleEmitter::SetPosition(XMFLOAT3 p_position) { m_this.m_position = p_position; } void ParticleEmitter::SetDirection(XMFLOAT4 p_direction) { m_this.m_direction = p_direction; } void ParticleEmitter::SetGravity(bool p_gravity) { m_particleSystem->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, p_gravity); } void ParticleEmitter::GetPositions(vector<XMFLOAT3>& o_positions) { // This is a bit harder than it really ought to be... PxParticleReadData* readData = m_particleSystem->lockParticleReadData(); PxStrideIterator<const PxVec3> positions = readData->positionBuffer; PxStrideIterator<const PxVec3> velocities = readData->velocityBuffer; PxStrideIterator<const PxParticleFlags> flags = readData->flagsBuffer; vector<XMFLOAT3> velocitiesVector; vector<int> indicesOfParticlesToBeReleased; uint32_t numParticles = readData->validParticleRange; for(uint32_t i = 0; i < numParticles; i++) { // Check if particles are supposed to be removed XMFLOAT3 position = XMFLOAT3(positions[i].x, positions[i].y, positions[i].z); XMFLOAT3 velocity = XMFLOAT3(velocities[i].x, velocities[i].y, velocities[i].z); XMVECTOR velVec = XMLoadFloat3(&velocity); velVec = XMVector3Normalize(velVec); XMStoreFloat3(&velocity, velVec); // TODOJB Remove normalization once it's fixed in CastRay if(flags[i] & (PxParticleFlag::eCOLLISION_WITH_DRAIN)) // | PxParticleFlag::eVALID)) { /// Particle should be removed // Add index to release list indicesOfParticlesToBeReleased.push_back(i); // Find out which actor it collided with using ray tracing (seriously. It was this easy...) m_drainsHit.push_back(m_utils.m_rayCastManager->CastRay(position, velocity, 5)); // Zero might turn up buggy } else if(flags[i] & PxParticleFlag::eVALID) { o_positions.push_back(position); } } readData->unlock(); if(indicesOfParticlesToBeReleased.size() != 0) { PxStrideIterator<const PxU32> inicesPX(reinterpret_cast<PxU32*>(&indicesOfParticlesToBeReleased[0])); m_particleSystem->releaseParticles(indicesOfParticlesToBeReleased.size(), inicesPX); } } vector<int> ParticleEmitter::GetDrainsHit() { return m_drainsHit; } void ParticleEmitter::SetData(ParticleEmitterData p_data) { m_this = p_data; } void ParticleEmitter::UpdateParticleLifeTimeAndRemoveExpired(float p_dt) { std::vector<PxU32> t_indicesToRemove; // Get particle indexData PxParticleReadData* t_particleData = m_particleSystem->lockParticleReadData(); PX_ASSERT(t_particleData); // Kolla om vi har ngra particlar som r valid annars ondigt att ens brja uppdatera if(t_particleData->validParticleRange > 0) { int length = t_particleData->validParticleRange; for(PxU32 i = 0; i <= (t_particleData->validParticleRange - 1) >> 5; i++) { for(PxU32 j = t_particleData->validParticleBitmap[i]; j; j &= j - 1) { // TODOXX super unsafe. I am not sure what i am doing here. I was following a tutorial and a function they used was missing. // This seems to be what they did essentially but WARNING!! // Get index from physx. you have to use bitoperations from their bittable for indices. Its pretty complicated and Im not 100% // sure this code is safe unsigned long b; _BitScanForward(&b, j); PxU32 t_index = (i << 5 | (PxU32)b); // Update particle lifetime m_particlesLifeTime[t_index] -= p_dt; // CHeck if particle is still alive if((m_particlesLifeTime[t_index]) < 0.0) { m_particlesLifeTime[t_index] = 0; t_indicesToRemove.push_back(t_index); } } } } else { // Do nothing } // Release the data we have been looking at t_particleData->unlock(); // Needs to not crash if(t_indicesToRemove.size() > 0) { // Need Stride for releaseparticle. PxStrideIterator<const PxU32> t_indexData(&t_indicesToRemove[0]); // Now release the particles that we want to remove m_particleSystem->releaseParticles(static_cast<PxU32>(t_indicesToRemove.size()), t_indexData); // TODOLH om vi skaffar indexPool kr m_indexpool->freeIndices(indices.size(), indexData); } } void ParticleEmitter::Update(float p_dt) { m_drainsHit.clear(); UpdateParticleLifeTimeAndRemoveExpired(p_dt); if(m_this.m_active) { // Update time since last particle wave was spawned m_timeSinceLast += p_dt; if(m_timeSinceLast > m_this.m_emissionRate) { m_timeSinceLast = 0; vector<XMFLOAT3> velocities; vector<XMFLOAT3> positions; vector<int> indices; /// Time for more particles! /// These particles will be spawned in a sort of grid (atm) for(int x = -m_this.m_density; x < m_this.m_density * 2 - 1; x++) { for(int y = -m_this.m_density; y < m_this.m_density * 2; y++) { // Calculate angles in local space float xAngle = (x / m_this.m_density) * m_this.m_emissionAreaDimensions.x; float yAngle = (y / m_this.m_density) * m_this.m_emissionAreaDimensions.y; // Define standard target in local space XMVECTOR particleVelocityVec = XMLoadFloat3(&XMFLOAT3(0, 0, 1)); XMMATRIX rotMatLocal = XMMatrixRotationRollPitchYaw(xAngle, yAngle, 0); particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatLocal); // Move velocity vector into world space XMMATRIX rotMatWorld = XMMatrixRotationQuaternion(XMLoadFloat4(&m_this.m_direction)); particleVelocityVec = XMVector3Transform(particleVelocityVec, rotMatWorld); // Multiply with pressure particleVelocityVec *= m_this.m_launchPressure; // Store in vector XMFLOAT3 velocity; XMStoreFloat3(&velocity, particleVelocityVec); velocities.push_back(velocity); // Add position (only emitts from the center of the emitter atm float launchOffset = 0.1f; XMVECTOR positionVec = XMLoadFloat3(&m_this.m_position); positionVec += launchOffset * particleVelocityVec; XMFLOAT3 position; XMStoreFloat3(&position, positionVec); positions.push_back(position); // Add index (silly way just to make it work atm) indices.push_back(m_nextIndex); // Set the lifetime of this particle TODOLH maybe add support for particles without lifetime. Some kind of bool. Hopefully we dont have to do this. Seems hard at first glance m_particlesLifeTime[m_nextIndex] = m_lifeTime; m_nextIndex++; } } if(positions.size() > 0 && !(m_nextIndex > PARTICLE_MAX_COUNT)) // no point doing things if there's no new particles { // Cast into PhysX datatypes PxVec3* positionsPX = reinterpret_cast<PxVec3*>(&positions[0]); PxVec3* velocitiesPX = reinterpret_cast<PxVec3*>(&velocities[0]); PxU32* indicesPX = reinterpret_cast<PxU32*>(&indices[0]); // Create the particles PxParticleCreationData newParticlesData; newParticlesData.numParticles = positions.size(); newParticlesData.positionBuffer = PxStrideIterator<const PxVec3>(positionsPX); newParticlesData.velocityBuffer = PxStrideIterator<const PxVec3>(velocitiesPX); newParticlesData.indexBuffer = PxStrideIterator<const PxU32>(indicesPX); m_particleSystem->createParticles(newParticlesData); } else { // No new particles. Do nothing } } } } } }<|endoftext|>
<commit_before>/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ofLog.h" #include "MidiThread.h" #include <errno.h> #include <fcntl.h> #include <string.h> #include <termios.h> #include <unistd.h> MidiThread::MidiThread(Poco::FastMutex &synthMutex, NSynth &synth) : ofThread(), synthMutex(synthMutex), synth(synth){ } bool MidiThread::setup(const std::string &device, int channel){ this->channel = channel; // The device setup is performed twice to ensure it works on device // startup. for(int i=0; i<2; ++i){ if(i != 0){ close(deviceFd); } deviceFd = open(device.c_str(), O_RDONLY | O_NOCTTY); if(deviceFd < 0){ ofLog(OF_LOG_WARNING) << "Failed to open MIDI input " << device; return false; } // Configure the serial port at 38400 baud. Settings on the Raspberry Pi // should adapt this to the MIDI baud rate of 31250. struct termios tty; memset(&tty, 0, sizeof tty); if(tcgetattr(deviceFd, &tty) != 0){ return false; } cfsetospeed(&tty, B38400); cfsetispeed(&tty, B38400); tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; tty.c_iflag &= ~IGNBRK; tty.c_lflag = 0; tty.c_oflag = 0; tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 0; tty.c_iflag &= ~(IXON | IXOFF | IXANY); tty.c_cflag |= (CLOCAL | CREAD); tty.c_cflag &= ~(PARENB | PARODD); tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CRTSCTS; if(tcsetattr(deviceFd, TCSANOW, &tty) != 0){ return false; } } return true; } void MidiThread::threadedFunction(){ auto read1 = [this]()->uint8_t{ uint8_t result; while(read(deviceFd, &result, 1) != 1){ if(!isThreadRunning()){ return 0xff; } } return result; }; uint8_t header = read1(); while(isThreadRunning()){ if((header & 0xf0) == 0x90){ // Note on - this is a 3 byte message. uint8_t note = read1(); if(!isThreadRunning()){ break; } if(note & 0x80){ // The note is badly formed, discard the current header // and continue; header = note; break; } uint8_t velocity = read1(); if(!isThreadRunning()){ break; } if(velocity & 0x80){ // The note is badly formed, discard the current header // and continue; header = note; break; } if((header & 0x0f) == channel){ synthMutex.lock(); synth.on(note, static_cast<float>(velocity) / 127.0f); synthMutex.unlock(); } // Start on the next message. header = read1(); }else if((header & 0xf0) == 0x80){ // Note off - this is a 3 byte message. uint8_t note = read1(); if(!isThreadRunning()){ break; } if(note & 0x80){ // The note is badly formed, discard the current header // and continue; header = note; break; } uint8_t velocity = read1(); if(!isThreadRunning()){ break; } if(velocity & 0x80){ // The note is badly formed, discard the current header // and continue; header = note; break; } if((header & 0x0f) == channel){ synthMutex.lock(); synth.off(note); synthMutex.unlock(); } // Start on the next message. header = read1(); }else{ // Discard the header as it is not understood. header = read1(); } } } <commit_msg>Fix #43 by filtering out system real-time messages<commit_after>/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ofLog.h" #include "MidiThread.h" #include <errno.h> #include <fcntl.h> #include <string.h> #include <termios.h> #include <unistd.h> MidiThread::MidiThread(Poco::FastMutex &synthMutex, NSynth &synth) : ofThread(), synthMutex(synthMutex), synth(synth){ } bool MidiThread::setup(const std::string &device, int channel){ this->channel = channel; // The device setup is performed twice to ensure it works on device // startup. for(int i=0; i<2; ++i){ if(i != 0){ close(deviceFd); } deviceFd = open(device.c_str(), O_RDONLY | O_NOCTTY); if(deviceFd < 0){ ofLog(OF_LOG_WARNING) << "Failed to open MIDI input " << device; return false; } // Configure the serial port at 38400 baud. Settings on the Raspberry Pi // should adapt this to the MIDI baud rate of 31250. struct termios tty; memset(&tty, 0, sizeof tty); if(tcgetattr(deviceFd, &tty) != 0){ return false; } cfsetospeed(&tty, B38400); cfsetispeed(&tty, B38400); tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; tty.c_iflag &= ~IGNBRK; tty.c_lflag = 0; tty.c_oflag = 0; tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 0; tty.c_iflag &= ~(IXON | IXOFF | IXANY); tty.c_cflag |= (CLOCAL | CREAD); tty.c_cflag &= ~(PARENB | PARODD); tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CRTSCTS; if(tcsetattr(deviceFd, TCSANOW, &tty) != 0){ return false; } } return true; } void MidiThread::threadedFunction(){ auto read1 = [this]()->uint8_t{ uint8_t result; while(true) { if(!isThreadRunning()){ return 0xff; } int readCount = read(deviceFd, &result, 1); if (readCount != 1) { continue; } // ignore system real time bytes if (result == 0xFE || result == 0xFF || result == 0xF8 || result == 0xFA || result == 0xFB || result == 0xFC) { continue; } return result; } }; uint8_t header = read1(); while(isThreadRunning()){ if((header & 0xf0) == 0x90){ // Note on - this is a 3 byte message. uint8_t note = read1(); if(!isThreadRunning()){ break; } if(note & 0x80){ // The note is badly formed, discard the current header // and continue; header = note; break; } uint8_t velocity = read1(); if(!isThreadRunning()){ break; } if(velocity & 0x80){ // The note is badly formed, discard the current header // and continue; header = note; break; } if((header & 0x0f) == channel){ synthMutex.lock(); synth.on(note, static_cast<float>(velocity) / 127.0f); synthMutex.unlock(); } // Start on the next message. header = read1(); }else if((header & 0xf0) == 0x80){ // Note off - this is a 3 byte message. uint8_t note = read1(); if(!isThreadRunning()){ break; } if(note & 0x80){ // The note is badly formed, discard the current header // and continue; header = note; break; } uint8_t velocity = read1(); if(!isThreadRunning()){ break; } if(velocity & 0x80){ // The note is badly formed, discard the current header // and continue; header = note; break; } if((header & 0x0f) == channel){ synthMutex.lock(); synth.off(note); synthMutex.unlock(); } // Start on the next message. header = read1(); }else{ // Discard the header as it is not understood. header = read1(); } } } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: QueryViewSwitch.hxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef DBAUI_QUERYVIEWSWITCH_HXX #define DBAUI_QUERYVIEWSWITCH_HXX #ifndef DBAUI_QUERYVIEW_HXX #include "queryview.hxx" #endif namespace dbaui { class OQueryDesignView; class OQueryTextView; class OAddTableDlg; class OQueryContainerWindow; class OQueryViewSwitch { OQueryDesignView* m_pDesignView; OQueryTextView* m_pTextView; sal_Bool m_bAddTableDialogWasVisible; // true if so public: OQueryViewSwitch(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& ); virtual ~OQueryViewSwitch(); virtual sal_Bool isCutAllowed(); virtual sal_Bool isPasteAllowed(); virtual sal_Bool isCopyAllowed(); virtual void copy(); virtual void cut(); virtual void paste(); // clears the whole query virtual void clear(); // set the view readonly or not virtual void setReadOnly(sal_Bool _bReadOnly); // check if the statement is correct when not returning false virtual sal_Bool checkStatement(); // set the statement for representation virtual void setStatement(const ::rtl::OUString& _rsStatement); // returns the current sql statement virtual ::rtl::OUString getStatement(); /// late construction virtual void Construct(); virtual void initialize(); /** show the text or the design view @return <TRUE/> when all went right otherwise <FALSE/> which implies an aditional call of switchView from the controller to restore the old state */ sal_Bool switchView(); sal_Bool isSlotEnabled(sal_Int32 _nSlotId); void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable); void setNoneVisbleRow(sal_Int32 _nRows); // returs the add table dialog from the design view OAddTableDlg* getAddTableDialog(); void SaveUIConfig(); void reset(); void GrabFocus(); OQueryDesignView* getDesignView() const { return m_pDesignView; } OQueryContainerWindow* getContainer() const; void SetPosSizePixel( Point _rPt,Size _rSize); ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const; protected: // return the Rectangle where I can paint myself virtual void resizeDocumentView(Rectangle& rRect); }; } #endif // DBAUI_QUERYVIEWSWITCH_HXX <commit_msg>INTEGRATION: CWS dba30d (1.14.30); FILE MERGED 2008/05/29 11:25:58 fs 1.14.30.1: during #i80943#: refactoring: IController now passed around as reference, not as pointer<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: QueryViewSwitch.hxx,v $ * $Revision: 1.15 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef DBAUI_QUERYVIEWSWITCH_HXX #define DBAUI_QUERYVIEWSWITCH_HXX #ifndef DBAUI_QUERYVIEW_HXX #include "queryview.hxx" #endif namespace dbaui { class OQueryDesignView; class OQueryTextView; class OAddTableDlg; class OQueryContainerWindow; class OQueryViewSwitch { OQueryDesignView* m_pDesignView; OQueryTextView* m_pTextView; sal_Bool m_bAddTableDialogWasVisible; // true if so public: OQueryViewSwitch(OQueryContainerWindow* pParent, OQueryController& _rController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& ); virtual ~OQueryViewSwitch(); virtual sal_Bool isCutAllowed(); virtual sal_Bool isPasteAllowed(); virtual sal_Bool isCopyAllowed(); virtual void copy(); virtual void cut(); virtual void paste(); // clears the whole query virtual void clear(); // set the view readonly or not virtual void setReadOnly(sal_Bool _bReadOnly); // check if the statement is correct when not returning false virtual sal_Bool checkStatement(); // set the statement for representation virtual void setStatement(const ::rtl::OUString& _rsStatement); // returns the current sql statement virtual ::rtl::OUString getStatement(); /// late construction virtual void Construct(); virtual void initialize(); /** show the text or the design view @return <TRUE/> when all went right otherwise <FALSE/> which implies an aditional call of switchView from the controller to restore the old state */ sal_Bool switchView(); sal_Bool isSlotEnabled(sal_Int32 _nSlotId); void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable); void setNoneVisbleRow(sal_Int32 _nRows); // returs the add table dialog from the design view OAddTableDlg* getAddTableDialog(); void SaveUIConfig(); void reset(); void GrabFocus(); OQueryDesignView* getDesignView() const { return m_pDesignView; } OQueryContainerWindow* getContainer() const; void SetPosSizePixel( Point _rPt,Size _rSize); ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const; protected: // return the Rectangle where I can paint myself virtual void resizeDocumentView(Rectangle& rRect); }; } #endif // DBAUI_QUERYVIEWSWITCH_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: RelationControl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: oj $ $Date: 2002-11-08 09:27:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_RELATIONCONTROL_HXX #define DBAUI_RELATIONCONTROL_HXX #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef DBAUI_JOINTABLEVIEW_HXX #include "JoinTableView.hxx" #endif namespace dbaui { //======================================================================== class OTableListBoxControl; class OTableConnectionData; class ORelationTableConnectionData; class IRelationControlInterface; class ORelationControl; class OTableListBoxControl : public Window { FixedLine m_aFL_InvolvedTables; ListBox m_lmbLeftTable, m_lmbRightTable; FixedLine m_aFL_InvolvedFields; ORelationControl* m_pRC_Tables; const OJoinTableView::OTableWindowMap* m_pTableMap; IRelationControlInterface* m_pParentDialog; String m_strCurrentLeft; String m_strCurrentRight; private: DECL_LINK( OnTableChanged, ListBox* ); public: OTableListBoxControl(Window* _pParent, const ResId& _rResId, const OJoinTableView::OTableWindowMap* _pTableMap, IRelationControlInterface* _pParentDialog); virtual ~OTableListBoxControl(); /** fillListBoxes fills the list boxes with the table windows */ void fillListBoxes(); /** fillAndDisable fill the listboxes only with one entry and then disable them @param _pConnectionData contains the data which should be filled into the listboxes */ void fillAndDisable(OTableConnectionData* _pConnectionData); /** NotifyCellChange notifies the browse control that the conenction data has changed */ void NotifyCellChange(); /** Init is a call through to the control inside this one @param _pConnData the connection data which is used to init the control */ void Init(OTableConnectionData* _pConnData); void lateInit(); BOOL SaveModified(); String getSourceWinName() const; String getDestWinName() const; /** getContainer returns the container interface @return the interface of the container */ IRelationControlInterface* getContainer() const { return m_pParentDialog; } }; } #endif // DBAUI_RELATIONCONTROL_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.472); FILE MERGED 2005/09/05 17:34:24 rt 1.3.472.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: RelationControl.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 15:32:26 $ * * 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 DBAUI_RELATIONCONTROL_HXX #define DBAUI_RELATIONCONTROL_HXX #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef DBAUI_JOINTABLEVIEW_HXX #include "JoinTableView.hxx" #endif namespace dbaui { //======================================================================== class OTableListBoxControl; class OTableConnectionData; class ORelationTableConnectionData; class IRelationControlInterface; class ORelationControl; class OTableListBoxControl : public Window { FixedLine m_aFL_InvolvedTables; ListBox m_lmbLeftTable, m_lmbRightTable; FixedLine m_aFL_InvolvedFields; ORelationControl* m_pRC_Tables; const OJoinTableView::OTableWindowMap* m_pTableMap; IRelationControlInterface* m_pParentDialog; String m_strCurrentLeft; String m_strCurrentRight; private: DECL_LINK( OnTableChanged, ListBox* ); public: OTableListBoxControl(Window* _pParent, const ResId& _rResId, const OJoinTableView::OTableWindowMap* _pTableMap, IRelationControlInterface* _pParentDialog); virtual ~OTableListBoxControl(); /** fillListBoxes fills the list boxes with the table windows */ void fillListBoxes(); /** fillAndDisable fill the listboxes only with one entry and then disable them @param _pConnectionData contains the data which should be filled into the listboxes */ void fillAndDisable(OTableConnectionData* _pConnectionData); /** NotifyCellChange notifies the browse control that the conenction data has changed */ void NotifyCellChange(); /** Init is a call through to the control inside this one @param _pConnData the connection data which is used to init the control */ void Init(OTableConnectionData* _pConnData); void lateInit(); BOOL SaveModified(); String getSourceWinName() const; String getDestWinName() const; /** getContainer returns the container interface @return the interface of the container */ IRelationControlInterface* getContainer() const { return m_pParentDialog; } }; } #endif // DBAUI_RELATIONCONTROL_HXX <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of duicompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtDebug> #include <MSceneManager> #include <MScene> #include <QApplication> #include <QDesktopWidget> #include <QX11Info> #include <QGLFormat> #include <QGLWidget> #include "mdecoratorwindow.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <X11/Xmd.h> #include <X11/extensions/Xfixes.h> #include <X11/extensions/shape.h> #include <mabstractdecorator.h> class MDecorator: public MAbstractDecorator { Q_OBJECT public: MDecorator(MDecoratorWindow *p) : MAbstractDecorator(p), decorwindow(p) { } ~MDecorator() { } virtual void manageEvent(Qt::HANDLE window) { XTextProperty p; QString title; if(XGetWMName(QX11Info::display(), window, &p)) { if (p.value) { title = (char*) p.value; XFree(p.value); } } decorwindow->setInputRegion(); setAvailableGeometry(decorwindow->availableClientRect()); decorwindow->setWindowTitle(title); } protected: virtual void activateEvent() { } virtual void setAutoRotation(bool mode) { Q_UNUSED(mode) // we follow the orientation of the topmost app } virtual void setOnlyStatusbar(bool mode) { decorwindow->setOnlyStatusbar(mode); decorwindow->setInputRegion(); setAvailableGeometry(decorwindow->availableClientRect()); } private: MDecoratorWindow *decorwindow; }; #if 0 static QRect windowRectFromGraphicsItem(const QGraphicsView &view, const QGraphicsItem &item) { return view.mapFromScene( item.mapToScene( item.boundingRect() ) ).boundingRect(); } #endif MDecoratorWindow::MDecoratorWindow(QWidget *parent) : MWindow(parent) { onlyStatusbarAtom = XInternAtom(QX11Info::display(), "_MDECORATOR_ONLY_STATUSBAR", False); managedWindowAtom = XInternAtom(QX11Info::display(), "_MDECORATOR_MANAGED_WINDOW", False); homeButtonPanel = new MHomeButtonPanel(); escapeButtonPanel = new MEscapeButtonPanel(); navigationBar = new MNavigationBar(); statusBar = new MStatusBar(); connect(homeButtonPanel, SIGNAL(buttonClicked()), this, SIGNAL(homeClicked())); connect(escapeButtonPanel, SIGNAL(buttonClicked()), this, SIGNAL(escapeClicked())); sceneManager()->appearSceneWindowNow(statusBar); setOnlyStatusbar(false); d = new MDecorator(this); connect(this, SIGNAL(homeClicked()), d, SLOT(minimize())); connect(this, SIGNAL(escapeClicked()), d, SLOT(close())); connect(sceneManager(), SIGNAL(orientationChanged(M::Orientation)), this, SLOT(screenRotated(M::Orientation))); setFocusPolicy(Qt::NoFocus); setSceneSize(); setMDecoratorWindowProperty(); setInputRegion(); setProperty("followsCurrentApplicationWindowOrientation", true); } void MDecoratorWindow::setWindowTitle(const QString& title) { navigationBar->setViewMenuDescription(title); } MDecoratorWindow::~MDecoratorWindow() { } bool MDecoratorWindow::x11Event(XEvent *e) { Atom actual; int format, result; unsigned long n, left; unsigned char *data = 0; if (e->type == PropertyNotify && ((XPropertyEvent*)e)->atom == onlyStatusbarAtom) { result = XGetWindowProperty(QX11Info::display(), winId(), onlyStatusbarAtom, 0, 1, False, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && data) { bool val = *((long*)data); if (val != only_statusbar) d->RemoteSetOnlyStatusbar(val); } if (data) XFree(data); return true; } else if (e->type == PropertyNotify && ((XPropertyEvent*)e)->atom == managedWindowAtom) { result = XGetWindowProperty(QX11Info::display(), winId(), managedWindowAtom, 0, 1, False, XA_WINDOW, &actual, &format, &n, &left, &data); if (result == Success && data) d->RemoteSetManagedWinId(*((long*)data)); if (data) XFree(data); return true; } return false; } void MDecoratorWindow::setOnlyStatusbar(bool mode) { if (mode) { sceneManager()->disappearSceneWindowNow(navigationBar); sceneManager()->disappearSceneWindowNow(homeButtonPanel); sceneManager()->disappearSceneWindowNow(escapeButtonPanel); } else { sceneManager()->appearSceneWindowNow(navigationBar); sceneManager()->appearSceneWindowNow(homeButtonPanel); sceneManager()->appearSceneWindowNow(escapeButtonPanel); } only_statusbar = mode; } void MDecoratorWindow::screenRotated(const M::Orientation &orientation) { Q_UNUSED(orientation); setInputRegion(); d->setAvailableGeometry(availableClientRect()); } XRectangle MDecoratorWindow::itemRectToScreenRect(const QRect& r) { XRectangle rect; Display *dpy = QX11Info::display(); int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width; int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height; switch (sceneManager()->orientationAngle()) { case 0: rect.x = r.x(); rect.y = r.y(); rect.width = r.width(); rect.height = r.height(); break; case 90: rect.x = xres - r.height(); rect.y = 0; rect.width = r.height(); rect.height = r.width(); break; case 270: rect.x = rect.y = 0; rect.width = r.height(); rect.height = r.width(); break; case 180: rect.x = 0; rect.y = yres - r.height(); rect.width = r.width(); rect.height = r.height(); break; default: memset(&rect, 0, sizeof(rect)); break; } return rect; } void MDecoratorWindow::setInputRegion() { static XRectangle prev_rect = {0, 0, 0, 0}; QRegion region; QRect r_tmp(statusBar->geometry().toRect()); region += statusBar->mapToScene(r_tmp).boundingRect().toRect(); if (!only_statusbar) { r_tmp = QRect(navigationBar->geometry().toRect()); region += navigationBar->mapToScene(r_tmp).boundingRect().toRect(); r_tmp = QRect(homeButtonPanel->geometry().toRect()); region += homeButtonPanel->mapToScene(r_tmp).boundingRect().toRect(); r_tmp = QRect(escapeButtonPanel->geometry().toRect()); region += escapeButtonPanel->mapToScene(r_tmp).boundingRect().toRect(); } const QRect fs(QApplication::desktop()->screenGeometry()); decoratorRect = region.boundingRect(); // crop it to fullscreen to work around a weird issue if (decoratorRect.width() > fs.width()) decoratorRect.setWidth(fs.width()); if (decoratorRect.height() > fs.height()) decoratorRect.setHeight(fs.height()); if (!only_statusbar && decoratorRect.width() > fs.width() / 2 && decoratorRect.height() > fs.height() / 2) { // decorator is so big that it is probably in more than one part // (which is not yet supported) setOnlyStatusbar(true); region = decoratorRect = statusBar->geometry().toRect(); } XRectangle rect = itemRectToScreenRect(decoratorRect); if (memcmp(&prev_rect, &rect, sizeof(XRectangle))) { Display *dpy = QX11Info::display(); XserverRegion shapeRegion = XFixesCreateRegion(dpy, &rect, 1); XShapeCombineRectangles(dpy, winId(), ShapeBounding, 0, 0, &rect, 1, ShapeSet, Unsorted); XFixesSetWindowShapeRegion(dpy, winId(), ShapeInput, 0, 0, shapeRegion); XFixesDestroyRegion(dpy, shapeRegion); XSync(dpy, False); prev_rect = rect; } // selective compositing if (isVisible() && region.isEmpty()) { hide(); } else if (!isVisible() && !region.isEmpty()) { show(); } } void MDecoratorWindow::setSceneSize() { // always keep landscape size Display *dpy = QX11Info::display(); int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width; int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height; scene()->setSceneRect(0, 0, xres, yres); setMinimumSize(xres, yres); setMaximumSize(xres, yres); } void MDecoratorWindow::setMDecoratorWindowProperty() { long on = 1; XChangeProperty(QX11Info::display(), winId(), XInternAtom(QX11Info::display(), "_MEEGOTOUCH_DECORATOR_WINDOW", False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &on, 1); } const QRect MDecoratorWindow::availableClientRect() const { return decoratorRect; } void MDecoratorWindow::closeEvent(QCloseEvent * event ) { // never close the decorator! return event->ignore(); } #include "mdecoratorwindow.moc" <commit_msg>set right decoratorRect in case it's too large<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of duicompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtDebug> #include <MSceneManager> #include <MScene> #include <QApplication> #include <QDesktopWidget> #include <QX11Info> #include <QGLFormat> #include <QGLWidget> #include "mdecoratorwindow.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include <X11/Xmd.h> #include <X11/extensions/Xfixes.h> #include <X11/extensions/shape.h> #include <mabstractdecorator.h> class MDecorator: public MAbstractDecorator { Q_OBJECT public: MDecorator(MDecoratorWindow *p) : MAbstractDecorator(p), decorwindow(p) { } ~MDecorator() { } virtual void manageEvent(Qt::HANDLE window) { XTextProperty p; QString title; if(XGetWMName(QX11Info::display(), window, &p)) { if (p.value) { title = (char*) p.value; XFree(p.value); } } decorwindow->setInputRegion(); setAvailableGeometry(decorwindow->availableClientRect()); decorwindow->setWindowTitle(title); } protected: virtual void activateEvent() { } virtual void setAutoRotation(bool mode) { Q_UNUSED(mode) // we follow the orientation of the topmost app } virtual void setOnlyStatusbar(bool mode) { decorwindow->setOnlyStatusbar(mode); decorwindow->setInputRegion(); setAvailableGeometry(decorwindow->availableClientRect()); } private: MDecoratorWindow *decorwindow; }; #if 0 static QRect windowRectFromGraphicsItem(const QGraphicsView &view, const QGraphicsItem &item) { return view.mapFromScene( item.mapToScene( item.boundingRect() ) ).boundingRect(); } #endif MDecoratorWindow::MDecoratorWindow(QWidget *parent) : MWindow(parent) { onlyStatusbarAtom = XInternAtom(QX11Info::display(), "_MDECORATOR_ONLY_STATUSBAR", False); managedWindowAtom = XInternAtom(QX11Info::display(), "_MDECORATOR_MANAGED_WINDOW", False); homeButtonPanel = new MHomeButtonPanel(); escapeButtonPanel = new MEscapeButtonPanel(); navigationBar = new MNavigationBar(); statusBar = new MStatusBar(); connect(homeButtonPanel, SIGNAL(buttonClicked()), this, SIGNAL(homeClicked())); connect(escapeButtonPanel, SIGNAL(buttonClicked()), this, SIGNAL(escapeClicked())); sceneManager()->appearSceneWindowNow(statusBar); setOnlyStatusbar(false); d = new MDecorator(this); connect(this, SIGNAL(homeClicked()), d, SLOT(minimize())); connect(this, SIGNAL(escapeClicked()), d, SLOT(close())); connect(sceneManager(), SIGNAL(orientationChanged(M::Orientation)), this, SLOT(screenRotated(M::Orientation))); setFocusPolicy(Qt::NoFocus); setSceneSize(); setMDecoratorWindowProperty(); setInputRegion(); setProperty("followsCurrentApplicationWindowOrientation", true); } void MDecoratorWindow::setWindowTitle(const QString& title) { navigationBar->setViewMenuDescription(title); } MDecoratorWindow::~MDecoratorWindow() { } bool MDecoratorWindow::x11Event(XEvent *e) { Atom actual; int format, result; unsigned long n, left; unsigned char *data = 0; if (e->type == PropertyNotify && ((XPropertyEvent*)e)->atom == onlyStatusbarAtom) { result = XGetWindowProperty(QX11Info::display(), winId(), onlyStatusbarAtom, 0, 1, False, XA_CARDINAL, &actual, &format, &n, &left, &data); if (result == Success && data) { bool val = *((long*)data); if (val != only_statusbar) d->RemoteSetOnlyStatusbar(val); } if (data) XFree(data); return true; } else if (e->type == PropertyNotify && ((XPropertyEvent*)e)->atom == managedWindowAtom) { result = XGetWindowProperty(QX11Info::display(), winId(), managedWindowAtom, 0, 1, False, XA_WINDOW, &actual, &format, &n, &left, &data); if (result == Success && data) d->RemoteSetManagedWinId(*((long*)data)); if (data) XFree(data); return true; } return false; } void MDecoratorWindow::setOnlyStatusbar(bool mode) { if (mode) { sceneManager()->disappearSceneWindowNow(navigationBar); sceneManager()->disappearSceneWindowNow(homeButtonPanel); sceneManager()->disappearSceneWindowNow(escapeButtonPanel); } else { sceneManager()->appearSceneWindowNow(navigationBar); sceneManager()->appearSceneWindowNow(homeButtonPanel); sceneManager()->appearSceneWindowNow(escapeButtonPanel); } only_statusbar = mode; } void MDecoratorWindow::screenRotated(const M::Orientation &orientation) { Q_UNUSED(orientation); setInputRegion(); d->setAvailableGeometry(availableClientRect()); } XRectangle MDecoratorWindow::itemRectToScreenRect(const QRect& r) { XRectangle rect; Display *dpy = QX11Info::display(); int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width; int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height; switch (sceneManager()->orientationAngle()) { case 0: rect.x = r.x(); rect.y = r.y(); rect.width = r.width(); rect.height = r.height(); break; case 90: rect.x = xres - r.height(); rect.y = 0; rect.width = r.height(); rect.height = r.width(); break; case 270: rect.x = rect.y = 0; rect.width = r.height(); rect.height = r.width(); break; case 180: rect.x = 0; rect.y = yres - r.height(); rect.width = r.width(); rect.height = r.height(); break; default: memset(&rect, 0, sizeof(rect)); break; } return rect; } void MDecoratorWindow::setInputRegion() { static XRectangle prev_rect = {0, 0, 0, 0}; QRegion region; QRect r_tmp(statusBar->geometry().toRect()); region += statusBar->mapToScene(r_tmp).boundingRect().toRect(); if (!only_statusbar) { r_tmp = QRect(navigationBar->geometry().toRect()); region += navigationBar->mapToScene(r_tmp).boundingRect().toRect(); r_tmp = QRect(homeButtonPanel->geometry().toRect()); region += homeButtonPanel->mapToScene(r_tmp).boundingRect().toRect(); r_tmp = QRect(escapeButtonPanel->geometry().toRect()); region += escapeButtonPanel->mapToScene(r_tmp).boundingRect().toRect(); } const QRect fs(QApplication::desktop()->screenGeometry()); decoratorRect = region.boundingRect(); // crop it to fullscreen to work around a weird issue if (decoratorRect.width() > fs.width()) decoratorRect.setWidth(fs.width()); if (decoratorRect.height() > fs.height()) decoratorRect.setHeight(fs.height()); if (!only_statusbar && decoratorRect.width() > fs.width() / 2 && decoratorRect.height() > fs.height() / 2) { // decorator is so big that it is probably in more than one part // (which is not yet supported) setOnlyStatusbar(true); r_tmp = statusBar->geometry().toRect(); region = decoratorRect = statusBar->mapToScene(r_tmp).boundingRect().toRect(); } XRectangle rect = itemRectToScreenRect(decoratorRect); if (memcmp(&prev_rect, &rect, sizeof(XRectangle))) { Display *dpy = QX11Info::display(); XserverRegion shapeRegion = XFixesCreateRegion(dpy, &rect, 1); XShapeCombineRectangles(dpy, winId(), ShapeBounding, 0, 0, &rect, 1, ShapeSet, Unsorted); XFixesSetWindowShapeRegion(dpy, winId(), ShapeInput, 0, 0, shapeRegion); XFixesDestroyRegion(dpy, shapeRegion); XSync(dpy, False); prev_rect = rect; } // selective compositing if (isVisible() && region.isEmpty()) { hide(); } else if (!isVisible() && !region.isEmpty()) { show(); } } void MDecoratorWindow::setSceneSize() { // always keep landscape size Display *dpy = QX11Info::display(); int xres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->width; int yres = ScreenOfDisplay(dpy, DefaultScreen(dpy))->height; scene()->setSceneRect(0, 0, xres, yres); setMinimumSize(xres, yres); setMaximumSize(xres, yres); } void MDecoratorWindow::setMDecoratorWindowProperty() { long on = 1; XChangeProperty(QX11Info::display(), winId(), XInternAtom(QX11Info::display(), "_MEEGOTOUCH_DECORATOR_WINDOW", False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) &on, 1); } const QRect MDecoratorWindow::availableClientRect() const { return decoratorRect; } void MDecoratorWindow::closeEvent(QCloseEvent * event ) { // never close the decorator! return event->ignore(); } #include "mdecoratorwindow.moc" <|endoftext|>
<commit_before>#include "Animation_Seasonal.hpp" /* ~~~ Animation Seasonal Spring: Clear Sky Blue Color Fade */ Animation_Seasonal_Spring_ClearSkyFade::Animation_Seasonal_Spring_ClearSkyFade(Adafruit_NeoPixel* strip) { this->strip = strip; } void Animation_Seasonal_Spring_ClearSkyFade::init() { Animation_Seasonal::init(); this->name = getNameOfStrip(this->strip); this->name += F(": Clear Skies"); this->num_strips = 1; this->update_rate = 50; this->strips = getAsStripArray(this->strip); this->stack = new LocalStack(); this->stack->push(new MemObj(new unsigned int(0))); this->stack->push(new MemObj(new bool(true))); this->stack->push(new MemObj(new unsigned short int(0))); this->stack->push(new MemObj(new unsigned short int(0))); } void Animation_Seasonal_Spring_ClearSkyFade::step() { static const int MAX_RED = 200; static const int MAX_GREEN = 180; static const int BLUE = 255; unsigned int& i = this->stack->get(0)->get<unsigned int>(); bool& increasing = this->stack->get(1)->get<bool>(); unsigned short int& red = this->stack->get(2)->get<unsigned short int>(); unsigned short int& green = this->stack->get(3)->get<unsigned short int>(); // step animation for (unsigned int x = 0; x < this->strip->numPixels(); x++) { this->strip->setPixelColor(x, MAX_RED - i, MAX_GREEN - i, BLUE); } if (increasing) { if (i >= 50) { i--; increasing = false; } else { i++; } } else { if (i <= 0) { i++; increasing = true; this->current_exec++; } else { i--; } } } void Animation_Seasonal_Spring_ClearSkyFade::clean() { this->stack->get(0)->destroy<unsigned int>(); this->stack->get(1)->destroy<bool>(); this->stack->get(2)->destroy<unsigned short int>(); this->stack->get(3)->destroy<unsigned short int>(); delete this->stack; } <commit_msg>show() helps things actually work<commit_after>#include "Animation_Seasonal.hpp" /* ~~~ Animation Seasonal Spring: Clear Sky Blue Color Fade */ Animation_Seasonal_Spring_ClearSkyFade::Animation_Seasonal_Spring_ClearSkyFade(Adafruit_NeoPixel* strip) { this->strip = strip; } void Animation_Seasonal_Spring_ClearSkyFade::init() { Animation_Seasonal::init(); this->name = getNameOfStrip(this->strip); this->name += F(": Clear Skies"); this->num_strips = 1; this->update_rate = 50; this->strips = getAsStripArray(this->strip); this->stack = new LocalStack(); this->stack->push(new MemObj(new unsigned int(0))); this->stack->push(new MemObj(new bool(true))); this->stack->push(new MemObj(new unsigned short int(0))); this->stack->push(new MemObj(new unsigned short int(0))); } void Animation_Seasonal_Spring_ClearSkyFade::step() { static const int MAX_RED = 200; static const int MAX_GREEN = 180; static const int BLUE = 255; unsigned int& i = this->stack->get(0)->get<unsigned int>(); bool& increasing = this->stack->get(1)->get<bool>(); // step animation for (unsigned int x = 0; x < this->strip->numPixels(); x++) { this->strip->setPixelColor(x, MAX_RED - i, MAX_GREEN - i, BLUE); } this->strip->show(); if (increasing) { if (i >= 150) { i--; increasing = false; } else { i++; } } else { if (i <= 0) { i++; increasing = true; this->current_exec++; } else { i--; } } } void Animation_Seasonal_Spring_ClearSkyFade::clean() { this->stack->get(0)->destroy<unsigned int>(); this->stack->get(1)->destroy<bool>(); this->stack->get(2)->destroy<unsigned short int>(); this->stack->get(3)->destroy<unsigned short int>(); delete this->stack; } <|endoftext|>
<commit_before>/* * filter_rbpitch.c -- adjust audio pitch * Copyright (C) 2020 Meltytech, LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <framework/mlt.h> #include <framework/mlt_log.h> #include <rubberband/RubberBandStretcher.h> #include <algorithm> #include <cstring> #include <math.h> using namespace RubberBand; // Private Types typedef struct { RubberBandStretcher* s; int rubberband_frequency; uint64_t in_samples; uint64_t out_samples; } private_data; static const size_t MAX_CHANNELS = 10; static int rbpitch_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples ) { mlt_filter filter = static_cast<mlt_filter>(mlt_frame_pop_audio( frame )); mlt_properties filter_properties = MLT_FILTER_PROPERTIES(filter); private_data* pdata = (private_data*)filter->child; if ( *channels > (int)MAX_CHANNELS ) { mlt_log_error( MLT_FILTER_SERVICE(filter), "Too many channels requested: %d > %d\n", *channels, (int)MAX_CHANNELS ); return mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples ); } int requested_samples = *samples; mlt_properties unique_properties = mlt_frame_get_unique_properties( frame, MLT_FILTER_SERVICE(filter) ); if ( !unique_properties ) { mlt_log_error( MLT_FILTER_SERVICE(filter), "Missing unique_properites\n" ); return mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples ); } // Get the producer's audio *format = mlt_audio_float; int error = mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples ); if ( error ) return error; // Make sure the audio is in the correct format // This is useful if the filter is encapsulated in a producer and does not // have a normalizing filter before it. if (*format != mlt_audio_float && frame->convert_audio != NULL) { frame->convert_audio( frame, buffer, format, mlt_audio_float ); } // Sanity check parameters // rubberband library crashes have been seen with a very large scale factor // or very small sampling frequency. Very small scale factor and very high // sampling frequency can result in too much audio lag. // Disallow these extreme scenarios for now. Maybe it will be improved in // the future. double pitchscale = mlt_properties_get_double( unique_properties, "pitchscale" ); pitchscale = CLAMP( pitchscale, 0.05, 50.0 ); int rubberband_frequency = CLAMP( *frequency, 10000, 300000 ); // Protect the RubberBandStretcher instance. mlt_service_lock( MLT_FILTER_SERVICE(filter) ); // Configure the stretcher. RubberBandStretcher* s = pdata->s; if ( !s || s->available() == -1 || (int)s->getChannelCount() != *channels || pdata->rubberband_frequency != rubberband_frequency ) { mlt_log_debug( MLT_FILTER_SERVICE(filter), "Create a new stretcher\t%d\t%d\t%f\n", *channels, rubberband_frequency, pitchscale ); delete s; // Create a rubberband instance RubberBandStretcher::Options options = RubberBandStretcher::OptionProcessRealTime; s = new RubberBandStretcher(rubberband_frequency, *channels, options, 1.0, pitchscale); pdata->s = s; pdata->rubberband_frequency = rubberband_frequency; pdata->in_samples = 0; pdata->out_samples = 0; } s->setPitchScale(pitchscale); if( pitchscale > 0.5 && pitchscale < 2.0 ) { // Pitch adjustment < 200% s->setPitchOption(RubberBandStretcher::OptionPitchHighQuality); s->setTransientsOption(RubberBandStretcher::OptionTransientsCrisp); } else { // Pitch adjustment > 200% // "HighConsistency" and "Smooth" options help to avoid large memory // consumption and crashes that can occur for large pitch adjustments. s->setPitchOption(RubberBandStretcher::OptionPitchHighConsistency); s->setTransientsOption(RubberBandStretcher::OptionTransientsSmooth); } // Configure input and output buffers and counters. int consumed_samples = 0; int total_consumed_samples = 0; int received_samples = 0; struct mlt_audio_s in; struct mlt_audio_s out; mlt_audio_set_values( &in, *buffer, *frequency, *format, *samples, *channels ); mlt_audio_set_values( &out, NULL, *frequency, *format, *samples, *channels ); mlt_audio_alloc_data( &out ); // Process all input samples while ( true ) { // Send more samples to the stretcher if ( consumed_samples == in.samples ) { // Continue to repeat input samples into the stretcher until it // provides the desired number of samples out. consumed_samples = 0; mlt_log_debug( MLT_FILTER_SERVICE(filter), "Repeat samples\n"); } int process_samples = std::min( in.samples - consumed_samples, (int)s->getSamplesRequired() ); if ( process_samples == 0 && received_samples == out.samples && total_consumed_samples < in.samples ) { // No more out samples are needed, but input samples are still available. // Send the final input samples for processing. process_samples = in.samples - total_consumed_samples; } if ( process_samples > 0 ) { float* in_planes[MAX_CHANNELS]; for ( int i = 0; i < in.channels; i++ ) { in_planes[i] = ((float*)in.data) + (in.samples * i) + consumed_samples; } s->process( in_planes, process_samples, false ); consumed_samples += process_samples; total_consumed_samples += process_samples; pdata->in_samples += process_samples; } // Receive samples from the stretcher int retrieve_samples = std::min( out.samples - received_samples, s->available() ); if ( retrieve_samples > 0 ) { float* out_planes[MAX_CHANNELS]; for ( int i = 0; i < out.channels; i++ ) { out_planes[i] = ((float*)out.data) + (out.samples * i) + received_samples; } retrieve_samples = (int)s->retrieve( out_planes, retrieve_samples ); received_samples += retrieve_samples; pdata->out_samples += retrieve_samples; } mlt_log_debug( MLT_FILTER_SERVICE(filter), "Process: %d\t Retrieve: %d\n", process_samples, retrieve_samples ); if ( received_samples == out.samples && total_consumed_samples >= in.samples ) { // There is nothing more to do; break; } } // Save the processed samples. mlt_audio_shrink( &out, received_samples ); mlt_frame_set_audio( frame, out.data, out.format, 0, out.release_data ); mlt_audio_get_values( &out, buffer, frequency, format, samples, channels ); // Report the latency. double latency = (double)(pdata->in_samples - pdata->out_samples) * 1000.0 / (double)*frequency; mlt_properties_set_double( filter_properties, "latency", latency ); mlt_service_unlock( MLT_FILTER_SERVICE(filter) ); mlt_log_debug( MLT_FILTER_SERVICE(filter), "Requested: %d\tReceived: %d\tSent: %d\tLatency: %d(%fms)\n", requested_samples, in.samples, out.samples, (int)(pdata->in_samples - pdata->out_samples), latency ); return error; } static mlt_frame filter_process( mlt_filter filter, mlt_frame frame ) { mlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter ); mlt_position position = mlt_filter_get_position( filter, frame ); mlt_position length = mlt_filter_get_length2( filter, frame ); // Determine the pitchscale double pitchscale = 1.0; if ( mlt_properties_exists( filter_properties, "pitchscale" ) ) { pitchscale = mlt_properties_anim_get_double( filter_properties, "pitchscale", position, length ); } else { double octaveshift = mlt_properties_anim_get_double( filter_properties, "octaveshift", position, length ); pitchscale = pow(2, octaveshift); } if ( pitchscale <= 0.0 || /*check for nan:*/pitchscale != pitchscale ) { pitchscale = 1.0; } // Save the pitchscale on the frame to be used in rbpitch_get_audio mlt_properties unique_properties = mlt_frame_unique_properties( frame, MLT_FILTER_SERVICE(filter) ); mlt_properties_set_double( unique_properties, "pitchscale", pitchscale ); mlt_frame_push_audio( frame, (void*)filter ); mlt_frame_push_audio( frame, (void*)rbpitch_get_audio ); return frame; } static void close_filter( mlt_filter filter ) { private_data* pdata = (private_data*)filter->child; if ( pdata ) { RubberBandStretcher* s = static_cast<RubberBandStretcher*>(pdata->s); if ( s ) { delete s; } free( pdata ); filter->child = NULL; } } extern "C" { mlt_filter filter_rbpitch_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg ) { mlt_filter filter = mlt_filter_new(); private_data* pdata = (private_data*)calloc( 1, sizeof(private_data) ); if( filter && pdata ) { pdata->s = NULL; pdata->rubberband_frequency = 0; pdata->in_samples = 0; pdata->out_samples = 0; filter->process = filter_process; filter->close = close_filter; filter->child = pdata; } else { mlt_log_error( MLT_FILTER_SERVICE(filter), "Failed to initialize\n" ); if( filter ) { mlt_filter_close( filter ); } if( pdata ) { free( pdata ); } filter = NULL; } return filter; } } <commit_msg>Include 0.5 and 2.0 in higher quality transient setting<commit_after>/* * filter_rbpitch.c -- adjust audio pitch * Copyright (C) 2020 Meltytech, LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <framework/mlt.h> #include <framework/mlt_log.h> #include <rubberband/RubberBandStretcher.h> #include <algorithm> #include <cstring> #include <math.h> using namespace RubberBand; // Private Types typedef struct { RubberBandStretcher* s; int rubberband_frequency; uint64_t in_samples; uint64_t out_samples; } private_data; static const size_t MAX_CHANNELS = 10; static int rbpitch_get_audio( mlt_frame frame, void **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples ) { mlt_filter filter = static_cast<mlt_filter>(mlt_frame_pop_audio( frame )); mlt_properties filter_properties = MLT_FILTER_PROPERTIES(filter); private_data* pdata = (private_data*)filter->child; if ( *channels > (int)MAX_CHANNELS ) { mlt_log_error( MLT_FILTER_SERVICE(filter), "Too many channels requested: %d > %d\n", *channels, (int)MAX_CHANNELS ); return mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples ); } int requested_samples = *samples; mlt_properties unique_properties = mlt_frame_get_unique_properties( frame, MLT_FILTER_SERVICE(filter) ); if ( !unique_properties ) { mlt_log_error( MLT_FILTER_SERVICE(filter), "Missing unique_properites\n" ); return mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples ); } // Get the producer's audio *format = mlt_audio_float; int error = mlt_frame_get_audio( frame, buffer, format, frequency, channels, samples ); if ( error ) return error; // Make sure the audio is in the correct format // This is useful if the filter is encapsulated in a producer and does not // have a normalizing filter before it. if (*format != mlt_audio_float && frame->convert_audio != NULL) { frame->convert_audio( frame, buffer, format, mlt_audio_float ); } // Sanity check parameters // rubberband library crashes have been seen with a very large scale factor // or very small sampling frequency. Very small scale factor and very high // sampling frequency can result in too much audio lag. // Disallow these extreme scenarios for now. Maybe it will be improved in // the future. double pitchscale = mlt_properties_get_double( unique_properties, "pitchscale" ); pitchscale = CLAMP( pitchscale, 0.05, 50.0 ); int rubberband_frequency = CLAMP( *frequency, 10000, 300000 ); // Protect the RubberBandStretcher instance. mlt_service_lock( MLT_FILTER_SERVICE(filter) ); // Configure the stretcher. RubberBandStretcher* s = pdata->s; if ( !s || s->available() == -1 || (int)s->getChannelCount() != *channels || pdata->rubberband_frequency != rubberband_frequency ) { mlt_log_debug( MLT_FILTER_SERVICE(filter), "Create a new stretcher\t%d\t%d\t%f\n", *channels, rubberband_frequency, pitchscale ); delete s; // Create a rubberband instance RubberBandStretcher::Options options = RubberBandStretcher::OptionProcessRealTime; s = new RubberBandStretcher(rubberband_frequency, *channels, options, 1.0, pitchscale); pdata->s = s; pdata->rubberband_frequency = rubberband_frequency; pdata->in_samples = 0; pdata->out_samples = 0; } s->setPitchScale(pitchscale); if( pitchscale >= 0.5 && pitchscale <= 2.0 ) { // Pitch adjustment < 200% s->setPitchOption(RubberBandStretcher::OptionPitchHighQuality); s->setTransientsOption(RubberBandStretcher::OptionTransientsCrisp); } else { // Pitch adjustment > 200% // "HighConsistency" and "Smooth" options help to avoid large memory // consumption and crashes that can occur for large pitch adjustments. s->setPitchOption(RubberBandStretcher::OptionPitchHighConsistency); s->setTransientsOption(RubberBandStretcher::OptionTransientsSmooth); } // Configure input and output buffers and counters. int consumed_samples = 0; int total_consumed_samples = 0; int received_samples = 0; struct mlt_audio_s in; struct mlt_audio_s out; mlt_audio_set_values( &in, *buffer, *frequency, *format, *samples, *channels ); mlt_audio_set_values( &out, NULL, *frequency, *format, *samples, *channels ); mlt_audio_alloc_data( &out ); // Process all input samples while ( true ) { // Send more samples to the stretcher if ( consumed_samples == in.samples ) { // Continue to repeat input samples into the stretcher until it // provides the desired number of samples out. consumed_samples = 0; mlt_log_debug( MLT_FILTER_SERVICE(filter), "Repeat samples\n"); } int process_samples = std::min( in.samples - consumed_samples, (int)s->getSamplesRequired() ); if ( process_samples == 0 && received_samples == out.samples && total_consumed_samples < in.samples ) { // No more out samples are needed, but input samples are still available. // Send the final input samples for processing. process_samples = in.samples - total_consumed_samples; } if ( process_samples > 0 ) { float* in_planes[MAX_CHANNELS]; for ( int i = 0; i < in.channels; i++ ) { in_planes[i] = ((float*)in.data) + (in.samples * i) + consumed_samples; } s->process( in_planes, process_samples, false ); consumed_samples += process_samples; total_consumed_samples += process_samples; pdata->in_samples += process_samples; } // Receive samples from the stretcher int retrieve_samples = std::min( out.samples - received_samples, s->available() ); if ( retrieve_samples > 0 ) { float* out_planes[MAX_CHANNELS]; for ( int i = 0; i < out.channels; i++ ) { out_planes[i] = ((float*)out.data) + (out.samples * i) + received_samples; } retrieve_samples = (int)s->retrieve( out_planes, retrieve_samples ); received_samples += retrieve_samples; pdata->out_samples += retrieve_samples; } mlt_log_debug( MLT_FILTER_SERVICE(filter), "Process: %d\t Retrieve: %d\n", process_samples, retrieve_samples ); if ( received_samples == out.samples && total_consumed_samples >= in.samples ) { // There is nothing more to do; break; } } // Save the processed samples. mlt_audio_shrink( &out, received_samples ); mlt_frame_set_audio( frame, out.data, out.format, 0, out.release_data ); mlt_audio_get_values( &out, buffer, frequency, format, samples, channels ); // Report the latency. double latency = (double)(pdata->in_samples - pdata->out_samples) * 1000.0 / (double)*frequency; mlt_properties_set_double( filter_properties, "latency", latency ); mlt_service_unlock( MLT_FILTER_SERVICE(filter) ); mlt_log_debug( MLT_FILTER_SERVICE(filter), "Requested: %d\tReceived: %d\tSent: %d\tLatency: %d(%fms)\n", requested_samples, in.samples, out.samples, (int)(pdata->in_samples - pdata->out_samples), latency ); return error; } static mlt_frame filter_process( mlt_filter filter, mlt_frame frame ) { mlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter ); mlt_position position = mlt_filter_get_position( filter, frame ); mlt_position length = mlt_filter_get_length2( filter, frame ); // Determine the pitchscale double pitchscale = 1.0; if ( mlt_properties_exists( filter_properties, "pitchscale" ) ) { pitchscale = mlt_properties_anim_get_double( filter_properties, "pitchscale", position, length ); } else { double octaveshift = mlt_properties_anim_get_double( filter_properties, "octaveshift", position, length ); pitchscale = pow(2, octaveshift); } if ( pitchscale <= 0.0 || /*check for nan:*/pitchscale != pitchscale ) { pitchscale = 1.0; } // Save the pitchscale on the frame to be used in rbpitch_get_audio mlt_properties unique_properties = mlt_frame_unique_properties( frame, MLT_FILTER_SERVICE(filter) ); mlt_properties_set_double( unique_properties, "pitchscale", pitchscale ); mlt_frame_push_audio( frame, (void*)filter ); mlt_frame_push_audio( frame, (void*)rbpitch_get_audio ); return frame; } static void close_filter( mlt_filter filter ) { private_data* pdata = (private_data*)filter->child; if ( pdata ) { RubberBandStretcher* s = static_cast<RubberBandStretcher*>(pdata->s); if ( s ) { delete s; } free( pdata ); filter->child = NULL; } } extern "C" { mlt_filter filter_rbpitch_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg ) { mlt_filter filter = mlt_filter_new(); private_data* pdata = (private_data*)calloc( 1, sizeof(private_data) ); if( filter && pdata ) { pdata->s = NULL; pdata->rubberband_frequency = 0; pdata->in_samples = 0; pdata->out_samples = 0; filter->process = filter_process; filter->close = close_filter; filter->child = pdata; } else { mlt_log_error( MLT_FILTER_SERVICE(filter), "Failed to initialize\n" ); if( filter ) { mlt_filter_close( filter ); } if( pdata ) { free( pdata ); } filter = NULL; } return filter; } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_Windows #include <windows.h> #include <shellapi.h> #include <shlobj.h> #elif qPlatform_POSIX #include <unistd.h> #endif #include "../../Characters/StringBuilder.h" #include "../../Containers/Set.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #include "../../Execution/Platform/Windows/HRESULTErrorException.h" #endif #include "../../Execution/ErrNoException.h" #include "../../IO/FileAccessException.h" #include "../../IO/FileBusyException.h" #include "../../IO/FileFormatException.h" #include "../../Memory/SmallStackBuffer.h" #include "FileUtils.h" #include "FileSystem.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; using Execution::Platform::Windows::ThrowIfZeroGetLastError; #endif // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** **************************** FileSystem::FileSystem **************************** ******************************************************************************** */ IO::FileSystem::FileSystem IO::FileSystem::FileSystem::Default () { static IO::FileSystem::FileSystem sThe_; return sThe_; } bool IO::FileSystem::FileSystem::Access (const String& fileFullPath, FileAccessMode accessMode) const { #if qPlatform_Windows if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) { DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ()); if (attribs == INVALID_FILE_ATTRIBUTES) { return false; } } if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) { DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ()); if ((attribs == INVALID_FILE_ATTRIBUTES) or (attribs & FILE_ATTRIBUTE_READONLY)) { return false; } } return true; #elif qPlatform_POSIX // Not REALLY right - but an OK hack for now... -- LGP 2011-09-26 //http://linux.die.net/man/2/access if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) { if (access (fileFullPath.AsSDKString().c_str (), R_OK) != 0) { return false; } } if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) { if (access (fileFullPath.AsSDKString().c_str (), W_OK) != 0) { return false; } } return true; #else AssertNotImplemented (); return false; #endif } void IO::FileSystem::FileSystem::CheckAccess (const String& fileFullPath, FileAccessMode accessMode) { // quick hack - not fully implemented - but since advsiory only - not too important... if (not Access (fileFullPath, accessMode)) { // FOR NOW - MIMIC OLD CODE - BUT FIX TO CHECK READ AND WRITE (AND BOTH) ACCESS DEPENDING ON ARGS) -- LGP 2009-08-15 Execution::DoThrow (FileAccessException (fileFullPath, accessMode)); } } void IO::FileSystem::FileSystem::CheckFileAccess (const String& fileFullPath, bool checkCanRead, bool checkCanWrite) { if (checkCanRead and checkCanWrite) { CheckAccess (fileFullPath, IO::FileAccessMode::eReadWrite); } else if (checkCanRead) { CheckAccess (fileFullPath, IO::FileAccessMode::eRead); } else if (checkCanWrite) { CheckAccess (fileFullPath, IO::FileAccessMode::eWrite); } } String IO::FileSystem::FileSystem::ResolveShortcut (const String& path2FileOrShortcut) { #if qPlatform_Windows // @todo WRONG semantics if file doesnt exist. Wed should raise an exception here. // But OK if not a shortcut. THEN just rutn the givne file // // // NB: this requires COM, and for now - I don't want the support module depending on the COM module, // so just allow this to fail if COM isn't initialized. // -- LGP 2007-09-23 // { SHFILEINFO info; memset (&info, 0, sizeof (info)); if (::SHGetFileInfo (path2FileOrShortcut.AsSDKString ().c_str (), 0, &info, sizeof (info), SHGFI_ATTRIBUTES) == 0) { return path2FileOrShortcut; } // not a shortcut? if (!(info.dwAttributes & SFGAO_LINK)) { return path2FileOrShortcut; } } // obtain the IShellLink interface IShellLink* psl = nullptr; IPersistFile* ppf = nullptr; try { if (FAILED (::CoCreateInstance (CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl))) { return path2FileOrShortcut; } if (SUCCEEDED (psl->QueryInterface (IID_IPersistFile, (LPVOID*)&ppf))) { if (SUCCEEDED (ppf->Load (path2FileOrShortcut.c_str (), STGM_READ))) { // Resolve the link, this may post UI to find the link if (SUCCEEDED (psl->Resolve(0, SLR_NO_UI))) { TCHAR path[MAX_PATH + 1]; memset (path, 0, sizeof (path)); if (SUCCEEDED (psl->GetPath (path, NEltsOf (path), nullptr, 0))) { ppf->Release (); ppf = nullptr; psl->Release (); psl = nullptr; return String::FromSDKString (path); } } } } } catch (...) { if (ppf != nullptr) { ppf->Release (); } if (psl != nullptr) { psl->Release (); } Execution::DoReThrow (); } if (ppf != nullptr) { ppf->Release (); } if (psl != nullptr) { psl->Release (); } return path2FileOrShortcut; #else Memory::SmallStackBuffer<Characters::SDKChar> buf (1024); ssize_t n; while ( (n = ::readlink (path2FileOrShortcut.AsSDKString ().c_str (), buf, buf.GetSize ())) == buf.GetSize ()) { buf.GrowToSize (buf.GetSize () * 2); } if (n < 0) { auto e = errno; if (e == EINVAL) { // According to http://linux.die.net/man/2/readlink - this means the target is not a shortcut which is OK return path2FileOrShortcut; } else { Execution::errno_ErrorException::DoThrow (e); } } Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed constexpr bool kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_ = true; if (kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_) { const Characters::SDKChar* b = buf.begin (); const Characters::SDKChar* e = b + n; const Characters::SDKChar* i = find (b, e, '\0'); if (i != e) { size_t newN = i - buf.begin (); Assert (newN < n); n = newN; } } return String::FromSDKString (SDKString (buf.begin (), buf.begin () + n)); #endif } String IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, bool throwIfComponentsNotFound) { #if qPlatform_POSIX // We used to call canonicalize_file_name() - but this doesnt work with AIX 7.1/g++4.9.2, and // according to http://man7.org/linux/man-pages/man3/canonicalize_file_name.3.html: // The call canonicalize_file_name(path) is equivalent to the call: // realpath(path, NULL) char* tmp { ::realpath (path2FileOrShortcut.AsSDKString ().c_str (), nullptr) }; if (tmp == nullptr) { errno_ErrorException::DoThrow (errno); } String result { String::FromNarrowSDKString (tmp) }; free (tmp); return result; #elif qPlatform_Windows // @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11 /* * Note: PathCanonicalize has lots of problems, PathCanonicalizeCh, and * PathCchCanonicalizeEx is better, but only works with windows 8 or later. */ using Characters::StringBuilder; String tmp = ResolveShortcut (path2FileOrShortcut); StringBuilder sb; Components c = GetPathComponents (path2FileOrShortcut); if (c.fAbsolutePath == Components::eAbsolutePath) { // use UNC notation sb += L"\\\\?"; if (c.fDriveLetter) { sb += *c.fDriveLetter; } else if (c.fServerAndShare) { sb += c.fServerAndShare->fServer + L"\\" + c.fServerAndShare->fShare; } else { Execution::DoThrow (Execution::StringException (L"for absolute path need drive letter or server/share")); } } else { if (c.fDriveLetter) { sb += *c.fDriveLetter + L":"; } } bool prefixWIthSlash = false; for (String i : c.fPath) { if (prefixWIthSlash) { sb += L"\\"; } sb += i; prefixWIthSlash = true; } return sb.str (); #else AssertNotImplemented (); return path2FileOrShortcut; #endif } String IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, const String& relativeToDirectory, bool throwIfComponentsNotFound) { AssertNotImplemented (); return path2FileOrShortcut; } IO::FileSystem::FileSystem::Components IO::FileSystem::FileSystem::GetPathComponents (const String& fileName) { // @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11 // See http://en.wikipedia.org/wiki/Path_%28computing%29 to write this #if 0 //windows C: \user\docs\Letter.txt / user / docs / Letter.txt C: Letter.txt \\Server01\user\docs\Letter.txt \\ ? \UNC\Server01\user\docs\Letter.txt \\ ? \C : \user\docs\Letter.txt C : \user\docs\somefile.ext : alternate_stream_name . / inthisdir .. / .. / greatgrandparent #endif #if 0 // unix / home / user / docs / Letter.txt . / inthisdir .. / .. / greatgrandparent ~ / .rcinfo #endif IO::FileSystem::FileSystem::Components result; using Traversal::Iterator; using Characters::Character; #if qPlatform_Windows bool isUNCName = fileName.length () > 2 and fileName.StartsWith (L"\\\\"); bool isAbsolutePath = fileName.length () >= 1 and fileName.StartsWith (L"\\"); #else #endif #if qPlatform_Windows const Set<Character> kSlashChars_ = { '\\', '/' }; #else const Set<Character> kSlashChars_ = { '/' }; #endif Sequence<String> rawComponents = fileName.Tokenize (kSlashChars_, false); Iterator<String> i = rawComponents.begin (); #if qPlatform_Windows if (isUNCName) { // work todo } #endif for (; i != rawComponents.end (); ++i) { result.fPath.Append (*i); } AssertNotImplemented (); return result; } FileOffset_t IO::FileSystem::FileSystem::GetFileSize (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return fileAttrData.nFileSizeLow + (static_cast<FileOffset_t> (fileAttrData.nFileSizeHigh) << 32); #else AssertNotImplemented (); return 0; #endif } DateTime IO::FileSystem::FileSystem::GetFileLastModificationDate (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return DateTime (fileAttrData.ftLastWriteTime); #else AssertNotImplemented (); return DateTime (); #endif } DateTime IO::FileSystem::FileSystem::GetFileLastAccessDate (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return DateTime (fileAttrData.ftLastAccessTime); #else AssertNotImplemented (); return DateTime (); #endif } void IO::FileSystem::FileSystem::RemoveFile (const String& fileName) { #if qPlatform_Windows && qTargetPlatformSDKUseswchar_t Execution::ThrowErrNoIfNegative (::_wunlink (fileName.c_str ())); #else Execution::ThrowErrNoIfNegative (::unlink (fileName.AsNarrowSDKString ().c_str ())); #endif } void IO::FileSystem::FileSystem::RemoveFileIf (const String& fileName) { #if qPlatform_Windows && qTargetPlatformSDKUseswchar_t int r = ::_wunlink (fileName.c_str ()); #else int r = ::unlink (fileName.AsNarrowSDKString ().c_str ()); #endif if (r < 0) { if (errno != ENOENT) { errno_ErrorException::DoThrow (errno); } } } String IO::FileSystem::FileSystem::GetCurrentDirectory () const { #if qPlatform_POSIX SDKChar buf[MAX_PATH]; Execution::ThrowErrNoIfNull (::getcwd (buf, NEltsOf (buf))); return String::FromSDKString (buf); #elif qPlatform_Windows SDKChar buf[MAX_PATH]; ThrowIfZeroGetLastError (::GetCurrentDirectory (MAX_PATH, buf)); return String::FromSDKString (buf); #else #endif } void IO::FileSystem::FileSystem::SetCurrentDirectory (const String& newDir) { #if qPlatform_POSIX Execution::ThrowErrNoIfNegative (::chdir (newDir.AsNarrowSDKString ().c_str ())); #elif qPlatform_Windows ::SetCurrentDirectory(newDir.AsSDKString ().c_str ()); #else #endif } <commit_msg>POSIX typo<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #if qPlatform_Windows #include <windows.h> #include <shellapi.h> #include <shlobj.h> #elif qPlatform_POSIX #include <unistd.h> #endif #include "../../Characters/StringBuilder.h" #include "../../Containers/Set.h" #if qPlatform_Windows #include "../../Execution/Platform/Windows/Exception.h" #include "../../Execution/Platform/Windows/HRESULTErrorException.h" #endif #include "../../Execution/ErrNoException.h" #include "../../IO/FileAccessException.h" #include "../../IO/FileBusyException.h" #include "../../IO/FileFormatException.h" #include "../../Memory/SmallStackBuffer.h" #include "FileUtils.h" #include "FileSystem.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::FileSystem; #if qPlatform_Windows using Execution::Platform::Windows::ThrowIfFalseGetLastError; using Execution::Platform::Windows::ThrowIfZeroGetLastError; #endif // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** **************************** FileSystem::FileSystem **************************** ******************************************************************************** */ IO::FileSystem::FileSystem IO::FileSystem::FileSystem::Default () { static IO::FileSystem::FileSystem sThe_; return sThe_; } bool IO::FileSystem::FileSystem::Access (const String& fileFullPath, FileAccessMode accessMode) const { #if qPlatform_Windows if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) { DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ()); if (attribs == INVALID_FILE_ATTRIBUTES) { return false; } } if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) { DWORD attribs = ::GetFileAttributesW (fileFullPath.c_str ()); if ((attribs == INVALID_FILE_ATTRIBUTES) or (attribs & FILE_ATTRIBUTE_READONLY)) { return false; } } return true; #elif qPlatform_POSIX // Not REALLY right - but an OK hack for now... -- LGP 2011-09-26 //http://linux.die.net/man/2/access if ((accessMode & FileAccessMode::eRead) == FileAccessMode::eRead) { if (access (fileFullPath.AsSDKString().c_str (), R_OK) != 0) { return false; } } if ((accessMode & FileAccessMode::eWrite) == FileAccessMode::eWrite) { if (access (fileFullPath.AsSDKString().c_str (), W_OK) != 0) { return false; } } return true; #else AssertNotImplemented (); return false; #endif } void IO::FileSystem::FileSystem::CheckAccess (const String& fileFullPath, FileAccessMode accessMode) { // quick hack - not fully implemented - but since advsiory only - not too important... if (not Access (fileFullPath, accessMode)) { // FOR NOW - MIMIC OLD CODE - BUT FIX TO CHECK READ AND WRITE (AND BOTH) ACCESS DEPENDING ON ARGS) -- LGP 2009-08-15 Execution::DoThrow (FileAccessException (fileFullPath, accessMode)); } } void IO::FileSystem::FileSystem::CheckFileAccess (const String& fileFullPath, bool checkCanRead, bool checkCanWrite) { if (checkCanRead and checkCanWrite) { CheckAccess (fileFullPath, IO::FileAccessMode::eReadWrite); } else if (checkCanRead) { CheckAccess (fileFullPath, IO::FileAccessMode::eRead); } else if (checkCanWrite) { CheckAccess (fileFullPath, IO::FileAccessMode::eWrite); } } String IO::FileSystem::FileSystem::ResolveShortcut (const String& path2FileOrShortcut) { #if qPlatform_Windows // @todo WRONG semantics if file doesnt exist. Wed should raise an exception here. // But OK if not a shortcut. THEN just rutn the givne file // // // NB: this requires COM, and for now - I don't want the support module depending on the COM module, // so just allow this to fail if COM isn't initialized. // -- LGP 2007-09-23 // { SHFILEINFO info; memset (&info, 0, sizeof (info)); if (::SHGetFileInfo (path2FileOrShortcut.AsSDKString ().c_str (), 0, &info, sizeof (info), SHGFI_ATTRIBUTES) == 0) { return path2FileOrShortcut; } // not a shortcut? if (!(info.dwAttributes & SFGAO_LINK)) { return path2FileOrShortcut; } } // obtain the IShellLink interface IShellLink* psl = nullptr; IPersistFile* ppf = nullptr; try { if (FAILED (::CoCreateInstance (CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl))) { return path2FileOrShortcut; } if (SUCCEEDED (psl->QueryInterface (IID_IPersistFile, (LPVOID*)&ppf))) { if (SUCCEEDED (ppf->Load (path2FileOrShortcut.c_str (), STGM_READ))) { // Resolve the link, this may post UI to find the link if (SUCCEEDED (psl->Resolve(0, SLR_NO_UI))) { TCHAR path[MAX_PATH + 1]; memset (path, 0, sizeof (path)); if (SUCCEEDED (psl->GetPath (path, NEltsOf (path), nullptr, 0))) { ppf->Release (); ppf = nullptr; psl->Release (); psl = nullptr; return String::FromSDKString (path); } } } } } catch (...) { if (ppf != nullptr) { ppf->Release (); } if (psl != nullptr) { psl->Release (); } Execution::DoReThrow (); } if (ppf != nullptr) { ppf->Release (); } if (psl != nullptr) { psl->Release (); } return path2FileOrShortcut; #else Memory::SmallStackBuffer<Characters::SDKChar> buf (1024); ssize_t n; while ( (n = ::readlink (path2FileOrShortcut.AsSDKString ().c_str (), buf, buf.GetSize ())) == buf.GetSize ()) { buf.GrowToSize (buf.GetSize () * 2); } if (n < 0) { auto e = errno; if (e == EINVAL) { // According to http://linux.die.net/man/2/readlink - this means the target is not a shortcut which is OK return path2FileOrShortcut; } else { Execution::errno_ErrorException::DoThrow (e); } } Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed constexpr bool kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_ = true; if (kWorkaroundBuggyCentos5ReturnsNulBytesInBuf_) { const Characters::SDKChar* b = buf.begin (); const Characters::SDKChar* e = b + n; const Characters::SDKChar* i = find (b, e, '\0'); if (i != e) { size_t newN = i - buf.begin (); Assert (newN < n); n = newN; } } return String::FromSDKString (SDKString (buf.begin (), buf.begin () + n)); #endif } String IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, bool throwIfComponentsNotFound) { #if qPlatform_POSIX // We used to call canonicalize_file_name() - but this doesnt work with AIX 7.1/g++4.9.2, and // according to http://man7.org/linux/man-pages/man3/canonicalize_file_name.3.html: // The call canonicalize_file_name(path) is equivalent to the call: // realpath(path, NULL) char* tmp { ::realpath (path2FileOrShortcut.AsSDKString ().c_str (), nullptr) }; if (tmp == nullptr) { errno_ErrorException::DoThrow (errno); } String result { String::FromNarrowSDKString (tmp) }; free (tmp); return result; #elif qPlatform_Windows // @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11 /* * Note: PathCanonicalize has lots of problems, PathCanonicalizeCh, and * PathCchCanonicalizeEx is better, but only works with windows 8 or later. */ using Characters::StringBuilder; String tmp = ResolveShortcut (path2FileOrShortcut); StringBuilder sb; Components c = GetPathComponents (path2FileOrShortcut); if (c.fAbsolutePath == Components::eAbsolutePath) { // use UNC notation sb += L"\\\\?"; if (c.fDriveLetter) { sb += *c.fDriveLetter; } else if (c.fServerAndShare) { sb += c.fServerAndShare->fServer + L"\\" + c.fServerAndShare->fShare; } else { Execution::DoThrow (Execution::StringException (L"for absolute path need drive letter or server/share")); } } else { if (c.fDriveLetter) { sb += *c.fDriveLetter + L":"; } } bool prefixWIthSlash = false; for (String i : c.fPath) { if (prefixWIthSlash) { sb += L"\\"; } sb += i; prefixWIthSlash = true; } return sb.str (); #else AssertNotImplemented (); return path2FileOrShortcut; #endif } String IO::FileSystem::FileSystem::CanonicalizeName (const String& path2FileOrShortcut, const String& relativeToDirectory, bool throwIfComponentsNotFound) { AssertNotImplemented (); return path2FileOrShortcut; } IO::FileSystem::FileSystem::Components IO::FileSystem::FileSystem::GetPathComponents (const String& fileName) { // @todo LARGELY UNSTED ROUGH DRAFT - 2015-05-11 // See http://en.wikipedia.org/wiki/Path_%28computing%29 to write this #if 0 //windows C: \user\docs\Letter.txt / user / docs / Letter.txt C: Letter.txt \\Server01\user\docs\Letter.txt \\ ? \UNC\Server01\user\docs\Letter.txt \\ ? \C : \user\docs\Letter.txt C : \user\docs\somefile.ext : alternate_stream_name . / inthisdir .. / .. / greatgrandparent #endif #if 0 // unix / home / user / docs / Letter.txt . / inthisdir .. / .. / greatgrandparent ~ / .rcinfo #endif IO::FileSystem::FileSystem::Components result; using Traversal::Iterator; using Characters::Character; #if qPlatform_Windows bool isUNCName = fileName.length () > 2 and fileName.StartsWith (L"\\\\"); bool isAbsolutePath = fileName.length () >= 1 and fileName.StartsWith (L"\\"); #else #endif #if qPlatform_Windows const Set<Character> kSlashChars_ = { '\\', '/' }; #else const Set<Character> kSlashChars_ = { '/' }; #endif Sequence<String> rawComponents = fileName.Tokenize (kSlashChars_, false); Iterator<String> i = rawComponents.begin (); #if qPlatform_Windows if (isUNCName) { // work todo } #endif for (; i != rawComponents.end (); ++i) { result.fPath.Append (*i); } AssertNotImplemented (); return result; } FileOffset_t IO::FileSystem::FileSystem::GetFileSize (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return fileAttrData.nFileSizeLow + (static_cast<FileOffset_t> (fileAttrData.nFileSizeHigh) << 32); #else AssertNotImplemented (); return 0; #endif } DateTime IO::FileSystem::FileSystem::GetFileLastModificationDate (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return DateTime (fileAttrData.ftLastWriteTime); #else AssertNotImplemented (); return DateTime (); #endif } DateTime IO::FileSystem::FileSystem::GetFileLastAccessDate (const String& fileName) { #if qPlatform_Windows WIN32_FILE_ATTRIBUTE_DATA fileAttrData; (void)::memset (&fileAttrData, 0, sizeof (fileAttrData)); ThrowIfFalseGetLastError (::GetFileAttributesExW (fileName.c_str (), GetFileExInfoStandard, &fileAttrData)); return DateTime (fileAttrData.ftLastAccessTime); #else AssertNotImplemented (); return DateTime (); #endif } void IO::FileSystem::FileSystem::RemoveFile (const String& fileName) { #if qPlatform_Windows && qTargetPlatformSDKUseswchar_t Execution::ThrowErrNoIfNegative (::_wunlink (fileName.c_str ())); #else Execution::ThrowErrNoIfNegative (::unlink (fileName.AsNarrowSDKString ().c_str ())); #endif } void IO::FileSystem::FileSystem::RemoveFileIf (const String& fileName) { #if qPlatform_Windows && qTargetPlatformSDKUseswchar_t int r = ::_wunlink (fileName.c_str ()); #else int r = ::unlink (fileName.AsNarrowSDKString ().c_str ()); #endif if (r < 0) { if (errno != ENOENT) { errno_ErrorException::DoThrow (errno); } } } String IO::FileSystem::FileSystem::GetCurrentDirectory () const { #if qPlatform_POSIX SDKChar buf[PATH_MAX]; Execution::ThrowErrNoIfNull (::getcwd (buf, NEltsOf (buf))); return String::FromSDKString (buf); #elif qPlatform_Windows SDKChar buf[MAX_PATH]; ThrowIfZeroGetLastError (::GetCurrentDirectory (NEltsOf (buf), buf)); return String::FromSDKString (buf); #else #endif } void IO::FileSystem::FileSystem::SetCurrentDirectory (const String& newDir) { #if qPlatform_POSIX Execution::ThrowErrNoIfNegative (::chdir (newDir.AsNarrowSDKString ().c_str ())); #elif qPlatform_Windows ::SetCurrentDirectory(newDir.AsSDKString ().c_str ()); #else #endif } <|endoftext|>
<commit_before>#include "motor/multirotor_tri_motor_mapper.hpp" #include <array> #include <cstddef> #include "protocol/messages.hpp" #include "util/time.hpp" #include <chprintf.h> constexpr float M_PI = 3.1415926535; MultirotorTriMotorMapper::MultirotorTriMotorMapper(PWMDeviceGroup<3>& motors, PWMDeviceGroup<1>& servos, Communicator& communicator, Logger& logger) : motors(motors), servos(servos), throttleStream(communicator, 5), logger(logger){ } void MultirotorTriMotorMapper::run(bool armed, ActuatorSetpoint& input) { // TODO(yoos): comment on motor indexing convention starting from positive // X in counterclockwise order. // Calculate servo output std::array<float, 1> sOutputs; sOutputs[0] = 0.540 - 0.5*input.yaw; // Magic number servo bias for pusher yaw prop. sOutputs[0] = std::min(1.0, std::max(-1.0, sOutputs[0])); servos.set(armed, sOutputs); // Scale throttle to compensate for roll and pitch up to max angles input.throttle /= std::cos(std::min(std::fabs(input.roll), M_PI/3)); input.throttle /= std::cos(std::min(std::fabs(input.pitch), M_PI/3)); input.throttle = std::min(input.throttle, 1.0); // Not entirely necessary, but perhaps preserve some control authority. // Calculate motor outputs std::array<float, 3> mOutputs; mOutputs[0] = input.throttle + 0.866025*input.roll - 0.5*input.pitch; // Left mOutputs[1] = input.throttle + input.pitch; // Tail mOutputs[2] = input.throttle - 0.866025*input.roll - 0.5*input.pitch; // Right motors.set(armed, mOutputs); // Scale tail thrust per servo tilt // TODO(yoos): Again, resolve magic number. mOutputs[1] /= std::cos(3.1415926535/4*input.yaw); // DEBUG //static int loop=0; //if (loop == 0) { // chprintf((BaseSequentialStream*)&SD4, "MM %f %f %f %f\r\n", mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0]); //} //loop = (loop+1) % 50; protocol::message::motor_throttle_message_t m { .time = ST2MS(chibios_rt::System::getTime()), .throttles = { mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0] } }; if(throttleStream.ready()) { throttleStream.publish(m); } logger.write(m); } <commit_msg>Scale tail thrust based on capped output.<commit_after>#include "motor/multirotor_tri_motor_mapper.hpp" #include <array> #include <cstddef> #include "protocol/messages.hpp" #include "util/time.hpp" #include <chprintf.h> constexpr float M_PI = 3.1415926535; MultirotorTriMotorMapper::MultirotorTriMotorMapper(PWMDeviceGroup<3>& motors, PWMDeviceGroup<1>& servos, Communicator& communicator, Logger& logger) : motors(motors), servos(servos), throttleStream(communicator, 5), logger(logger){ } void MultirotorTriMotorMapper::run(bool armed, ActuatorSetpoint& input) { // TODO(yoos): comment on motor indexing convention starting from positive // X in counterclockwise order. // Calculate servo output std::array<float, 1> sOutputs; sOutputs[0] = 0.540 - 0.5*input.yaw; // Magic number servo bias for pusher yaw prop. sOutputs[0] = std::min(1.0, std::max(-1.0, sOutputs[0])); servos.set(armed, sOutputs); // Scale throttle to compensate for roll and pitch up to max angles input.throttle /= std::cos(std::min(std::fabs(input.roll), M_PI/3)); input.throttle /= std::cos(std::min(std::fabs(input.pitch), M_PI/3)); input.throttle = std::min(input.throttle, 1.0); // Not entirely necessary, but perhaps preserve some control authority. // Calculate motor outputs std::array<float, 3> mOutputs; mOutputs[0] = input.throttle + 0.866025*input.roll - 0.5*input.pitch; // Left mOutputs[1] = input.throttle + input.pitch; // Tail mOutputs[2] = input.throttle - 0.866025*input.roll - 0.5*input.pitch; // Right motors.set(armed, mOutputs); // Scale tail thrust per servo tilt // TODO(yoos): Again, resolve magic number. mOutputs[1] /= std::cos(3.1415926535/4*sOutputs[0]); // DEBUG //static int loop=0; //if (loop == 0) { // chprintf((BaseSequentialStream*)&SD4, "MM %f %f %f %f\r\n", mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0]); //} //loop = (loop+1) % 50; protocol::message::motor_throttle_message_t m { .time = ST2MS(chibios_rt::System::getTime()), .throttles = { mOutputs[0], mOutputs[1], mOutputs[2], sOutputs[0] } }; if(throttleStream.ready()) { throttleStream.publish(m); } logger.write(m); } <|endoftext|>
<commit_before>#include <babylon/materials/textures/raw_texture_2d_array.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/textures/internal_texture.h> namespace BABYLON { RawTexture2DArray::RawTexture2DArray(const ArrayBufferView& data, int width, int height, int depth, unsigned int iFormat, Scene* scene, bool generateMipMaps, bool iInvertY, unsigned int iSamplingMode, unsigned int iTextureType) : Texture{nullptr, scene, !generateMipMaps, iInvertY}, format{iFormat} { _texture = scene->getEngine()->createRawTexture2DArray(data, // width, // height, // depth, // iFormat, // generateMipMaps, // invertY, // iSamplingMode, // "", // iTextureType // ); is2DArray = true; } RawTexture2DArray::~RawTexture2DArray() = default; void RawTexture2DArray::update(const ArrayBufferView& data) { if (!_texture) { return; } _getEngine()->updateRawTexture2DArray(_texture, data, _texture->format, _texture->invertY, "", _texture->type); } } // end of namespace BABYLON <commit_msg>Checking for valid engine reference<commit_after>#include <babylon/materials/textures/raw_texture_2d_array.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/materials/textures/internal_texture.h> namespace BABYLON { RawTexture2DArray::RawTexture2DArray(const ArrayBufferView& data, int width, int height, int depth, unsigned int iFormat, Scene* scene, bool generateMipMaps, bool iInvertY, unsigned int iSamplingMode, unsigned int iTextureType) : Texture{nullptr, scene, !generateMipMaps, iInvertY}, format{iFormat} { _texture = scene->getEngine()->createRawTexture2DArray(data, // width, // height, // depth, // iFormat, // generateMipMaps, // invertY, // iSamplingMode, // "", // iTextureType // ); is2DArray = true; } RawTexture2DArray::~RawTexture2DArray() = default; void RawTexture2DArray::update(const ArrayBufferView& data) { if (!_texture || !_getEngine()) { return; } _getEngine()->updateRawTexture2DArray(_texture, data, _texture->format, _texture->invertY, "", _texture->type); } } // end of namespace BABYLON <|endoftext|>