commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
35dc54d16594ebafe1c84d678b3d1ab91f34c44c
framework/src/auxkernels/BuildArrayVariableAux.C
framework/src/auxkernels/BuildArrayVariableAux.C
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "BuildArrayVariableAux.h" registerMooseObject("MooseApp", BuildArrayVariableAux); defineLegacyParams(BuildArrayVariableAux); InputParameters BuildArrayVariableAux::validParams() { InputParameters params = ArrayAuxKernel::validParams(); params.addParam<std::vector<VariableName>>("component_variables", "The variables that make up each component of the output array variable."); params.addClassDescription( "Copy multiple variables into the components of an array variable."); return params; } BuildArrayVariableAux::BuildArrayVariableAux(const InputParameters & parameters) : ArrayAuxKernel(parameters) { const auto & var_names = parameters.get<std::vector<VariableName>>("component_variables"); // Check the number of component variables if (var_names.size() != _var.count()) mooseError("The array variable has ", _var.count(), " components, but ", var_names.size(), " component variables were specified."); // Get pointers to each of the component vars THREAD_ID tid = parameters.get<THREAD_ID>("_tid"); for (VariableName name : var_names) _component_vars.push_back(& _subproblem.getVariable(tid, name)); // Check the FEType of the output variable if ((_var.feType().family != FEFamily::MONOMIAL) || (_var.feType().order != Order::CONSTANT)) mooseError( "BuildArrayVariableAux only supports constant monomial variables"); // Check the FEType of the component vars for (auto var : _component_vars) { if ((var->feType().family != FEFamily::MONOMIAL) || (var->feType().order != Order::CONSTANT)) mooseError( "BuildArrayVariableAux only supports constant monomial variables"); } } RealEigenVector BuildArrayVariableAux::computeValue() { // This function assumes that DoFs are indexed by element and that there is // only 1 DoF per element, i.e. that all variables are constant monomials. constexpr unsigned int fe_comp {0}; // Get the value of each component std::vector<Real> component_vals; component_vals.reserve(_component_vars.size()); for (auto var : _component_vars) { unsigned int sys_num = var->sys().number(); unsigned int var_num = var->number(); dof_id_type component_dof = _current_elem->dof_number(sys_num, var_num, fe_comp); component_vals.push_back(var->sys().solution()(component_dof)); } // Convert the output to an Eigen matrix and return RealEigenVector out; out = Eigen::Map<RealEigenVector>(component_vals.data(), component_vals.size()); return out; }
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "BuildArrayVariableAux.h" registerMooseObject("MooseApp", BuildArrayVariableAux); defineLegacyParams(BuildArrayVariableAux); InputParameters BuildArrayVariableAux::validParams() { InputParameters params = ArrayAuxKernel::validParams(); params.addParam<std::vector<VariableName>>( "component_variables", "The variables that make up each component of the output array variable."); params.addClassDescription("Copy multiple variables into the components of an array variable."); return params; } BuildArrayVariableAux::BuildArrayVariableAux(const InputParameters & parameters) : ArrayAuxKernel(parameters) { const auto & var_names = parameters.get<std::vector<VariableName>>("component_variables"); // Check the number of component variables if (var_names.size() != _var.count()) mooseError("The array variable has ", _var.count(), " components, but ", var_names.size(), " component variables were specified."); // Get pointers to each of the component vars THREAD_ID tid = parameters.get<THREAD_ID>("_tid"); for (VariableName name : var_names) _component_vars.push_back(&_subproblem.getVariable(tid, name)); // Check the FEType of the output variable if ((_var.feType().family != FEFamily::MONOMIAL) || (_var.feType().order != Order::CONSTANT)) mooseError("BuildArrayVariableAux only supports constant monomial variables"); // Check the FEType of the component vars for (auto var : _component_vars) { if ((var->feType().family != FEFamily::MONOMIAL) || (var->feType().order != Order::CONSTANT)) mooseError("BuildArrayVariableAux only supports constant monomial variables"); } } RealEigenVector BuildArrayVariableAux::computeValue() { // This function assumes that DoFs are indexed by element and that there is // only 1 DoF per element, i.e. that all variables are constant monomials. constexpr unsigned int fe_comp{0}; // Get the value of each component std::vector<Real> component_vals; component_vals.reserve(_component_vars.size()); for (auto var : _component_vars) { unsigned int sys_num = var->sys().number(); unsigned int var_num = var->number(); dof_id_type component_dof = _current_elem->dof_number(sys_num, var_num, fe_comp); component_vals.push_back(var->sys().solution()(component_dof)); } // Convert the output to an Eigen matrix and return RealEigenVector out; out = Eigen::Map<RealEigenVector>(component_vals.data(), component_vals.size()); return out; }
Use clang-format to make code lines longer
Use clang-format to make code lines longer
C++
lgpl-2.1
lindsayad/moose,harterj/moose,idaholab/moose,lindsayad/moose,laagesen/moose,lindsayad/moose,SudiptaBiswas/moose,jessecarterMOOSE/moose,harterj/moose,dschwen/moose,sapitts/moose,bwspenc/moose,jessecarterMOOSE/moose,milljm/moose,idaholab/moose,andrsd/moose,nuclear-wizard/moose,jessecarterMOOSE/moose,harterj/moose,jessecarterMOOSE/moose,nuclear-wizard/moose,milljm/moose,idaholab/moose,bwspenc/moose,bwspenc/moose,sapitts/moose,SudiptaBiswas/moose,milljm/moose,jessecarterMOOSE/moose,SudiptaBiswas/moose,milljm/moose,nuclear-wizard/moose,idaholab/moose,dschwen/moose,SudiptaBiswas/moose,nuclear-wizard/moose,dschwen/moose,idaholab/moose,lindsayad/moose,dschwen/moose,bwspenc/moose,bwspenc/moose,harterj/moose,harterj/moose,SudiptaBiswas/moose,laagesen/moose,lindsayad/moose,laagesen/moose,sapitts/moose,laagesen/moose,sapitts/moose,sapitts/moose,milljm/moose,andrsd/moose,andrsd/moose,laagesen/moose,andrsd/moose,dschwen/moose,andrsd/moose
612212ef791faa756d89a93d6a93e530c3de95fe
yahttp/utility.hpp
yahttp/utility.hpp
#ifndef _YAHTTP_UTILITY_HPP #define _YAHTTP_UTILITY_HPP 1 #include <string> #include <algorithm> #include <cstdio> namespace YaHTTP { class Utility { public: static std::string decodeURL(const std::string& component) { std::string result = component; size_t pos1,pos2; pos2 = 0; while((pos1 = result.find_first_of("%", pos2))!=std::string::npos) { std::string code; char a,b,c; if (pos1 + 2 > result.length()) return result; // end of result code = result.substr(pos1+1, 2); a = std::tolower(code[0]); b = std::tolower(code[1]); if ((( '0' > a || a > '9') && ('a' > a || a > 'f')) || (( '0' > b || b > '9') && ('a' > b || b > 'f'))) { pos2 = pos1+3; continue; } if ('0' <= a && a <= '9') a = a - '0'; if ('a' <= a && a <= 'f') a = a - 'a' + 0x0a; if ('0' <= b && b <= '9') b = b - '0'; if ('a' <= b && b <= 'f') b = b - 'a' + 0x0a; c = (a<<4)+b; result = result.replace(pos1,3,1,c); pos2=pos1; } return result; }; static std::string encodeURL(const std::string& component, bool encodeSlash = true) { std::string result = component; char repl[3]; size_t pos; for(std::string::iterator iter = result.begin(); iter != result.end(); iter++) { if (*iter != '+' && !(encodeSlash == false || *iter == '/') && !std::isalnum(*iter)) { // replace with different thing pos = std::distance(result.begin(), iter); std::snprintf(repl,3,"%02x", *iter); result = result.replace(pos, 1, "%", 1).insert(pos+1, repl, 2); iter = result.begin() + pos + 2; } } return result; }; static std::string status2text(int status) { switch(status) { case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Time-out"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-URI Too Large"; case 415: return "Unsupported Media Type"; case 416: return "Requested range not satisfiable"; case 417: return "Expectation Failed"; case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Time-out"; case 505: return "HTTP Version not supported"; default: return "Unknown Status"; } }; static std::map<std::string,std::string> parseUrlParameters(std::string parameters) { std::string::size_type pos = 0; std::map<std::string,std::string> parameter_map; while (pos != std::string::npos) { // find next parameter start std::string::size_type nextpos = parameters.find("&", pos); std::string::size_type delim = parameters.find("=", pos); if (delim > nextpos) { delim = nextpos; } std::string key; std::string value; if (delim == std::string::npos) { key = parameters.substr(pos); } else { key = parameters.substr(pos, delim-pos); if (nextpos == std::string::npos) { value = parameters.substr(delim); } else { value = parameters.substr(delim, nextpos-delim); } } if (key.empty()) { // no parameters at all break; } key = decodeURL(key); value = decodeURL(value); parameter_map[key] = value; pos = nextpos; } return parameter_map; }; static void trim_right(std::string &str) { const std::locale &loc = std::locale::classic(); std::string::reverse_iterator iter = str.rbegin(); while(iter != str.rend() && std::isspace(*iter, loc)) iter++; str.erase(iter.base(), str.end()); }; static std::string camelizeHeader(const std::string &str) { std::string::const_iterator iter = str.begin(); std::string result; const std::locale &loc = std::locale::classic(); bool doNext = true; while(iter != str.end()) { if (doNext) result.insert(result.end(), std::toupper(*iter, loc)); else result.insert(result.end(), std::tolower(*iter, loc)); doNext = (*(iter++) == '-'); } return result; }; }; }; #endif
#ifndef _YAHTTP_UTILITY_HPP #define _YAHTTP_UTILITY_HPP 1 #include <string> #include <algorithm> #include <cstdio> namespace YaHTTP { class Utility { public: static std::string decodeURL(const std::string& component) { std::string result = component; size_t pos1,pos2; pos2 = 0; while((pos1 = result.find_first_of("%", pos2))!=std::string::npos) { std::string code; char a,b,c; if (pos1 + 2 > result.length()) return result; // end of result code = result.substr(pos1+1, 2); a = std::tolower(code[0]); b = std::tolower(code[1]); if ((( '0' > a || a > '9') && ('a' > a || a > 'f')) || (( '0' > b || b > '9') && ('a' > b || b > 'f'))) { pos2 = pos1+3; continue; } if ('0' <= a && a <= '9') a = a - '0'; if ('a' <= a && a <= 'f') a = a - 'a' + 0x0a; if ('0' <= b && b <= '9') b = b - '0'; if ('a' <= b && b <= 'f') b = b - 'a' + 0x0a; c = (a<<4)+b; result = result.replace(pos1,3,1,c); pos2=pos1; } return result; }; static std::string encodeURL(const std::string& component, bool encodeSlash = true) { std::string result = component; char repl[3]; size_t pos; for(std::string::iterator iter = result.begin(); iter != result.end(); iter++) { if (*iter != '+' && !(encodeSlash == false || *iter == '/') && !std::isalnum(*iter)) { // replace with different thing pos = std::distance(result.begin(), iter); std::snprintf(repl,3,"%02x", *iter); result = result.replace(pos, 1, "%", 1).insert(pos+1, repl, 2); iter = result.begin() + pos + 2; } } return result; }; static std::string status2text(int status) { switch(status) { case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Time-out"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-URI Too Large"; case 415: return "Unsupported Media Type"; case 416: return "Requested range not satisfiable"; case 417: return "Expectation Failed"; case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Time-out"; case 505: return "HTTP Version not supported"; default: return "Unknown Status"; } }; static std::map<std::string,std::string> parseUrlParameters(std::string parameters) { std::string::size_type pos = 0; std::map<std::string,std::string> parameter_map; while (pos != std::string::npos) { // find next parameter start std::string::size_type nextpos = parameters.find("&", pos); std::string::size_type delim = parameters.find("=", pos); if (delim > nextpos) { delim = nextpos; } std::string key; std::string value; if (delim == std::string::npos) { key = parameters.substr(pos); } else { key = parameters.substr(pos, delim-pos); if (nextpos == std::string::npos) { value = parameters.substr(delim+1); } else { value = parameters.substr(delim+1, nextpos-delim); } } if (key.empty()) { // no parameters at all break; } key = decodeURL(key); value = decodeURL(value); parameter_map[key] = value; pos = nextpos; } return parameter_map; }; static void trim_right(std::string &str) { const std::locale &loc = std::locale::classic(); std::string::reverse_iterator iter = str.rbegin(); while(iter != str.rend() && std::isspace(*iter, loc)) iter++; str.erase(iter.base(), str.end()); }; static std::string camelizeHeader(const std::string &str) { std::string::const_iterator iter = str.begin(); std::string result; const std::locale &loc = std::locale::classic(); bool doNext = true; while(iter != str.end()) { if (doNext) result.insert(result.end(), std::toupper(*iter, loc)); else result.insert(result.end(), std::tolower(*iter, loc)); doNext = (*(iter++) == '-'); } return result; }; }; }; #endif
fix off by one in parameter parser
fix off by one in parameter parser
C++
mit
cmouse/yahttp,cmouse/yahttp,cmouse/yahttp
5d5601c42982482552b9cde144558ddce9f789da
fuzz/FuzzDrawFunctions.cpp
fuzz/FuzzDrawFunctions.cpp
/* * Copyright 2016 Mozilla Foundation * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Fuzz.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkImage.h" #include "SkLayerRasterizer.h" #include "SkPath.h" #include "SkSurface.h" #include "SkTypeface.h" #include "SkClipOpPriv.h" static const int kBmpSize = 24; static const int kMaxX = 250; static const int kMaxY = 250; static const int kPtsLen = 10; static const int kTxtLen = 5; static void init_string(Fuzz* fuzz, char* str, size_t bufSize) { for (size_t i = 0; i < bufSize-1; ++i) { fuzz->nextRange(&str[i], 0x20, 0x7E); // printable ASCII } str[bufSize-1] = '\0'; } // make_paint mostly borrowed from FilterFuzz.cpp static void init_paint(Fuzz* fuzz, SkPaint* p) { bool b; fuzz->next(&b); p->setAntiAlias(b); uint8_t tmp_u8; fuzz->nextRange(&tmp_u8, 0, (int)SkBlendMode::kLastMode); p->setBlendMode(static_cast<SkBlendMode>(tmp_u8)); SkColor co; fuzz->next(&co); p->setColor(co); fuzz->next(&b); p->setDither(b); fuzz->nextRange(&tmp_u8, 0, (int)kHigh_SkFilterQuality); p->setFilterQuality(static_cast<SkFilterQuality>(tmp_u8)); fuzz->nextRange(&tmp_u8, 0, (int)SkPaint::kFull_Hinting); p->setHinting(static_cast<SkPaint::Hinting>(tmp_u8)); fuzz->nextRange(&tmp_u8, 0, (int)SkPaint::kLast_Cap); p->setStrokeCap(static_cast<SkPaint::Cap>(tmp_u8)); fuzz->nextRange(&tmp_u8, 0, (int)SkPaint::kLast_Join); p->setStrokeJoin(static_cast<SkPaint::Join>(tmp_u8)); SkScalar sc; fuzz->next(&sc); p->setStrokeMiter(sc); fuzz->next(&sc); p->setStrokeWidth(sc); fuzz->nextRange(&tmp_u8, 0, (int)SkPaint::kStrokeAndFill_Style); p->setStyle(static_cast<SkPaint::Style>(tmp_u8)); } static void init_bitmap(Fuzz* fuzz, SkBitmap* bmp) { uint8_t colorType; fuzz->nextRange(&colorType, 0, (int)kLastEnum_SkColorType); bool b; fuzz->next(&b); SkImageInfo info = SkImageInfo::Make(kBmpSize, kBmpSize, (SkColorType)colorType, b ? kOpaque_SkAlphaType : kPremul_SkAlphaType); if (!bmp->tryAllocPixels(info)) { SkDebugf("Bitmap not allocated\n"); } SkColor c; fuzz->next(&c); bmp->eraseColor(c); fuzz->next(&b); SkPaint p; if (b) { init_paint(fuzz, &p); } else { fuzz->next(&c); p.setColor(c); } } static void init_surface(Fuzz* fuzz, sk_sp<SkSurface>* s) { uint8_t x, y; fuzz->nextRange(&x, 1, kMaxX); fuzz->nextRange(&y, 1, kMaxY); *s = SkSurface::MakeRasterN32Premul(x, y); } static void fuzz_drawText(Fuzz* fuzz, sk_sp<SkTypeface> font) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); char text[kTxtLen]; init_string(fuzz, text, kTxtLen); SkScalar x, y; fuzz->next(&x, &y); // populate pts array SkPoint pts[kPtsLen]; for (uint8_t i = 0; i < kPtsLen; ++i) { pts[i].set(x, y); x += p.getTextSize(); } p.setTypeface(font); // set text related attributes bool b; fuzz->next(&b); p.setAutohinted(b); fuzz->next(&b); p.setDevKernText(b); fuzz->next(&b); p.setEmbeddedBitmapText(b); fuzz->next(&b); p.setFakeBoldText(b); fuzz->next(&b); p.setLCDRenderText(b); fuzz->next(&b); p.setLinearText(b); fuzz->next(&b); p.setStrikeThruText(b); fuzz->next(&b); p.setSubpixelText(b); fuzz->next(&x); p.setTextScaleX(x); fuzz->next(&x); p.setTextSkewX(x); fuzz->next(&x); p.setTextSize(x); fuzz->next(&b); p.setUnderlineText(b); fuzz->next(&b); p.setVerticalText(b); SkCanvas* cnv = surface->getCanvas(); cnv->drawPosText(text, (kTxtLen-1), pts, p); fuzz->next(&x); fuzz->next(&y); cnv->drawText(text, (kTxtLen-1), x, y, p); } static void fuzz_drawCircle(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkScalar a, b, c; fuzz->next(&a, &b, &c); surface->getCanvas()->drawCircle(a, b, c, p); } static void fuzz_drawLine(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkScalar a, b, c, d; fuzz->next(&a, &b, &c, &d); surface->getCanvas()->drawLine(a, b, c, d, p); } static void fuzz_drawRect(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkScalar a, b, c, d; fuzz->next(&a, &b, &c, &d); SkRect r; r = SkRect::MakeXYWH(a, b, c, d); SkCanvas* cnv = surface->getCanvas(); cnv->drawRect(r, p); bool bl; fuzz->next(&bl); fuzz->next(&a, &b, &c, &d); r = SkRect::MakeXYWH(a, b, c, d); cnv->clipRect(r, kIntersect_SkClipOp, bl); } static void fuzz_drawPath(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); // TODO(kjlubick): put the ability to fuzz a path in shared file, with // other common things (e.g. rects, lines) uint8_t i, j; fuzz->nextRange(&i, 0, 10); // set i to number of operations to perform SkPath path; SkScalar a, b, c, d, e, f; for (int k = 0; k < i; ++k) { fuzz->nextRange(&j, 0, 5); // set j to choose operation to perform switch (j) { case 0: fuzz->next(&a, &b); path.moveTo(a, b); break; case 1: fuzz->next(&a, &b); path.lineTo(a, b); break; case 2: fuzz->next(&a, &b, &c, &d); path.quadTo(a, b, c, d); break; case 3: fuzz->next(&a, &b, &c, &d, &e); path.conicTo(a, b, c, d, e); break; case 4: fuzz->next(&a, &b, &c, &d, &e, &f); path.cubicTo(a, b, c, d, e, f); break; case 5: fuzz->next(&a, &b, &c, &d, &e); path.arcTo(a, b, c, d, e); break; } } path.close(); SkCanvas* cnv = surface->getCanvas(); cnv->drawPath(path, p); bool bl; fuzz->next(&bl); cnv->clipPath(path, kIntersect_SkClipOp, bl); } static void fuzz_drawBitmap(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkBitmap bmp; init_bitmap(fuzz, &bmp); SkScalar a, b; fuzz->next(&a, &b); surface->getCanvas()->drawBitmap(bmp, a, b, &p); } static void fuzz_drawImage(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkBitmap bmp; init_bitmap(fuzz, &bmp); sk_sp<SkImage> image(SkImage::MakeFromBitmap(bmp)); bool bl; fuzz->next(&bl); SkScalar a, b; fuzz->next(&a, &b); if (bl) { surface->getCanvas()->drawImage(image, a, b, &p); } else { SkRect dst = SkRect::MakeWH(a, b); fuzz->next(&a, &b); SkRect src = SkRect::MakeWH(a, b); uint8_t x; fuzz->nextRange(&x, 0, 1); SkCanvas::SrcRectConstraint cst = (SkCanvas::SrcRectConstraint)x; surface->getCanvas()->drawImageRect(image, src, dst, &p, cst); } } static void fuzz_drawPaint(Fuzz* fuzz) { SkPaint l, p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); // add layers uint8_t x; fuzz->nextRange(&x, 1, 3); // max 3 layers SkLayerRasterizer::Builder builder; for (int i = 0; i < x; i++) { init_paint(fuzz, &l); builder.addLayer(l); } sk_sp<SkLayerRasterizer> raster(builder.detach()); p.setRasterizer(raster); surface->getCanvas()->drawPaint(p); } DEF_FUZZ(DrawFunctions, fuzz) { uint8_t i; fuzz->next(&i); switch(i) { case 0: { sk_sp<SkTypeface> f = SkTypeface::MakeDefault(); if (f == nullptr) { SkDebugf("Could not initialize font.\n"); fuzz->signalBug(); } SkDebugf("Fuzz DrawText\n"); fuzz_drawText(fuzz, f); return; } case 1: SkDebugf("Fuzz DrawRect\n"); fuzz_drawRect(fuzz); return; case 2: SkDebugf("Fuzz DrawCircle\n"); fuzz_drawCircle(fuzz); return; case 3: SkDebugf("Fuzz DrawLine\n"); fuzz_drawLine(fuzz); return; case 4: SkDebugf("Fuzz DrawPath\n"); fuzz_drawPath(fuzz); return; case 5: SkDebugf("Fuzz DrawImage/DrawImageRect\n"); fuzz_drawImage(fuzz); return; case 6: SkDebugf("Fuzz DrawBitmap\n"); fuzz_drawBitmap(fuzz); return; case 7: SkDebugf("Fuzz DrawPaint\n"); fuzz_drawPaint(fuzz); return; } }
/* * Copyright 2016 Mozilla Foundation * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Fuzz.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkImage.h" #include "SkLayerRasterizer.h" #include "SkPath.h" #include "SkSurface.h" #include "SkTypeface.h" #include "SkClipOpPriv.h" static const int kBmpSize = 24; static const int kMaxX = 250; static const int kMaxY = 250; static const int kPtsLen = 10; static const int kTxtLen = 5; static void init_string(Fuzz* fuzz, char* str, size_t bufSize) { for (size_t i = 0; i < bufSize-1; ++i) { fuzz->nextRange(&str[i], 0x20, 0x7E); // printable ASCII } str[bufSize-1] = '\0'; } // make_paint mostly borrowed from FilterFuzz.cpp static void init_paint(Fuzz* fuzz, SkPaint* p) { bool b; fuzz->next(&b); p->setAntiAlias(b); uint8_t tmp_u8; fuzz->nextRange(&tmp_u8, 0, (int)SkBlendMode::kLastMode); p->setBlendMode(static_cast<SkBlendMode>(tmp_u8)); SkColor co; fuzz->next(&co); p->setColor(co); fuzz->next(&b); p->setDither(b); fuzz->nextRange(&tmp_u8, 0, (int)kHigh_SkFilterQuality); p->setFilterQuality(static_cast<SkFilterQuality>(tmp_u8)); fuzz->nextRange(&tmp_u8, 0, (int)SkPaint::kFull_Hinting); p->setHinting(static_cast<SkPaint::Hinting>(tmp_u8)); fuzz->nextRange(&tmp_u8, 0, (int)SkPaint::kLast_Cap); p->setStrokeCap(static_cast<SkPaint::Cap>(tmp_u8)); fuzz->nextRange(&tmp_u8, 0, (int)SkPaint::kLast_Join); p->setStrokeJoin(static_cast<SkPaint::Join>(tmp_u8)); SkScalar sc; fuzz->next(&sc); p->setStrokeMiter(sc); fuzz->next(&sc); p->setStrokeWidth(sc); fuzz->nextRange(&tmp_u8, 0, (int)SkPaint::kStrokeAndFill_Style); p->setStyle(static_cast<SkPaint::Style>(tmp_u8)); } static void init_bitmap(Fuzz* fuzz, SkBitmap* bmp) { uint8_t colorType; fuzz->nextRange(&colorType, 0, (int)kLastEnum_SkColorType); // ColorType needs to match what the system configuration is. if (colorType == kRGBA_8888_SkColorType || colorType == kBGRA_8888_SkColorType) { colorType = kN32_SkColorType; } bool b; fuzz->next(&b); SkImageInfo info = SkImageInfo::Make(kBmpSize, kBmpSize, (SkColorType)colorType, b ? kOpaque_SkAlphaType : kPremul_SkAlphaType); if (!bmp->tryAllocPixels(info)) { SkDebugf("Bitmap not allocated\n"); } SkColor c; fuzz->next(&c); bmp->eraseColor(c); fuzz->next(&b); SkPaint p; if (b) { init_paint(fuzz, &p); } else { fuzz->next(&c); p.setColor(c); } } static void init_surface(Fuzz* fuzz, sk_sp<SkSurface>* s) { uint8_t x, y; fuzz->nextRange(&x, 1, kMaxX); fuzz->nextRange(&y, 1, kMaxY); *s = SkSurface::MakeRasterN32Premul(x, y); } static void fuzz_drawText(Fuzz* fuzz, sk_sp<SkTypeface> font) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); char text[kTxtLen]; init_string(fuzz, text, kTxtLen); SkScalar x, y; fuzz->next(&x, &y); // populate pts array SkPoint pts[kPtsLen]; for (uint8_t i = 0; i < kPtsLen; ++i) { pts[i].set(x, y); x += p.getTextSize(); } p.setTypeface(font); // set text related attributes bool b; fuzz->next(&b); p.setAutohinted(b); fuzz->next(&b); p.setDevKernText(b); fuzz->next(&b); p.setEmbeddedBitmapText(b); fuzz->next(&b); p.setFakeBoldText(b); fuzz->next(&b); p.setLCDRenderText(b); fuzz->next(&b); p.setLinearText(b); fuzz->next(&b); p.setStrikeThruText(b); fuzz->next(&b); p.setSubpixelText(b); fuzz->next(&x); p.setTextScaleX(x); fuzz->next(&x); p.setTextSkewX(x); fuzz->next(&x); p.setTextSize(x); fuzz->next(&b); p.setUnderlineText(b); fuzz->next(&b); p.setVerticalText(b); SkCanvas* cnv = surface->getCanvas(); cnv->drawPosText(text, (kTxtLen-1), pts, p); fuzz->next(&x); fuzz->next(&y); cnv->drawText(text, (kTxtLen-1), x, y, p); } static void fuzz_drawCircle(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkScalar a, b, c; fuzz->next(&a, &b, &c); surface->getCanvas()->drawCircle(a, b, c, p); } static void fuzz_drawLine(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkScalar a, b, c, d; fuzz->next(&a, &b, &c, &d); surface->getCanvas()->drawLine(a, b, c, d, p); } static void fuzz_drawRect(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkScalar a, b, c, d; fuzz->next(&a, &b, &c, &d); SkRect r; r = SkRect::MakeXYWH(a, b, c, d); SkCanvas* cnv = surface->getCanvas(); cnv->drawRect(r, p); bool bl; fuzz->next(&bl); fuzz->next(&a, &b, &c, &d); r = SkRect::MakeXYWH(a, b, c, d); cnv->clipRect(r, kIntersect_SkClipOp, bl); } static void fuzz_drawPath(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); // TODO(kjlubick): put the ability to fuzz a path in shared file, with // other common things (e.g. rects, lines) uint8_t i, j; fuzz->nextRange(&i, 0, 10); // set i to number of operations to perform SkPath path; SkScalar a, b, c, d, e, f; for (int k = 0; k < i; ++k) { fuzz->nextRange(&j, 0, 5); // set j to choose operation to perform switch (j) { case 0: fuzz->next(&a, &b); path.moveTo(a, b); break; case 1: fuzz->next(&a, &b); path.lineTo(a, b); break; case 2: fuzz->next(&a, &b, &c, &d); path.quadTo(a, b, c, d); break; case 3: fuzz->next(&a, &b, &c, &d, &e); path.conicTo(a, b, c, d, e); break; case 4: fuzz->next(&a, &b, &c, &d, &e, &f); path.cubicTo(a, b, c, d, e, f); break; case 5: fuzz->next(&a, &b, &c, &d, &e); path.arcTo(a, b, c, d, e); break; } } path.close(); SkCanvas* cnv = surface->getCanvas(); cnv->drawPath(path, p); bool bl; fuzz->next(&bl); cnv->clipPath(path, kIntersect_SkClipOp, bl); } static void fuzz_drawBitmap(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkBitmap bmp; init_bitmap(fuzz, &bmp); SkScalar a, b; fuzz->next(&a, &b); surface->getCanvas()->drawBitmap(bmp, a, b, &p); } static void fuzz_drawImage(Fuzz* fuzz) { SkPaint p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); SkBitmap bmp; init_bitmap(fuzz, &bmp); sk_sp<SkImage> image(SkImage::MakeFromBitmap(bmp)); bool bl; fuzz->next(&bl); SkScalar a, b; fuzz->next(&a, &b); if (bl) { surface->getCanvas()->drawImage(image, a, b, &p); } else { SkRect dst = SkRect::MakeWH(a, b); fuzz->next(&a, &b); SkRect src = SkRect::MakeWH(a, b); uint8_t x; fuzz->nextRange(&x, 0, 1); SkCanvas::SrcRectConstraint cst = (SkCanvas::SrcRectConstraint)x; surface->getCanvas()->drawImageRect(image, src, dst, &p, cst); } } static void fuzz_drawPaint(Fuzz* fuzz) { SkPaint l, p; init_paint(fuzz, &p); sk_sp<SkSurface> surface; init_surface(fuzz, &surface); // add layers uint8_t x; fuzz->nextRange(&x, 1, 3); // max 3 layers SkLayerRasterizer::Builder builder; for (int i = 0; i < x; i++) { init_paint(fuzz, &l); builder.addLayer(l); } sk_sp<SkLayerRasterizer> raster(builder.detach()); p.setRasterizer(raster); surface->getCanvas()->drawPaint(p); } DEF_FUZZ(DrawFunctions, fuzz) { uint8_t i; fuzz->next(&i); switch(i) { case 0: { sk_sp<SkTypeface> f = SkTypeface::MakeDefault(); if (f == nullptr) { SkDebugf("Could not initialize font.\n"); fuzz->signalBug(); } SkDebugf("Fuzz DrawText\n"); fuzz_drawText(fuzz, f); return; } case 1: SkDebugf("Fuzz DrawRect\n"); fuzz_drawRect(fuzz); return; case 2: SkDebugf("Fuzz DrawCircle\n"); fuzz_drawCircle(fuzz); return; case 3: SkDebugf("Fuzz DrawLine\n"); fuzz_drawLine(fuzz); return; case 4: SkDebugf("Fuzz DrawPath\n"); fuzz_drawPath(fuzz); return; case 5: SkDebugf("Fuzz DrawImage/DrawImageRect\n"); fuzz_drawImage(fuzz); return; case 6: SkDebugf("Fuzz DrawBitmap\n"); fuzz_drawBitmap(fuzz); return; case 7: SkDebugf("Fuzz DrawPaint\n"); fuzz_drawPaint(fuzz); return; } }
Make sure fuzzer can't pick an illegal colortype
Make sure fuzzer can't pick an illegal colortype BUG=skia:6216 Change-Id: Ifb0a0a1e634bb291c586d2094401ec10349dcd0e Reviewed-on: https://skia-review.googlesource.com/8817 Reviewed-by: Herb Derby <[email protected]> Commit-Queue: Kevin Lubick <[email protected]>
C++
bsd-3-clause
google/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,HalCanary/skia-hc,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,google/skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,HalCanary/skia-hc,rubenvb/skia,rubenvb/skia,aosp-mirror/platform_external_skia,rubenvb/skia,rubenvb/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,google/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia
d32b454c5b7fec2bc64b4480819701fb526a8652
features/storage/blockdevice/MBRBlockDevice.cpp
features/storage/blockdevice/MBRBlockDevice.cpp
/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MBRBlockDevice.h" #include "mbed_critical.h" #include <algorithm> // On disk structures, all entries are little endian MBED_PACKED(struct) mbr_entry { uint8_t status; uint8_t chs_start[3]; uint8_t type; uint8_t chs_stop[3]; uint32_t lba_offset; uint32_t lba_size; }; MBED_PACKED(struct) mbr_table { struct mbr_entry entries[4]; uint8_t signature[2]; }; // Little-endian conversion, should compile to noop // if system is little-endian static inline uint32_t tole32(uint32_t a) { union { uint32_t u32; uint8_t u8[4]; } w; w.u8[0] = a >> 0; w.u8[1] = a >> 8; w.u8[2] = a >> 16; w.u8[3] = a >> 24; return w.u32; } static inline uint32_t fromle32(uint32_t a) { return tole32(a); } static void tochs(uint32_t lba, uint8_t chs[3]) { uint32_t sector = std::min<uint32_t>(lba, 0xfffffd)+1; chs[0] = (sector >> 6) & 0xff; chs[1] = ((sector >> 0) & 0x3f) | ((sector >> 16) & 0xc0); chs[2] = (sector >> 14) & 0xff; } // Partition after address are turned into absolute // addresses, assumes bd is initialized static int partition_absolute( BlockDevice *bd, int part, uint8_t type, bd_size_t offset, bd_size_t size) { // Allocate smallest buffer necessary to write MBR uint32_t buffer_size = std::max<uint32_t>(bd->get_program_size(), sizeof(struct mbr_table)); uint8_t *buffer = new uint8_t[buffer_size]; // Check for existing MBR int err = bd->read(buffer, 512-buffer_size, buffer_size); if (err) { delete[] buffer; return err; } struct mbr_table *table = reinterpret_cast<struct mbr_table*>( &buffer[buffer_size - sizeof(struct mbr_table)]); if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) { // Setup default values for MBR table->signature[0] = 0x55; table->signature[1] = 0xaa; memset(table->entries, 0, sizeof(table->entries)); } // Setup new partition MBED_ASSERT(part >= 1 && part <= 4); table->entries[part-1].status = 0x00; // inactive (not bootable) table->entries[part-1].type = type; // lba dimensions MBED_ASSERT(bd->is_valid_erase(offset, size)); uint32_t sector = std::max<uint32_t>(bd->get_erase_size(), 512); uint32_t lba_offset = offset / sector; uint32_t lba_size = size / sector; table->entries[part-1].lba_offset = tole32(lba_offset); table->entries[part-1].lba_size = tole32(lba_size); // chs dimensions tochs(lba_offset, table->entries[part-1].chs_start); tochs(lba_offset+lba_size-1, table->entries[part-1].chs_stop); // Check that we don't overlap other entries for (int i = 1; i <= 4; i++) { if (i != part && table->entries[i-1].type != 0x00) { uint32_t neighbor_lba_offset = fromle32(table->entries[i-1].lba_offset); uint32_t neighbor_lba_size = fromle32(table->entries[i-1].lba_size); MBED_ASSERT( (lba_offset >= neighbor_lba_offset + neighbor_lba_size) || (lba_offset + lba_size <= neighbor_lba_offset)); (void)neighbor_lba_offset; (void)neighbor_lba_size; } } // Write out MBR err = bd->erase(0, bd->get_erase_size()); if (err) { delete[] buffer; return err; } err = bd->program(buffer, 512-buffer_size, buffer_size); delete[] buffer; return err; } int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start) { int err = bd->init(); if (err) { return err; } // Calculate dimensions bd_size_t offset = ((int64_t)start < 0) ? -start : start; bd_size_t size = bd->size(); if (offset < 512) { offset += std::max<uint32_t>(bd->get_erase_size(), 512); } size -= offset; err = partition_absolute(bd, part, type, offset, size); if (err) { return err; } err = bd->deinit(); if (err) { return err; } return 0; } int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start, bd_addr_t stop) { int err = bd->init(); if (err) { return err; } // Calculate dimensions bd_size_t offset = ((int64_t)start < 0) ? -start : start; bd_size_t size = ((int64_t)stop < 0) ? -stop : stop; if (offset < 512) { offset += std::max<uint32_t>(bd->get_erase_size(), 512); } size -= offset; err = partition_absolute(bd, part, type, offset, size); if (err) { return err; } err = bd->deinit(); if (err) { return err; } return 0; } MBRBlockDevice::MBRBlockDevice(BlockDevice *bd, int part) : _bd(bd), _offset(0), _size(0), _type(0), _part(part), _init_ref_count(0), _is_initialized(false) { MBED_ASSERT(_part >= 1 && _part <= 4); } int MBRBlockDevice::init() { uint32_t buffer_size; uint8_t *buffer = 0; struct mbr_table *table; bd_size_t sector; int err; uint32_t val = core_util_atomic_incr_u32(&_init_ref_count, 1); if (val != 1) { return BD_ERROR_OK; } err = _bd->init(); if (err) { goto fail; } // Allocate smallest buffer necessary to write MBR buffer_size = std::max<uint32_t>(_bd->get_read_size(), sizeof(struct mbr_table)); buffer = new uint8_t[buffer_size]; err = _bd->read(buffer, 512-buffer_size, buffer_size); if (err) { goto fail; } // Check for valid table table = reinterpret_cast<struct mbr_table*>(&buffer[buffer_size - sizeof(struct mbr_table)]); if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) { err = BD_ERROR_INVALID_MBR; goto fail; } // Check for valid entry // 0x00 = no entry // 0x05, 0x0f = extended partitions, currently not supported if ((table->entries[_part-1].type == 0x00 || table->entries[_part-1].type == 0x05 || table->entries[_part-1].type == 0x0f)) { err = BD_ERROR_INVALID_PARTITION; goto fail; } // Get partition attributes sector = std::max<uint32_t>(_bd->get_erase_size(), 512); _type = table->entries[_part-1].type; _offset = fromle32(table->entries[_part-1].lba_offset) * sector; _size = fromle32(table->entries[_part-1].lba_size) * sector; // Check that block addresses are valid if (!_bd->is_valid_erase(_offset, _size)) { err = BD_ERROR_INVALID_PARTITION; goto fail; } _is_initialized = true; delete[] buffer; return BD_ERROR_OK; fail: delete[] buffer; _is_initialized = false; _init_ref_count = 0; return err; } int MBRBlockDevice::deinit() { if (!_is_initialized) { return BD_ERROR_OK; } uint32_t val = core_util_atomic_decr_u32(&_init_ref_count, 1); if (val) { return BD_ERROR_OK; } _is_initialized = false; return _bd->deinit(); } int MBRBlockDevice::sync() { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->sync(); } int MBRBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) { MBED_ASSERT(is_valid_read(addr, size)); if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->read(b, addr + _offset, size); } int MBRBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) { MBED_ASSERT(is_valid_program(addr, size)); if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->program(b, addr + _offset, size); } int MBRBlockDevice::erase(bd_addr_t addr, bd_size_t size) { MBED_ASSERT(is_valid_erase(addr, size)); if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->erase(addr + _offset, size); } bd_size_t MBRBlockDevice::get_read_size() const { if (!_is_initialized) { return 0; } return _bd->get_read_size(); } bd_size_t MBRBlockDevice::get_program_size() const { if (!_is_initialized) { return 0; } return _bd->get_program_size(); } bd_size_t MBRBlockDevice::get_erase_size() const { if (!_is_initialized) { return 0; } return _bd->get_erase_size(); } bd_size_t MBRBlockDevice::get_erase_size(bd_addr_t addr) const { if (!_is_initialized) { return 0; } return _bd->get_erase_size(_offset + addr); } int MBRBlockDevice::get_erase_value() const { if (!_is_initialized) { return 0; } return _bd->get_erase_value(); } bd_size_t MBRBlockDevice::size() const { return _size; } bd_size_t MBRBlockDevice::get_partition_start() const { return _offset; } bd_size_t MBRBlockDevice::get_partition_stop() const { return _offset+_size; } uint8_t MBRBlockDevice::get_partition_type() const { return _type; } int MBRBlockDevice::get_partition_number() const { return _part; }
/* mbed Microcontroller Library * Copyright (c) 2017 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MBRBlockDevice.h" #include "mbed_critical.h" #include <algorithm> // On disk structures, all entries are little endian MBED_PACKED(struct) mbr_entry { uint8_t status; uint8_t chs_start[3]; uint8_t type; uint8_t chs_stop[3]; uint32_t lba_offset; uint32_t lba_size; }; MBED_PACKED(struct) mbr_table { struct mbr_entry entries[4]; uint8_t signature[2]; }; // Little-endian conversion, should compile to noop // if system is little-endian static inline uint32_t tole32(uint32_t a) { union { uint32_t u32; uint8_t u8[4]; } w; w.u8[0] = a >> 0; w.u8[1] = a >> 8; w.u8[2] = a >> 16; w.u8[3] = a >> 24; return w.u32; } static inline uint32_t fromle32(uint32_t a) { return tole32(a); } static void tochs(uint32_t lba, uint8_t chs[3]) { uint32_t sector = std::min<uint32_t>(lba, 0xfffffd)+1; chs[0] = (sector >> 6) & 0xff; chs[1] = ((sector >> 0) & 0x3f) | ((sector >> 16) & 0xc0); chs[2] = (sector >> 14) & 0xff; } // Partition after address are turned into absolute // addresses, assumes bd is initialized static int partition_absolute( BlockDevice *bd, int part, uint8_t type, bd_size_t offset, bd_size_t size) { // Allocate smallest buffer necessary to write MBR uint32_t buffer_size = std::max<uint32_t>(bd->get_program_size(), sizeof(struct mbr_table)); // Prevent alignment issues if(buffer_size % bd->get_program_size() != 0) { buffer_size += bd->get_program_size() - (buffer_size % bd->get_program_size()); } uint8_t *buffer = new uint8_t[buffer_size]; // Check for existing MBR int err = bd->read(buffer, 512-buffer_size, buffer_size); if (err) { delete[] buffer; return err; } struct mbr_table *table = reinterpret_cast<struct mbr_table*>( &buffer[buffer_size - sizeof(struct mbr_table)]); if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) { // Setup default values for MBR table->signature[0] = 0x55; table->signature[1] = 0xaa; memset(table->entries, 0, sizeof(table->entries)); } // Setup new partition MBED_ASSERT(part >= 1 && part <= 4); table->entries[part-1].status = 0x00; // inactive (not bootable) table->entries[part-1].type = type; // lba dimensions MBED_ASSERT(bd->is_valid_erase(offset, size)); uint32_t sector = std::max<uint32_t>(bd->get_erase_size(), 512); uint32_t lba_offset = offset / sector; uint32_t lba_size = size / sector; table->entries[part-1].lba_offset = tole32(lba_offset); table->entries[part-1].lba_size = tole32(lba_size); // chs dimensions tochs(lba_offset, table->entries[part-1].chs_start); tochs(lba_offset+lba_size-1, table->entries[part-1].chs_stop); // Check that we don't overlap other entries for (int i = 1; i <= 4; i++) { if (i != part && table->entries[i-1].type != 0x00) { uint32_t neighbor_lba_offset = fromle32(table->entries[i-1].lba_offset); uint32_t neighbor_lba_size = fromle32(table->entries[i-1].lba_size); MBED_ASSERT( (lba_offset >= neighbor_lba_offset + neighbor_lba_size) || (lba_offset + lba_size <= neighbor_lba_offset)); (void)neighbor_lba_offset; (void)neighbor_lba_size; } } // Write out MBR err = bd->erase(0, bd->get_erase_size()); if (err) { delete[] buffer; return err; } err = bd->program(buffer, 512-buffer_size, buffer_size); delete[] buffer; return err; } int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start) { int err = bd->init(); if (err) { return err; } // Calculate dimensions bd_size_t offset = ((int64_t)start < 0) ? -start : start; bd_size_t size = bd->size(); if (offset < 512) { offset += std::max<uint32_t>(bd->get_erase_size(), 512); } size -= offset; err = partition_absolute(bd, part, type, offset, size); if (err) { return err; } err = bd->deinit(); if (err) { return err; } return 0; } int MBRBlockDevice::partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start, bd_addr_t stop) { int err = bd->init(); if (err) { return err; } // Calculate dimensions bd_size_t offset = ((int64_t)start < 0) ? -start : start; bd_size_t size = ((int64_t)stop < 0) ? -stop : stop; if (offset < 512) { offset += std::max<uint32_t>(bd->get_erase_size(), 512); } size -= offset; err = partition_absolute(bd, part, type, offset, size); if (err) { return err; } err = bd->deinit(); if (err) { return err; } return 0; } MBRBlockDevice::MBRBlockDevice(BlockDevice *bd, int part) : _bd(bd), _offset(0), _size(0), _type(0), _part(part), _init_ref_count(0), _is_initialized(false) { MBED_ASSERT(_part >= 1 && _part <= 4); } int MBRBlockDevice::init() { uint32_t buffer_size; uint8_t *buffer = 0; struct mbr_table *table; bd_size_t sector; int err; uint32_t val = core_util_atomic_incr_u32(&_init_ref_count, 1); if (val != 1) { return BD_ERROR_OK; } err = _bd->init(); if (err) { goto fail; } // Allocate smallest buffer necessary to write MBR buffer_size = std::max<uint32_t>(_bd->get_read_size(), sizeof(struct mbr_table)); buffer = new uint8_t[buffer_size]; err = _bd->read(buffer, 512-buffer_size, buffer_size); if (err) { goto fail; } // Check for valid table table = reinterpret_cast<struct mbr_table*>(&buffer[buffer_size - sizeof(struct mbr_table)]); if (table->signature[0] != 0x55 || table->signature[1] != 0xaa) { err = BD_ERROR_INVALID_MBR; goto fail; } // Check for valid entry // 0x00 = no entry // 0x05, 0x0f = extended partitions, currently not supported if ((table->entries[_part-1].type == 0x00 || table->entries[_part-1].type == 0x05 || table->entries[_part-1].type == 0x0f)) { err = BD_ERROR_INVALID_PARTITION; goto fail; } // Get partition attributes sector = std::max<uint32_t>(_bd->get_erase_size(), 512); _type = table->entries[_part-1].type; _offset = fromle32(table->entries[_part-1].lba_offset) * sector; _size = fromle32(table->entries[_part-1].lba_size) * sector; // Check that block addresses are valid if (!_bd->is_valid_erase(_offset, _size)) { err = BD_ERROR_INVALID_PARTITION; goto fail; } _is_initialized = true; delete[] buffer; return BD_ERROR_OK; fail: delete[] buffer; _is_initialized = false; _init_ref_count = 0; return err; } int MBRBlockDevice::deinit() { if (!_is_initialized) { return BD_ERROR_OK; } uint32_t val = core_util_atomic_decr_u32(&_init_ref_count, 1); if (val) { return BD_ERROR_OK; } _is_initialized = false; return _bd->deinit(); } int MBRBlockDevice::sync() { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->sync(); } int MBRBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) { MBED_ASSERT(is_valid_read(addr, size)); if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->read(b, addr + _offset, size); } int MBRBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) { MBED_ASSERT(is_valid_program(addr, size)); if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->program(b, addr + _offset, size); } int MBRBlockDevice::erase(bd_addr_t addr, bd_size_t size) { MBED_ASSERT(is_valid_erase(addr, size)); if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->erase(addr + _offset, size); } bd_size_t MBRBlockDevice::get_read_size() const { if (!_is_initialized) { return 0; } return _bd->get_read_size(); } bd_size_t MBRBlockDevice::get_program_size() const { if (!_is_initialized) { return 0; } return _bd->get_program_size(); } bd_size_t MBRBlockDevice::get_erase_size() const { if (!_is_initialized) { return 0; } return _bd->get_erase_size(); } bd_size_t MBRBlockDevice::get_erase_size(bd_addr_t addr) const { if (!_is_initialized) { return 0; } return _bd->get_erase_size(_offset + addr); } int MBRBlockDevice::get_erase_value() const { if (!_is_initialized) { return 0; } return _bd->get_erase_value(); } bd_size_t MBRBlockDevice::size() const { return _size; } bd_size_t MBRBlockDevice::get_partition_start() const { return _offset; } bd_size_t MBRBlockDevice::get_partition_stop() const { return _offset+_size; } uint8_t MBRBlockDevice::get_partition_type() const { return _type; } int MBRBlockDevice::get_partition_number() const { return _part; }
Align writes to blockdevice write size in MBRBlockDevice
Align writes to blockdevice write size in MBRBlockDevice
C++
apache-2.0
kjbracey-arm/mbed,andcor02/mbed-os,kjbracey-arm/mbed,andcor02/mbed-os,c1728p9/mbed-os,kjbracey-arm/mbed,c1728p9/mbed-os,andcor02/mbed-os,c1728p9/mbed-os,c1728p9/mbed-os,c1728p9/mbed-os,kjbracey-arm/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,andcor02/mbed-os,c1728p9/mbed-os,andcor02/mbed-os,mbedmicro/mbed,mbedmicro/mbed,andcor02/mbed-os
4ef4e419844282e87a0b6633211e3cbaef1ca3a9
firmware/node_firmware/lib/MeshNet/src/node.cpp
firmware/node_firmware/lib/MeshNet/src/node.cpp
#include "node.hpp" #include "common.hpp" Node::Node(uint8_t node_id, const uint8_t *key) : radio(CE_PIN, CS_PIN), network(radio), mesh(radio, network), node_id(node_id), key(key), session(micros()), own_id(0), other_id(0), last_pong(millis()) {} void Node::init() { mesh.setNodeID(0); mesh.begin(); update(); Message *boot_message = prepareSendMessage(); boot_message->setShort(millis()); DEBUG_LOG("Send booted packet"); if (!send(MASTER_ADDR, booted, boot_message)) { // Mesh not available? try again?. DEBUG_LOG("Send of booted failed"); delay(1000); RESET(); } DEBUG_LOG("Sent ... "); uint16_t last = millis(); for (;;) { Message *recieve_message = prepareRecieveMessage(); node_t sender; messages_t type; DEBUG_LOG("Try to recieve config..."); if (0 != fetch(&sender, &type, recieve_message)) { last = millis(); switch (type) { case configure: registry.configure(recieve_message); sendPong(); break; case configured: setSession(recieve_message->getShort()); sendPong(); return; default: DEBUG_LOG("Got an unexpected message from %x with type %x", sender, type); break; } continue; } if (last + CONFIG_TIMEOUT < millis()) { // reset if we did not get an answer. DEBUG_LOG("Reset controller .. "); RESET(); } delay(50); } } void Node::update() { mesh.update(); } void Node::checkConn() { if (!mesh.checkConnection()) { // refresh the network address mesh.renewAddress(); } } msg_size_t Node::fetch(uint16_t *sender, messages_t *type, Message *msg) { if (network.available()) { RF24NetworkHeader header; network.peek(header); *sender = header.from_node; *type = (messages_t)header.type; // Read the data uint16_t size = network.read(header, msg->rawBuffer(), Message::maxLen()); if (!msg->verify(key, header.from_node, header.to_node, header.type, size)) { DEBUG_LOG("Cannot verify message"); return 0; } session_t pkt_session = msg->getShort(); if (pkt_session != session) { DEBUG_LOG("Wrong session: %d", pkt_session); return 0; } /** * reset the controller on reset request message. * * We do not check the counter here as the sender may * have restarted and lost its state. * * Should be enough to check the session id as this * can be adapted from the sender from our pong packets * and as we restart after this packet and negotiate a * new session replay should not be a problem. */ if (*type == reset) { DEBUG_LOG("Reset controller after reset message"); RESET(); } /* check that we cot a packet with an incremented counter */ counter_t pkt_cnt = msg->getShort(); if (pkt_cnt <= other_id) { DEBUG_LOG("Wrong counter: %d", pkt_cnt); return 0; } other_id = pkt_cnt; return msg->len(); } else { return 0; } } bool Node::send(uint16_t reciever, messages_t type, Message *msg) { uint16_t len = msg->finalize(key, node_id, reciever, type); for (uint8_t i = 0; i < 3; ++i) { // Write the message if (mesh.write(reciever, msg->rawBuffer(), type, len)) { return true; } else { checkConn(); } } return false; } void Node::setSession(session_t _session) { session = _session; own_id = 0; other_id = 0; } Message *Node::prepareSendMessage() { message.init(session, own_id++); return &message; } Message *Node::prepareRecieveMessage() { message.reset(); return &message; } void Node::process() { update(); // Handle incomming packets { Message *recieved = prepareRecieveMessage(); uint16_t sender; messages_t type; msg_size_t recieved_len = fetch(&sender, &type, recieved); if (recieved_len > 0) { session_t new_session; switch (type) { case set_state: registry.setState(recieved); return; case get_state: registry.requestState(recieved); return; case ping: new_session = recieved->getShort(); if (new_session != session) { setSession(new_session); sendPong(); last_pong = millis(); } return; // Messages that should not arrive here. case pong: case booted: case configure: case configured: case reading: case reset: default: DEBUG_LOG("Got an unexpected message from %x with type %x", sender, type); } } } // Send pong if (last_pong + PONG_INTERVAL < millis()) { sendPong(); last_pong = millis(); return; } // Send out state Message *state_packet = prepareSendMessage(); if (registry.nextState(state_packet)) { return; } // Update state of items if (last_check + CHECK_INTERVAL < millis()) { registry.checkItems(); last_check = millis(); } } void Node::sendPong() { Message *pong_message = prepareSendMessage(); pong_message->setShort(millis()); send(MASTER_ADDR, pong, pong_message); }
#include "node.hpp" #include "common.hpp" Node::Node(uint8_t node_id, const uint8_t *key) : radio(CE_PIN, CS_PIN), network(radio), mesh(radio, network), node_id(node_id), key(key), session(micros()), own_id(0), other_id(0), last_pong(millis()) {} void Node::init() { mesh.setNodeID(node_id); mesh.begin(); update(); Message *boot_message = prepareSendMessage(); boot_message->setShort(millis()); DEBUG_LOG("Send booted packet"); if (!send(MASTER_ADDR, booted, boot_message)) { // Mesh not available? try again?. DEBUG_LOG("Send of booted failed"); delay(1000); RESET(); } DEBUG_LOG("Sent ... "); uint16_t last = millis(); for (;;) { Message *recieve_message = prepareRecieveMessage(); node_t sender; messages_t type; DEBUG_LOG("Try to recieve config..."); if (0 != fetch(&sender, &type, recieve_message)) { last = millis(); switch (type) { case configure: registry.configure(recieve_message); sendPong(); break; case configured: setSession(recieve_message->getShort()); sendPong(); return; default: DEBUG_LOG("Got an unexpected message from %x with type %x", sender, type); break; } continue; } if (last + CONFIG_TIMEOUT < millis()) { // reset if we did not get an answer. DEBUG_LOG("Reset controller .. "); RESET(); } delay(50); } } void Node::update() { mesh.update(); } void Node::checkConn() { if (!mesh.checkConnection()) { // refresh the network address mesh.renewAddress(); } } msg_size_t Node::fetch(uint16_t *sender, messages_t *type, Message *msg) { if (network.available()) { RF24NetworkHeader header; network.peek(header); *sender = header.from_node; *type = (messages_t)header.type; // Read the data uint16_t size = network.read(header, msg->rawBuffer(), Message::maxLen()); if (!msg->verify(key, header.from_node, header.to_node, header.type, size)) { DEBUG_LOG("Cannot verify message"); return 0; } session_t pkt_session = msg->getShort(); if (pkt_session != session) { DEBUG_LOG("Wrong session: %d", pkt_session); return 0; } /** * reset the controller on reset request message. * * We do not check the counter here as the sender may * have restarted and lost its state. * * Should be enough to check the session id as this * can be adapted from the sender from our pong packets * and as we restart after this packet and negotiate a * new session replay should not be a problem. */ if (*type == reset) { DEBUG_LOG("Reset controller after reset message"); RESET(); } /* check that we cot a packet with an incremented counter */ counter_t pkt_cnt = msg->getShort(); if (pkt_cnt <= other_id) { DEBUG_LOG("Wrong counter: %d", pkt_cnt); return 0; } other_id = pkt_cnt; return msg->len(); } else { return 0; } } bool Node::send(uint16_t reciever, messages_t type, Message *msg) { uint16_t len = msg->finalize(key, node_id, reciever, type); for (uint8_t i = 0; i < 3; ++i) { // Write the message if (mesh.write(reciever, msg->rawBuffer(), type, len)) { return true; } else { checkConn(); } } return false; } void Node::setSession(session_t _session) { session = _session; own_id = 0; other_id = 0; } Message *Node::prepareSendMessage() { message.init(session, own_id++); return &message; } Message *Node::prepareRecieveMessage() { message.reset(); return &message; } void Node::process() { update(); // Handle incomming packets { Message *recieved = prepareRecieveMessage(); uint16_t sender; messages_t type; msg_size_t recieved_len = fetch(&sender, &type, recieved); if (recieved_len > 0) { session_t new_session; switch (type) { case set_state: registry.setState(recieved); return; case get_state: registry.requestState(recieved); return; case ping: new_session = recieved->getShort(); if (new_session != session) { setSession(new_session); sendPong(); last_pong = millis(); } return; // Messages that should not arrive here. case pong: case booted: case configure: case configured: case reading: case reset: default: DEBUG_LOG("Got an unexpected message from %x with type %x", sender, type); } } } // Send pong if (last_pong + PONG_INTERVAL < millis()) { sendPong(); last_pong = millis(); return; } // Send out state Message *state_packet = prepareSendMessage(); if (registry.nextState(state_packet)) { return; } // Update state of items if (last_check + CHECK_INTERVAL < millis()) { registry.checkItems(); last_check = millis(); } } void Node::sendPong() { Message *pong_message = prepareSendMessage(); pong_message->setShort(millis()); send(MASTER_ADDR, pong, pong_message); }
Fix that nodeid was never set
Fix that nodeid was never set Signed-off-by: Jan Losinski <[email protected]>
C++
bsd-3-clause
janLo/automation_mesh,janLo/automation_mesh,janLo/automation_mesh
a41d60240f925b7085a27f59c24c81c3b78d9a22
pic32/cores/pic32/main.cpp
pic32/cores/pic32/main.cpp
//************************************************************************ //* main.c //* //* Arduino core files for PIC32 //* Copyright (c) 2010, 2011 by Mark Sproul //* //* //************************************************************************ //* this code is based on code Copyright (c) 2005-2006 David A. Mellis //* //* 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 //* //* //************************************************************************ //* Edit History //************************************************************************ //* Oct 12, 2010 Got MPLAB X working on MacOSX 1.6 for the first time //* Dec 12, 2011 <GeneApperson> added call to _scheduleTask() before call //* to loop(). //************************************************************************ //!!! This section is a read only section !!! #define OPT_SYSTEM_INTERNAL #include <System_Defs.h> #if (ARDUINO >= 100) #include <Arduino.h> #else #include <WProgram.h> #endif #if !defined(__PIC32MZXX__) extern "C" { extern void __use_isr_install(void); __attribute__((section(".comment"))) void (*__use_force_isr_install)(void) = &__use_isr_install; } #endif //************************************************************************ int main(void) { init(); setup(); while (1) { _scheduleTask(); loop(); if (serialEventRun) serialEventRun(); } return 0; }
//************************************************************************ //* main.c //* //* Arduino core files for PIC32 //* Copyright (c) 2010, 2011 by Mark Sproul //* //* //************************************************************************ //* this code is based on code Copyright (c) 2005-2006 David A. Mellis //* //* 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 //* //* //************************************************************************ //* Edit History //************************************************************************ //* Oct 12, 2010 Got MPLAB X working on MacOSX 1.6 for the first time //* Dec 12, 2011 <GeneApperson> added call to _scheduleTask() before call //* to loop(). //************************************************************************ //!!! This section is a read only section !!! #define OPT_SYSTEM_INTERNAL #include <System_Defs.h> #if (ARDUINO >= 100) #include <Arduino.h> #else #include <WProgram.h> #endif #if !defined(__PIC32MZXX__) extern "C" { extern void __use_isr_install(void); __attribute__((section(".comment"))) void (*__use_force_isr_install)(void) = &__use_isr_install; } #endif //************************************************************************ int main(void) { init(); setup(); while (1) { _scheduleTask(); loop(); if (serialEventRun != NULL) serialEventRun(); } return 0; }
Fix for issue #345 : serialEventRun compiler warning in main.cpp
Fix for issue #345 : serialEventRun compiler warning in main.cpp
C++
apache-2.0
adamwolf/chipKIT-core,EmbeddedMan/chipKIT-core,adamwolf/chipKIT-core,adamwolf/chipKIT-core,adamwolf/chipKIT-core,EmbeddedMan/chipKIT-core,adamwolf/chipKIT-core,ricklon/chipKIT-core,pontech/chipKIT-core,pontech/chipKIT-core,EmbeddedMan/chipKIT-core,chipKIT32/chipkit-core,EmbeddedMan/chipKIT-core,chipKIT32/chipkit-core,majenkotech/chipKIT-core,majenkotech/chipKIT-core,majenkotech/chipKIT-core,pontech/chipKIT-core,majenkotech/chipKIT-core,ricklon/chipKIT-core,EmbeddedMan/chipKIT-core,pontech/chipKIT-core,chipKIT32/chipkit-core,EmbeddedMan/chipKIT-core,pontech/chipKIT-core,pontech/chipKIT-core,majenkotech/chipKIT-core,chipKIT32/chipkit-core,ricklon/chipKIT-core,adamwolf/chipKIT-core,majenkotech/chipKIT-core,chipKIT32/chipkit-core,ricklon/chipKIT-core,majenkotech/chipKIT-core,EmbeddedMan/chipKIT-core,ricklon/chipKIT-core,pontech/chipKIT-core,ricklon/chipKIT-core,adamwolf/chipKIT-core
e6992da2aa979daa870fad91cc53c20b20652e5e
framework/JPetParamManager/JPetParamManager.cpp
framework/JPetParamManager/JPetParamManager.cpp
#include "JPetParamManager.h" #include <TFile.h> #include <boost/property_tree/xml_parser.hpp> using namespace std; JPetParamManager::JPetParamManager(): fBank(0) { /* */ } JPetParamManager::~JPetParamManager() { if (fBank) { delete fBank; fBank = 0; } } /// @param DBConfigFile configuration file with the database connection settings JPetParamManager::JPetParamManager(const char* dBConfigFile): fDBParamGetter(dBConfigFile), fBank(0) { } void JPetParamManager::getParametersFromDatabase(const int run) { if (fBank) { delete fBank; fBank = 0; } fBank = fDBParamGetter.generateParamBank(run); } bool JPetParamManager::saveParametersToFile(const char* filename) { TFile file(filename, "UPDATE"); if (!file.IsOpen()) { ERROR("Could not write to file."); return false; } file.cd(); file.WriteObject(fBank, "ParamBank"); return true; } bool JPetParamManager::saveParametersToFile(JPetWriter * writer) { if (!writer->isOpen()) { ERROR("Could not write parameters to file. The provided JPetWriter is closed."); return false; } writer->writeObject(fBank, "ParamBank"); return true; } bool JPetParamManager::readParametersFromFile(JPetReader * reader) { if (!reader->isOpen()) { ERROR("Cannot read parameters from file. The provided JPetReader is closed."); return false; } fBank = static_cast<JPetParamBank*>(reader->getObject("ParamBank")); if (!fBank) return false; return true; } bool JPetParamManager::readParametersFromFile(const char* filename) { TFile file(filename, "READ"); if (!file.IsOpen()) { ERROR("Could not read from file."); return false; } fBank = static_cast<JPetParamBank*>(file.Get("ParamBank")); if (!fBank) return false; return true; } void JPetParamManager::clearParameters() { assert(fBank); fBank->clear(); } void JPetParamManager::createXMLFile(const std::string &channelDataFileName, int channelOffset, int numberOfChannels) { using boost::property_tree::ptree; ptree pt; std::string debug = "OFF"; std::string dataSourceType = "TRB3_S"; std::string dataSourceTrbNetAddress = "8000"; std::string dataSourceHubAddress = "8000"; std::string dataSourceReferenceChannel = "0"; std::string dataSourceCorrectionFile = "raw"; pt.put("READOUT.DEBUG", debug); pt.put("READOUT.DATA_SOURCE.TYPE", dataSourceType); pt.put("READOUT.DATA_SOURCE.TRBNET_ADDRESS", dataSourceTrbNetAddress); pt.put("READOUT.DATA_SOURCE.HUB_ADDRESS", dataSourceHubAddress); pt.put("READOUT.DATA_SOURCE.REFERENCE_CHANNEL", dataSourceReferenceChannel); pt.put("READOUT.DATA_SOURCE.CORRECTION_FILE", dataSourceCorrectionFile); ptree &externalNode = pt.add("READOUT.DATA_SOURCE.MODULES", ""); ptree &internalNode = externalNode.add("MODULE", ""); internalNode.put("TYPE", "LATTICE_TDC"); internalNode.put("TRBNET_ADDRESS", "e000"); internalNode.put("NUMBER_OF_CHANNELS", numberOfChannels); internalNode.put("CHANNEL_OFFSET", channelOffset); internalNode.put("RESOLUTION", "100"); internalNode.put("MEASUREMENT_TYPE", "TDC"); write_xml(channelDataFileName, pt); } void JPetParamManager::getTOMBDataAndCreateXMLFile(const int p_run_id) { fDBParamGetter.fillTOMBChannels(p_run_id, *fBank);//private (add friend) int TOMBChannelsSize = fBank->getTOMBChannelsSize(); int channelOffset = 0; int numberOfChannels = 0; if(TOMBChannelsSize) { for(unsigned int i=0;i<TOMBChannelsSize;++i) { if(i==0) { std::string description = fBank->getTOMBChannel(i).getDescription(); channelOffset = fDBParamGetter.getTOMBChannelFromDescription(description);//private (add friend) } ++numberOfChannels; } createXMLFile("out.xml", channelOffset, numberOfChannels); return; } ERROR("TOMBChannelsSize is equal to zero."); }
#include "JPetParamManager.h" #include <TFile.h> #include <boost/property_tree/xml_parser.hpp> using namespace std; JPetParamManager::JPetParamManager(): fBank(0) { /* */ } JPetParamManager::~JPetParamManager() { if (fBank) { delete fBank; fBank = 0; } } /// @param DBConfigFile configuration file with the database connection settings JPetParamManager::JPetParamManager(const char* dBConfigFile): fDBParamGetter(dBConfigFile), fBank(0) { } void JPetParamManager::getParametersFromDatabase(const int run) { if (fBank) { delete fBank; fBank = 0; } fBank = fDBParamGetter.generateParamBank(run); } bool JPetParamManager::saveParametersToFile(const char* filename) { TFile file(filename, "UPDATE"); if (!file.IsOpen()) { ERROR("Could not write to file."); return false; } file.cd(); file.WriteObject(fBank, "ParamBank"); return true; } bool JPetParamManager::saveParametersToFile(JPetWriter * writer) { if (!writer->isOpen()) { ERROR("Could not write parameters to file. The provided JPetWriter is closed."); return false; } writer->writeObject(fBank, "ParamBank"); return true; } bool JPetParamManager::readParametersFromFile(JPetReader * reader) { if (!reader->isOpen()) { ERROR("Cannot read parameters from file. The provided JPetReader is closed."); return false; } fBank = static_cast<JPetParamBank*>(reader->getObject("ParamBank")); if (!fBank) return false; return true; } bool JPetParamManager::readParametersFromFile(const char* filename) { TFile file(filename, "READ"); if (!file.IsOpen()) { ERROR("Could not read from file."); return false; } fBank = static_cast<JPetParamBank*>(file.Get("ParamBank")); if (!fBank) return false; return true; } void JPetParamManager::clearParameters() { assert(fBank); fBank->clear(); } void JPetParamManager::createXMLFile(const std::string &channelDataFileName, int channelOffset, int numberOfChannels) { using boost::property_tree::ptree; ptree pt; std::string debug = "OFF"; std::string dataSourceType = "TRB3_S"; std::string dataSourceTrbNetAddress = "8000"; std::string dataSourceHubAddress = "8000"; std::string dataSourceReferenceChannel = "0"; std::string dataSourceCorrectionFile = "raw"; pt.put("READOUT.DEBUG", debug); pt.put("READOUT.DATA_SOURCE.TYPE", dataSourceType); pt.put("READOUT.DATA_SOURCE.TRBNET_ADDRESS", dataSourceTrbNetAddress); pt.put("READOUT.DATA_SOURCE.HUB_ADDRESS", dataSourceHubAddress); pt.put("READOUT.DATA_SOURCE.REFERENCE_CHANNEL", dataSourceReferenceChannel); pt.put("READOUT.DATA_SOURCE.CORRECTION_FILE", dataSourceCorrectionFile); ptree &externalNode = pt.add("READOUT.DATA_SOURCE.MODULES", ""); ptree &internalNode = externalNode.add("MODULE", ""); internalNode.put("TYPE", "LATTICE_TDC"); internalNode.put("TRBNET_ADDRESS", "e000"); internalNode.put("NUMBER_OF_CHANNELS", numberOfChannels); internalNode.put("CHANNEL_OFFSET", channelOffset); internalNode.put("RESOLUTION", "100"); internalNode.put("MEASUREMENT_TYPE", "TDC"); write_xml(channelDataFileName, pt); } void JPetParamManager::getTOMBDataAndCreateXMLFile(const int p_run_id) { fDBParamGetter.fillTOMBChannels(p_run_id, *fBank);//private (add friend) int TOMBChannelsSize = fBank->getTOMBChannelsSize(); int channelOffset = 0; int numberOfChannels = 0; if(TOMBChannelsSize) { for(unsigned int i=0;i<TOMBChannelsSize;++i) { if(i==0) { std::string description = fBank->getTOMBChannel(i).getDescription(); channelOffset = fDBParamGetter.getTOMBChannelFromDescription(description);//private (add friend) } ++numberOfChannels; } createXMLFile("conf.xml", channelOffset, numberOfChannels); return; } ERROR("TOMBChannelsSize is equal to zero."); }
Change xml configuration file name.
Change xml configuration file name. Former-commit-id: 5c9c6aab5d2ed7c82f11d7f3ad5e4afcc1795a69
C++
apache-2.0
kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework
ff0a2295cb450dc369ced93e2f1018499a886341
framework/src/media/streaming/audio_encoder.cpp
framework/src/media/streaming/audio_encoder.cpp
/****************************************************************** * * Copyright 2018 Samsung Electronics 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 <tinyara/config.h> #include <sys/types.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include <pthread.h> #include <debug.h> #include "audio_encoder.h" #include "../utils/internal_defs.h" namespace media { /**************************************************************************** * Private Declarations ****************************************************************************/ /** * @struct priv_data_s * @brief Player private data structure define. */ struct priv_data_s { ssize_t mCurrentPos; /* read position when encoding */ }; typedef struct priv_data_s priv_data_t; typedef struct priv_data_s *priv_data_p; /**************************************************************************** * Private Functions ****************************************************************************/ static size_t _input_callback(void *data, rbstream_p rbsp) { audio_encoder_p encoder = (audio_encoder_p) data; assert(encoder != NULL); size_t wlen = 0; RETURN_VAL_IF_FAIL((encoder->input_func != NULL), wlen); wlen = encoder->input_func(encoder->cb_data, encoder); return wlen; } static int _init_encoder(audio_encoder_p encoder, void *enc_ext) { priv_data_p priv = (priv_data_p) encoder->priv_data; assert(priv != NULL); switch (encoder->audio_type) { #ifdef CONFIG_CODEC_LIBOPUS case AUDIO_TYPE_OPUS: { encoder->enc_ext = calloc(1, sizeof(opus_enc_external_t)); RETURN_VAL_IF_FAIL((encoder->enc_ext != NULL), AUDIO_ENCODER_ERROR); encoder->enc_mem = calloc(1, opus_encoderMemRequirements()); RETURN_VAL_IF_FAIL((encoder->enc_mem != NULL), AUDIO_ENCODER_ERROR); opus_enc_external_t *opus_ext = (opus_enc_external_t *) encoder->enc_ext; *opus_ext = * ((opus_enc_external_t *) enc_ext); // TODO: check opus_ext-> param validation RETURN_VAL_IF_FAIL((opus_ext->pInputBuffer != NULL), AUDIO_ENCODER_ERROR); RETURN_VAL_IF_FAIL((opus_ext->pOutputBuffer != NULL), AUDIO_ENCODER_ERROR); opus_resetEncoder(encoder->enc_mem); int err = opus_initEncoder((opus_enc_external_t *) encoder->enc_ext, encoder->enc_mem); RETURN_VAL_IF_FAIL((err == OPUS_OK), AUDIO_ENCODER_ERROR); priv->mCurrentPos = 0; break; } #endif default: // Maybe do not need to init, return success. return AUDIO_ENCODER_OK; } return AUDIO_ENCODER_OK; } /**************************************************************************** * Public Functions ****************************************************************************/ // check if the given auido type is supportted or not bool audio_encoder_check_audio_type(int audio_type) { switch (audio_type) { #ifdef CONFIG_CODEC_LIBOPUS case AUDIO_TYPE_OPUS: return true; #endif default: return false; } } size_t audio_encoder_pushdata(audio_encoder_p encoder, const void *data, size_t len) { assert(encoder != NULL); assert(data != NULL); static pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&s_mutex); len = rbs_write(data, 1, len, encoder->rbsp); pthread_mutex_unlock(&s_mutex); return len; } size_t audio_encoder_dataspace(audio_encoder_p encoder) { assert(encoder != NULL); return rb_avail(&encoder->ringbuffer); } bool audio_encoder_dataspace_is_empty(audio_encoder_p encoder) { assert(encoder != NULL); return (rb_used(&encoder->ringbuffer) == SIZE_ZERO); } int audio_encoder_getframe(audio_encoder_p encoder, void *data, size_t len) { assert(encoder != NULL); priv_data_p priv = (priv_data_p) encoder->priv_data; assert(priv != NULL); switch (encoder->audio_type) { #ifdef CONFIG_CODEC_LIBOPUS case AUDIO_TYPE_OPUS: { opus_enc_external_t *opus_ext = (opus_enc_external_t *) encoder->enc_ext; int analysis_frame_size = opus_ext->inputSampleRate * opus_ext->frameSizeMS / 1000; size_t size = analysis_frame_size * opus_ext->inputChannels * sizeof(signed short); int ret = rbs_seek(encoder->rbsp, priv->mCurrentPos, SEEK_SET); RETURN_VAL_IF_FAIL((ret == OK), AUDIO_ENCODER_ERROR); RETURN_VAL_IF_FAIL((size <= (size_t) opus_ext->inputBufferMaxLength), AUDIO_ENCODER_ERROR); size_t rlen = rbs_read((void *) opus_ext->pInputBuffer, 1, size, encoder->rbsp); RETURN_VAL_IF_FAIL((rlen == size), AUDIO_ENCODER_ERROR); opus_ext->inputBufferCurrentLength = rlen; priv->mCurrentPos += rlen; rbs_seek_ext(encoder->rbsp, priv->mCurrentPos, SEEK_SET); ret = opus_frameEncode(opus_ext, encoder->enc_mem); RETURN_VAL_IF_FAIL((ret == OK), AUDIO_ENCODER_ERROR); RETURN_VAL_IF_FAIL(((int32_t) len >= opus_ext->outputDataSize), AUDIO_ENCODER_ERROR); // TODO: get part of data memcpy(data, opus_ext->pOutputBuffer, opus_ext->outputDataSize); return opus_ext->outputDataSize; } #endif default: medwdbg("[%s] unsupported audio type: %d\n", __FUNCTION__, encoder->audio_type); return AUDIO_ENCODER_ERROR; } } int audio_encoder_init(audio_encoder_p encoder, size_t rbuf_size, audio_type_t audio_type, void *enc_ext) { assert(encoder != NULL); RETURN_VAL_IF_FAIL(audio_encoder_check_audio_type(audio_type), AUDIO_ENCODER_ERROR); encoder->audio_type = audio_type; encoder->cb_data = NULL; encoder->input_func = NULL; // init private data priv_data_p priv = (priv_data_p) malloc(sizeof(priv_data_t)); RETURN_VAL_IF_FAIL((priv != NULL), AUDIO_ENCODER_ERROR); priv->mCurrentPos = 0; encoder->priv_data = priv; int ret = _init_encoder(encoder, enc_ext); RETURN_VAL_IF_FAIL((ret == AUDIO_ENCODER_OK), AUDIO_ENCODER_ERROR); // init ring-buffer and open it as a stream rb_init(&encoder->ringbuffer, rbuf_size); encoder->rbsp = rbs_open(&encoder->ringbuffer, _input_callback, (void *)encoder); RETURN_VAL_IF_FAIL((encoder->rbsp != NULL), AUDIO_ENCODER_ERROR); rbs_ctrl(encoder->rbsp, OPTION_ALLOW_TO_DEQUEUE, 1); return AUDIO_ENCODER_OK; } int audio_encoder_register_callbacks(audio_encoder_p encoder, void *user_data, input_func_f input_func) { // init encoder data encoder->cb_data = user_data; encoder->input_func = input_func; return AUDIO_ENCODER_OK; } int audio_encoder_finish(audio_encoder_p encoder) { assert(encoder != NULL); // close stream rbs_close(encoder->rbsp); encoder->rbsp = NULL; // free ring-buffer instance rb_free(&encoder->ringbuffer); // free encoder external buffer if (encoder->enc_ext != NULL) { free(encoder->enc_ext); encoder->enc_ext = NULL; } // free encoder buffer if (encoder->enc_mem != NULL) { #ifdef CONFIG_CODEC_LIBOPUS opus_uninitEncoder(encoder->enc_mem); #endif free(encoder->enc_mem); encoder->enc_mem = NULL; } // free private data buffer if (encoder->priv_data != NULL) { free(encoder->priv_data); encoder->priv_data = NULL; } return AUDIO_ENCODER_OK; } } // namespace media
/****************************************************************** * * Copyright 2018 Samsung Electronics 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 <tinyara/config.h> #include <sys/types.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> #include <pthread.h> #include <debug.h> #include "audio_encoder.h" #include "../utils/internal_defs.h" namespace media { /**************************************************************************** * Private Declarations ****************************************************************************/ /** * @struct priv_data_s * @brief Player private data structure define. */ struct priv_data_s { ssize_t mCurrentPos; /* read position when encoding */ }; typedef struct priv_data_s priv_data_t; typedef struct priv_data_s *priv_data_p; /**************************************************************************** * Private Functions ****************************************************************************/ static size_t _input_callback(void *data, rbstream_p rbsp) { audio_encoder_p encoder = (audio_encoder_p) data; assert(encoder != NULL); size_t wlen = 0; RETURN_VAL_IF_FAIL((encoder->input_func != NULL), wlen); wlen = encoder->input_func(encoder->cb_data, encoder); return wlen; } static int _init_encoder(audio_encoder_p encoder, void *enc_ext) { priv_data_p priv = (priv_data_p) encoder->priv_data; assert(priv != NULL); switch (encoder->audio_type) { #ifdef CONFIG_CODEC_LIBOPUS case AUDIO_TYPE_OPUS: { encoder->enc_ext = calloc(1, sizeof(opus_enc_external_t)); RETURN_VAL_IF_FAIL((encoder->enc_ext != NULL), AUDIO_ENCODER_ERROR); encoder->enc_mem = calloc(1, opus_encoderMemRequirements()); RETURN_VAL_IF_FAIL((encoder->enc_mem != NULL), AUDIO_ENCODER_ERROR); opus_enc_external_t *opus_ext = (opus_enc_external_t *) encoder->enc_ext; *opus_ext = * ((opus_enc_external_t *) enc_ext); RETURN_VAL_IF_FAIL((opus_ext->pInputBuffer != NULL), AUDIO_ENCODER_ERROR); RETURN_VAL_IF_FAIL((opus_ext->pOutputBuffer != NULL), AUDIO_ENCODER_ERROR); opus_resetEncoder(encoder->enc_mem); int err = opus_initEncoder((opus_enc_external_t *) encoder->enc_ext, encoder->enc_mem); RETURN_VAL_IF_FAIL((err == OPUS_OK), AUDIO_ENCODER_ERROR); priv->mCurrentPos = 0; break; } #endif default: // Maybe do not need to init, return success. return AUDIO_ENCODER_OK; } return AUDIO_ENCODER_OK; } /**************************************************************************** * Public Functions ****************************************************************************/ // check if the given auido type is supportted or not bool audio_encoder_check_audio_type(int audio_type) { switch (audio_type) { #ifdef CONFIG_CODEC_LIBOPUS case AUDIO_TYPE_OPUS: return true; #endif default: return false; } } size_t audio_encoder_pushdata(audio_encoder_p encoder, const void *data, size_t len) { assert(encoder != NULL); assert(data != NULL); static pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&s_mutex); len = rbs_write(data, 1, len, encoder->rbsp); pthread_mutex_unlock(&s_mutex); return len; } size_t audio_encoder_dataspace(audio_encoder_p encoder) { assert(encoder != NULL); return rb_avail(&encoder->ringbuffer); } bool audio_encoder_dataspace_is_empty(audio_encoder_p encoder) { assert(encoder != NULL); return (rb_used(&encoder->ringbuffer) == SIZE_ZERO); } int audio_encoder_getframe(audio_encoder_p encoder, void *data, size_t len) { assert(encoder != NULL); priv_data_p priv = (priv_data_p) encoder->priv_data; assert(priv != NULL); switch (encoder->audio_type) { #ifdef CONFIG_CODEC_LIBOPUS case AUDIO_TYPE_OPUS: { opus_enc_external_t *opus_ext = (opus_enc_external_t *) encoder->enc_ext; int analysis_frame_size = opus_ext->inputSampleRate * opus_ext->frameSizeMS / 1000; size_t size = analysis_frame_size * opus_ext->inputChannels * sizeof(signed short); int ret = rbs_seek(encoder->rbsp, priv->mCurrentPos, SEEK_SET); RETURN_VAL_IF_FAIL((ret == OK), AUDIO_ENCODER_ERROR); RETURN_VAL_IF_FAIL((size <= (size_t) opus_ext->inputBufferMaxLength), AUDIO_ENCODER_ERROR); size_t rlen = rbs_read((void *) opus_ext->pInputBuffer, 1, size, encoder->rbsp); RETURN_VAL_IF_FAIL((rlen == size), AUDIO_ENCODER_ERROR); opus_ext->inputBufferCurrentLength = rlen; priv->mCurrentPos += rlen; rbs_seek_ext(encoder->rbsp, priv->mCurrentPos, SEEK_SET); ret = opus_frameEncode(opus_ext, encoder->enc_mem); RETURN_VAL_IF_FAIL((ret == OK), AUDIO_ENCODER_ERROR); RETURN_VAL_IF_FAIL(((int32_t) len >= opus_ext->outputDataSize), AUDIO_ENCODER_ERROR); memcpy(data, opus_ext->pOutputBuffer, opus_ext->outputDataSize); return opus_ext->outputDataSize; } #endif default: medwdbg("[%s] unsupported audio type: %d\n", __FUNCTION__, encoder->audio_type); return AUDIO_ENCODER_ERROR; } } int audio_encoder_init(audio_encoder_p encoder, size_t rbuf_size, audio_type_t audio_type, void *enc_ext) { assert(encoder != NULL); RETURN_VAL_IF_FAIL(audio_encoder_check_audio_type(audio_type), AUDIO_ENCODER_ERROR); encoder->audio_type = audio_type; encoder->cb_data = NULL; encoder->input_func = NULL; // init private data priv_data_p priv = (priv_data_p) malloc(sizeof(priv_data_t)); RETURN_VAL_IF_FAIL((priv != NULL), AUDIO_ENCODER_ERROR); priv->mCurrentPos = 0; encoder->priv_data = priv; int ret = _init_encoder(encoder, enc_ext); RETURN_VAL_IF_FAIL((ret == AUDIO_ENCODER_OK), AUDIO_ENCODER_ERROR); // init ring-buffer and open it as a stream rb_init(&encoder->ringbuffer, rbuf_size); encoder->rbsp = rbs_open(&encoder->ringbuffer, _input_callback, (void *)encoder); RETURN_VAL_IF_FAIL((encoder->rbsp != NULL), AUDIO_ENCODER_ERROR); rbs_ctrl(encoder->rbsp, OPTION_ALLOW_TO_DEQUEUE, 1); return AUDIO_ENCODER_OK; } int audio_encoder_register_callbacks(audio_encoder_p encoder, void *user_data, input_func_f input_func) { // init encoder data encoder->cb_data = user_data; encoder->input_func = input_func; return AUDIO_ENCODER_OK; } int audio_encoder_finish(audio_encoder_p encoder) { assert(encoder != NULL); // close stream rbs_close(encoder->rbsp); encoder->rbsp = NULL; // free ring-buffer instance rb_free(&encoder->ringbuffer); // free encoder external buffer if (encoder->enc_ext != NULL) { free(encoder->enc_ext); encoder->enc_ext = NULL; } // free encoder buffer if (encoder->enc_mem != NULL) { #ifdef CONFIG_CODEC_LIBOPUS opus_uninitEncoder(encoder->enc_mem); #endif free(encoder->enc_mem); encoder->enc_mem = NULL; } // free private data buffer if (encoder->priv_data != NULL) { free(encoder->priv_data); encoder->priv_data = NULL; } return AUDIO_ENCODER_OK; } } // namespace media
Remove unnecessary TODO comment in audio encoder
framework/media: Remove unnecessary TODO comment in audio encoder
C++
apache-2.0
an4967/TizenRT,jsdosa/TizenRT,jsdosa/TizenRT,Samsung/TizenRT,davidfather/TizenRT,pillip8282/TizenRT,jeongarmy/TizenRT,jeongchanKim/TizenRT,sunghan-chang/TizenRT,pillip8282/TizenRT,chanijjani/TizenRT,davidfather/TizenRT,jeongchanKim/TizenRT,JeonginKim/TizenRT,jsdosa/TizenRT,Samsung/TizenRT,junmin-kim/TizenRT,davidfather/TizenRT,junmin-kim/TizenRT,chanijjani/TizenRT,jsdosa/TizenRT,junmin-kim/TizenRT,jeongchanKim/TizenRT,jeongarmy/TizenRT,HONGCHAEHEE/TizenRT,Samsung/TizenRT,pillip8282/TizenRT,jeongarmy/TizenRT,junmin-kim/TizenRT,HONGCHAEHEE/TizenRT,jeongarmy/TizenRT,jeongarmy/TizenRT,sunghan-chang/TizenRT,JeonginKim/TizenRT,sunghan-chang/TizenRT,jsdosa/TizenRT,jsdosa/TizenRT,Samsung/TizenRT,HONGCHAEHEE/TizenRT,sunghan-chang/TizenRT,an4967/TizenRT,jeongarmy/TizenRT,pillip8282/TizenRT,davidfather/TizenRT,pillip8282/TizenRT,an4967/TizenRT,Samsung/TizenRT,an4967/TizenRT,sunghan-chang/TizenRT,jeongchanKim/TizenRT,an4967/TizenRT,JeonginKim/TizenRT,HONGCHAEHEE/TizenRT,jsdosa/TizenRT,junmin-kim/TizenRT,chanijjani/TizenRT,jeongchanKim/TizenRT,davidfather/TizenRT,davidfather/TizenRT,junmin-kim/TizenRT,an4967/TizenRT,an4967/TizenRT,davidfather/TizenRT,chanijjani/TizenRT,jeongchanKim/TizenRT,JeonginKim/TizenRT,HONGCHAEHEE/TizenRT,jeongarmy/TizenRT,chanijjani/TizenRT,HONGCHAEHEE/TizenRT,junmin-kim/TizenRT,sunghan-chang/TizenRT,pillip8282/TizenRT,Samsung/TizenRT,chanijjani/TizenRT,JeonginKim/TizenRT,pillip8282/TizenRT,jeongchanKim/TizenRT,JeonginKim/TizenRT,sunghan-chang/TizenRT,Samsung/TizenRT,chanijjani/TizenRT
673e2154a85dc87468bc4dcd822e29f6838dee9b
tests/test_coro.cpp
tests/test_coro.cpp
#include <atomic> #include <asyncply/cmd.h> #include <asyncply/parallel.h> #include <asyncply/run.h> #include <asyncply/algorithm.h> #include <gtest/gtest.h> class CoroTest : testing::Test { }; using namespace asyncply; TEST(CoroTest, Test1) { std::vector<std::string> lines; cmd(find("../.."), grep("test_"), out(lines)); for (auto& line : lines) std::cout << line << std::endl; } TEST(CoroTest, Test2) { cmd(find("../.."), grep(".*\\.cpp$|.*\\.h$"), cat(), grep("class|struct|typedef|using|void|int|double|float"), grep_v("enable_if|;|\"|\'"), split(" "), trim(), uniq(), join(" "), out()); } TEST(CoroTest, Test3) { std::vector<asyncply::coroutine<int> > coros; for(int i=1; i<10; ++i) { coros.emplace_back(asyncply::make_coroutine<int>( [=](auto& yield) { std::cout << "create " << i << std::endl; yield(0); std::cout << "download " << i << std::endl; yield(1); std::cout << "patching " << i << std::endl; yield(2); std::cout << "compile " << i << std::endl; yield(3); std::cout << "tests " << i << std::endl; yield(4); std::cout << "packing " << i << std::endl; yield(5); std::cout << "destroy " << i << std::endl; } )); } std::cout << "-- ticking coroutines" << std::endl; #if 1 // std::atomic<bool> any_updated; // any_updated = true; bool any_updated = true; while(any_updated) { any_updated = false; // asyncply::for_each_sync(coros.begin(), coros.end(), [&any_updated](auto& c) { for(auto& c : coros) { if(*c) { any_updated = true; (*c)(); } // }); } } #else for(auto& co : coros) { for(auto& c : *co) { std::cout << c << std::endl; } } #endif }
#include <atomic> #include <asyncply/cmd.h> #include <asyncply/parallel.h> #include <asyncply/run.h> #include <asyncply/algorithm.h> #include <gtest/gtest.h> class CoroTest : testing::Test { }; using namespace asyncply; TEST(CoroTest, Test1) { std::vector<std::string> lines; cmd(find("../.."), grep("test_"), out(lines)); for (auto& line : lines) std::cout << line << std::endl; } TEST(CoroTest, Test2) { cmd(find("../.."), grep(".*\\.cpp$|.*\\.h$"), cat(), grep("class|struct|typedef|using|void|int|double|float"), grep_v("enable_if|;|\"|\'"), split(" "), trim(), uniq(), join(" "), out()); } TEST(CoroTest, Test3) { std::vector<asyncply::coroutine<void> > coros; for(int i=1; i<10; ++i) { coros.emplace_back(asyncply::make_coroutine<void>( [=](auto& yield) { std::cout << "create " << i << std::endl; yield(); std::cout << "download " << i << std::endl; yield(); std::cout << "patching " << i << std::endl; yield(); std::cout << "compile " << i << std::endl; yield(); std::cout << "tests " << i << std::endl; yield(); std::cout << "packing " << i << std::endl; yield(); std::cout << "destroy " << i << std::endl; } )); } std::cout << "-- ticking coroutines" << std::endl; #if 0 // std::atomic<bool> any_updated; // any_updated = true; bool any_updated = true; while(any_updated) { any_updated = false; // asyncply::for_each_sync(coros.begin(), coros.end(), [&any_updated](auto& c) { for(auto& c : coros) { if(*c) { any_updated = true; (*c)(); } // }); } } #else for(auto& co : coros) { for(auto& c : *co) { ; } } #endif }
Update test_coro.cpp
Update test_coro.cpp
C++
cc0-1.0
makiolo/asyncply,makiolo/asyncply,makiolo/asyncply,makiolo/async-ply
02931751c1b0aab6c404b58513b0f6388343254d
source/Plugins/Process/Linux/SingleStepCheck.cpp
source/Plugins/Process/Linux/SingleStepCheck.cpp
//===-- SingleStepCheck.cpp ----------------------------------- -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SingleStepCheck.h" #include <sched.h> #include <signal.h> #include <sys/wait.h> #include <unistd.h> #include "NativeProcessLinux.h" #include "llvm/Support/Compiler.h" #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" #include "lldb/Host/linux/Ptrace.h" #include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; using namespace lldb_private::process_linux; #if defined(__arm64__) || defined(__aarch64__) namespace { void LLVM_ATTRIBUTE_NORETURN Child() { if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) _exit(1); // We just do an endless loop SIGSTOPPING ourselves until killed. The tracer // will fiddle with our cpu affinities and monitor the behaviour. for (;;) { raise(SIGSTOP); // Generate a bunch of instructions here, so that a single-step does not // land in the raise() accidentally. If single-stepping works, we will be // spinning in this loop. If it doesn't, we'll land in the raise() call // above. for (volatile unsigned i = 0; i < CPU_SETSIZE; ++i) ; } } struct ChildDeleter { ::pid_t pid; ~ChildDeleter() { int status; kill(pid, SIGKILL); // Kill the child. waitpid(pid, &status, __WALL); // Pick up the remains. } }; bool WorkaroundNeeded() { // We shall spawn a child, and use it to verify the debug capabilities of the // cpu. We shall iterate through the cpus, bind the child to each one in turn, // and verify that single-stepping works on that cpu. A workaround is needed // if we find at least one broken cpu. Log *log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); ::pid_t child_pid = fork(); if (child_pid == -1) { LLDB_LOG(log, "failed to fork(): {0}", Error(errno, eErrorTypePOSIX)); return false; } if (child_pid == 0) Child(); ChildDeleter child_deleter{child_pid}; cpu_set_t available_cpus; if (sched_getaffinity(child_pid, sizeof available_cpus, &available_cpus) == -1) { LLDB_LOG(log, "failed to get available cpus: {0}", Status(errno, eErrorTypePOSIX)); return false; } int status; ::pid_t wpid = waitpid(child_pid, &status, __WALL); if (wpid != child_pid || !WIFSTOPPED(status)) { LLDB_LOG(log, "waitpid() failed (status = {0:x}): {1}", status, Status(errno, eErrorTypePOSIX)); return false; } unsigned cpu; for (cpu = 0; cpu < CPU_SETSIZE; ++cpu) { if (!CPU_ISSET(cpu, &available_cpus)) continue; cpu_set_t cpus; CPU_ZERO(&cpus); CPU_SET(cpu, &cpus); if (sched_setaffinity(child_pid, sizeof cpus, &cpus) == -1) { LLDB_LOG(log, "failed to switch to cpu {0}: {1}", cpu, Status(errno, eErrorTypePOSIX)); continue; } int status; Status error = NativeProcessLinux::PtraceWrapper(PTRACE_SINGLESTEP, child_pid); if (error.Fail()) { LLDB_LOG(log, "single step failed: {0}", error); break; } wpid = waitpid(child_pid, &status, __WALL); if (wpid != child_pid || !WIFSTOPPED(status)) { LLDB_LOG(log, "waitpid() failed (status = {0:x}): {1}", status, Status(errno, eErrorTypePOSIX)); break; } if (WSTOPSIG(status) != SIGTRAP) { LLDB_LOG(log, "single stepping on cpu {0} failed with status {1:x}", cpu, status); break; } } // cpu is either the index of the first broken cpu, or CPU_SETSIZE. if (cpu == 0) { LLDB_LOG(log, "SINGLE STEPPING ON FIRST CPU IS NOT WORKING. DEBUGGING " "LIKELY TO BE UNRELIABLE."); // No point in trying to fiddle with the affinities, just give it our best // shot and see how it goes. return false; } return cpu != CPU_SETSIZE; } } // end anonymous namespace std::unique_ptr<SingleStepWorkaround> SingleStepWorkaround::Get(::pid_t tid) { Log *log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); static bool workaround_needed = WorkaroundNeeded(); if (!workaround_needed) { LLDB_LOG(log, "workaround for thread {0} not needed", tid); return nullptr; } cpu_set_t original_set; if (sched_getaffinity(tid, sizeof original_set, &original_set) != 0) { // This should really not fail. But, just in case... LLDB_LOG(log, "Unable to get cpu affinity for thread {0}: {1}", tid, Status(errno, eErrorTypePOSIX)); return nullptr; } cpu_set_t set; CPU_ZERO(&set); CPU_SET(0, &set); if (sched_setaffinity(tid, sizeof set, &set) != 0) { // This may fail in very locked down systems, if the thread is not allowed // to run on cpu 0. If that happens, only thing we can do is it log it and // continue... LLDB_LOG(log, "Unable to set cpu affinity for thread {0}: {1}", tid, Status(errno, eErrorTypePOSIX)); } LLDB_LOG(log, "workaround for thread {0} prepared", tid); return llvm::make_unique<SingleStepWorkaround>(tid, original_set); } SingleStepWorkaround::~SingleStepWorkaround() { Log *log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); LLDB_LOG(log, "Removing workaround"); if (sched_setaffinity(m_tid, sizeof m_original_set, &m_original_set) != 0) { LLDB_LOG(log, "Unable to reset cpu affinity for thread {0}: {1}", m_tid, Status(errno, eErrorTypePOSIX)); } } #endif
//===-- SingleStepCheck.cpp ----------------------------------- -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SingleStepCheck.h" #include <sched.h> #include <signal.h> #include <sys/wait.h> #include <unistd.h> #include "NativeProcessLinux.h" #include "llvm/Support/Compiler.h" #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" #include "lldb/Host/linux/Ptrace.h" #include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; using namespace lldb_private::process_linux; #if defined(__arm64__) || defined(__aarch64__) namespace { void LLVM_ATTRIBUTE_NORETURN Child() { if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) _exit(1); // We just do an endless loop SIGSTOPPING ourselves until killed. The tracer // will fiddle with our cpu affinities and monitor the behaviour. for (;;) { raise(SIGSTOP); // Generate a bunch of instructions here, so that a single-step does not // land in the raise() accidentally. If single-stepping works, we will be // spinning in this loop. If it doesn't, we'll land in the raise() call // above. for (volatile unsigned i = 0; i < CPU_SETSIZE; ++i) ; } } struct ChildDeleter { ::pid_t pid; ~ChildDeleter() { int status; kill(pid, SIGKILL); // Kill the child. waitpid(pid, &status, __WALL); // Pick up the remains. } }; bool WorkaroundNeeded() { // We shall spawn a child, and use it to verify the debug capabilities of the // cpu. We shall iterate through the cpus, bind the child to each one in turn, // and verify that single-stepping works on that cpu. A workaround is needed // if we find at least one broken cpu. Log *log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); ::pid_t child_pid = fork(); if (child_pid == -1) { LLDB_LOG(log, "failed to fork(): {0}", Status(errno, eErrorTypePOSIX)); return false; } if (child_pid == 0) Child(); ChildDeleter child_deleter{child_pid}; cpu_set_t available_cpus; if (sched_getaffinity(child_pid, sizeof available_cpus, &available_cpus) == -1) { LLDB_LOG(log, "failed to get available cpus: {0}", Status(errno, eErrorTypePOSIX)); return false; } int status; ::pid_t wpid = waitpid(child_pid, &status, __WALL); if (wpid != child_pid || !WIFSTOPPED(status)) { LLDB_LOG(log, "waitpid() failed (status = {0:x}): {1}", status, Status(errno, eErrorTypePOSIX)); return false; } unsigned cpu; for (cpu = 0; cpu < CPU_SETSIZE; ++cpu) { if (!CPU_ISSET(cpu, &available_cpus)) continue; cpu_set_t cpus; CPU_ZERO(&cpus); CPU_SET(cpu, &cpus); if (sched_setaffinity(child_pid, sizeof cpus, &cpus) == -1) { LLDB_LOG(log, "failed to switch to cpu {0}: {1}", cpu, Status(errno, eErrorTypePOSIX)); continue; } int status; Status error = NativeProcessLinux::PtraceWrapper(PTRACE_SINGLESTEP, child_pid); if (error.Fail()) { LLDB_LOG(log, "single step failed: {0}", error); break; } wpid = waitpid(child_pid, &status, __WALL); if (wpid != child_pid || !WIFSTOPPED(status)) { LLDB_LOG(log, "waitpid() failed (status = {0:x}): {1}", status, Status(errno, eErrorTypePOSIX)); break; } if (WSTOPSIG(status) != SIGTRAP) { LLDB_LOG(log, "single stepping on cpu {0} failed with status {1:x}", cpu, status); break; } } // cpu is either the index of the first broken cpu, or CPU_SETSIZE. if (cpu == 0) { LLDB_LOG(log, "SINGLE STEPPING ON FIRST CPU IS NOT WORKING. DEBUGGING " "LIKELY TO BE UNRELIABLE."); // No point in trying to fiddle with the affinities, just give it our best // shot and see how it goes. return false; } return cpu != CPU_SETSIZE; } } // end anonymous namespace std::unique_ptr<SingleStepWorkaround> SingleStepWorkaround::Get(::pid_t tid) { Log *log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); static bool workaround_needed = WorkaroundNeeded(); if (!workaround_needed) { LLDB_LOG(log, "workaround for thread {0} not needed", tid); return nullptr; } cpu_set_t original_set; if (sched_getaffinity(tid, sizeof original_set, &original_set) != 0) { // This should really not fail. But, just in case... LLDB_LOG(log, "Unable to get cpu affinity for thread {0}: {1}", tid, Status(errno, eErrorTypePOSIX)); return nullptr; } cpu_set_t set; CPU_ZERO(&set); CPU_SET(0, &set); if (sched_setaffinity(tid, sizeof set, &set) != 0) { // This may fail in very locked down systems, if the thread is not allowed // to run on cpu 0. If that happens, only thing we can do is it log it and // continue... LLDB_LOG(log, "Unable to set cpu affinity for thread {0}: {1}", tid, Status(errno, eErrorTypePOSIX)); } LLDB_LOG(log, "workaround for thread {0} prepared", tid); return llvm::make_unique<SingleStepWorkaround>(tid, original_set); } SingleStepWorkaround::~SingleStepWorkaround() { Log *log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); LLDB_LOG(log, "Removing workaround"); if (sched_setaffinity(m_tid, sizeof m_original_set, &m_original_set) != 0) { LLDB_LOG(log, "Unable to reset cpu affinity for thread {0}: {1}", m_tid, Status(errno, eErrorTypePOSIX)); } } #endif
Fix Linux Buildbot.
Fix Linux Buildbot. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@302874 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb
6a15b8e40aab99646c3bbcdc9b66bf90b6035274
tools/fpcollect.cpp
tools/fpcollect.cpp
#include <iostream> #include <dirent.h> #include <sys/stat.h> //#include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <fileref.h> #include <tag.h> #include "chromaprint.h" #include "fingerprinter.h" #include "fingerprinter_configuration.h" #include "fingerprint_compressor.h" #include "base64.h" #include "ext/ffmpeg_decoder.h" using namespace std; static const int kChromaprintAlgorithm = CHROMAPRINT_ALGORITHM_DEFAULT; typedef vector<string> string_vector; void FindFiles(const string &dirname, string_vector *result) { DIR *dirp = opendir(dirname.c_str()); while (dirp) { struct dirent *dp; if ((dp = readdir(dirp)) != NULL) { struct stat sp; string filename = dirname + '/' + string(dp->d_name); stat(filename.c_str(), &sp); if (S_ISREG(sp.st_mode)) { result->push_back(filename); } if (S_ISDIR(sp.st_mode) && dp->d_name[0] != '.') { FindFiles(filename, result); } } else { break; } } closedir(dirp); } string_vector FindFiles(const char *dirname) { string_vector result; FindFiles(dirname, &result); sort(result.begin(), result.end()); return result; } #define DISPATCH_TAGLIB_FILE(type, file) \ { \ type *tmp = dynamic_cast<type *>(file); \ if (tmp) { \ return ExtractMBIDFromFile(tmp); \ } \ } #include <xiphcomment.h> #include <apetag.h> #include <vorbisfile.h> #include <oggflacfile.h> #include <speexfile.h> #include <flacfile.h> #include <mpcfile.h> #include <wavpackfile.h> #ifdef TAGLIB_WITH_ASF #include <asffile.h> #endif #ifdef TAGLIB_WITH_MP4 #include <mp4file.h> #endif #include <mpegfile.h> #include <id3v2tag.h> #include <uniquefileidentifierframe.h> string ExtractMBIDFromXiphComment(TagLib::Ogg::XiphComment *tag) { string key = "MUSICBRAINZ_TRACKID"; if (tag->fieldListMap().contains(key)) { return tag->fieldListMap()[key].front().to8Bit(true); } return string(); } string ExtractMBIDFromAPETag(TagLib::APE::Tag *tag) { string key = "MUSICBRAINZ_TRACKID"; if (tag->itemListMap().contains(key)) { return tag->itemListMap()[key].toString().to8Bit(true); } return string(); } string ExtractMBIDFromFile(TagLib::Ogg::Vorbis::File *file) { return ExtractMBIDFromXiphComment(file->tag()); } string ExtractMBIDFromFile(TagLib::Ogg::FLAC::File *file) { return ExtractMBIDFromXiphComment(file->tag()); } string ExtractMBIDFromFile(TagLib::Ogg::Speex::File *file) { return ExtractMBIDFromXiphComment(file->tag()); } string ExtractMBIDFromFile(TagLib::FLAC::File *file) { return ExtractMBIDFromXiphComment(file->xiphComment()); } string ExtractMBIDFromFile(TagLib::MPC::File *file) { return ExtractMBIDFromAPETag(file->APETag()); } string ExtractMBIDFromFile(TagLib::WavPack::File *file) { return ExtractMBIDFromAPETag(file->APETag()); } /*string ExtractMBIDFromFile(TagLib::APE::File *file) { return ExtractMBIDFromAPETag(file->APETag()); }*/ #ifdef TAGLIB_WITH_ASF string ExtractMBIDFromFile(TagLib::ASF::File *file) { string key = "MusicBrainz/Track Id"; TagLib::ASF::Tag *tag = file->tag(); if (tag->attributeListMap().contains(key)) { return tag->attributeListMap()[key].front().toString().to8Bit(true); } return string(); } #endif #ifdef TAGLIB_WITH_MP4 string ExtractMBIDFromFile(TagLib::MP4::File *file) { string key = "----:com.apple.iTunes:MusicBrainz Track Id"; TagLib::MP4::Tag *tag = file->tag(); if (tag->itemListMap().contains(key)) { return tag->itemListMap()[key].toStringList().toString().to8Bit(true); } return string(); } #endif string ExtractMBIDFromFile(TagLib::MPEG::File *file) { TagLib::ID3v2::Tag *tag = file->ID3v2Tag(); TagLib::ID3v2::FrameList ufid = tag->frameListMap()["UFID"]; if (!ufid.isEmpty()) { for (TagLib::ID3v2::FrameList::Iterator i = ufid.begin(); i != ufid.end(); i++) { TagLib::ID3v2::UniqueFileIdentifierFrame *frame = dynamic_cast<TagLib::ID3v2::UniqueFileIdentifierFrame *>(*i); if (frame && frame->owner() == "http://musicbrainz.org") { TagLib::ByteVector id = frame->identifier(); return string(id.data(), id.size()); } } } return string(); } string ExtractMusicBrainzTrackID(TagLib::File *file) { DISPATCH_TAGLIB_FILE(TagLib::FLAC::File, file); DISPATCH_TAGLIB_FILE(TagLib::Ogg::Vorbis::File, file); DISPATCH_TAGLIB_FILE(TagLib::Ogg::FLAC::File, file); DISPATCH_TAGLIB_FILE(TagLib::Ogg::Speex::File, file); DISPATCH_TAGLIB_FILE(TagLib::MPC::File, file); DISPATCH_TAGLIB_FILE(TagLib::WavPack::File, file); #ifdef TAGLIB_WITH_ASF DISPATCH_TAGLIB_FILE(TagLib::ASF::File, file); #endif #ifdef TAGLIB_WITH_MP4 DISPATCH_TAGLIB_FILE(TagLib::MP4::File, file); #endif DISPATCH_TAGLIB_FILE(TagLib::MPEG::File, file); return string(); } bool ReadTags(const string &filename) { TagLib::FileRef file(filename.c_str(), true); if (file.isNull()) return false; TagLib::Tag *tags = file.tag(); TagLib::AudioProperties *props = file.audioProperties(); if (!tags || !props) return false; //cout << "ARTIST=" << tags->artist().to8Bit(true) << "\n"; //cout << "TITLE=" << tags->title().to8Bit(true) << "\n"; //cout << "ALBUM=" << tags->album().to8Bit(true) << "\n"; int length = props->length(); string mbid = ExtractMusicBrainzTrackID(file.file()); if (!length || mbid.size() != 36) return false; cout << "LENGTH=" << length << "\n"; cout << "BITRATE=" << props->bitrate() << "\n"; cout << "MBID=" << mbid << "\n"; return true; } string ExtractExtension(const string &filename) { size_t pos = filename.find_last_of('.'); if (pos == string::npos) { return string(); } return boost::to_upper_copy(filename.substr(pos + 1)); } string EncodeFingerprint(const vector<uint32_t> &fp) { string res; res.resize(fp.size()); } bool ProcessFile(Chromaprint::Fingerprinter *fingerprinter, const string &filename) { if (!ReadTags(filename)) return false; Decoder decoder(filename); if (!decoder.Open()) return false; if (!fingerprinter->Start(decoder.SampleRate(), decoder.Channels())) return false; cerr << filename << "\n"; // cout << "FILENAME=" << filename << "\n"; cout << "FORMAT=" << ExtractExtension(filename) << "\n"; decoder.Decode(fingerprinter, 120); vector<int32_t> fp = fingerprinter->Finish(); /*cout << "FINGERPRINT1="; for (int i = 0; i < fp.size(); i++) { cout << fp[i] << ", "; } cout << "\n";*/ cout << "FINGERPRINT=" << Chromaprint::Base64Encode(Chromaprint::CompressFingerprint(fp, kChromaprintAlgorithm)) << "\n\n"; return true; } int main(int argc, char **argv) { if (argc < 2) { cerr << "Usage: " << argv[0] << " DIR\n"; return 1; } Chromaprint::Fingerprinter fingerprinter(Chromaprint::CreateFingerprinterConfiguration(kChromaprintAlgorithm)); string_vector files = FindFiles(argv[1]); for (string_vector::iterator it = files.begin(); it != files.end(); it++) { ProcessFile(&fingerprinter, *it); } return 0; }
#include <iostream> #include <dirent.h> #include <sys/stat.h> //#include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <fileref.h> #include <tag.h> #include "chromaprint.h" #include "fingerprinter.h" #include "fingerprinter_configuration.h" #include "fingerprint_compressor.h" #include "base64.h" #include "ext/ffmpeg_decoder.h" using namespace std; static const int kChromaprintAlgorithm = CHROMAPRINT_ALGORITHM_DEFAULT; typedef vector<string> string_vector; void FindFiles(const string &dirname, string_vector *result, time_t changed_since) { DIR *dirp = opendir(dirname.c_str()); while (dirp) { struct dirent *dp; if ((dp = readdir(dirp)) != NULL) { struct stat sp; string filename = dirname + '/' + string(dp->d_name); stat(filename.c_str(), &sp); if (S_ISREG(sp.st_mode)) { //cerr << "file " << filename << " mtime=" << sp.st_mtime << " ch=" << changed_since << "\n"; if (!changed_since || sp.st_mtime >= changed_since) { result->push_back(filename); } } if (S_ISDIR(sp.st_mode) && dp->d_name[0] != '.') { FindFiles(filename, result, changed_since); } } else { break; } } closedir(dirp); } string_vector FindFiles(const char *dirname, time_t changed_since) { string_vector result; FindFiles(dirname, &result, changed_since); sort(result.begin(), result.end()); return result; } #define DISPATCH_TAGLIB_FILE(type, file) \ { \ type *tmp = dynamic_cast<type *>(file); \ if (tmp) { \ return ExtractMBIDFromFile(tmp); \ } \ } #include <xiphcomment.h> #include <apetag.h> #include <vorbisfile.h> #include <oggflacfile.h> #include <speexfile.h> #include <flacfile.h> #include <mpcfile.h> #include <wavpackfile.h> #ifdef TAGLIB_WITH_ASF #include <asffile.h> #endif #ifdef TAGLIB_WITH_MP4 #include <mp4file.h> #endif #include <mpegfile.h> #include <id3v2tag.h> #include <uniquefileidentifierframe.h> string ExtractMBIDFromXiphComment(TagLib::Ogg::XiphComment *tag) { string key = "MUSICBRAINZ_TRACKID"; if (tag->fieldListMap().contains(key)) { return tag->fieldListMap()[key].front().to8Bit(true); } return string(); } string ExtractMBIDFromAPETag(TagLib::APE::Tag *tag) { string key = "MUSICBRAINZ_TRACKID"; if (tag->itemListMap().contains(key)) { return tag->itemListMap()[key].toString().to8Bit(true); } return string(); } string ExtractMBIDFromFile(TagLib::Ogg::Vorbis::File *file) { return ExtractMBIDFromXiphComment(file->tag()); } string ExtractMBIDFromFile(TagLib::Ogg::FLAC::File *file) { return ExtractMBIDFromXiphComment(file->tag()); } string ExtractMBIDFromFile(TagLib::Ogg::Speex::File *file) { return ExtractMBIDFromXiphComment(file->tag()); } string ExtractMBIDFromFile(TagLib::FLAC::File *file) { return ExtractMBIDFromXiphComment(file->xiphComment()); } string ExtractMBIDFromFile(TagLib::MPC::File *file) { return ExtractMBIDFromAPETag(file->APETag()); } string ExtractMBIDFromFile(TagLib::WavPack::File *file) { return ExtractMBIDFromAPETag(file->APETag()); } /*string ExtractMBIDFromFile(TagLib::APE::File *file) { return ExtractMBIDFromAPETag(file->APETag()); }*/ #ifdef TAGLIB_WITH_ASF string ExtractMBIDFromFile(TagLib::ASF::File *file) { string key = "MusicBrainz/Track Id"; TagLib::ASF::Tag *tag = file->tag(); if (tag->attributeListMap().contains(key)) { return tag->attributeListMap()[key].front().toString().to8Bit(true); } return string(); } #endif #ifdef TAGLIB_WITH_MP4 string ExtractMBIDFromFile(TagLib::MP4::File *file) { string key = "----:com.apple.iTunes:MusicBrainz Track Id"; TagLib::MP4::Tag *tag = file->tag(); if (tag->itemListMap().contains(key)) { return tag->itemListMap()[key].toStringList().toString().to8Bit(true); } return string(); } #endif string ExtractMBIDFromFile(TagLib::MPEG::File *file) { TagLib::ID3v2::Tag *tag = file->ID3v2Tag(); TagLib::ID3v2::FrameList ufid = tag->frameListMap()["UFID"]; if (!ufid.isEmpty()) { for (TagLib::ID3v2::FrameList::Iterator i = ufid.begin(); i != ufid.end(); i++) { TagLib::ID3v2::UniqueFileIdentifierFrame *frame = dynamic_cast<TagLib::ID3v2::UniqueFileIdentifierFrame *>(*i); if (frame && frame->owner() == "http://musicbrainz.org") { TagLib::ByteVector id = frame->identifier(); return string(id.data(), id.size()); } } } return string(); } string ExtractMusicBrainzTrackID(TagLib::File *file) { DISPATCH_TAGLIB_FILE(TagLib::FLAC::File, file); DISPATCH_TAGLIB_FILE(TagLib::Ogg::Vorbis::File, file); DISPATCH_TAGLIB_FILE(TagLib::Ogg::FLAC::File, file); DISPATCH_TAGLIB_FILE(TagLib::Ogg::Speex::File, file); DISPATCH_TAGLIB_FILE(TagLib::MPC::File, file); DISPATCH_TAGLIB_FILE(TagLib::WavPack::File, file); #ifdef TAGLIB_WITH_ASF DISPATCH_TAGLIB_FILE(TagLib::ASF::File, file); #endif #ifdef TAGLIB_WITH_MP4 DISPATCH_TAGLIB_FILE(TagLib::MP4::File, file); #endif DISPATCH_TAGLIB_FILE(TagLib::MPEG::File, file); return string(); } bool ReadTags(const string &filename) { TagLib::FileRef file(filename.c_str(), true); if (file.isNull()) return false; TagLib::Tag *tags = file.tag(); TagLib::AudioProperties *props = file.audioProperties(); if (!tags || !props) return false; //cout << "ARTIST=" << tags->artist().to8Bit(true) << "\n"; //cout << "TITLE=" << tags->title().to8Bit(true) << "\n"; //cout << "ALBUM=" << tags->album().to8Bit(true) << "\n"; int length = props->length(); string mbid = ExtractMusicBrainzTrackID(file.file()); if (!length || mbid.size() != 36) return false; cout << "LENGTH=" << length << "\n"; cout << "BITRATE=" << props->bitrate() << "\n"; cout << "MBID=" << mbid << "\n"; return true; } string ExtractExtension(const string &filename) { size_t pos = filename.find_last_of('.'); if (pos == string::npos) { return string(); } return boost::to_upper_copy(filename.substr(pos + 1)); } string EncodeFingerprint(const vector<uint32_t> &fp) { string res; res.resize(fp.size()); } bool ProcessFile(Chromaprint::Fingerprinter *fingerprinter, const string &filename) { if (!ReadTags(filename)) return false; Decoder decoder(filename); if (!decoder.Open()) return false; if (!fingerprinter->Start(decoder.SampleRate(), decoder.Channels())) return false; cerr << filename << "\n"; // cout << "FILENAME=" << filename << "\n"; cout << "FORMAT=" << ExtractExtension(filename) << "\n"; decoder.Decode(fingerprinter, 120); vector<int32_t> fp = fingerprinter->Finish(); /*cout << "FINGERPRINT1="; for (int i = 0; i < fp.size(); i++) { cout << fp[i] << ", "; } cout << "\n";*/ cout << "FINGERPRINT=" << Chromaprint::Base64Encode(Chromaprint::CompressFingerprint(fp, kChromaprintAlgorithm)) << "\n\n"; return true; } int main(int argc, char **argv) { if (argc < 2) { cerr << "Usage: " << argv[0] << " DIR [DATE]\n"; return 1; } time_t changed_since = 0; if (argc > 2) { struct tm tm; memset(&tm, 0, sizeof(tm)); if (strptime(argv[2], "%Y-%m-%d %H:%M", &tm) == NULL) { if (strptime(argv[2], "%Y-%m-%d", &tm) == NULL) { cerr << "ERROR: Invalid date, the expected format is 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM'\n"; return 1; } } tm.tm_isdst = -1; changed_since = mktime(&tm); cerr << "Calculating fingerprints for files in " << argv[1] << " that were changed since " << argv[2] << "\n"; } else { cerr << "Calculating fingerprints for all files in " << argv[1] << "\n"; } Chromaprint::Fingerprinter fingerprinter(Chromaprint::CreateFingerprinterConfiguration(kChromaprintAlgorithm)); string_vector files = FindFiles(argv[1], changed_since); for (string_vector::iterator it = files.begin(); it != files.end(); it++) { ProcessFile(&fingerprinter, *it); } return 0; }
Add an option to filter files by modification date
Add an option to filter files by modification date
C++
lgpl-2.1
lalinsky/chromaprint,capcomvertigo/chromaprint,vonwenm/chromaprint,capcomvertigo/chromaprint,vonwenm/chromaprint,lalinsky/chromaprint
4d2d165b70235f44a56e1868d454e6753228084e
include/Sieve.hpp
include/Sieve.hpp
/// /// @file Sieve.hpp /// @brief The Sieve class is a highly optimized sieve of /// Eratosthenes implementation with 30 numbers per byte /// i.e. the 8 bits of each byte correspond to the offsets /// { 1, 7, 11, 13, 17, 19, 23, 29 }. This Sieve also /// skips multiples of 2, 3, 5 using wheel factorization. /// /// Unlike a traditional prime sieve this sieve is /// designed for use in the combinatorial prime counting /// algorithms: this sieve removes primes as well as /// multiples of primes and it counts the number of /// elements that have been crossed off for the first /// time in the sieve array. /// /// Copyright (C) 2019 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef SIEVE_HPP #define SIEVE_HPP #include <stdint.h> #include <vector> namespace primecount { using byte_t = uint8_t; struct Wheel { Wheel() : multiple(0), index(0) { } Wheel(uint32_t m, uint32_t i) : multiple(m), index(i) { } uint32_t multiple; uint32_t index; }; class Sieve { public: Sieve(uint64_t start, uint64_t segment_size, uint64_t wheel_size); static uint64_t get_segment_size(uint64_t size); uint64_t segment_size() const; uint64_t pre_sieve(uint64_t c, uint64_t low, uint64_t high); uint64_t cross_off(uint64_t i, uint64_t prime); /// Count 1 bits inside [start, stop] uint64_t count(uint64_t start, uint64_t stop) const; /// Count 1 bits inside [0, stop] uint64_t count(uint64_t stop) const { return count(0, stop); } /// Count 1 bits inside [start, stop]. /// This method counts either forwards or backwards /// depending on what's faster. /// uint64_t count(uint64_t start, uint64_t stop, uint64_t low, uint64_t high, uint64_t count_0_start, uint64_t count_low_high) const { if (start > stop) return 0; if (stop - start < ((high - 1) - low) - stop) return count(start, stop); else return count_low_high - count_0_start - count(stop + 1, (high - 1) - low); } private: void set_sieve_size(uint64_t segment_size); void add(uint64_t prime); uint64_t start_; std::vector<byte_t> sieve_; std::vector<Wheel> wheel_; }; } // namespace #endif
/// /// @file Sieve.hpp /// @brief The Sieve class is a highly optimized sieve of /// Eratosthenes implementation with 30 numbers per byte /// i.e. the 8 bits of each byte correspond to the offsets /// { 1, 7, 11, 13, 17, 19, 23, 29 }. This Sieve also /// skips multiples of 2, 3, 5 using wheel factorization. /// /// Unlike a traditional prime sieve this sieve is /// designed for use in the combinatorial prime counting /// algorithms: this sieve removes primes as well as /// multiples of primes and it counts the number of /// elements that have been crossed off for the first /// time in the sieve array. /// /// Copyright (C) 2019 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef SIEVE_HPP #define SIEVE_HPP #include <stdint.h> #include <vector> namespace primecount { using byte_t = uint8_t; struct Wheel { Wheel() : multiple(0), index(0) { } Wheel(uint32_t m, uint32_t i) : multiple(m), index(i) { } uint32_t multiple; uint32_t index; }; class Sieve { public: Sieve(uint64_t start, uint64_t segment_size, uint64_t wheel_size); static uint64_t get_segment_size(uint64_t size); uint64_t segment_size() const; uint64_t pre_sieve(uint64_t c, uint64_t low, uint64_t high); uint64_t cross_off(uint64_t i, uint64_t prime); /// Count 1 bits inside [start, stop] uint64_t count(uint64_t start, uint64_t stop) const; /// Count 1 bits inside [start, stop]. /// This method counts either forwards or backwards /// depending on what's faster. /// uint64_t count(uint64_t start, uint64_t stop, uint64_t low, uint64_t high, uint64_t count_0_start, uint64_t count_low_high) const { if (start > stop) return 0; if (stop - start < ((high - 1) - low) - stop) return count(start, stop); else return count_low_high - count_0_start - count(stop + 1, (high - 1) - low); } private: void set_sieve_size(uint64_t segment_size); void add(uint64_t prime); uint64_t start_; std::vector<byte_t> sieve_; std::vector<Wheel> wheel_; }; } // namespace #endif
Remove unused method
Remove unused method
C++
bsd-2-clause
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
7e1de0c7255363d345c7245e54871c3e941a3c83
plugin/hdCycles/points.cpp
plugin/hdCycles/points.cpp
// Copyright 2020 Tangent Animation // // 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, // including without limitation, as related to merchantability and fitness // for a particular purpose. // // In no event shall any copyright holder be liable for any damages of any kind // arising from the use of this software, whether in contract, tort or otherwise. // See the License for the specific language governing permissions and // limitations under the License. #include "points.h" #include "config.h" #include "material.h" #include "renderParam.h" #include "utils.h" #include <render/mesh.h> #include <render/object.h> #include <render/scene.h> #include <render/shader.h> #include <util/util_math_float3.h> #include <util/util_string.h> #include <pxr/base/gf/vec3f.h> #include <pxr/base/gf/vec3i.h> #include <pxr/imaging/hd/mesh.h> #include <pxr/imaging/hd/sceneDelegate.h> #ifdef USE_USD_CYCLES_SCHEMA # include <usdCycles/tokens.h> #endif PXR_NAMESPACE_OPEN_SCOPE HdCyclesPoints::HdCyclesPoints(SdfPath const& id, SdfPath const& instancerId, HdCyclesRenderDelegate* a_renderDelegate) : HdPoints(id, instancerId) , m_renderDelegate(a_renderDelegate) , m_transform(ccl::transform_identity()) { static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); config.enable_motion_blur.eval(m_useMotionBlur, true); config.default_point_style.eval(m_pointStyle, true); config.default_point_resolution.eval(m_pointResolution, true); if (m_useMotionBlur) { config.motion_steps.eval(m_motionSteps, true); } m_cyclesMesh = new ccl::Mesh(); m_renderDelegate->GetCyclesRenderParam()->AddGeometry(m_cyclesMesh); } HdCyclesPoints::~HdCyclesPoints() { // Remove points for (size_t i = 0; i < m_cyclesObjects.size(); i++) { m_renderDelegate->GetCyclesRenderParam()->RemoveObject(m_cyclesObjects[i]); } m_cyclesObjects.clear(); // Remove mesh m_renderDelegate->GetCyclesRenderParam()->RemoveMesh(m_cyclesMesh); delete m_cyclesMesh; } void HdCyclesPoints::_InitRepr(TfToken const& reprToken, HdDirtyBits* dirtyBits) { } HdDirtyBits HdCyclesPoints::_PropagateDirtyBits(HdDirtyBits bits) const { return bits; } void HdCyclesPoints::Finalize(HdRenderParam* renderParam) { } void HdCyclesPoints::Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits, TfToken const& reprSelector) { HdCyclesRenderParam* param = static_cast<HdCyclesRenderParam*>(renderParam); const SdfPath& id = GetId(); HdCyclesPDPIMap pdpi; ccl::Scene* scene = param->GetCyclesScene(); bool needs_update = false; bool needs_newMesh = true; // Read Cycles Primvars #ifdef USE_USD_CYCLES_SCHEMA if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, usdCyclesTokens->cyclesObjectPoint_style)) { needs_newMesh = true; HdTimeSampleArray<VtValue, 1> xf; sceneDelegate->SamplePrimvar(id, usdCyclesTokens->cyclesObjectPoint_style, &xf); if (xf.count > 0) { const TfToken& styles = xf.values[0].Get<TfToken>(); m_pointStyle = POINT_DISCS; if (styles == usdCyclesTokens->sphere) { m_pointStyle = POINT_SPHERES; } } } if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, usdCyclesTokens->cyclesObjectPoint_resolution)) { needs_newMesh = true; HdTimeSampleArray<VtValue, 1> xf; sceneDelegate->SamplePrimvar(id, usdCyclesTokens->cyclesObjectPoint_resolution, &xf); if (xf.count > 0) { const int& resolutions = xf.values[0].Get<int>(); m_pointResolution = std::max(resolutions, 10); } } #endif // Create Points if (*dirtyBits & HdChangeTracker::DirtyPoints || needs_newMesh) { needs_update = true; m_cyclesMesh->clear(); if (m_pointStyle == HdCyclesPointStyle::POINT_DISCS) { _CreateDiscMesh(); } else { _CreateSphereMesh(); } m_cyclesMesh->tag_update(scene, true); const auto pointsValue = sceneDelegate->Get(id, HdTokens->points); if (!pointsValue.IsEmpty() && pointsValue.IsHolding<VtVec3fArray>()) { const VtVec3fArray& points = pointsValue.Get<VtVec3fArray>(); for (size_t i = 0; i < m_cyclesObjects.size(); i++) { param->RemoveObject(m_cyclesObjects[i]); } m_cyclesObjects.clear(); for (size_t i = 0; i < points.size(); i++) { ccl::Object* pointObject = _CreatePointsObject(ccl::transform_translate(vec3f_to_float3(points[i])), m_cyclesMesh); pointObject->random_id = i; pointObject->name = ccl::ustring::format("%s@%08x", pointObject->name, pointObject->random_id); m_cyclesObjects.push_back(pointObject); param->AddObject(pointObject); } } } if (*dirtyBits & HdChangeTracker::DirtyTransform) { ccl::Transform newTransform = HdCyclesExtractTransform(sceneDelegate, id); for (size_t i = 0; i < m_cyclesObjects.size(); i++) { m_cyclesObjects[i]->tfm = ccl::transform_inverse(m_transform) * m_cyclesObjects[i]->tfm; m_cyclesObjects[i]->tfm = newTransform * m_cyclesObjects[i]->tfm; } m_transform = newTransform; needs_update = true; } // TODO: It's likely that this can cause double transforms due to modifying the core transform if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->widths)) { needs_update = true; if (m_cyclesObjects.size() > 0) { HdTimeSampleArray<VtValue, 2> xf; sceneDelegate->SamplePrimvar(id, HdTokens->widths, &xf); if (xf.count > 0) { const VtFloatArray& widths = xf.values[0].Get<VtFloatArray>(); for (size_t i = 0; i < widths.size(); i++) { if (i < m_cyclesObjects.size()) { float w = widths[i]; m_cyclesObjects[i]->tfm = m_cyclesObjects[i]->tfm * ccl::transform_scale(w, w, w); } } } } } if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals)) { needs_update = true; if (m_cyclesObjects.size() > 0) { HdTimeSampleArray<VtValue, 1> xf; sceneDelegate->SamplePrimvar(id, HdTokens->normals, &xf); if (xf.count > 0) { const VtVec3fArray& normals = xf.values[0].Get<VtVec3fArray>(); for (size_t i = 0; i < normals.size(); i++) { if (i < m_cyclesObjects.size()) { ccl::float3 rotAxis = ccl::cross(ccl::make_float3(0.0f, 0.0f, 1.0f), ccl::make_float3(normals[i][0], normals[i][1], normals[i][2])); float d = ccl::dot(ccl::make_float3(0.0f, 0.0f, 1.0f), ccl::make_float3(normals[i][0], normals[i][1], normals[i][2])); float angle = atan2f(ccl::len(rotAxis), d); m_cyclesObjects[i]->tfm = m_cyclesObjects[i]->tfm * ccl::transform_rotate((angle), rotAxis); } } } else { // handle orient to camera } } } if (*dirtyBits & HdChangeTracker::DirtyVisibility) { needs_update = true; bool visible = sceneDelegate->GetVisible(id); for (size_t i = 0; i < m_cyclesObjects.size(); i++) { if (visible) { m_cyclesObjects[i]->visibility |= ccl::PATH_RAY_ALL_VISIBILITY; } else { m_cyclesObjects[i]->visibility &= ~ccl::PATH_RAY_ALL_VISIBILITY; } } } if (needs_update) param->Interrupt(); *dirtyBits = HdChangeTracker::Clean; } HdDirtyBits HdCyclesPoints::GetInitialDirtyBitsMask() const { return HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyTransform | HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyWidths | HdChangeTracker::DirtyMaterialId | HdChangeTracker::DirtyInstanceIndex | HdChangeTracker::DirtyNormals; } bool HdCyclesPoints::IsValid() const { return true; } // Creates z up disc void HdCyclesPoints::_CreateDiscMesh() { m_cyclesMesh->clear(); m_cyclesMesh->name = ccl::ustring("generated_disc"); m_cyclesMesh->subdivision_type = ccl::Mesh::SUBDIVISION_NONE; int numVerts = m_pointResolution; int numFaces = m_pointResolution - 2; m_cyclesMesh->reserve_mesh(numVerts, numFaces); m_cyclesMesh->verts.reserve(numVerts); for (int i = 0; i < m_pointResolution; i++) { float d = (static_cast<float>(i) / static_cast<float>(m_pointResolution)) * 2.0f * M_PI_F; float x = sin(d) * 0.5f; float y = cos(d) * 0.5f; m_cyclesMesh->verts.push_back_reserved(ccl::make_float3(x, y, 0.0f)); } for (int i = 1; i < m_pointResolution - 1; i++) { int v0 = 0; int v1 = i; int v2 = i + 1; m_cyclesMesh->add_triangle(v0, v1, v2, 0, true); } m_cyclesMesh->compute_bounds(); } void HdCyclesPoints::_CreateSphereMesh() { float radius = 0.5f; int sectorCount = m_pointResolution; int stackCount = m_pointResolution; m_cyclesMesh->clear(); m_cyclesMesh->name = ccl::ustring("generated_sphere"); m_cyclesMesh->subdivision_type = ccl::Mesh::SUBDIVISION_NONE; float z, xy; float sectorStep = 2.0f * M_PI_F / sectorCount; float stackStep = M_PI_F / stackCount; float sectorAngle, stackAngle; for (int i = 0; i <= stackCount; ++i) { stackAngle = M_PI_F / 2.0f - i * stackStep; xy = radius * cosf(stackAngle); z = radius * sinf(stackAngle); for (int j = 0; j <= sectorCount; ++j) { sectorAngle = j * sectorStep; m_cyclesMesh->verts.push_back_slow(ccl::make_float3(xy * cosf(sectorAngle), xy * sinf(sectorAngle), z)); // TODO: Add normals and uvs } } int k1, k2; for (int i = 0; i < stackCount; ++i) { k1 = i * (sectorCount + 1); k2 = k1 + sectorCount + 1; for (int j = 0; j < sectorCount; ++j, ++k1, ++k2) { if (i != 0) { m_cyclesMesh->add_triangle(k1, k2, k1 + 1, 0, true); } if (i != (stackCount - 1)) { m_cyclesMesh->add_triangle(k1 + 1, k2, k2 + 1, 0, true); } } } m_cyclesMesh->compute_bounds(); } ccl::Object* HdCyclesPoints::_CreatePointsObject(const ccl::Transform& transform, ccl::Mesh* mesh) { /* create object*/ ccl::Object* object = new ccl::Object(); object->geometry = mesh; object->tfm = transform; object->motion.clear(); return object; } PXR_NAMESPACE_CLOSE_SCOPE
// Copyright 2020 Tangent Animation // // 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, // including without limitation, as related to merchantability and fitness // for a particular purpose. // // In no event shall any copyright holder be liable for any damages of any kind // arising from the use of this software, whether in contract, tort or otherwise. // See the License for the specific language governing permissions and // limitations under the License. #include "points.h" #include "config.h" #include "material.h" #include "renderParam.h" #include "utils.h" #include <render/mesh.h> #include <render/object.h> #include <render/scene.h> #include <render/shader.h> #include <util/util_math_float3.h> #include <util/util_string.h> #include <pxr/base/gf/vec3f.h> #include <pxr/base/gf/vec3i.h> #include <pxr/imaging/hd/mesh.h> #include <pxr/imaging/hd/sceneDelegate.h> #ifdef USE_USD_CYCLES_SCHEMA # include <usdCycles/tokens.h> #endif PXR_NAMESPACE_OPEN_SCOPE HdCyclesPoints::HdCyclesPoints(SdfPath const& id, SdfPath const& instancerId, HdCyclesRenderDelegate* a_renderDelegate) : HdPoints(id, instancerId) , m_renderDelegate(a_renderDelegate) , m_transform(ccl::transform_identity()) { static const HdCyclesConfig& config = HdCyclesConfig::GetInstance(); config.enable_motion_blur.eval(m_useMotionBlur, true); config.default_point_style.eval(m_pointStyle, true); config.default_point_resolution.eval(m_pointResolution, true); if (m_useMotionBlur) { config.motion_steps.eval(m_motionSteps, true); } m_cyclesMesh = new ccl::Mesh(); m_renderDelegate->GetCyclesRenderParam()->AddGeometry(m_cyclesMesh); } HdCyclesPoints::~HdCyclesPoints() { // Remove points for (size_t i = 0; i < m_cyclesObjects.size(); i++) { m_renderDelegate->GetCyclesRenderParam()->RemoveObject(m_cyclesObjects[i]); } m_cyclesObjects.clear(); // Remove mesh m_renderDelegate->GetCyclesRenderParam()->RemoveMesh(m_cyclesMesh); delete m_cyclesMesh; } void HdCyclesPoints::_InitRepr(TfToken const& reprToken, HdDirtyBits* dirtyBits) { } HdDirtyBits HdCyclesPoints::_PropagateDirtyBits(HdDirtyBits bits) const { return bits; } void HdCyclesPoints::Finalize(HdRenderParam* renderParam) { } void HdCyclesPoints::Sync(HdSceneDelegate* sceneDelegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits, TfToken const& reprSelector) { HdCyclesRenderParam* param = static_cast<HdCyclesRenderParam*>(renderParam); const SdfPath& id = GetId(); HdCyclesPDPIMap pdpi; ccl::Scene* scene = param->GetCyclesScene(); bool needs_update = false; bool needs_newMesh = true; // Read Cycles Primvars #ifdef USE_USD_CYCLES_SCHEMA if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, usdCyclesTokens->cyclesObjectPoint_style)) { needs_newMesh = true; HdTimeSampleArray<VtValue, 1> xf; sceneDelegate->SamplePrimvar(id, usdCyclesTokens->cyclesObjectPoint_style, &xf); if (xf.count > 0) { const TfToken& styles = xf.values[0].Get<TfToken>(); m_pointStyle = POINT_DISCS; if (styles == usdCyclesTokens->sphere) { m_pointStyle = POINT_SPHERES; } } } if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, usdCyclesTokens->cyclesObjectPoint_resolution)) { needs_newMesh = true; HdTimeSampleArray<VtValue, 1> xf; sceneDelegate->SamplePrimvar(id, usdCyclesTokens->cyclesObjectPoint_resolution, &xf); if (xf.count > 0) { const int& resolutions = xf.values[0].Get<int>(); m_pointResolution = std::max(resolutions, 10); } } #endif // Create Points if (*dirtyBits & HdChangeTracker::DirtyPoints || needs_newMesh) { needs_update = true; m_cyclesMesh->clear(); if (m_pointStyle == HdCyclesPointStyle::POINT_DISCS) { _CreateDiscMesh(); } else { _CreateSphereMesh(); } m_cyclesMesh->tag_update(scene, true); const auto pointsValue = sceneDelegate->Get(id, HdTokens->points); if (!pointsValue.IsEmpty() && pointsValue.IsHolding<VtVec3fArray>()) { const VtVec3fArray& points = pointsValue.Get<VtVec3fArray>(); for (size_t i = 0; i < m_cyclesObjects.size(); i++) { param->RemoveObject(m_cyclesObjects[i]); } m_cyclesObjects.clear(); for (size_t i = 0; i < points.size(); i++) { ccl::Object* pointObject = _CreatePointsObject(ccl::transform_translate(vec3f_to_float3(points[i])), m_cyclesMesh); pointObject->random_id = static_cast<uint>(i); pointObject->name = ccl::ustring::format("%s@%08x", pointObject->name, pointObject->random_id); m_cyclesObjects.push_back(pointObject); param->AddObject(pointObject); } } } if (*dirtyBits & HdChangeTracker::DirtyTransform) { ccl::Transform newTransform = HdCyclesExtractTransform(sceneDelegate, id); for (size_t i = 0; i < m_cyclesObjects.size(); i++) { m_cyclesObjects[i]->tfm = ccl::transform_inverse(m_transform) * m_cyclesObjects[i]->tfm; m_cyclesObjects[i]->tfm = newTransform * m_cyclesObjects[i]->tfm; } m_transform = newTransform; needs_update = true; } // TODO: It's likely that this can cause double transforms due to modifying the core transform if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->widths)) { needs_update = true; if (m_cyclesObjects.size() > 0) { HdTimeSampleArray<VtValue, 2> xf; sceneDelegate->SamplePrimvar(id, HdTokens->widths, &xf); if (xf.count > 0) { const VtFloatArray& widths = xf.values[0].Get<VtFloatArray>(); for (size_t i = 0; i < widths.size(); i++) { if (i < m_cyclesObjects.size()) { float w = widths[i]; m_cyclesObjects[i]->tfm = m_cyclesObjects[i]->tfm * ccl::transform_scale(w, w, w); } } } } } if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals)) { needs_update = true; if (m_cyclesObjects.size() > 0) { HdTimeSampleArray<VtValue, 1> xf; sceneDelegate->SamplePrimvar(id, HdTokens->normals, &xf); if (xf.count > 0) { const VtVec3fArray& normals = xf.values[0].Get<VtVec3fArray>(); for (size_t i = 0; i < normals.size(); i++) { if (i < m_cyclesObjects.size()) { ccl::float3 rotAxis = ccl::cross(ccl::make_float3(0.0f, 0.0f, 1.0f), ccl::make_float3(normals[i][0], normals[i][1], normals[i][2])); float d = ccl::dot(ccl::make_float3(0.0f, 0.0f, 1.0f), ccl::make_float3(normals[i][0], normals[i][1], normals[i][2])); float angle = atan2f(ccl::len(rotAxis), d); m_cyclesObjects[i]->tfm = m_cyclesObjects[i]->tfm * ccl::transform_rotate((angle), rotAxis); } } } else { // handle orient to camera } } } if (*dirtyBits & HdChangeTracker::DirtyVisibility) { needs_update = true; bool visible = sceneDelegate->GetVisible(id); for (size_t i = 0; i < m_cyclesObjects.size(); i++) { if (visible) { m_cyclesObjects[i]->visibility |= ccl::PATH_RAY_ALL_VISIBILITY; } else { m_cyclesObjects[i]->visibility &= ~ccl::PATH_RAY_ALL_VISIBILITY; } } } if (needs_update) param->Interrupt(); *dirtyBits = HdChangeTracker::Clean; } HdDirtyBits HdCyclesPoints::GetInitialDirtyBitsMask() const { return HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyTransform | HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyWidths | HdChangeTracker::DirtyMaterialId | HdChangeTracker::DirtyInstanceIndex | HdChangeTracker::DirtyNormals; } bool HdCyclesPoints::IsValid() const { return true; } // Creates z up disc void HdCyclesPoints::_CreateDiscMesh() { m_cyclesMesh->clear(); m_cyclesMesh->name = ccl::ustring("generated_disc"); m_cyclesMesh->subdivision_type = ccl::Mesh::SUBDIVISION_NONE; int numVerts = m_pointResolution; int numFaces = m_pointResolution - 2; m_cyclesMesh->reserve_mesh(numVerts, numFaces); m_cyclesMesh->verts.reserve(numVerts); for (int i = 0; i < m_pointResolution; i++) { float d = (static_cast<float>(i) / static_cast<float>(m_pointResolution)) * 2.0f * M_PI_F; float x = sin(d) * 0.5f; float y = cos(d) * 0.5f; m_cyclesMesh->verts.push_back_reserved(ccl::make_float3(x, y, 0.0f)); } for (int i = 1; i < m_pointResolution - 1; i++) { int v0 = 0; int v1 = i; int v2 = i + 1; m_cyclesMesh->add_triangle(v0, v1, v2, 0, true); } m_cyclesMesh->compute_bounds(); } void HdCyclesPoints::_CreateSphereMesh() { float radius = 0.5f; int sectorCount = m_pointResolution; int stackCount = m_pointResolution; m_cyclesMesh->clear(); m_cyclesMesh->name = ccl::ustring("generated_sphere"); m_cyclesMesh->subdivision_type = ccl::Mesh::SUBDIVISION_NONE; float z, xy; float sectorStep = 2.0f * M_PI_F / static_cast<float>(sectorCount); float stackStep = M_PI_F / static_cast<float>(stackCount); float sectorAngle, stackAngle; for (int i = 0; i <= stackCount; ++i) { stackAngle = M_PI_F / 2.0f - static_cast<float>(i) * stackStep; xy = radius * cosf(stackAngle); z = radius * sinf(stackAngle); for (int j = 0; j <= sectorCount; ++j) { sectorAngle = static_cast<float>(j) * sectorStep; m_cyclesMesh->verts.push_back_slow(ccl::make_float3(xy * cosf(sectorAngle), xy * sinf(sectorAngle), z)); // TODO: Add normals and uvs } } int k1, k2; for (int i = 0; i < stackCount; ++i) { k1 = i * (sectorCount + 1); k2 = k1 + sectorCount + 1; for (int j = 0; j < sectorCount; ++j, ++k1, ++k2) { if (i != 0) { m_cyclesMesh->add_triangle(k1, k2, k1 + 1, 0, true); } if (i != (stackCount - 1)) { m_cyclesMesh->add_triangle(k1 + 1, k2, k2 + 1, 0, true); } } } m_cyclesMesh->compute_bounds(); } ccl::Object* HdCyclesPoints::_CreatePointsObject(const ccl::Transform& transform, ccl::Mesh* mesh) { /* create object*/ ccl::Object* object = new ccl::Object(); object->geometry = mesh; object->tfm = transform; object->motion.clear(); return object; } PXR_NAMESPACE_CLOSE_SCOPE
fix points warnings
fix points warnings
C++
apache-2.0
tangent-opensource/hdBlackbird,tangent-opensource/hdBlackbird,tangent-opensource/hdBlackbird
8929e8f824f080b6ac4ad39bf0be4026a227fec0
src/stream.cpp
src/stream.cpp
/* * ALURE OpenAL utility library * Copyright (C) 2009 by Chris Robinson. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * Or go to http://www.gnu.org/copyleft/lgpl.html */ /* Title: Streaming */ #include "config.h" #include "main.h" #include <string.h> #include <memory> static bool SizeIsUS = false; static alureStream *InitStream(alureStream *instream, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { std::auto_ptr<alureStream> stream(instream); ALenum format; ALuint freq, blockAlign; if(!stream->GetFormat(&format, &freq, &blockAlign)) { SetError("Could not get stream format"); return NULL; } if(format == AL_NONE) { SetError("No valid format"); return NULL; } if(blockAlign == 0) { SetError("Invalid block size"); return NULL; } if(freq == 0) { SetError("Invalid sample rate"); return NULL; } ALuint framesPerBlock; DetectCompressionRate(format, &framesPerBlock); alureUInt64 len64 = (SizeIsUS ? (alureUInt64)chunkLength * freq / 1000000 / framesPerBlock * blockAlign : (alureUInt64)chunkLength); if(len64 > 0xFFFFFFFF) { SetError("Chunk length too large"); return NULL; } chunkLength = len64 - (len64%blockAlign); if(chunkLength <= 0) { SetError("Chunk length too small"); return NULL; } stream->chunkLen = chunkLength; stream->dataChunk = new ALubyte[stream->chunkLen]; alGenBuffers(numBufs, bufs); if(alGetError() != AL_NO_ERROR) { SetError("Buffer creation failed"); return NULL; } ALsizei filled; for(filled = 0;filled < numBufs;filled++) { ALuint got = stream->GetData(stream->dataChunk, stream->chunkLen); got -= got%blockAlign; if(got == 0) break; alBufferData(bufs[filled], format, stream->dataChunk, got, freq); if(alGetError() != AL_NO_ERROR) { alDeleteBuffers(numBufs, bufs); alGetError(); SetError("Buffering error"); return NULL; } } while(filled < numBufs) { alBufferData(bufs[filled], format, stream->dataChunk, 0, freq); if(alGetError() != AL_NO_ERROR) { SetError("Buffer load failed"); return NULL; } filled++; } return stream.release(); } extern "C" { /* Function: alureStreamSizeIsMicroSec * * Specifies whether the chunk size given to alureCreateStreamFrom* functions * are bytes (AL_FALSE, default) or microseconds (AL_TRUE). Specifying the size * in microseconds can help manage the time needed in between needed updates * (since the format and sample rate of the stream may not be known ahead of * time), while specifying the size can help control memory usage. * * Returns: * Previously set value. * * See Also: * <alureCreateStreamFromFile>, <alureCreateStreamFromMemory>, * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback> */ ALURE_API ALboolean ALURE_APIENTRY alureStreamSizeIsMicroSec(ALboolean useUS) { ALboolean old = (SizeIsUS ? AL_TRUE : AL_FALSE); SizeIsUS = !!useUS; return old; } /* Function: alureCreateStreamFromFile * * Opens a file and sets it up for streaming. The given chunkLength is the * number of bytes, or microseconds worth of bytes if * <alureStreamSizeIsMicroSec> was last called with AL_TRUE, each buffer will * fill with. ALURE will optionally generate the specified number of buffer * objects, fill them with the beginning of the data, then place the new IDs * into the provided storage, before returning. Requires an active context. * * Returns: * An opaque handle used to control the opened stream, or NULL on error. * * See Also: * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromMemory>, * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback> */ ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromFile(const ALchar *fname, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return NULL; } if(chunkLength < 0) { SetError("Invalid chunk length"); return NULL; } if(numBufs < 0) { SetError("Invalid buffer count"); return NULL; } alureStream *stream = create_stream(fname); if(!stream->IsValid()) { delete stream; return NULL; } return InitStream(stream, chunkLength, numBufs, bufs); } /* Function: alureCreateStreamFromMemory * * Opens a file image from memory and sets it up for streaming, similar to * <alureCreateStreamFromFile>. The given data buffer can be safely deleted * after calling this function. Requires an active context. * * Returns: * An opaque handle used to control the opened stream, or NULL on error. * * See Also: * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>, * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback> */ ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return NULL; } if(chunkLength < 0) { SetError("Invalid chunk length"); return NULL; } if(numBufs < 0) { SetError("Invalid buffer count"); return NULL; } if(length <= 0) { SetError("Invalid data length"); return NULL; } ALubyte *streamData = new ALubyte[length]; memcpy(streamData, fdata, length); MemDataInfo memData; memData.Data = streamData; memData.Length = length; memData.Pos = 0; alureStream *stream = create_stream(memData); stream->data = streamData; if(!stream->IsValid()) { delete stream; return NULL; } return InitStream(stream, chunkLength, numBufs, bufs); } /* Function: alureCreateStreamFromStaticMemory * * Identical to <alureCreateStreamFromMemory>, except the given memory is used * directly and not duplicated. As a consequence, the data buffer must remain * valid while the stream is alive. Requires an active context. * * Returns: * An opaque handle used to control the opened stream, or NULL on error. * * See Also: * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>, * <alureCreateStreamFromMemory>, <alureCreateStreamFromCallback> */ ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromStaticMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return NULL; } if(chunkLength < 0) { SetError("Invalid chunk length"); return NULL; } if(numBufs < 0) { SetError("Invalid buffer count"); return NULL; } if(length <= 0) { SetError("Invalid data length"); return NULL; } MemDataInfo memData; memData.Data = fdata; memData.Length = length; memData.Pos = 0; alureStream *stream = create_stream(memData); if(!stream->IsValid()) { delete stream; return NULL; } return InitStream(stream, chunkLength, numBufs, bufs); } /* Function: alureCreateStreamFromCallback * * Creates a stream using the specified callback to retrieve data. Requires an * active context. * * Parameters: * callback - This is called when more data is needed from the stream. Up to * the specified number of bytes should be written to the data * pointer, and the number of bytes actually written should be * returned. The number of bytes written must be block aligned for * the format (eg. a multiple of 4 for AL_FORMAT_STEREO16), or an * OpenAL error may occur during buffering. * userdata - A handle passed through to the callback. * format - The format of the data the callback will be giving. The format must * be valid for the context. * samplerate - The sample rate (frequency) of the stream * * Returns: * An opaque handle used to control the opened stream, or NULL on error. * * See Also: * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>, * <alureCreateStreamFromMemory>, <alureCreateStreamFromStaticMemory> */ ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromCallback( ALuint (*callback)(void *userdata, ALubyte *data, ALuint bytes), void *userdata, ALenum format, ALuint samplerate, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return NULL; } if(callback == NULL) { SetError("Invalid callback"); return NULL; } if(chunkLength < 0) { SetError("Invalid chunk length"); return NULL; } if(numBufs < 0) { SetError("Invalid buffer count"); return NULL; } UserCallbacks newcb; newcb.open_file = NULL; newcb.open_mem = NULL; newcb.get_fmt = NULL; newcb.decode = callback; newcb.rewind = NULL; newcb.close = NULL; alureStream *stream = create_stream(userdata, format, samplerate, newcb); return InitStream(stream, chunkLength, numBufs, bufs); } /* Function: alureGetStreamFormat * * Retrieves the format, frequency, and block-alignment used for the given * stream. If a parameter is NULL, that value will not be returned. * * Returns: * AL_FALSE on error. */ ALURE_API ALboolean ALURE_APIENTRY alureGetStreamFormat(alureStream *stream, ALenum *format, ALuint *frequency, ALuint *blockAlign) { ALenum _fmt; ALuint _rate, _balign; if(!alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return AL_FALSE; } if(!format) format = &_fmt; if(!frequency) frequency = &_rate; if(!blockAlign) blockAlign = &_balign; if(!stream->GetFormat(format, frequency, blockAlign)) { SetError("Could not get stream format"); return AL_FALSE; } return AL_TRUE; } /* Function: alureBufferDataFromStream * * Buffers the given buffer objects with the next chunks of data from the * stream. The given buffer objects do not need to be ones given by the * alureCreateStreamFrom* functions. Requires an active context. * * Returns: * The number of buffers filled with new data, or -1 on error. If the value * returned is less than the number requested, the end of the stream has been * reached. */ ALURE_API ALsizei ALURE_APIENTRY alureBufferDataFromStream(alureStream *stream, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return -1; } if(!alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return -1; } if(numBufs < 0) { SetError("Invalid buffer count"); return -1; } ALenum format; ALuint freq, blockAlign; if(!stream->GetFormat(&format, &freq, &blockAlign)) { SetError("Could not get stream format"); return -1; } ALsizei filled; for(filled = 0;filled < numBufs;filled++) { ALuint got = stream->GetData(stream->dataChunk, stream->chunkLen); got -= got%blockAlign; if(got == 0) break; alBufferData(bufs[filled], format, stream->dataChunk, got, freq); if(alGetError() != AL_NO_ERROR) { SetError("Buffer load failed"); return -1; } } return filled; } /* Function: alureRewindStream * * Rewinds the stream so that the next alureBufferDataFromStream call will * restart from the beginning of the audio file. * * Returns: * AL_FALSE on error. * * See Also: * <alureSetStreamOrder> */ ALURE_API ALboolean ALURE_APIENTRY alureRewindStream(alureStream *stream) { if(!alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return AL_FALSE; } return stream->Rewind(); } /* Function: alureSetStreamOrder * * Skips the module decoder to the specified order, so following buffering * calls will decode from the specified order. For non-module formats, setting * order 0 is identical to rewinding the stream (other orders will fail). * * Returns: * AL_FALSE on error. * * See Also: * <alureRewindStream> */ ALURE_API ALboolean ALURE_APIENTRY alureSetStreamOrder(alureStream *stream, ALuint order) { if(!alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return AL_FALSE; } return stream->SetOrder(order); } /* Function: alureDestroyStream * * Closes an opened stream. For convenience, it will also delete the given * buffer objects. The given buffer objects do not need to be ones given by the * alureCreateStreamFrom* functions. Requires an active context. * * Returns: * AL_FALSE on error. */ ALURE_API ALboolean ALURE_APIENTRY alureDestroyStream(alureStream *stream, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return AL_FALSE; } if(numBufs < 0) { SetError("Invalid buffer count"); return AL_FALSE; } if(stream && !alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return AL_FALSE; } alDeleteBuffers(numBufs, bufs); if(alGetError() != AL_NO_ERROR) { SetError("Buffer deletion failed"); return AL_FALSE; } if(stream) { StopStream(stream); std::istream *f = stream->fstream; delete stream; delete f; } return AL_TRUE; } }
/* * ALURE OpenAL utility library * Copyright (C) 2009 by Chris Robinson. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * Or go to http://www.gnu.org/copyleft/lgpl.html */ /* Title: Streaming */ #include "config.h" #include "main.h" #include <string.h> #include <memory> static bool SizeIsUS = false; static alureStream *InitStream(alureStream *instream, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { std::auto_ptr<alureStream> stream(instream); ALenum format; ALuint freq, blockAlign; if(!stream->GetFormat(&format, &freq, &blockAlign)) { SetError("Could not get stream format"); return NULL; } if(format == AL_NONE) { SetError("No valid format"); return NULL; } if(blockAlign == 0) { SetError("Invalid block size"); return NULL; } if(freq == 0) { SetError("Invalid sample rate"); return NULL; } ALuint framesPerBlock; DetectCompressionRate(format, &framesPerBlock); alureUInt64 len64 = (SizeIsUS ? (alureUInt64)chunkLength * freq / 1000000 / framesPerBlock * blockAlign : (alureUInt64)chunkLength); if(len64 > 0xFFFFFFFF) { SetError("Chunk length too large"); return NULL; } chunkLength = len64 - (len64%blockAlign); if(chunkLength <= 0) { SetError("Chunk length too small"); return NULL; } stream->chunkLen = chunkLength; stream->dataChunk = new ALubyte[stream->chunkLen]; alGenBuffers(numBufs, bufs); if(alGetError() != AL_NO_ERROR) { SetError("Buffer creation failed"); return NULL; } ALsizei filled; for(filled = 0;filled < numBufs;filled++) { ALuint got = stream->GetData(stream->dataChunk, stream->chunkLen); got -= got%blockAlign; if(got == 0) break; alBufferData(bufs[filled], format, stream->dataChunk, got, freq); } while(filled < numBufs) { alBufferData(bufs[filled], format, stream->dataChunk, 0, freq); filled++; } if(alGetError() != AL_NO_ERROR) { alDeleteBuffers(numBufs, bufs); alGetError(); SetError("Buffering error"); return NULL; } return stream.release(); } extern "C" { /* Function: alureStreamSizeIsMicroSec * * Specifies whether the chunk size given to alureCreateStreamFrom* functions * are bytes (AL_FALSE, default) or microseconds (AL_TRUE). Specifying the size * in microseconds can help manage the time needed in between needed updates * (since the format and sample rate of the stream may not be known ahead of * time), while specifying the size can help control memory usage. * * Returns: * Previously set value. * * See Also: * <alureCreateStreamFromFile>, <alureCreateStreamFromMemory>, * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback> */ ALURE_API ALboolean ALURE_APIENTRY alureStreamSizeIsMicroSec(ALboolean useUS) { ALboolean old = (SizeIsUS ? AL_TRUE : AL_FALSE); SizeIsUS = !!useUS; return old; } /* Function: alureCreateStreamFromFile * * Opens a file and sets it up for streaming. The given chunkLength is the * number of bytes, or microseconds worth of bytes if * <alureStreamSizeIsMicroSec> was last called with AL_TRUE, each buffer will * fill with. ALURE will optionally generate the specified number of buffer * objects, fill them with the beginning of the data, then place the new IDs * into the provided storage, before returning. Requires an active context. * * Returns: * An opaque handle used to control the opened stream, or NULL on error. * * See Also: * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromMemory>, * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback> */ ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromFile(const ALchar *fname, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return NULL; } if(chunkLength < 0) { SetError("Invalid chunk length"); return NULL; } if(numBufs < 0) { SetError("Invalid buffer count"); return NULL; } alureStream *stream = create_stream(fname); if(!stream->IsValid()) { delete stream; return NULL; } return InitStream(stream, chunkLength, numBufs, bufs); } /* Function: alureCreateStreamFromMemory * * Opens a file image from memory and sets it up for streaming, similar to * <alureCreateStreamFromFile>. The given data buffer can be safely deleted * after calling this function. Requires an active context. * * Returns: * An opaque handle used to control the opened stream, or NULL on error. * * See Also: * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>, * <alureCreateStreamFromStaticMemory>, <alureCreateStreamFromCallback> */ ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return NULL; } if(chunkLength < 0) { SetError("Invalid chunk length"); return NULL; } if(numBufs < 0) { SetError("Invalid buffer count"); return NULL; } if(length <= 0) { SetError("Invalid data length"); return NULL; } ALubyte *streamData = new ALubyte[length]; memcpy(streamData, fdata, length); MemDataInfo memData; memData.Data = streamData; memData.Length = length; memData.Pos = 0; alureStream *stream = create_stream(memData); stream->data = streamData; if(!stream->IsValid()) { delete stream; return NULL; } return InitStream(stream, chunkLength, numBufs, bufs); } /* Function: alureCreateStreamFromStaticMemory * * Identical to <alureCreateStreamFromMemory>, except the given memory is used * directly and not duplicated. As a consequence, the data buffer must remain * valid while the stream is alive. Requires an active context. * * Returns: * An opaque handle used to control the opened stream, or NULL on error. * * See Also: * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>, * <alureCreateStreamFromMemory>, <alureCreateStreamFromCallback> */ ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromStaticMemory(const ALubyte *fdata, ALuint length, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return NULL; } if(chunkLength < 0) { SetError("Invalid chunk length"); return NULL; } if(numBufs < 0) { SetError("Invalid buffer count"); return NULL; } if(length <= 0) { SetError("Invalid data length"); return NULL; } MemDataInfo memData; memData.Data = fdata; memData.Length = length; memData.Pos = 0; alureStream *stream = create_stream(memData); if(!stream->IsValid()) { delete stream; return NULL; } return InitStream(stream, chunkLength, numBufs, bufs); } /* Function: alureCreateStreamFromCallback * * Creates a stream using the specified callback to retrieve data. Requires an * active context. * * Parameters: * callback - This is called when more data is needed from the stream. Up to * the specified number of bytes should be written to the data * pointer, and the number of bytes actually written should be * returned. The number of bytes written must be block aligned for * the format (eg. a multiple of 4 for AL_FORMAT_STEREO16), or an * OpenAL error may occur during buffering. * userdata - A handle passed through to the callback. * format - The format of the data the callback will be giving. The format must * be valid for the context. * samplerate - The sample rate (frequency) of the stream * * Returns: * An opaque handle used to control the opened stream, or NULL on error. * * See Also: * <alureStreamSizeIsMicroSec>, <alureCreateStreamFromFile>, * <alureCreateStreamFromMemory>, <alureCreateStreamFromStaticMemory> */ ALURE_API alureStream* ALURE_APIENTRY alureCreateStreamFromCallback( ALuint (*callback)(void *userdata, ALubyte *data, ALuint bytes), void *userdata, ALenum format, ALuint samplerate, ALsizei chunkLength, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return NULL; } if(callback == NULL) { SetError("Invalid callback"); return NULL; } if(chunkLength < 0) { SetError("Invalid chunk length"); return NULL; } if(numBufs < 0) { SetError("Invalid buffer count"); return NULL; } UserCallbacks newcb; newcb.open_file = NULL; newcb.open_mem = NULL; newcb.get_fmt = NULL; newcb.decode = callback; newcb.rewind = NULL; newcb.close = NULL; alureStream *stream = create_stream(userdata, format, samplerate, newcb); return InitStream(stream, chunkLength, numBufs, bufs); } /* Function: alureGetStreamFormat * * Retrieves the format, frequency, and block-alignment used for the given * stream. If a parameter is NULL, that value will not be returned. * * Returns: * AL_FALSE on error. */ ALURE_API ALboolean ALURE_APIENTRY alureGetStreamFormat(alureStream *stream, ALenum *format, ALuint *frequency, ALuint *blockAlign) { ALenum _fmt; ALuint _rate, _balign; if(!alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return AL_FALSE; } if(!format) format = &_fmt; if(!frequency) frequency = &_rate; if(!blockAlign) blockAlign = &_balign; if(!stream->GetFormat(format, frequency, blockAlign)) { SetError("Could not get stream format"); return AL_FALSE; } return AL_TRUE; } /* Function: alureBufferDataFromStream * * Buffers the given buffer objects with the next chunks of data from the * stream. The given buffer objects do not need to be ones given by the * alureCreateStreamFrom* functions. Requires an active context. * * Returns: * The number of buffers filled with new data, or -1 on error. If the value * returned is less than the number requested, the end of the stream has been * reached. */ ALURE_API ALsizei ALURE_APIENTRY alureBufferDataFromStream(alureStream *stream, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return -1; } if(!alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return -1; } if(numBufs < 0) { SetError("Invalid buffer count"); return -1; } ALenum format; ALuint freq, blockAlign; if(!stream->GetFormat(&format, &freq, &blockAlign)) { SetError("Could not get stream format"); return -1; } ALsizei filled; for(filled = 0;filled < numBufs;filled++) { ALuint got = stream->GetData(stream->dataChunk, stream->chunkLen); got -= got%blockAlign; if(got == 0) break; alBufferData(bufs[filled], format, stream->dataChunk, got, freq); if(alGetError() != AL_NO_ERROR) { SetError("Buffer load failed"); return -1; } } return filled; } /* Function: alureRewindStream * * Rewinds the stream so that the next alureBufferDataFromStream call will * restart from the beginning of the audio file. * * Returns: * AL_FALSE on error. * * See Also: * <alureSetStreamOrder> */ ALURE_API ALboolean ALURE_APIENTRY alureRewindStream(alureStream *stream) { if(!alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return AL_FALSE; } return stream->Rewind(); } /* Function: alureSetStreamOrder * * Skips the module decoder to the specified order, so following buffering * calls will decode from the specified order. For non-module formats, setting * order 0 is identical to rewinding the stream (other orders will fail). * * Returns: * AL_FALSE on error. * * See Also: * <alureRewindStream> */ ALURE_API ALboolean ALURE_APIENTRY alureSetStreamOrder(alureStream *stream, ALuint order) { if(!alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return AL_FALSE; } return stream->SetOrder(order); } /* Function: alureDestroyStream * * Closes an opened stream. For convenience, it will also delete the given * buffer objects. The given buffer objects do not need to be ones given by the * alureCreateStreamFrom* functions. Requires an active context. * * Returns: * AL_FALSE on error. */ ALURE_API ALboolean ALURE_APIENTRY alureDestroyStream(alureStream *stream, ALsizei numBufs, ALuint *bufs) { if(alGetError() != AL_NO_ERROR) { SetError("Existing OpenAL error"); return AL_FALSE; } if(numBufs < 0) { SetError("Invalid buffer count"); return AL_FALSE; } if(stream && !alureStream::Verify(stream)) { SetError("Invalid stream pointer"); return AL_FALSE; } alDeleteBuffers(numBufs, bufs); if(alGetError() != AL_NO_ERROR) { SetError("Buffer deletion failed"); return AL_FALSE; } if(stream) { StopStream(stream); std::istream *f = stream->fstream; delete stream; delete f; } return AL_TRUE; } }
Combine two error paths
Combine two error paths
C++
mit
NickNick/alure,NickNick/alure,NickNick/alure
1e975290e61248d1c1c70faa84f09dcce5442091
include/stack.hpp
include/stack.hpp
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> #include <memory> class bitset { public: explicit bitset(size_t size) /*strong*/; bitset(bitset const & other) = delete; auto operator =(bitset const & other)->bitset & = delete; bitset(bitset && other) = delete; auto operator =(bitset && other)->bitset & = delete; auto set(size_t index) /*strong*/ -> void; auto reset(size_t index) /*strong*/ -> void; auto test(size_t index) /*strong*/ -> bool; auto size() /*noexcept*/ -> size_t; auto counter() /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {} auto bitset::set(size_t index) -> void { if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; } else throw; } auto bitset::reset(size_t index) -> void { if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; } else throw; } auto bitset::test(size_t index) -> bool { if (index >= 0 && index < size_) { return !ptr_[index]; } else throw; } auto bitset::size() -> size_t { return size_; } auto bitset::counter() -> size_t { return counter_; } template <typename T> class allocator { public: explicit allocator(std::size_t size = 0) /*strong*/; allocator(allocator const & other) /*strong*/; auto operator =(allocator const & other)->allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value) /*strong*/ -> void; auto destroy(T * ptr) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; private: auto destroy(T * first, T * last) /*noexcept*/ -> void; auto swap(allocator & other) /*noexcept*/ -> void; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template <typename T> class stack { public: explicit stack(size_t size = 0); auto operator =(stack const & other) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push(T const & value) /*strong*/ -> void; auto pop() /*strong*/ -> void; auto top() /*strong*/ -> T &; auto top() const /*strong*/ -> T const &; private: allocator<T> allocator_; auto throw_is_empty() const -> void; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {}; template<typename T> inline allocator<T>::allocator(allocator const & other) : ptr_((T *)(other.size_ == 0 ? nullptr : operator new(other.size_ * sizeof(T)))), size_(other.size_), map_(other.map_) { for (size_t i = 0; i < other.count_; ++i) { if (map_.test(i)) { this->construct(this->ptr_ + i, other.ptr_[i]); } } } template<typename T> allocator<T>::~allocator() { operator delete(ptr_); } template<typename T> auto allocator<T>::resize() -> void { allocator<T> buff(size_ * 2 + (size_ == 0)); for (size_t i = 0; i < size_; i++) construct(buff.ptr_ + i, ptr_[i]); this->swap(buff); } template<typename T> auto allocator<T>::construct(T * ptr, T const & value)->void { if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) { new(ptr)T(value); map_->set(ptr - ptr_); } else throw("error"); } template<typename T> auto allocator<T>::destroy(T * ptr) -> void { ptr->~T(); map_->reset(ptr-ptr_); } template<typename T> auto allocator<T>::destroy(T * first, T * last) -> void { for (; first != last; ++first) { destroy(&*first); } } template<typename T> auto allocator<T>::get()-> T* { return ptr_; } template<typename T> auto allocator<T>::get() const -> T const * { return ptr_; } template<typename T> auto allocator<T>::count() const -> size_t { return map_->counter_; } template<typename T> auto allocator<T>::full() const -> bool { return map_->counter_==size_; } template<typename T> auto allocator<T>::empty() const -> bool { return map_->counter_==0; } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(map_, other.map_); std::swap(size_, other.size_); } template <typename T> size_t stack<T>::count() const { return allocator_.count_; } template <typename T> stack<T>::stack(size_t size) :allocator<T>(size) {} template <typename T> void stack<T>::push(T const &item) { if (allocator<T>::count_ == allocator<T>::size_) { size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]); this->swap(temp); } construct(allocator<T>::ptr_ + allocator<T>::count_, item); ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator<T>::count_> 0) { --allocator<T>::count_; } else throw_is_empty(); } template<typename T> const T& stack<T>::top() { if (allocator<T>::count_ == 0) { throw_is_empty(); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::top() const -> T const & { if (allocator<T>::count_ == 0) { throw_is_empty(); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::throw_is_empty() const -> void { throw("Stack is empty!"); } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { stack<T> temp(right.size_); while (temp.count_ < right.count_) { construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]); ++temp.count_; } this->swap(temp); } return *this; } template<typename T> auto stack<T>::empty() const -> bool { return allocator_.empty; #endif
#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> #include <memory> class bitset { public: explicit bitset(size_t size) /*strong*/; bitset(bitset const & other) = delete; auto operator =(bitset const & other)->bitset & = delete; bitset(bitset && other) = delete; auto operator =(bitset && other)->bitset & = delete; auto set(size_t index) /*strong*/ -> void; auto reset(size_t index) /*strong*/ -> void; auto test(size_t index) /*strong*/ -> bool; auto size() /*noexcept*/ -> size_t; auto counter() /*noexcept*/ -> size_t; private: std::unique_ptr<bool[]> ptr_; size_t size_; size_t counter_; }; bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {} auto bitset::set(size_t index) -> void { if (index >= 0 && index < size_) { ptr_[index] = true; ++counter_; } else throw; } auto bitset::reset(size_t index) -> void { if (index >= 0 && index < size_) { ptr_[index] = false; --counter_; } else throw; } auto bitset::test(size_t index) -> bool { if (index >= 0 && index < size_) { return !ptr_[index]; } else throw; } auto bitset::size() -> size_t { return size_; } auto bitset::counter() -> size_t { return counter_; } template <typename T> class allocator { public: explicit allocator(std::size_t size = 0) /*strong*/; allocator(allocator const & other) /*strong*/; auto operator =(allocator const & other)->allocator & = delete; ~allocator(); auto resize() /*strong*/ -> void; auto construct(T * ptr, T const & value) /*strong*/ -> void; auto destroy(T * ptr) /*noexcept*/ -> void; auto get() /*noexcept*/ -> T *; auto get() const /*noexcept*/ -> T const *; auto count() const /*noexcept*/ -> size_t; auto full() const /*noexcept*/ -> bool; auto empty() const /*noexcept*/ -> bool; private: auto destroy(T * first, T * last) /*noexcept*/ -> void; auto swap(allocator & other) /*noexcept*/ -> void; T * ptr_; size_t size_; std::unique_ptr<bitset> map_; }; template <typename T> class stack { public: explicit stack(size_t size = 0); auto operator =(stack const & other) /*strong*/ -> stack &; auto empty() const /*noexcept*/ -> bool; auto count() const /*noexcept*/ -> size_t; auto push(T const & value) /*strong*/ -> void; auto pop() /*strong*/ -> void; auto top() /*strong*/ -> T &; auto top() const /*strong*/ -> T const &; private: allocator<T> allocator_; auto throw_is_empty() const -> void; }; template <typename T> allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {}; template<typename T> allocator<T>::allocator(allocator const& other) : ptr_(static_cast<T*>(operator new(other.size_))), size_(other.size_), map_(std::make_unique<bitset>(size_)){ for (size_t i; i < size_; i++) construct(ptr_ + i, other.ptr_[i]); } template<typename T> allocator<T>::~allocator() { operator delete(ptr_); } template<typename T> auto allocator<T>::resize() -> void { allocator<T> buff(size_ * 2 + (size_ == 0)); for (size_t i = 0; i < size_; i++) construct(buff.ptr_ + i, ptr_[i]); this->swap(buff); } template<typename T> auto allocator<T>::construct(T * ptr, T const & value)->void { if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_)) { new(ptr)T(value); map_->set(ptr - ptr_); } else throw("error"); } template<typename T> auto allocator<T>::destroy(T * ptr) -> void { ptr->~T(); map_->reset(ptr-ptr_); } template<typename T> auto allocator<T>::destroy(T * first, T * last) -> void { for (; first != last; ++first) { destroy(&*first); } } template<typename T> auto allocator<T>::get()-> T* { return ptr_; } template<typename T> auto allocator<T>::get() const -> T const * { return ptr_; } template<typename T> auto allocator<T>::count() const -> size_t { return map_->counter_; } template<typename T> auto allocator<T>::full() const -> bool { return map_->counter_==size_; } template<typename T> auto allocator<T>::empty() const -> bool { return map_->counter_==0; } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(map_, other.map_); std::swap(size_, other.size_); } template <typename T> size_t stack<T>::count() const { return allocator_.count_; } template <typename T> stack<T>::stack(size_t size) :allocator<T>(size) {} template <typename T> void stack<T>::push(T const &item) { if (allocator<T>::count_ == allocator<T>::size_) { size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]); this->swap(temp); } construct(allocator<T>::ptr_ + allocator<T>::count_, item); ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator<T>::count_> 0) { --allocator<T>::count_; } else throw_is_empty(); } template<typename T> auto stack<T>::top() -> T &; { if (allocator<T>::count_ == 0) { throw_is_empty(); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::top() const -> T const & { if (allocator<T>::count_ == 0) { throw_is_empty(); } return allocator<T>::ptr_[allocator<T>::count_ - 1]; } template<typename T> auto stack<T>::throw_is_empty() const -> void { throw("Stack is empty!"); } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { stack<T> temp(right.size_); while (temp.count_ < right.count_) { construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]); ++temp.count_; } this->swap(temp); } return *this; } template<typename T> auto stack<T>::empty() const -> bool { return allocator_.empty; #endif
Update stack.hpp
Update stack.hpp
C++
mit
DANTEpolaris/stack
880daa6b2e54ac513aa05acd15c9e6cfbdbc1fcf
src/stream.cpp
src/stream.cpp
#include "stream.h" #include <cassert> #include <limits> #include <cstring> // for memcpy namespace Akumuli { StreamError::StreamError(std::string line, int pos) : line_(line) , pos_(pos) { } const char* StreamError::what() const throw() { return line_.c_str(); } std::string StreamError::get_bottom_line() const { return std::string(static_cast<size_t>(pos_), ' '); } ByteStreamReader::~ByteStreamReader() {} // MemStreamReader implementation MemStreamReader::MemStreamReader(const Byte *buffer, size_t buffer_len) : buf_(buffer) , size_(buffer_len) , pos_(0ul) { assert(size_ < std::numeric_limits<int>::max()); } Byte MemStreamReader::get() { if (pos_ < size_) { return buf_[pos_++]; } throw StreamError("unexpected end of stream", pos_); } Byte MemStreamReader::pick() const { if (pos_ < size_) { return buf_[pos_]; } throw StreamError("unexpected end of stream", pos_); } bool MemStreamReader::is_eof() { return pos_ == size_; } int MemStreamReader::read(Byte *buffer, size_t buffer_len) { int nbytes = static_cast<int>(std::min(buffer_len, size_ - pos_)); memcpy(buffer, buf_ + pos_, nbytes); pos_ += nbytes; return nbytes; } void MemStreamReader::close() { pos_ = size_; } std::tuple<std::string, size_t> MemStreamReader::get_error_context(const char* error_message) const { throw "Not implemented"; } }
#include "stream.h" #include <cassert> #include <limits> #include <cstring> // for memcpy namespace Akumuli { StreamError::StreamError(std::string line, int pos) : line_(line) , pos_(pos) { } const char* StreamError::what() const throw() { return line_.c_str(); } std::string StreamError::get_bottom_line() const { return std::string(static_cast<size_t>(pos_), ' '); } ByteStreamReader::~ByteStreamReader() {} // MemStreamReader implementation MemStreamReader::MemStreamReader(const Byte *buffer, size_t buffer_len) : buf_(buffer) , size_(buffer_len) , pos_(0ul) { assert(size_ < std::numeric_limits<int>::max()); } Byte MemStreamReader::get() { if (pos_ < size_) { return buf_[pos_++]; } throw StreamError("unexpected end of stream", pos_); } Byte MemStreamReader::pick() const { if (pos_ < size_) { return buf_[pos_]; } throw StreamError("unexpected end of stream", pos_); } bool MemStreamReader::is_eof() { return pos_ == size_; } int MemStreamReader::read(Byte *buffer, size_t buffer_len) { int nbytes = static_cast<int>(std::min(buffer_len, size_ - pos_)); memcpy(buffer, buf_ + pos_, nbytes); pos_ += nbytes; return nbytes; } void MemStreamReader::close() { pos_ = size_; } std::tuple<std::string, size_t> MemStreamReader::get_error_context(const char* error_message) const { return std::make_tuple(error_message, 0u); } }
Fix respstream_test
Fix respstream_test
C++
apache-2.0
akumuli/Akumuli,akumuli/Akumuli,akumuli/Akumuli,akumuli/Akumuli
211e25f931f770255a49cdf3c3600869ee269853
include/stack.hpp
include/stack.hpp
#include <iostream> #include <mutex> #include <thread> #include <memory> using namespace std; template <typename T> class stack { public: stack();/*noexept*/ stack(const stack<T> &);/*strong*/ size_t count() const; /*noexcept*/ void print()const;/*noexcept*/ void push(T const &); /*strong*/ void swap(stack<T>&); /*noexcept*/ auto pop()->std::shared_ptr<T>; /*strong*/ T top(); /*strong*/ bool empty() const; /*noexcept*/ stack<T>& operator=(stack<T> &); /*noexcept*/ ~stack();/*noexcept*/ private: T * array_; mutable std::mutex mutex_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr } {} template<class T> stack<T>::~stack() { count_ = 0; array_size_ = 0; delete[] array_; } template <typename T> stack<T>::stack(const stack<T>& copy) { std::lock_guard<std::mutex> lock(mutex_); T *tmp = new T[copy.array_size_]; count_ = copy.count_; array_size_ = copy.array_size_; array_ = tmp; if(array_ == nullptr){ throw "error"; delete[] array_; } std::copy(copy.array_, copy.array_ + count_, array_); } template<class T> size_t stack<T>::count() const { std::lock_guard<std::mutex> lock(mutex_); return count_; } template <typename T> bool stack<T>::empty() const { return (count_ == 0); } template<typename T> void stack<T>::swap(stack& x) { other.mutex_.lock(); std::swap(x.array_size_, array_size_); std::swap(count_, x.count_); std::swap(x.array_, array_); other.mutex_.unlock(); } template <typename T> T stack<T>::top() { if (empty()) { throw "Stack is empty!"; } return array_[count_ - 1]; } template <typename T> void stack<T>::push(T const &value) { mutex_.lock(); if (array_size_ == count_) { array_size_ *= 2; stack<T> temp(*this); swap(temp); } array_[count_] = value; ++count_; mutex_.unlock(); } template <typename T> auto stack<T>::pop() -> std::shared_ptr<T> { std::lock_guard<std::mutex> lock(mutex_); if (empty()) throw "Stack is empty" ; count_--; } template <typename T> void stack<T>::print() const { for (int i = 0; i < array_size_; i++) cout << array_[i]; } template<typename T> stack<T>& stack<T>::operator=(stack<T> & other) { std::lock_guard<std::mutex> lock(other.mutex_); if (this != &other) { stack<T> tmp(other); tmp.swap(*this); } return *this; }
#include <iostream> #include <mutex> #include <thread> #include <memory> using namespace std; template <typename T> class stack { public: stack();/*noexept*/ stack(const stack<T> &);/*strong*/ size_t count() const; /*noexcept*/ void print()const;/*noexcept*/ void push(T const &); /*strong*/ void swap(stack<T>&); /*noexcept*/ auto pop()->std::shared_ptr<T>; /*strong*/ T top(); /*strong*/ bool empty() const; /*noexcept*/ stack<T>& operator=(stack<T> &); /*noexcept*/ ~stack();/*noexcept*/ private: T * array_; mutable std::mutex mutex_; size_t array_size_; size_t count_; }; template <typename T> stack<T>::stack() : count_(0), array_size_(0), array_{ nullptr } {} template<class T> stack<T>::~stack() { count_ = 0; array_size_ = 0; delete[] array_; } template <typename T> stack<T>::stack(const stack<T>& copy) { std::lock_guard<std::mutex> lock(mutex_); T *tmp = new T[copy.array_size_]; count_ = copy.count_; array_size_ = copy.array_size_; array_ = tmp; if(array_ == nullptr){ throw "error"; delete[] array_; } std::copy(copy.array_, copy.array_ + count_, array_); } template<class T> size_t stack<T>::count() const { std::lock_guard<std::mutex> lock(mutex_); return count_; } template <typename T> bool stack<T>::empty() const { return (count_ == 0); } template<typename T> void stack<T>::swap(stack& x) { x.mutex_.lock(); std::swap(x.array_size_, array_size_); std::swap(count_, x.count_); std::swap(x.array_, array_); x.mutex_.unlock(); } template <typename T> T stack<T>::top() { if (empty()) { throw "Stack is empty!"; } return array_[count_ - 1]; } template <typename T> void stack<T>::push(T const &value) { mutex_.lock(); if (array_size_ == count_) { array_size_ *= 2; stack<T> temp(*this); swap(temp); } array_[count_] = value; ++count_; mutex_.unlock(); } template <typename T> auto stack<T>::pop() -> std::shared_ptr<T> { std::lock_guard<std::mutex> lock(mutex_); if (empty()) throw "Stack is empty" ; count_--; } template <typename T> void stack<T>::print() const { for (int i = 0; i < array_size_; i++) cout << array_[i]; } template<typename T> stack<T>& stack<T>::operator=(stack<T> & other) { std::lock_guard<std::mutex> lock(other.mutex_); if (this != &other) { stack<T> tmp(other); tmp.swap(*this); } return *this; }
Update stack.hpp
Update stack.hpp
C++
mit
rtv22/stack
386936874b716af0e8187d587328c3c2a204ac9b
include/token.hxx
include/token.hxx
#ifndef TOKEN_HXX_LGIKOUIZ #define TOKEN_HXX_LGIKOUIZ #include "id.hxx" #include "string.hxx" namespace miniml { /// Abstract class for tokens. struct Token { enum class Type; ///< Token types. virtual Type type() const = 0; ///< What type of token is this? virtual ~Token() {} /// Make an atomic token. template <Type ty> static Ptr<Token> atomic(); /// Whether a token type is atomic (needs no data). static constexpr bool is_atomic(Type); virtual void out(OStream &) const = 0; }; enum class Token::Type { ID, ///< identifier INT, ///< integer literal FN, ///< `fn` ARROW, ///< `=>` }; OStream &operator<<(OStream &out, const Token &tok); constexpr bool Token::is_atomic(Token::Type ty) { using Type = Token::Type; return !(ty == Type::ID || ty == Type::INT); } struct IdToken final: public Token { IdToken(Ptr<Id> id_): id(id_) {} IdToken(const Char *start, ptrdiff_t size): IdToken(ptr<Id>(ptr<String>(start, size))) {} Ptr<Id> id; virtual Token::Type type() const override { return Token::Type::ID; } virtual void out(OStream &) const; }; struct IntToken final: public Token { IntToken(long val_): val(val_) {} long val; virtual Token::Type type() const override { return Token::Type::INT; } virtual void out(OStream &) const; }; template <Token::Type Ty> class AtomicToken final: public Token { public: virtual Token::Type type() const { return Ty; } static_assert(Token::is_atomic(Ty), "tried to make an atomic token of a nonatomic type"); virtual void out(OStream &) const; }; template <Token::Type Ty> Ptr<Token> Token::atomic() { return ptr<AtomicToken<Ty>>(); } } #endif /* end of include guard: TOKEN_HXX_LGIKOUIZ */
#ifndef TOKEN_HXX_LGIKOUIZ #define TOKEN_HXX_LGIKOUIZ #include "id.hxx" #include "string.hxx" namespace miniml { /// Abstract class for tokens. struct Token { enum class Type; ///< Token types. virtual Type type() const = 0; ///< What type of token is this? virtual ~Token() {} /// Make an atomic token. template <Type ty> static Ptr<Token> atomic(); /// Whether a token type is atomic (needs no data). static constexpr bool is_atomic(Type); virtual void out(OStream &) const = 0; }; enum class Token::Type { ID, ///< identifier INT, ///< integer literal FN, ///< `fn` ARROW, ///< `=>` }; OStream &operator<<(OStream &out, const Token &tok); constexpr bool Token::is_atomic(Token::Type ty) { using Type = Token::Type; return !(ty == Type::ID || ty == Type::INT); } struct IdToken final: public Token { IdToken(Id *id_): id(id_) {} IdToken(const Char *start, ptrdiff_t size): IdToken(new Id(ptr<String>(start, size))) {} virtual ~IdToken() { delete id; } Id *id; virtual Token::Type type() const override { return Token::Type::ID; } virtual void out(OStream &) const; }; struct IntToken final: public Token { IntToken(long val_): val(val_) {} long val; virtual Token::Type type() const override { return Token::Type::INT; } virtual void out(OStream &) const; }; template <Token::Type Ty> class AtomicToken final: public Token { public: virtual Token::Type type() const { return Ty; } static_assert(Token::is_atomic(Ty), "tried to make an atomic token of a nonatomic type"); virtual void out(OStream &) const; }; template <Token::Type Ty> Ptr<Token> Token::atomic() { return ptr<AtomicToken<Ty>>(); } } #endif /* end of include guard: TOKEN_HXX_LGIKOUIZ */
Use raw pointers for Token because Lemon is C
Use raw pointers for Token because Lemon is C
C++
bsd-3-clause
andy-morris/miniml
32bfa7759d9af8b9cd4a535ac5c01d52acc28f75
iRODS/server/api/src/rsDataObjPhymv.cpp
iRODS/server/api/src/rsDataObjPhymv.cpp
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ #include "dataObjPhymv.h" #include "reFuncDefs.hpp" #include "dataObjRepl.h" #include "dataObjOpr.hpp" #include "rodsLog.h" #include "objMetaOpr.hpp" #include "specColl.hpp" #include "reGlobalsExtern.hpp" #include "reDefines.h" #include "icatDefines.h" #include "reSysDataObjOpr.hpp" #include "dataObjCreate.h" #include "getRemoteZoneResc.h" // =-=-=-=-=-=-=- #include "irods_resource_redirect.hpp" /* rsDataObjPhymv - The Api handler of the rcDataObjPhymv call - phymove * a data object from one resource to another. * Input - * rsComm_t *rsComm * dataObjInp_t *dataObjInp - The replication input * transferStat_t **transStat - transfer stat output */ int rsDataObjPhymv( rsComm_t *rsComm, dataObjInp_t *dataObjInp, transferStat_t **transStat ) { int status = 0; dataObjInfo_t *dataObjInfoHead = NULL; dataObjInfo_t *oldDataObjInfoHead = NULL; ruleExecInfo_t rei; int multiCopyFlag = 0; char *accessPerm = NULL; int remoteFlag = 0; rodsServerHost_t *rodsServerHost = NULL; specCollCache_t *specCollCache = NULL; std::string resc_name; resolveLinkedPath( rsComm, dataObjInp->objPath, &specCollCache, &dataObjInp->condInput ); remoteFlag = getAndConnRemoteZone( rsComm, dataObjInp, &rodsServerHost, REMOTE_OPEN ); if ( remoteFlag < 0 ) { return remoteFlag; } else if ( remoteFlag == REMOTE_HOST ) { status = _rcDataObjPhymv( rodsServerHost->conn, dataObjInp, transStat ); return status; } char* dest_resc = getValByKey( &dataObjInp->condInput, DEST_RESC_NAME_KW ); if ( dest_resc ) { irods::resource_ptr resc; irods::error ret = resc_mgr.resolve( dest_resc, resc ); if ( !ret.ok() ) { return SYS_RESC_DOES_NOT_EXIST; } } // =-=-=-=-=-=-=- // determine hierarchy string if ( getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW ) == NULL ) { std::string hier; irods::error ret = irods::resolve_resource_hierarchy( irods::OPEN_OPERATION, rsComm, dataObjInp, hier ); if ( !ret.ok() ) { std::stringstream msg; msg << __FUNCTION__; msg << " :: failed in irods::resolve_resource_hierarchy for ["; msg << dataObjInp->objPath << "]"; irods::log( PASSMSG( msg.str(), ret ) ); return ret.code(); } // =-=-=-=-=-=-=- // we resolved the redirect and have a host, set the hier str for subsequent // api calls, etc. addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() ); } // if keyword *transStat = ( transferStat_t* )malloc( sizeof( transferStat_t ) ); memset( *transStat, 0, sizeof( transferStat_t ) ); if ( getValByKey( &dataObjInp->condInput, ADMIN_KW ) != NULL ) { if ( rsComm->clientUser.authInfo.authFlag < LOCAL_PRIV_USER_AUTH ) { return CAT_INSUFFICIENT_PRIVILEGE_LEVEL; } accessPerm = NULL; } else { accessPerm = ACCESS_DELETE_OBJECT; } /* query rcat for resource info and sort it */ status = getRescForCreate( rsComm, dataObjInp, resc_name ); if ( status < 0 ) { return status; } initReiWithDataObjInp( &rei, rsComm, dataObjInp ); status = applyRule( "acSetMultiReplPerResc", NULL, &rei, NO_SAVE_REI ); if ( strcmp( rei.statusStr, MULTI_COPIES_PER_RESC ) == 0 ) { multiCopyFlag = 1; } else { multiCopyFlag = 0; } /* query rcat for dataObjInfo and sort it */ status = getDataObjInfo( rsComm, dataObjInp, &dataObjInfoHead, accessPerm, 1 ); if ( status < 0 ) { rodsLog( LOG_NOTICE, "rsDataObjPhymv: getDataObjInfo for %s", dataObjInp->objPath ); return status; } status = resolveInfoForPhymv( &dataObjInfoHead, &oldDataObjInfoHead, resc_name, &dataObjInp->condInput, multiCopyFlag ); if ( status < 0 ) { freeAllDataObjInfo( dataObjInfoHead ); freeAllDataObjInfo( oldDataObjInfoHead ); if ( status == CAT_NO_ROWS_FOUND ) { return 0; } else { return status; } } status = _rsDataObjPhymv( rsComm, dataObjInp, dataObjInfoHead, resc_name.c_str(), *transStat, multiCopyFlag ); freeAllDataObjInfo( dataObjInfoHead ); freeAllDataObjInfo( oldDataObjInfoHead ); return status; } int _rsDataObjPhymv( rsComm_t *rsComm, dataObjInp_t *dataObjInp, dataObjInfo_t *srcDataObjInfoHead, const char *_resc_name, transferStat_t *transStat, int multiCopyFlag ) { dataObjInfo_t *srcDataObjInfo; int status = 0; int savedStatus = 0; srcDataObjInfo = srcDataObjInfoHead; while ( srcDataObjInfo ) { /* use _rsDataObjReplS for the phymv */ dataObjInp->oprType = PHYMV_OPR; /* should be set already */ status = _rsDataObjReplS( rsComm, dataObjInp, srcDataObjInfo, _resc_name, NULL, 0 ); if ( multiCopyFlag == 0 ) { if ( status >= 0 ) { srcDataObjInfo = srcDataObjInfo->next; } else { savedStatus = status; } /* use another resc */ break; } else { if ( status < 0 ) { savedStatus = status; /* use another resc */ break; } } srcDataObjInfo = srcDataObjInfo->next; } if ( status >= 0 ) { transStat->numThreads = dataObjInp->numThreads; } if ( srcDataObjInfo != NULL ) { /* not everything got moved */ if ( savedStatus == 0 ) { status = SYS_COPY_ALREADY_IN_RESC; } } else { savedStatus = 0; } return savedStatus; }
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ #include "dataObjPhymv.h" #include "reFuncDefs.hpp" #include "dataObjRepl.h" #include "dataObjOpr.hpp" #include "rodsLog.h" #include "objMetaOpr.hpp" #include "specColl.hpp" #include "reGlobalsExtern.hpp" #include "reDefines.h" #include "icatDefines.h" #include "reSysDataObjOpr.hpp" #include "dataObjCreate.h" #include "getRemoteZoneResc.h" // =-=-=-=-=-=-=- #include "irods_resource_redirect.hpp" /* rsDataObjPhymv - The Api handler of the rcDataObjPhymv call - phymove * a data object from one resource to another. * Input - * rsComm_t *rsComm * dataObjInp_t *dataObjInp - The replication input * transferStat_t **transStat - transfer stat output */ int rsDataObjPhymv( rsComm_t *rsComm, dataObjInp_t *dataObjInp, transferStat_t **transStat ) { int status = 0; dataObjInfo_t *dataObjInfoHead = NULL; dataObjInfo_t *oldDataObjInfoHead = NULL; ruleExecInfo_t rei; int multiCopyFlag = 0; char *accessPerm = NULL; int remoteFlag = 0; rodsServerHost_t *rodsServerHost = NULL; specCollCache_t *specCollCache = NULL; std::string resc_name; resolveLinkedPath( rsComm, dataObjInp->objPath, &specCollCache, &dataObjInp->condInput ); remoteFlag = getAndConnRemoteZone( rsComm, dataObjInp, &rodsServerHost, REMOTE_OPEN ); if ( remoteFlag < 0 ) { return remoteFlag; } else if ( remoteFlag == REMOTE_HOST ) { status = _rcDataObjPhymv( rodsServerHost->conn, dataObjInp, transStat ); return status; } char* dest_resc = getValByKey( &dataObjInp->condInput, DEST_RESC_NAME_KW ); if ( dest_resc ) { irods::resource_ptr resc; irods::error ret = resc_mgr.resolve( dest_resc, resc ); if ( !ret.ok() ) { return SYS_RESC_DOES_NOT_EXIST; } } char* src_resc = getValByKey( &dataObjInp->condInput, RESC_NAME_KW ); if ( src_resc ) { irods::resource_ptr resc; irods::error ret = resc_mgr.resolve( src_resc, resc ); if ( !ret.ok() ) { return SYS_RESC_DOES_NOT_EXIST; } } // =-=-=-=-=-=-=- // determine hierarchy string if ( getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW ) == NULL ) { std::string hier; irods::error ret = irods::resolve_resource_hierarchy( irods::OPEN_OPERATION, rsComm, dataObjInp, hier ); if ( !ret.ok() ) { std::stringstream msg; msg << __FUNCTION__; msg << " :: failed in irods::resolve_resource_hierarchy for ["; msg << dataObjInp->objPath << "]"; irods::log( PASSMSG( msg.str(), ret ) ); return ret.code(); } // =-=-=-=-=-=-=- // we resolved the redirect and have a host, set the hier str for subsequent // api calls, etc. addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() ); } // if keyword *transStat = ( transferStat_t* )malloc( sizeof( transferStat_t ) ); memset( *transStat, 0, sizeof( transferStat_t ) ); if ( getValByKey( &dataObjInp->condInput, ADMIN_KW ) != NULL ) { if ( rsComm->clientUser.authInfo.authFlag < LOCAL_PRIV_USER_AUTH ) { return CAT_INSUFFICIENT_PRIVILEGE_LEVEL; } accessPerm = NULL; } else { accessPerm = ACCESS_DELETE_OBJECT; } /* query rcat for resource info and sort it */ status = getRescForCreate( rsComm, dataObjInp, resc_name ); if ( status < 0 ) { return status; } initReiWithDataObjInp( &rei, rsComm, dataObjInp ); status = applyRule( "acSetMultiReplPerResc", NULL, &rei, NO_SAVE_REI ); if ( strcmp( rei.statusStr, MULTI_COPIES_PER_RESC ) == 0 ) { multiCopyFlag = 1; } else { multiCopyFlag = 0; } /* query rcat for dataObjInfo and sort it */ status = getDataObjInfo( rsComm, dataObjInp, &dataObjInfoHead, accessPerm, 1 ); if ( status < 0 ) { rodsLog( LOG_NOTICE, "rsDataObjPhymv: getDataObjInfo for %s", dataObjInp->objPath ); return status; } status = resolveInfoForPhymv( &dataObjInfoHead, &oldDataObjInfoHead, resc_name, &dataObjInp->condInput, multiCopyFlag ); if ( status < 0 ) { freeAllDataObjInfo( dataObjInfoHead ); freeAllDataObjInfo( oldDataObjInfoHead ); if ( status == CAT_NO_ROWS_FOUND ) { return 0; } else { return status; } } status = _rsDataObjPhymv( rsComm, dataObjInp, dataObjInfoHead, resc_name.c_str(), *transStat, multiCopyFlag ); freeAllDataObjInfo( dataObjInfoHead ); freeAllDataObjInfo( oldDataObjInfoHead ); return status; } int _rsDataObjPhymv( rsComm_t *rsComm, dataObjInp_t *dataObjInp, dataObjInfo_t *srcDataObjInfoHead, const char *_resc_name, transferStat_t *transStat, int multiCopyFlag ) { dataObjInfo_t *srcDataObjInfo; int status = 0; int savedStatus = 0; srcDataObjInfo = srcDataObjInfoHead; while ( srcDataObjInfo ) { /* use _rsDataObjReplS for the phymv */ dataObjInp->oprType = PHYMV_OPR; /* should be set already */ status = _rsDataObjReplS( rsComm, dataObjInp, srcDataObjInfo, _resc_name, NULL, 0 ); if ( multiCopyFlag == 0 ) { if ( status >= 0 ) { srcDataObjInfo = srcDataObjInfo->next; } else { savedStatus = status; } /* use another resc */ break; } else { if ( status < 0 ) { savedStatus = status; /* use another resc */ break; } } srcDataObjInfo = srcDataObjInfo->next; } if ( status >= 0 ) { transStat->numThreads = dataObjInp->numThreads; } if ( srcDataObjInfo != NULL ) { /* not everything got moved */ if ( savedStatus == 0 ) { status = SYS_COPY_ALREADY_IN_RESC; } } else { savedStatus = 0; } return savedStatus; }
validate source resource
[#2821] validate source resource
C++
bsd-3-clause
PaulVanSchayck/irods,PaulVanSchayck/irods,PaulVanSchayck/irods,PaulVanSchayck/irods,PaulVanSchayck/irods,janiheikkinen/irods,PaulVanSchayck/irods,janiheikkinen/irods,PaulVanSchayck/irods,PaulVanSchayck/irods,janiheikkinen/irods,janiheikkinen/irods,janiheikkinen/irods,janiheikkinen/irods,PaulVanSchayck/irods,janiheikkinen/irods,janiheikkinen/irods,janiheikkinen/irods
6f2f52c9b35c775d3d4e917a2112290831b5314d
include/config.cpp
include/config.cpp
/** * @file config.CPP * @brief Config file loader * @author Byunghun Hwang<[email protected]> * @date 2015. 6. 21 * @details Load config file to run the engine */ #include "config.hpp" #include "configloader.hpp" namespace cossb { namespace base { config::config():_doc(nullptr) { } config::~config() { if(!_dependency.empty()) { for(auto& itr:_dependency) delete itr; } if(_doc) delete _doc; } bool config::load(const char* manifest_conf) { if(_doc!=nullptr) { delete _doc; _doc = nullptr; } _doc = new tinyxml2::XMLDocument; if(_doc->LoadFile(manifest_conf)==XML_SUCCESS) { parse_dependency(); parse_product(); parse_path(); parse_repository(); return true; } return false; } bool config::update(config* conf) { return false; } /*map<string, string> config::get_dependency() { switch(type) { case deptype::LIBRARY: return parse_dependency("library"); break; case deptype::COMPONENT: return parse_dependency("component"); break; default: cout << "unknown dependency type" << endl; } return list<string>(); }*/ void config::parse_dependency() { XMLElement* elem_com = _doc->FirstChildElement("manifest"); for(XMLElement* child = elem_com->FirstChildElement("dependency");child!=nullptr; child = child->NextSiblingElement("dependency")) { if(child->Attribute("type","library")) _dependency.push_back(new sDependency(dependencyType::LIBRARY, child->GetText())); else if(child->Attribute("type","component")) _dependency.push_back(new sDependency(dependencyType::COMPONENT, child->GetText())); } } void config::parse_path() { XMLElement* elem_com = _doc->FirstChildElement("manifest")->FirstChildElement("property"); for(XMLElement* child = elem_com->FirstChildElement("path");child!=nullptr; child = child->NextSiblingElement("path")) _path[child->Attribute("name")] = child->GetText(); } void config::parse_repository() { XMLElement* elem_uri = _doc->FirstChildElement("manifest")->FirstChildElement("repository"); for(XMLElement* child = elem_uri->FirstChildElement("uri");child!=nullptr; child = child->NextSiblingElement("uri")) if(child->GetText()) _repository.push_back(child->GetText()); } void config::parse_product() { XMLElement* elem_com = _doc->FirstChildElement("manifest")->FirstChildElement("product"); for(XMLElement* child = elem_com->FirstChildElement();child!=nullptr; child = child->NextSiblingElement()) _product[child->Value()] = child->GetText(); } } /* namespace base */ } /* namespace cossb */
/** * @file config.CPP * @brief Config file loader * @author Byunghun Hwang<[email protected]> * @date 2015. 6. 21 * @details Load config file to run the engine */ #include "config.hpp" namespace cossb { namespace base { config::config():_doc(nullptr) { } config::~config() { if(!_dependency.empty()) { for(auto& itr:_dependency) delete itr; } if(_doc) delete _doc; } bool config::load(const char* manifest_conf) { if(_doc!=nullptr) { delete _doc; _doc = nullptr; } _doc = new tinyxml2::XMLDocument; if(_doc->LoadFile(manifest_conf)==XML_SUCCESS) { parse_dependency(); parse_product(); parse_path(); parse_repository(); return true; } return false; } bool config::update(config* conf) { return false; } void config::parse_dependency() { XMLElement* elem_com = _doc->FirstChildElement("manifest"); for(XMLElement* child = elem_com->FirstChildElement("dependency");child!=nullptr; child = child->NextSiblingElement("dependency")) { if(child->Attribute("type","library")) _dependency.push_back(new sDependency(dependencyType::LIBRARY, child->GetText())); else if(child->Attribute("type","component")) _dependency.push_back(new sDependency(dependencyType::COMPONENT, child->GetText())); } } void config::parse_path() { XMLElement* elem_com = _doc->FirstChildElement("manifest")->FirstChildElement("property"); for(XMLElement* child = elem_com->FirstChildElement("path");child!=nullptr; child = child->NextSiblingElement("path")) _path[child->Attribute("name")] = child->GetText(); } void config::parse_repository() { XMLElement* elem_uri = _doc->FirstChildElement("manifest")->FirstChildElement("repository"); for(XMLElement* child = elem_uri->FirstChildElement("uri");child!=nullptr; child = child->NextSiblingElement("uri")) if(child->GetText()) _repository.push_back(child->GetText()); } void config::parse_product() { XMLElement* elem_com = _doc->FirstChildElement("manifest")->FirstChildElement("product"); for(XMLElement* child = elem_com->FirstChildElement();child!=nullptr; child = child->NextSiblingElement()) _product[child->Value()] = child->GetText(); } } /* namespace base */ } /* namespace cossb */
clean up the source
clean up the source
C++
mit
bhhwang/cossb,bhhwang/cossb,bhhwang/cossb
cd1c6227c1c91ec6fb7bcbdbbf97cc47dd1e0b2d
cpp/src/parquet/arrow/arrow-reader-writer-benchmark.cc
cpp/src/parquet/arrow/arrow-reader-writer-benchmark.cc
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "benchmark/benchmark.h" #include "parquet/arrow/reader.h" #include "parquet/arrow/writer.h" #include "parquet/column_reader.h" #include "parquet/column_writer.h" #include "parquet/file/reader-internal.h" #include "parquet/file/writer-internal.h" #include "parquet/util/memory.h" #include "arrow/api.h" using arrow::NumericBuilder; #define ABORT_NOT_OK(s) \ do { \ ::arrow::Status _s = (s); \ if (ARROW_PREDICT_FALSE(!_s.ok())) { \ exit(-1); \ } \ } while (0); namespace parquet { using arrow::FileReader; using arrow::WriteTable; using schema::PrimitiveNode; namespace benchmark { // This should result in multiple pages for most primitive types constexpr int64_t BENCHMARK_SIZE = 10 * 1024 * 1024; template <typename ParquetType> struct benchmark_traits {}; template <> struct benchmark_traits<Int32Type> { using arrow_type = ::arrow::Int32Type; }; template <> struct benchmark_traits<Int64Type> { using arrow_type = ::arrow::Int64Type; }; template <> struct benchmark_traits<DoubleType> { using arrow_type = ::arrow::DoubleType; }; template <typename ParquetType> using ArrowType = typename benchmark_traits<ParquetType>::arrow_type; template <typename ParquetType> std::shared_ptr<ColumnDescriptor> MakeSchema(Repetition::type repetition) { auto node = PrimitiveNode::Make("int64", repetition, ParquetType::type_num); return std::make_shared<ColumnDescriptor>(node, repetition != Repetition::REQUIRED, repetition == Repetition::REPEATED); } template <bool nullable, typename ParquetType> void SetBytesProcessed(::benchmark::State& state) { int64_t bytes_processed = state.iterations() * BENCHMARK_SIZE * sizeof(typename ParquetType::c_type); if (nullable) { bytes_processed += state.iterations() * BENCHMARK_SIZE * sizeof(int16_t); } state.SetBytesProcessed(bytes_processed); } template <bool nullable, typename ParquetType> std::shared_ptr<::arrow::Table> TableFromVector( const std::vector<typename ParquetType::c_type>& vec) { ::arrow::TypePtr type = std::make_shared<ArrowType<ParquetType>>(); NumericBuilder<ArrowType<ParquetType>> builder(type, ::arrow::default_memory_pool()); if (nullable) { std::vector<uint8_t> valid_bytes(BENCHMARK_SIZE, 0); int n = {0}; std::generate(valid_bytes.begin(), valid_bytes.end(), [&n] { return n++ % 2; }); ABORT_NOT_OK(builder.Append(vec.data(), vec.size(), valid_bytes.data())); } else { ABORT_NOT_OK(builder.Append(vec.data(), vec.size(), nullptr)); } std::shared_ptr<::arrow::Array> array; ABORT_NOT_OK(builder.Finish(&array)); auto field = std::make_shared<::arrow::Field>("column", type, nullable); auto schema = std::make_shared<::arrow::Schema>( std::vector<std::shared_ptr<::arrow::Field>>({field})); auto column = std::make_shared<::arrow::Column>(field, array); return std::make_shared<::arrow::Table>( schema, std::vector<std::shared_ptr<::arrow::Column>>({column})); } template <bool nullable, typename ParquetType> static void BM_WriteColumn(::benchmark::State& state) { format::ColumnChunk thrift_metadata; std::vector<typename ParquetType::c_type> values(BENCHMARK_SIZE, 128); std::shared_ptr<::arrow::Table> table = TableFromVector<nullable, ParquetType>(values); while (state.KeepRunning()) { auto output = std::make_shared<InMemoryOutputStream>(); ABORT_NOT_OK( WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE)); } SetBytesProcessed<nullable, ParquetType>(state); } BENCHMARK_TEMPLATE2(BM_WriteColumn, false, Int32Type); BENCHMARK_TEMPLATE2(BM_WriteColumn, true, Int32Type); BENCHMARK_TEMPLATE2(BM_WriteColumn, false, Int64Type); BENCHMARK_TEMPLATE2(BM_WriteColumn, true, Int64Type); BENCHMARK_TEMPLATE2(BM_WriteColumn, false, DoubleType); BENCHMARK_TEMPLATE2(BM_WriteColumn, true, DoubleType); template <bool nullable, typename ParquetType> static void BM_ReadColumn(::benchmark::State& state) { std::vector<typename ParquetType::c_type> values(BENCHMARK_SIZE, 128); std::shared_ptr<::arrow::Table> table = TableFromVector<nullable, ParquetType>(values); auto output = std::make_shared<InMemoryOutputStream>(); ABORT_NOT_OK( WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE)); std::shared_ptr<Buffer> buffer = output->GetBuffer(); while (state.KeepRunning()) { auto reader = ParquetFileReader::Open(std::make_shared<::arrow::io::BufferReader>(buffer)); FileReader filereader(::arrow::default_memory_pool(), std::move(reader)); std::shared_ptr<::arrow::Table> table; ABORT_NOT_OK(filereader.ReadTable(&table)); } SetBytesProcessed<nullable, ParquetType>(state); } BENCHMARK_TEMPLATE2(BM_ReadColumn, false, Int32Type); BENCHMARK_TEMPLATE2(BM_ReadColumn, true, Int32Type); BENCHMARK_TEMPLATE2(BM_ReadColumn, false, Int64Type); BENCHMARK_TEMPLATE2(BM_ReadColumn, true, Int64Type); BENCHMARK_TEMPLATE2(BM_ReadColumn, false, DoubleType); BENCHMARK_TEMPLATE2(BM_ReadColumn, true, DoubleType); } // namespace benchmark } // namespace parquet
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "benchmark/benchmark.h" #include "parquet/arrow/reader.h" #include "parquet/arrow/writer.h" #include "parquet/column_reader.h" #include "parquet/column_writer.h" #include "parquet/file/reader-internal.h" #include "parquet/file/writer-internal.h" #include "parquet/util/memory.h" #include "arrow/api.h" using arrow::BooleanBuilder; using arrow::NumericBuilder; #define ABORT_NOT_OK(s) \ do { \ ::arrow::Status _s = (s); \ if (ARROW_PREDICT_FALSE(!_s.ok())) { \ exit(-1); \ } \ } while (0); namespace parquet { using arrow::FileReader; using arrow::WriteTable; using schema::PrimitiveNode; namespace benchmark { // This should result in multiple pages for most primitive types constexpr int64_t BENCHMARK_SIZE = 10 * 1024 * 1024; template <typename ParquetType> struct benchmark_traits {}; template <> struct benchmark_traits<Int32Type> { using arrow_type = ::arrow::Int32Type; }; template <> struct benchmark_traits<Int64Type> { using arrow_type = ::arrow::Int64Type; }; template <> struct benchmark_traits<DoubleType> { using arrow_type = ::arrow::DoubleType; }; template <> struct benchmark_traits<BooleanType> { using arrow_type = ::arrow::BooleanType; }; template <typename ParquetType> using ArrowType = typename benchmark_traits<ParquetType>::arrow_type; template <typename ParquetType> std::shared_ptr<ColumnDescriptor> MakeSchema(Repetition::type repetition) { auto node = PrimitiveNode::Make("int64", repetition, ParquetType::type_num); return std::make_shared<ColumnDescriptor>(node, repetition != Repetition::REQUIRED, repetition == Repetition::REPEATED); } template <bool nullable, typename ParquetType> void SetBytesProcessed(::benchmark::State& state) { int64_t bytes_processed = state.iterations() * BENCHMARK_SIZE * sizeof(typename ParquetType::c_type); if (nullable) { bytes_processed += state.iterations() * BENCHMARK_SIZE * sizeof(int16_t); } state.SetBytesProcessed(bytes_processed); } template <typename ParquetType> std::shared_ptr<::arrow::Table> TableFromVector( const std::vector<typename ParquetType::c_type>& vec, bool nullable) { ::arrow::TypePtr type = std::make_shared<ArrowType<ParquetType>>(); NumericBuilder<ArrowType<ParquetType>> builder; if (nullable) { std::vector<uint8_t> valid_bytes(BENCHMARK_SIZE, 0); int n = {0}; std::generate(valid_bytes.begin(), valid_bytes.end(), [&n] { return n++ % 2; }); ABORT_NOT_OK(builder.Append(vec.data(), vec.size(), valid_bytes.data())); } else { ABORT_NOT_OK(builder.Append(vec.data(), vec.size(), nullptr)); } std::shared_ptr<::arrow::Array> array; ABORT_NOT_OK(builder.Finish(&array)); auto field = ::arrow::field("column", type, nullable); auto schema = std::make_shared<::arrow::Schema>( std::vector<std::shared_ptr<::arrow::Field>>({field})); auto column = std::make_shared<::arrow::Column>(field, array); return std::make_shared<::arrow::Table>( schema, std::vector<std::shared_ptr<::arrow::Column>>({column})); } template <> std::shared_ptr<::arrow::Table> TableFromVector<BooleanType>(const std::vector<bool>& vec, bool nullable) { BooleanBuilder builder; if (nullable) { std::vector<bool> valid_bytes(BENCHMARK_SIZE, 0); int n = {0}; std::generate(valid_bytes.begin(), valid_bytes.end(), [&n] { return (n++ % 2) != 0; }); ABORT_NOT_OK(builder.Append(vec, valid_bytes)); } else { ABORT_NOT_OK(builder.Append(vec)); } std::shared_ptr<::arrow::Array> array; ABORT_NOT_OK(builder.Finish(&array)); auto field = ::arrow::field("column", ::arrow::boolean(), nullable); auto schema = std::make_shared<::arrow::Schema>( std::vector<std::shared_ptr<::arrow::Field>>({field})); auto column = std::make_shared<::arrow::Column>(field, array); return std::make_shared<::arrow::Table>( schema, std::vector<std::shared_ptr<::arrow::Column>>({column})); } template <bool nullable, typename ParquetType> static void BM_WriteColumn(::benchmark::State& state) { format::ColumnChunk thrift_metadata; std::vector<typename ParquetType::c_type> values(BENCHMARK_SIZE, 128); std::shared_ptr<::arrow::Table> table = TableFromVector<ParquetType>(values, nullable); while (state.KeepRunning()) { auto output = std::make_shared<InMemoryOutputStream>(); ABORT_NOT_OK( WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE)); } SetBytesProcessed<nullable, ParquetType>(state); } BENCHMARK_TEMPLATE2(BM_WriteColumn, false, Int32Type); BENCHMARK_TEMPLATE2(BM_WriteColumn, true, Int32Type); BENCHMARK_TEMPLATE2(BM_WriteColumn, false, Int64Type); BENCHMARK_TEMPLATE2(BM_WriteColumn, true, Int64Type); BENCHMARK_TEMPLATE2(BM_WriteColumn, false, DoubleType); BENCHMARK_TEMPLATE2(BM_WriteColumn, true, DoubleType); BENCHMARK_TEMPLATE2(BM_WriteColumn, false, BooleanType); BENCHMARK_TEMPLATE2(BM_WriteColumn, true, BooleanType); template <bool nullable, typename ParquetType> static void BM_ReadColumn(::benchmark::State& state) { std::vector<typename ParquetType::c_type> values(BENCHMARK_SIZE, 128); std::shared_ptr<::arrow::Table> table = TableFromVector<ParquetType>(values, nullable); auto output = std::make_shared<InMemoryOutputStream>(); ABORT_NOT_OK( WriteTable(*table, ::arrow::default_memory_pool(), output, BENCHMARK_SIZE)); std::shared_ptr<Buffer> buffer = output->GetBuffer(); while (state.KeepRunning()) { auto reader = ParquetFileReader::Open(std::make_shared<::arrow::io::BufferReader>(buffer)); FileReader filereader(::arrow::default_memory_pool(), std::move(reader)); std::shared_ptr<::arrow::Table> table; ABORT_NOT_OK(filereader.ReadTable(&table)); } SetBytesProcessed<nullable, ParquetType>(state); } BENCHMARK_TEMPLATE2(BM_ReadColumn, false, Int32Type); BENCHMARK_TEMPLATE2(BM_ReadColumn, true, Int32Type); BENCHMARK_TEMPLATE2(BM_ReadColumn, false, Int64Type); BENCHMARK_TEMPLATE2(BM_ReadColumn, true, Int64Type); BENCHMARK_TEMPLATE2(BM_ReadColumn, false, DoubleType); BENCHMARK_TEMPLATE2(BM_ReadColumn, true, DoubleType); BENCHMARK_TEMPLATE2(BM_ReadColumn, false, BooleanType); BENCHMARK_TEMPLATE2(BM_ReadColumn, true, BooleanType); } // namespace benchmark } // namespace parquet
Add benchmark for boolean Arrow column I/O
PARQUET-1094: Add benchmark for boolean Arrow column I/O Author: Uwe L. Korn <[email protected]> Closes #391 from xhochy/PARQUET-1094 and squashes the following commits: 089bb3c [Uwe L. Korn] PARQUET-1094: Add benchmark for boolean Arrow column I/O Change-Id: I2bb6a0894d13ce0c67f592cae069e09255d8d0e6
C++
apache-2.0
majetideepak/arrow,itaiin/arrow,kou/arrow,pcmoritz/arrow,wesm/arrow,xhochy/arrow,cpcloud/arrow,icexelloss/arrow,cpcloud/arrow,laurentgo/arrow,cpcloud/arrow,apache/arrow,icexelloss/arrow,pcmoritz/arrow,icexelloss/arrow,itaiin/arrow,pcmoritz/arrow,icexelloss/arrow,apache/arrow,itaiin/arrow,wesm/arrow,xhochy/arrow,icexelloss/arrow,itaiin/arrow,pcmoritz/arrow,laurentgo/arrow,pcmoritz/arrow,xhochy/arrow,laurentgo/arrow,apache/arrow,xhochy/arrow,apache/arrow,kou/arrow,icexelloss/arrow,tebeka/arrow,pcmoritz/arrow,pcmoritz/arrow,apache/arrow,apache/arrow,laurentgo/arrow,kou/arrow,laurentgo/arrow,pcmoritz/arrow,renesugar/arrow,wesm/arrow,tebeka/arrow,kou/arrow,wesm/arrow,tebeka/arrow,renesugar/arrow,itaiin/arrow,xhochy/arrow,pcmoritz/arrow,xhochy/arrow,renesugar/arrow,renesugar/arrow,laurentgo/arrow,tebeka/arrow,kou/arrow,majetideepak/arrow,laurentgo/arrow,laurentgo/arrow,cpcloud/arrow,renesugar/arrow,xhochy/arrow,apache/arrow,renesugar/arrow,itaiin/arrow,majetideepak/arrow,laurentgo/arrow,itaiin/arrow,renesugar/arrow,pcmoritz/arrow,icexelloss/arrow,kou/arrow,renesugar/arrow,pcmoritz/arrow,itaiin/arrow,cpcloud/arrow,kou/arrow,pcmoritz/arrow,tebeka/arrow,icexelloss/arrow,kou/arrow,tebeka/arrow,renesugar/arrow,wesm/arrow,majetideepak/arrow,itaiin/arrow,wesm/arrow,pcmoritz/arrow,kou/arrow,tebeka/arrow,renesugar/arrow,cpcloud/arrow,xhochy/arrow,wesm/arrow,cpcloud/arrow,icexelloss/arrow,majetideepak/arrow,laurentgo/arrow,tebeka/arrow,majetideepak/arrow,pcmoritz/arrow,majetideepak/arrow,renesugar/arrow,xhochy/arrow,kou/arrow,itaiin/arrow,xhochy/arrow,laurentgo/arrow,majetideepak/arrow,wesm/arrow,kou/arrow,apache/arrow,wesm/arrow,laurentgo/arrow,xhochy/arrow,renesugar/arrow,xhochy/arrow,laurentgo/arrow,itaiin/arrow,wesm/arrow,laurentgo/arrow,apache/arrow,kou/arrow,pcmoritz/arrow,majetideepak/arrow,majetideepak/arrow,itaiin/arrow,renesugar/arrow,laurentgo/arrow,cpcloud/arrow,wesm/arrow,majetideepak/arrow,itaiin/arrow,apache/arrow,majetideepak/arrow,apache/arrow,kou/arrow,majetideepak/arrow,renesugar/arrow,wesm/arrow,icexelloss/arrow,xhochy/arrow,xhochy/arrow,apache/arrow,icexelloss/arrow,cpcloud/arrow,renesugar/arrow,itaiin/arrow,icexelloss/arrow,majetideepak/arrow,tebeka/arrow,wesm/arrow,icexelloss/arrow,icexelloss/arrow,cpcloud/arrow,apache/arrow,tebeka/arrow,majetideepak/arrow,cpcloud/arrow,wesm/arrow,kou/arrow,xhochy/arrow,cpcloud/arrow,cpcloud/arrow,cpcloud/arrow,apache/arrow,itaiin/arrow
231daf9977e221a50d0150140c451d49ad224aee
ASCOfficeOdfFileW/source/utils.cpp
ASCOfficeOdfFileW/source/utils.cpp
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include "utils.h" #include <vector> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #include <gdiplus.h> #pragma comment(lib, "gdiplus.lib") #endif #include "../../../../DesktopEditor/raster/BgraFrame.h" #include "../../../../DesktopEditor/common/File.h" #include "../../../../ASCOfficeOdfFile/src/docx/measuredigits.h" namespace _graphics_utils_ { bool GetResolution(const wchar_t* fileName, double & Width, double &Height) //px { NSFile::CFileBinary file; if (false == file.OpenFile(fileName)) return false; long file_size = file.GetFileSize(); file.CloseFile(); if (file_size < 1) return false; bool result = false; CBgraFrame image; if (result = image.OpenFile(fileName, 0 )) { Width = image.get_Width(); Height = image.get_Height(); result = true; } else { #if defined(_WIN32) || defined(_WIN64) Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken=0; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); Gdiplus::Bitmap *file = new Gdiplus::Bitmap(fileName,false); if ((file) && (file->GetLastStatus()==Gdiplus::Ok)) { Height = file->GetHeight(); Width = file->GetWidth(); double dpi_x = file->GetHorizontalResolution(); double dpi_y = file->GetVerticalResolution(); if (dpi_x <1 )dpi_x = 96; if (dpi_y <1 )dpi_y = 96; Height = Height *72. / dpi_y; Width = Width * 72. /dpi_x; result = true; delete file; } Gdiplus::GdiplusShutdown(gdiplusToken); #endif } return result; } double calculate_size_symbol_win(std::wstring name, double size, bool italic, bool bold, std::wstring test_str) { double result =0; #if defined(_WIN32) || defined(_WIN64) Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken=0; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); //// bool to_one_char = false; if (test_str.length() <1 ) { test_str = L"0123456789"; to_one_char = true; } int style = Gdiplus::FontStyleRegular; if (bold && italic) style = Gdiplus::FontStyleBoldItalic; else if (bold) style = Gdiplus::FontStyleBold; else if (italic) style = Gdiplus::FontStyleItalic; Gdiplus::Graphics * gr = new Gdiplus::Graphics(GetWindowDC(NULL)); if (gr) { Gdiplus::Font *font = new Gdiplus::Font(name.c_str(),size,style); if (font) { Gdiplus::SizeF layout; Gdiplus::RectF bound; Gdiplus::Status res = gr->MeasureString(test_str.c_str(),test_str.length(),font,layout,&bound); if (res==0)result = (bound.Width - 2); if (to_one_char) result /= test_str.length(); //normalize to dpi = 96; double dpi = gr->GetDpiX(); result = result * 96./dpi; delete font; } delete gr; } Gdiplus::GdiplusShutdown(gdiplusToken); #endif return result; } std::pair<float,float> calculate_size_symbol_asc(std::wstring name, double size, bool italic, bool bold , NSFonts::IApplicationFonts *appFonts) { if (name.empty()) name = L"Arial"; std::pair<float,float> val = cpdoccore::utils::GetMaxDigitSizePixels(name, size, 96., 0 , appFonts); return val; } };
/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include "utils.h" #include <vector> #if defined(_WIN32) || defined(_WIN64) #ifndef min #define min(a,b) (((a)<(b))?(a):(b)) #endif #ifndef max #define max(a,b) (((a)>(b))?(a):(b)) #endif #include <windows.h> #include <gdiplus.h> #undef min #undef max #pragma comment(lib, "gdiplus.lib") #endif #include "../../../../DesktopEditor/raster/BgraFrame.h" #include "../../../../DesktopEditor/common/File.h" #include "../../../../ASCOfficeOdfFile/src/docx/measuredigits.h" namespace _graphics_utils_ { bool GetResolution(const wchar_t* fileName, double & Width, double &Height) //px { NSFile::CFileBinary file; if (false == file.OpenFile(fileName)) return false; long file_size = file.GetFileSize(); file.CloseFile(); if (file_size < 1) return false; bool result = false; CBgraFrame image; if (result = image.OpenFile(fileName, 0 )) { Width = image.get_Width(); Height = image.get_Height(); result = true; } else { #if defined(_WIN32) || defined(_WIN64) Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken=0; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); Gdiplus::Bitmap *file = new Gdiplus::Bitmap(fileName,false); if ((file) && (file->GetLastStatus()==Gdiplus::Ok)) { Height = file->GetHeight(); Width = file->GetWidth(); double dpi_x = file->GetHorizontalResolution(); double dpi_y = file->GetVerticalResolution(); if (dpi_x <1 )dpi_x = 96; if (dpi_y <1 )dpi_y = 96; Height = Height *72. / dpi_y; Width = Width * 72. /dpi_x; result = true; delete file; } Gdiplus::GdiplusShutdown(gdiplusToken); #endif } return result; } double calculate_size_symbol_win(std::wstring name, double size, bool italic, bool bold, std::wstring test_str) { double result =0; #if defined(_WIN32) || defined(_WIN64) Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken=0; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); //// bool to_one_char = false; if (test_str.length() <1 ) { test_str = L"0123456789"; to_one_char = true; } int style = Gdiplus::FontStyleRegular; if (bold && italic) style = Gdiplus::FontStyleBoldItalic; else if (bold) style = Gdiplus::FontStyleBold; else if (italic) style = Gdiplus::FontStyleItalic; Gdiplus::Graphics * gr = new Gdiplus::Graphics(GetWindowDC(NULL)); if (gr) { Gdiplus::Font *font = new Gdiplus::Font(name.c_str(),size,style); if (font) { Gdiplus::SizeF layout; Gdiplus::RectF bound; Gdiplus::Status res = gr->MeasureString(test_str.c_str(),test_str.length(),font,layout,&bound); if (res==0)result = (bound.Width - 2); if (to_one_char) result /= test_str.length(); //normalize to dpi = 96; double dpi = gr->GetDpiX(); result = result * 96./dpi; delete font; } delete gr; } Gdiplus::GdiplusShutdown(gdiplusToken); #endif return result; } std::pair<float,float> calculate_size_symbol_asc(std::wstring name, double size, bool italic, bool bold , NSFonts::IApplicationFonts *appFonts) { if (name.empty()) name = L"Arial"; std::pair<float,float> val = cpdoccore::utils::GetMaxDigitSizePixels(name, size, 96., 0 , appFonts); return val; } };
Fix build
Fix build
C++
agpl-3.0
ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core,ONLYOFFICE/core
aa84a3ea41a20632ddd9f671779e0601505412bb
kicad/commandframe.cpp
kicad/commandframe.cpp
/*****************************************************/ /* commandframe.cpp: window handling comman buttons */ /*****************************************************/ #include "fctsys.h" #include "common.h" #include "kicad.h" #include "macros.h" #define BITMAP wxBitmap // ---------------------------------------------------------------------------- // resources // ---------------------------------------------------------------------------- // USE_XPM_BITMAPS #include "bitmaps.h" #include "id.h" /************************************************************************************/ WinEDA_CommandFrame::WinEDA_CommandFrame( wxWindow* parent, int id, wxPoint pos, wxSize size, long style ) : wxSashLayoutWindow( parent, id, pos, size, style ) /************************************************************************************/ /** WinEDA_CommandFrame constructor * create the window which the buttons to call eeschema and others... */ { SetDefaultSize( wxSize( size.x, 100 ) ); SetOrientation( wxLAYOUT_HORIZONTAL ); SetAlignment( wxLAYOUT_TOP ); SetSashVisible( wxSASH_BOTTOM, TRUE ); SetSashVisible( wxSASH_LEFT, TRUE ); SetExtraBorderSize( 2 ); SetFont( *g_StdFont ); CreateCommandToolbar(); } /*************************************************/ void WinEDA_CommandFrame::CreateCommandToolbar( void ) /*************************************************/ /** Function CreateCommandToolbar * create the buttons to call eescheman cvpcb, pcbnew and gerbview */ { wxBitmapButton* btn; m_ButtonSeparation = 10; m_ButtonLastPosition.x = 20; m_ButtonLastPosition.y = 20; btn = new wxBitmapButton( this, ID_TO_EESCHEMA, BITMAP( icon_eeschema_xpm ) ); btn->SetToolTip( _( "eeschema (Schematic editor)" ) ); AddFastLaunch( btn ); btn = new wxBitmapButton( this, ID_TO_CVPCB, BITMAP( icon_cvpcb_xpm ) ); btn->SetToolTip( _( "cvpcb (Components to modules)" ) ); AddFastLaunch( btn ); btn = new wxBitmapButton( this, ID_TO_PCB, BITMAP( a_icon_pcbnew_xpm ) ); btn->SetToolTip( _( "pcbnew (PCB editor)" ) ); AddFastLaunch( btn ); btn = new wxBitmapButton( this, ID_TO_GERBVIEW, BITMAP( icon_gerbview_xpm ) ); btn->SetToolTip( _( "gerbview (Gerber viewer)" ) ); AddFastLaunch( btn ); // Set up toolbar #ifdef KICAD_PYTHON btn = new wxBitmapButton( this, ID_RUN_PYTHON, BITMAP( icon_python_xpm ) ); btn->SetToolTip( _( "Run Python Script" ) ); AddFastLaunch( btn ); #endif } /****************************************************************/ void WinEDA_CommandFrame::AddFastLaunch( wxBitmapButton * button ) /****************************************************************/ /** Function AddFastLaunch * add a Bitmap Button (fast launch button) to the window * @param button = wxBitmapButton to add to the window */ { button->Move( m_ButtonLastPosition ); m_ButtonLastPosition.x += button->GetSize().GetWidth() + m_ButtonSeparation; }
/*****************************************************/ /* commandframe.cpp: window handling comman buttons */ /*****************************************************/ #include "fctsys.h" #include "common.h" #include "kicad.h" #include "macros.h" #define BITMAP wxBitmap // ---------------------------------------------------------------------------- // resources // ---------------------------------------------------------------------------- // USE_XPM_BITMAPS #include "bitmaps.h" #include "id.h" /************************************************************************************/ WinEDA_CommandFrame::WinEDA_CommandFrame( wxWindow* parent, int id, wxPoint pos, wxSize size, long style ) : wxSashLayoutWindow( parent, id, pos, size, style ) /************************************************************************************/ /** WinEDA_CommandFrame constructor * create the window which the buttons to call eeschema and others... */ { SetDefaultSize( wxSize( size.x, 100 ) ); SetOrientation( wxLAYOUT_HORIZONTAL ); SetAlignment( wxLAYOUT_TOP ); SetSashVisible( wxSASH_BOTTOM, TRUE ); SetSashVisible( wxSASH_LEFT, TRUE ); SetExtraBorderSize( 2 ); SetFont( *g_StdFont ); CreateCommandToolbar(); } /*************************************************/ void WinEDA_CommandFrame::CreateCommandToolbar( void ) /*************************************************/ /** Function CreateCommandToolbar * create the buttons to call eescheman cvpcb, pcbnew and gerbview */ { wxBitmapButton* btn; m_ButtonSeparation = 10; m_ButtonLastPosition.x = 20; m_ButtonLastPosition.y = 20; btn = new wxBitmapButton( this, ID_TO_EESCHEMA, BITMAP( icon_eeschema_xpm ) ); btn->SetToolTip( _( "eeschema (Schematic editor)" ) ); AddFastLaunch( btn ); btn = new wxBitmapButton( this, ID_TO_CVPCB, BITMAP( icon_cvpcb_xpm ) ); btn->SetToolTip( _( "cvpcb (Components to modules)" ) ); AddFastLaunch( btn ); btn = new wxBitmapButton( this, ID_TO_PCB, BITMAP( a_icon_pcbnew_xpm ) ); btn->SetToolTip( _( "pcbnew (PCB editor)" ) ); AddFastLaunch( btn ); btn = new wxBitmapButton( this, ID_TO_GERBVIEW, BITMAP( icon_gerbview_xpm ) ); btn->SetToolTip( _( "gerbview (Gerber viewer)" ) ); AddFastLaunch( btn ); // Set up toolbar #ifdef KICAD_PYTHON btn = new wxBitmapButton( this, ID_RUN_PYTHON, BITMAP( icon_python_xpm ) ); btn->SetToolTip( _( "Run Python Script" ) ); AddFastLaunch( btn ); #endif } /****************************************************************/ void WinEDA_CommandFrame::AddFastLaunch( wxBitmapButton * button ) /****************************************************************/ /** Function AddFastLaunch * add a Bitmap Button (fast launch button) to the window * @param button = wxBitmapButton to add to the window */ { button->Move( m_ButtonLastPosition ); m_ButtonLastPosition.x += button->GetSize().GetWidth() + m_ButtonSeparation; }
set eol-style native on new file
set eol-style native on new file
C++
lgpl-2.1
hellamps/kicad,hellamps/kicad,hellamps/kicad,hellamps/kicad,hellamps/kicad
3cd7b6d332e26a157cb95409225005316813c9aa
kmailcvt/filter_oe.cxx
kmailcvt/filter_oe.cxx
/*************************************************************************** filter_oe.cxx - Outlook Express mail import ------------------- begin : Sat Feb 1 2003 copyright : (C) 2003 by Laurence Anderson email : [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 filter was created by looking at libdbx & liboe #include <config.h> #include <klocale.h> #include <kfiledialog.h> #include <kdirlister.h> #include <qregexp.h> #include <libgen.h> #include <qdir.h> #include <qfile.h> #include <qdatastream.h> #include <ktempfile.h> #include <kdebug.h> #include "filter_oe.hxx" #define OE4_SIG_1 0x36464d4a #define OE4_SIG_2 0x00010003 #define OE5_SIG_1 0xfe12adcf #define OE5_EMAIL_SIG_2 0x6f74fdc5 #define OE5_FOLDER_SIG_2 0x6f74fdc6 #define OE5_SIG_3 0x11d1e366 #define OE5_SIG_4 0xc0004e9a #define MBX_MAILMAGIC 0x7F007F00 FilterOE::FilterOE() : Filter( i18n("Import Outlook Express Emails"), "Laurence Anderson", i18n("<p><b>New Outlook Express 4/5/6 import filter</b></p>" "<p>This is a new Outlook Express import filter, which fully supports versions 4 to 6.</p>" "<p>Outlook Express generally stores its mailboxes in C:\\Windows\\Application Data\\Identities\\<profilename>\\Microsoft\\Outlook Express</p>" "<p><b>Note:</b> Emails will be imported into folders named after the file they came from, prefixed with either OE4 or OE5</p>" )) { } FilterOE::~FilterOE() { } void FilterOE::import(FilterInfo *info) { inf = info; // Select directory containing plain text emails QString mailDir = KFileDialog::getExistingDirectory(QDir::homeDirPath(),inf->parent()); if (mailDir.isEmpty()) { // No directory selected info->alert(i18n("No directory selected")); return; } QDir dir (mailDir); QStringList files = dir.entryList("*.[dDmM][bB][xX]", QDir::Files, QDir::Name); if (files.isEmpty()) { info->alert(i18n("No Outlook Express mailboxes found in directory %1").arg(mailDir)); return; } totalFiles = files.count(); currentFile = 0; inf->overall(0); int n=0; for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile ) { importMailBox(dir.filePath(*mailFile)); inf->overall(100 * ++n / files.count()); } inf->overall(100); inf->current(100); inf->log(i18n("Finished importing Outlook Express emails")); } void FilterOE::importMailBox(const QString& fileName) { QFile mailfile(fileName); QFileInfo mailfileinfo(fileName); folderName = "OE-" + mailfileinfo.baseName(TRUE); inf->from(mailfileinfo.fileName()); inf->to(folderName); if (!mailfile.open(IO_ReadOnly)) { inf->log(i18n("Couldn't open mailbox %1").arg(fileName)); return; } QDataStream mailbox(&mailfile); mailbox.setByteOrder(QDataStream::LittleEndian); // Parse magic Q_UINT32 sig_block1, sig_block2; mailbox >> sig_block1 >> sig_block2; if (sig_block1 == OE4_SIG_1 && sig_block2 == OE4_SIG_2) { inf->log(i18n("Importing OE4 Mailbox %1").arg(fileName)); mbxImport(mailbox); return; } else { Q_UINT32 sig_block3, sig_block4; mailbox >> sig_block3 >> sig_block4; if (sig_block1 == OE5_SIG_1 && sig_block3 == OE5_SIG_3 && sig_block4 == OE5_SIG_4) { if (sig_block2 == OE5_EMAIL_SIG_2) { inf->log(i18n("Importing OE5+ Mailbox %1").arg(fileName)); dbxImport(mailbox); return; } else if (sig_block2 == OE5_FOLDER_SIG_2) { inf->log(i18n("Ignoring OE5+ Folder file %1").arg(fileName)); return; } } } inf->log(i18n("File %1 doesn't seem to be an Outlook Express mailbox").arg(fileName)); } /* ------------------- MBX support ------------------- */ void FilterOE::mbxImport(QDataStream& ds) { Q_UINT32 msgCount, lastMsgNum, fileSize; // Read the header ds >> msgCount >> lastMsgNum >> fileSize; ds.device()->at( ds.device()->at() + 64 ); // Skip 0's kdDebug() << "This mailbox has " << msgCount << " messages" << endl; if (msgCount == 0) return; // Don't import empty mailbox Q_UINT32 msgMagic; ds >> msgMagic; // Read first magic while (!ds.atEnd()) { Q_UINT32 msgNumber, msgSize, msgTextSize; KTempFile tmp; tmp.dataStream()->setByteOrder(QDataStream::LittleEndian); // Read the messages ds >> msgNumber >> msgSize >> msgTextSize; // All seem to be lies...? do { ds >> msgMagic; if (msgMagic != MBX_MAILMAGIC) *tmp.dataStream() << msgMagic; else break; } while ( !ds.atEnd() ); tmp.close(); addMessage(inf, folderName, tmp.name()); tmp.unlink(); } } /* ------------------- DBX support ------------------- */ void FilterOE::dbxImport(QDataStream& ds) { // Get item count & offset of index Q_UINT32 itemCount, indexPtr; ds.device()->at(0xc4); ds >> itemCount; ds.device()->at(0xe4); ds >> indexPtr; kdDebug() << "Item count is " << itemCount << ", Index at " << indexPtr << endl; if (itemCount == 0) return; // Empty file totalEmails = itemCount; currentEmail = 0; // Parse the indexes ds.device()->at(indexPtr); dbxReadIndex(ds, indexPtr); } void FilterOE::dbxReadIndex(QDataStream& ds, int filePos) { Q_UINT32 self, unknown, nextIndexPtr, parent, indexCount; Q_UINT8 unknown2, ptrCount; Q_UINT16 unknown3; int wasAt = ds.device()->at(); ds.device()->at(filePos); kdDebug() << "Reading index of file " << folderName << endl; ds >> self >> unknown >> nextIndexPtr >> parent >> unknown2 >> ptrCount >> unknown3 >> indexCount; // _dbx_tableindexstruct if (indexCount > 0) { // deal with nextTablePtr kdDebug() << "Recuring to next table @ " << nextIndexPtr << endl; dbxReadIndex(ds, nextIndexPtr); } kdDebug() << "This index has " << (int) ptrCount << " data pointers" << endl; for (int count = 0; count < ptrCount; count++) { Q_UINT32 dataIndexPtr, anotherIndexPtr, anotherIndexCount; // _dbx_indexstruct ds >> dataIndexPtr >> anotherIndexPtr >> anotherIndexCount; if (anotherIndexCount > 0) { kdDebug() << "Recursing to another table @ " << anotherIndexPtr << endl; dbxReadIndex(ds, anotherIndexPtr); } kdDebug() << "Data index @ " << dataIndexPtr << endl; dbxReadDataBlock(ds, dataIndexPtr); } ds.device()->at(wasAt); // Restore file position to same as when function called } void FilterOE::dbxReadDataBlock(QDataStream& ds, int filePos) { Q_UINT32 curOffset, blockSize; Q_UINT16 unknown; Q_UINT8 count, unknown2; int wasAt = ds.device()->at(); ds.device()->at(filePos); ds >> curOffset >> blockSize >> unknown >> count >> unknown2; // _dbx_email_headerstruct kdDebug() << "Data block has " << (int) count << " elements" << endl; for (int c = 0; c < count; c++) { Q_UINT8 type; // _dbx_email_pointerstruct Q_UINT32 value; // Actually 24 bit ds >> type >> value; value &= 0xffffff; ds.device()->at(ds.device()->at() - 1); // We only wanted 3 bytes if (type == 0x84) { // It's an email! kdDebug() << "**** Offset of emaildata " << value << " ****" << endl; dbxReadEmail(ds, value); } } ds.device()->at(wasAt); // Restore file position to same as when function called } void FilterOE::dbxReadEmail(QDataStream& ds, int filePos) { Q_UINT32 self, nextAddressOffset, nextAddress=0; Q_UINT16 blockSize; Q_UINT8 intCount, unknown; KTempFile tmp; int wasAt = ds.device()->at(); ds.device()->at(filePos); do { ds >> self >> nextAddressOffset >> blockSize >> intCount >> unknown >> nextAddress; // _dbx_block_hdrstruct QByteArray blockBuffer(blockSize); ds.readRawBytes(blockBuffer.data(), blockSize); tmp.dataStream()->writeRawBytes(blockBuffer.data(), blockSize); ds.device()->at(nextAddress); } while (nextAddress != 0); tmp.close(); addMessage(inf, folderName, tmp.name()); inf->current( ++currentEmail / totalEmails * 100); tmp.unlink(); ds.device()->at(wasAt); } // vim: ts=2 sw=2 et
/*************************************************************************** filter_oe.cxx - Outlook Express mail import ------------------- begin : Sat Feb 1 2003 copyright : (C) 2003 by Laurence Anderson email : [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 filter was created by looking at libdbx & liboe #include <config.h> #include <klocale.h> #include <kfiledialog.h> #include <kdirlister.h> #include <qregexp.h> #include <libgen.h> #include <qdir.h> #include <qfile.h> #include <qdatastream.h> #include <ktempfile.h> #include <kdebug.h> #include "filter_oe.hxx" #define OE4_SIG_1 0x36464d4a #define OE4_SIG_2 0x00010003 #define OE5_SIG_1 0xfe12adcf #define OE5_EMAIL_SIG_2 0x6f74fdc5 #define OE5_FOLDER_SIG_2 0x6f74fdc6 #define OE5_SIG_3 0x11d1e366 #define OE5_SIG_4 0xc0004e9a #define MBX_MAILMAGIC 0x7F007F00 FilterOE::FilterOE() : Filter( i18n("Import Outlook Express Emails"), "Laurence Anderson", i18n("<p><b>New Outlook Express 4/5/6 import filter</b></p>" "<p>This is a new Outlook Express import filter, which fully supports versions 4 to 6.</p>" "<p>Outlook Express generally stores its mailboxes in C:\\Windows\\Application Data\\Identities\\<profilename>\\Microsoft\\Outlook Express</p>" "<p><b>Note:</b> Emails will be imported into folders named after the file they came from, prefixed with OE-</p>" )) { } FilterOE::~FilterOE() { } void FilterOE::import(FilterInfo *info) { inf = info; // Select directory containing plain text emails QString mailDir = KFileDialog::getExistingDirectory(QDir::homeDirPath(),inf->parent()); if (mailDir.isEmpty()) { // No directory selected info->alert(i18n("No directory selected")); return; } QDir dir (mailDir); QStringList files = dir.entryList("*.[dDmM][bB][xX]", QDir::Files, QDir::Name); if (files.isEmpty()) { info->alert(i18n("No Outlook Express mailboxes found in directory %1").arg(mailDir)); return; } totalFiles = files.count(); currentFile = 0; inf->overall(0); int n=0; for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile ) { importMailBox(dir.filePath(*mailFile)); inf->overall(100 * ++n / files.count()); } inf->overall(100); inf->current(100); inf->log(i18n("Finished importing Outlook Express emails")); } void FilterOE::importMailBox(const QString& fileName) { QFile mailfile(fileName); QFileInfo mailfileinfo(fileName); folderName = "OE-" + mailfileinfo.baseName(TRUE); inf->from(mailfileinfo.fileName()); inf->to(folderName); if (!mailfile.open(IO_ReadOnly)) { inf->log(i18n("Couldn't open mailbox %1").arg(fileName)); return; } QDataStream mailbox(&mailfile); mailbox.setByteOrder(QDataStream::LittleEndian); // Parse magic Q_UINT32 sig_block1, sig_block2; mailbox >> sig_block1 >> sig_block2; if (sig_block1 == OE4_SIG_1 && sig_block2 == OE4_SIG_2) { inf->log(i18n("Importing OE4 Mailbox %1").arg(fileName)); mbxImport(mailbox); return; } else { Q_UINT32 sig_block3, sig_block4; mailbox >> sig_block3 >> sig_block4; if (sig_block1 == OE5_SIG_1 && sig_block3 == OE5_SIG_3 && sig_block4 == OE5_SIG_4) { if (sig_block2 == OE5_EMAIL_SIG_2) { inf->log(i18n("Importing OE5+ Mailbox %1").arg(fileName)); dbxImport(mailbox); return; } else if (sig_block2 == OE5_FOLDER_SIG_2) { inf->log(i18n("Ignoring OE5+ Folder file %1").arg(fileName)); return; } } } inf->log(i18n("File %1 doesn't seem to be an Outlook Express mailbox").arg(fileName)); } /* ------------------- MBX support ------------------- */ void FilterOE::mbxImport(QDataStream& ds) { Q_UINT32 msgCount, lastMsgNum, fileSize; // Read the header ds >> msgCount >> lastMsgNum >> fileSize; ds.device()->at( ds.device()->at() + 64 ); // Skip 0's kdDebug() << "This mailbox has " << msgCount << " messages" << endl; if (msgCount == 0) return; // Don't import empty mailbox Q_UINT32 msgMagic; ds >> msgMagic; // Read first magic while (!ds.atEnd()) { Q_UINT32 msgNumber, msgSize, msgTextSize; KTempFile tmp; tmp.dataStream()->setByteOrder(QDataStream::LittleEndian); // Read the messages ds >> msgNumber >> msgSize >> msgTextSize; // All seem to be lies...? do { ds >> msgMagic; if (msgMagic != MBX_MAILMAGIC) *tmp.dataStream() << msgMagic; else break; } while ( !ds.atEnd() ); tmp.close(); addMessage(inf, folderName, tmp.name()); tmp.unlink(); } } /* ------------------- DBX support ------------------- */ void FilterOE::dbxImport(QDataStream& ds) { // Get item count & offset of index Q_UINT32 itemCount, indexPtr; ds.device()->at(0xc4); ds >> itemCount; ds.device()->at(0xe4); ds >> indexPtr; kdDebug() << "Item count is " << itemCount << ", Index at " << indexPtr << endl; if (itemCount == 0) return; // Empty file totalEmails = itemCount; currentEmail = 0; // Parse the indexes ds.device()->at(indexPtr); dbxReadIndex(ds, indexPtr); } void FilterOE::dbxReadIndex(QDataStream& ds, int filePos) { Q_UINT32 self, unknown, nextIndexPtr, parent, indexCount; Q_UINT8 unknown2, ptrCount; Q_UINT16 unknown3; int wasAt = ds.device()->at(); ds.device()->at(filePos); kdDebug() << "Reading index of file " << folderName << endl; ds >> self >> unknown >> nextIndexPtr >> parent >> unknown2 >> ptrCount >> unknown3 >> indexCount; // _dbx_tableindexstruct if (indexCount > 0) { // deal with nextTablePtr kdDebug() << "Recuring to next table @ " << nextIndexPtr << endl; dbxReadIndex(ds, nextIndexPtr); } kdDebug() << "This index has " << (int) ptrCount << " data pointers" << endl; for (int count = 0; count < ptrCount; count++) { Q_UINT32 dataIndexPtr, anotherIndexPtr, anotherIndexCount; // _dbx_indexstruct ds >> dataIndexPtr >> anotherIndexPtr >> anotherIndexCount; if (anotherIndexCount > 0) { kdDebug() << "Recursing to another table @ " << anotherIndexPtr << endl; dbxReadIndex(ds, anotherIndexPtr); } kdDebug() << "Data index @ " << dataIndexPtr << endl; dbxReadDataBlock(ds, dataIndexPtr); } ds.device()->at(wasAt); // Restore file position to same as when function called } void FilterOE::dbxReadDataBlock(QDataStream& ds, int filePos) { Q_UINT32 curOffset, blockSize; Q_UINT16 unknown; Q_UINT8 count, unknown2; int wasAt = ds.device()->at(); ds.device()->at(filePos); ds >> curOffset >> blockSize >> unknown >> count >> unknown2; // _dbx_email_headerstruct kdDebug() << "Data block has " << (int) count << " elements" << endl; for (int c = 0; c < count; c++) { Q_UINT8 type; // _dbx_email_pointerstruct Q_UINT32 value; // Actually 24 bit ds >> type >> value; value &= 0xffffff; ds.device()->at(ds.device()->at() - 1); // We only wanted 3 bytes if (type == 0x84) { // It's an email! kdDebug() << "**** Offset of emaildata " << value << " ****" << endl; dbxReadEmail(ds, value); } } ds.device()->at(wasAt); // Restore file position to same as when function called } void FilterOE::dbxReadEmail(QDataStream& ds, int filePos) { Q_UINT32 self, nextAddressOffset, nextAddress=0; Q_UINT16 blockSize; Q_UINT8 intCount, unknown; KTempFile tmp; int wasAt = ds.device()->at(); ds.device()->at(filePos); do { ds >> self >> nextAddressOffset >> blockSize >> intCount >> unknown >> nextAddress; // _dbx_block_hdrstruct QByteArray blockBuffer(blockSize); ds.readRawBytes(blockBuffer.data(), blockSize); tmp.dataStream()->writeRawBytes(blockBuffer.data(), blockSize); ds.device()->at(nextAddress); } while (nextAddress != 0); tmp.close(); addMessage(inf, folderName, tmp.name()); inf->current( ++currentEmail / totalEmails * 100); tmp.unlink(); ds.device()->at(wasAt); } // vim: ts=2 sw=2 et
Fix description
Fix description svn path=/trunk/kdepim/; revision=204887
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
bb3175cfca7f2064b3bf075aa429f92c2474f430
src/CheckpointOutput.cpp
src/CheckpointOutput.cpp
/******************************************************************************* GPU OPTIMIZED MONTE CARLO (GOMC) 2.70 Copyright (C) 2018 GOMC Group A copy of the GNU General Public License can be found in the COPYRIGHT.txt along with this program, also can be found at <http://www.gnu.org/licenses/>. ********************************************************************************/ #include <stdint.h> #include "CheckpointOutput.h" #include "MoleculeLookup.h" #include "System.h" #include "GOMC_Config.h" #include "Endian.h" namespace { union dbl_output_union { char bin_value[8]; double dbl_value; }; union uint32_output_union { char bin_value[4]; uint32_t uint_value; }; union uint64_output_union { char bin_value[8]; uint64_t uint_value; }; union int8_input_union { char bin_value[1]; int8_t int_value; }; } CheckpointOutput::CheckpointOutput(System & sys, StaticVals const& statV) : moveSetRef(sys.moveSettings), molLookupRef(sys.molLookupRef), boxDimRef(sys.boxDimRef), molRef(statV.mol), prngRef(sys.prng), coordCurrRef(sys.coordinates), #if GOMC_LIB_MPI prngPTRef(*sys.prngParallelTemp), enableParallelTempering(sys.ms->parallelTemperingEnabled) #else enableParallelTempering(false) #endif { outputFile = NULL; } void CheckpointOutput::Init(pdb_setup::Atoms const& atoms, config_setup::Output const& output) { enableOutCheckpoint = output.restart_dcd.settings.enable; stepsPerCheckpoint = output.restart_dcd.settings.frequency; std::string file = output.statistics.settings.uniqueStr.val + "_restart.chk"; #if GOMC_LIB_MPI filename = pathToReplicaOutputDirectory + file; #else filename = file; #endif } void CheckpointOutput::DoOutput(const ulong step) { if(enableOutCheckpoint) { std::cout << "Writing checkpoint to file " << filename << " at step " << step << "\n"; openOutputFile(); printGOMCVersion(); printStepNumber(step); printRandomNumbers(); printMoleculeLookupData(); printMoveSettingsData(); #if GOMC_LIB_MPI printParallelTemperingBoolean(); if(enableParallelTempering) printRandomNumbersParallelTempering(); #endif std::cout << "Checkpoint saved to " << filename << std::endl; } } void CheckpointOutput::setGOMCVersion() { sprintf(gomc_version, "%d.%02d\0", GOMC_VERSION_MAJOR, GOMC_VERSION_MINOR % 100); } void CheckpointOutput::printGOMCVersion() { setGOMCVersion(); fprintf(outputFile, "%c%s%c", '$', gomc_version, '$'); } void CheckpointOutput::printParallelTemperingBoolean() { int8_t s = (int8_t) enableParallelTempering; write_uint8_binary(s); } void CheckpointOutput::printStepNumber(const ulong step) { write_uint64_binary(step+1); } void CheckpointOutput::printBoxDimensionsData() { // print the number of boxes uint32_t totalBoxes = BOX_TOTAL; write_uint32_binary(totalBoxes); for(int b = 0; b < (int) totalBoxes; b++) { XYZ axis = boxDimRef.axis.Get(b); write_double_binary(axis.x); write_double_binary(axis.y); write_double_binary(axis.z); write_double_binary(boxDimRef.cosAngle[b][0]); write_double_binary(boxDimRef.cosAngle[b][1]); write_double_binary(boxDimRef.cosAngle[b][2]); } } void CheckpointOutput::printRandomNumbers() { // First let's save the state array inside prng // the length of the array is 624 // there is a save function inside MersenneTwister.h file // to read back we can use the load function const int N = 624; // The MT::save function also appends the "left" variable, // so need to allocate one more array element uint32_t* saveArray = new uint32_t[N + 1]; prngRef.GetGenerator()->save(saveArray); for(int i = 0; i < N; i++) { write_uint32_binary(saveArray[i]); } // Save the location of pointer in state uint32_t location = prngRef.GetGenerator()->pNext - prngRef.GetGenerator()->state; write_uint32_binary(location); // save the "left" value so we can restore it later write_uint32_binary(prngRef.GetGenerator()->left); // let's save seedValue just in case // not sure if that is used or not, or how important it is write_uint32_binary(prngRef.GetGenerator()->seedValue); delete[] saveArray; } #if GOMC_LIB_MPI void CheckpointOutput::printRandomNumbersParallelTempering() { // First let's save the state array inside prng // the length of the array is 624 // there is a save function inside MersenneTwister.h file // to read back we can use the load function const int N = 624; uint32_t* saveArray = new uint32_t[N]; prngPTRef.GetGenerator()->save(saveArray); for(int i = 0; i < N; i++) { write_uint32_binary(saveArray[i]); } // Save the location of pointer in state uint32_t location = prngPTRef.GetGenerator()->pNext - prngPTRef.GetGenerator()->state; write_uint32_binary(location); // save the "left" value so we can restore it later write_uint32_binary(prngPTRef.GetGenerator()->left); // let's save seedValue just in case // not sure if that is used or not, or how important it is write_uint32_binary(prngPTRef.GetGenerator()->seedValue); } #endif void CheckpointOutput::printCoordinates() { // first let's print the count uint32_t count = coordCurrRef.Count(); write_uint32_binary(count); // now let's print the coordinates one by one for(int i = 0; i < (int) count; i++) { write_double_binary(coordCurrRef[i].x); write_double_binary(coordCurrRef[i].y); write_double_binary(coordCurrRef[i].z); } } void CheckpointOutput::printMoleculeLookupData() { // print the size of molLookup array write_uint32_binary(molLookupRef.molLookupCount); // print the molLookup array itself for(int i = 0; i < (int) molLookupRef.molLookupCount; i++) { write_uint32_binary(molLookupRef.molLookup[i]); } // print the size of boxAndKindStart array write_uint32_binary(molLookupRef.boxAndKindStartCount); // print the BoxAndKindStart array for(int i = 0; i < (int) molLookupRef.boxAndKindStartCount; i++) { write_uint32_binary(molLookupRef.boxAndKindStart[i]); } // print numKinds write_uint32_binary(molLookupRef.numKinds); //print the size of fixedAtom array write_uint32_binary((uint)molLookupRef.fixedAtom.size()); //print the fixedAtom array itself for(int i = 0; i < (int) molLookupRef.fixedAtom.size(); i++) { write_uint32_binary(molLookupRef.fixedAtom[i]); } } void CheckpointOutput::printMoveSettingsData() { printVector3DDouble(moveSetRef.scale); printVector3DDouble(moveSetRef.acceptPercent); printVector3DUint(moveSetRef.accepted); printVector3DUint(moveSetRef.tries); printVector3DUint(moveSetRef.tempAccepted); printVector3DUint(moveSetRef.tempTries); printVector2DUint(moveSetRef.mp_tries); printVector2DUint(moveSetRef.mp_accepted); printVector1DDouble(moveSetRef.mp_t_max); printVector1DDouble(moveSetRef.mp_r_max); } void CheckpointOutput::printVector3DDouble(std::vector< std::vector< std::vector<double> > > data) { // print size of tempTries ulong size_x = data.size(); ulong size_y = data[0].size(); ulong size_z = data[0][0].size(); write_uint64_binary(size_x); write_uint64_binary(size_y); write_uint64_binary(size_z); printf("array size: %ld %ld %ld\n", size_x, size_y, size_z); // print tempTries array for(int i = 0; i < (int) size_x; i++) { for(int j = 0; j < (int) size_y; j++) { for(int k = 0; k < (int) size_z; k++) { write_double_binary(data[i][j][k]); } } } } void CheckpointOutput::printVector3DUint(std::vector< std::vector< std::vector<uint> > > data) { // print size of tempTries ulong size_x = data.size(); ulong size_y = data[0].size(); ulong size_z = data[0][0].size(); write_uint64_binary(size_x); write_uint64_binary(size_y); write_uint64_binary(size_z); // print tempTries array for(int i = 0; i < (int) size_x; i++) { for(int j = 0; j < (int) size_y; j++) { for(int k = 0; k < (int) size_z; k++) { write_uint32_binary(data[i][j][k]); } } } } void CheckpointOutput::printVector2DUint(std::vector< std::vector< uint > > data) { // print size of array ulong size_x = data.size(); ulong size_y = data[0].size(); write_uint64_binary(size_x); write_uint64_binary(size_y); // print array itself for(int i = 0; i < (int) size_x; i++) { for(int j = 0; j < (int) size_y; j++) { write_uint32_binary(data[i][j]); } } } void CheckpointOutput::printVector1DDouble(std::vector< double > data) { // print size of array ulong size_x = data.size(); write_uint64_binary(size_x); // print array itself for(int i = 0; i < (int) size_x; i++) { write_double_binary(data[i]); } } void CheckpointOutput::openOutputFile() { outputFile = fopen(filename.c_str(), "wb"); if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } } void CheckpointOutput::write_double_binary(double data) { if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } dbl_output_union temp; temp.dbl_value = data; fprintf(outputFile, "%c%c%c%c%c%c%c%c", temp.bin_value[0], temp.bin_value[1], temp.bin_value[2], temp.bin_value[3], temp.bin_value[4], temp.bin_value[5], temp.bin_value[6], temp.bin_value[7]); fflush(outputFile); } void CheckpointOutput::write_uint8_binary(int8_t data) { if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } int8_input_union temp; temp.int_value = data; fprintf(outputFile, "%c", temp.bin_value[0]); fflush(outputFile); } void CheckpointOutput::write_uint64_binary(uint64_t data) { if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } uint64_output_union temp; temp.uint_value = htof64(data); fprintf(outputFile, "%c%c%c%c%c%c%c%c", temp.bin_value[0], temp.bin_value[1], temp.bin_value[2], temp.bin_value[3], temp.bin_value[4], temp.bin_value[5], temp.bin_value[6], temp.bin_value[7]); fflush(outputFile); } void CheckpointOutput::write_uint32_binary(uint32_t data) { if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } uint32_output_union temp; temp.uint_value = htof32(data); fprintf(outputFile, "%c%c%c%c", temp.bin_value[0], temp.bin_value[1], temp.bin_value[2], temp.bin_value[3]); fflush(outputFile); }
/******************************************************************************* GPU OPTIMIZED MONTE CARLO (GOMC) 2.70 Copyright (C) 2018 GOMC Group A copy of the GNU General Public License can be found in the COPYRIGHT.txt along with this program, also can be found at <http://www.gnu.org/licenses/>. ********************************************************************************/ #include <stdint.h> #include "CheckpointOutput.h" #include "MoleculeLookup.h" #include "System.h" #include "GOMC_Config.h" #include "Endian.h" namespace { union dbl_output_union { char bin_value[8]; double dbl_value; }; union uint32_output_union { char bin_value[4]; uint32_t uint_value; }; union uint64_output_union { char bin_value[8]; uint64_t uint_value; }; union int8_input_union { char bin_value[1]; int8_t int_value; }; } CheckpointOutput::CheckpointOutput(System & sys, StaticVals const& statV) : moveSetRef(sys.moveSettings), molLookupRef(sys.molLookupRef), boxDimRef(sys.boxDimRef), molRef(statV.mol), prngRef(sys.prng), coordCurrRef(sys.coordinates), #if GOMC_LIB_MPI prngPTRef(*sys.prngParallelTemp), enableParallelTempering(sys.ms->parallelTemperingEnabled) #else enableParallelTempering(false) #endif { outputFile = NULL; } void CheckpointOutput::Init(pdb_setup::Atoms const& atoms, config_setup::Output const& output) { enableOutCheckpoint = output.restart_dcd.settings.enable; stepsPerCheckpoint = output.restart_dcd.settings.frequency; std::string file = output.statistics.settings.uniqueStr.val + "_restart.chk"; printf("%d, %d, %s\n", enableOutCheckpoint, stepsPerCheckpoint, file); #if GOMC_LIB_MPI filename = pathToReplicaOutputDirectory + file; #else filename = file; #endif } void CheckpointOutput::DoOutput(const ulong step) { if(enableOutCheckpoint) { std::cout << "Writing checkpoint to file " << filename << " at step " << step << "\n"; openOutputFile(); printGOMCVersion(); printStepNumber(step); printRandomNumbers(); printMoleculeLookupData(); printMoveSettingsData(); #if GOMC_LIB_MPI printParallelTemperingBoolean(); if(enableParallelTempering) printRandomNumbersParallelTempering(); #endif std::cout << "Checkpoint saved to " << filename << std::endl; } } void CheckpointOutput::setGOMCVersion() { sprintf(gomc_version, "%d.%02d\0", GOMC_VERSION_MAJOR, GOMC_VERSION_MINOR % 100); } void CheckpointOutput::printGOMCVersion() { setGOMCVersion(); fprintf(outputFile, "%c%s%c", '$', gomc_version, '$'); } void CheckpointOutput::printParallelTemperingBoolean() { int8_t s = (int8_t) enableParallelTempering; write_uint8_binary(s); } void CheckpointOutput::printStepNumber(const ulong step) { write_uint64_binary(step+1); } void CheckpointOutput::printBoxDimensionsData() { // print the number of boxes uint32_t totalBoxes = BOX_TOTAL; write_uint32_binary(totalBoxes); for(int b = 0; b < (int) totalBoxes; b++) { XYZ axis = boxDimRef.axis.Get(b); write_double_binary(axis.x); write_double_binary(axis.y); write_double_binary(axis.z); write_double_binary(boxDimRef.cosAngle[b][0]); write_double_binary(boxDimRef.cosAngle[b][1]); write_double_binary(boxDimRef.cosAngle[b][2]); } } void CheckpointOutput::printRandomNumbers() { // First let's save the state array inside prng // the length of the array is 624 // there is a save function inside MersenneTwister.h file // to read back we can use the load function const int N = 624; // The MT::save function also appends the "left" variable, // so need to allocate one more array element uint32_t* saveArray = new uint32_t[N + 1]; prngRef.GetGenerator()->save(saveArray); for(int i = 0; i < N; i++) { write_uint32_binary(saveArray[i]); } // Save the location of pointer in state uint32_t location = prngRef.GetGenerator()->pNext - prngRef.GetGenerator()->state; write_uint32_binary(location); // save the "left" value so we can restore it later write_uint32_binary(prngRef.GetGenerator()->left); // let's save seedValue just in case // not sure if that is used or not, or how important it is write_uint32_binary(prngRef.GetGenerator()->seedValue); delete[] saveArray; } #if GOMC_LIB_MPI void CheckpointOutput::printRandomNumbersParallelTempering() { // First let's save the state array inside prng // the length of the array is 624 // there is a save function inside MersenneTwister.h file // to read back we can use the load function const int N = 624; uint32_t* saveArray = new uint32_t[N]; prngPTRef.GetGenerator()->save(saveArray); for(int i = 0; i < N; i++) { write_uint32_binary(saveArray[i]); } // Save the location of pointer in state uint32_t location = prngPTRef.GetGenerator()->pNext - prngPTRef.GetGenerator()->state; write_uint32_binary(location); // save the "left" value so we can restore it later write_uint32_binary(prngPTRef.GetGenerator()->left); // let's save seedValue just in case // not sure if that is used or not, or how important it is write_uint32_binary(prngPTRef.GetGenerator()->seedValue); } #endif void CheckpointOutput::printCoordinates() { // first let's print the count uint32_t count = coordCurrRef.Count(); write_uint32_binary(count); // now let's print the coordinates one by one for(int i = 0; i < (int) count; i++) { write_double_binary(coordCurrRef[i].x); write_double_binary(coordCurrRef[i].y); write_double_binary(coordCurrRef[i].z); } } void CheckpointOutput::printMoleculeLookupData() { // print the size of molLookup array write_uint32_binary(molLookupRef.molLookupCount); // print the molLookup array itself for(int i = 0; i < (int) molLookupRef.molLookupCount; i++) { write_uint32_binary(molLookupRef.molLookup[i]); } // print the size of boxAndKindStart array write_uint32_binary(molLookupRef.boxAndKindStartCount); // print the BoxAndKindStart array for(int i = 0; i < (int) molLookupRef.boxAndKindStartCount; i++) { write_uint32_binary(molLookupRef.boxAndKindStart[i]); } // print numKinds write_uint32_binary(molLookupRef.numKinds); //print the size of fixedAtom array write_uint32_binary((uint)molLookupRef.fixedAtom.size()); //print the fixedAtom array itself for(int i = 0; i < (int) molLookupRef.fixedAtom.size(); i++) { write_uint32_binary(molLookupRef.fixedAtom[i]); } } void CheckpointOutput::printMoveSettingsData() { printVector3DDouble(moveSetRef.scale); printVector3DDouble(moveSetRef.acceptPercent); printVector3DUint(moveSetRef.accepted); printVector3DUint(moveSetRef.tries); printVector3DUint(moveSetRef.tempAccepted); printVector3DUint(moveSetRef.tempTries); printVector2DUint(moveSetRef.mp_tries); printVector2DUint(moveSetRef.mp_accepted); printVector1DDouble(moveSetRef.mp_t_max); printVector1DDouble(moveSetRef.mp_r_max); } void CheckpointOutput::printVector3DDouble(std::vector< std::vector< std::vector<double> > > data) { // print size of tempTries ulong size_x = data.size(); ulong size_y = data[0].size(); ulong size_z = data[0][0].size(); write_uint64_binary(size_x); write_uint64_binary(size_y); write_uint64_binary(size_z); printf("array size: %ld %ld %ld\n", size_x, size_y, size_z); // print tempTries array for(int i = 0; i < (int) size_x; i++) { for(int j = 0; j < (int) size_y; j++) { for(int k = 0; k < (int) size_z; k++) { write_double_binary(data[i][j][k]); } } } } void CheckpointOutput::printVector3DUint(std::vector< std::vector< std::vector<uint> > > data) { // print size of tempTries ulong size_x = data.size(); ulong size_y = data[0].size(); ulong size_z = data[0][0].size(); write_uint64_binary(size_x); write_uint64_binary(size_y); write_uint64_binary(size_z); // print tempTries array for(int i = 0; i < (int) size_x; i++) { for(int j = 0; j < (int) size_y; j++) { for(int k = 0; k < (int) size_z; k++) { write_uint32_binary(data[i][j][k]); } } } } void CheckpointOutput::printVector2DUint(std::vector< std::vector< uint > > data) { // print size of array ulong size_x = data.size(); ulong size_y = data[0].size(); write_uint64_binary(size_x); write_uint64_binary(size_y); // print array itself for(int i = 0; i < (int) size_x; i++) { for(int j = 0; j < (int) size_y; j++) { write_uint32_binary(data[i][j]); } } } void CheckpointOutput::printVector1DDouble(std::vector< double > data) { // print size of array ulong size_x = data.size(); write_uint64_binary(size_x); // print array itself for(int i = 0; i < (int) size_x; i++) { write_double_binary(data[i]); } } void CheckpointOutput::openOutputFile() { outputFile = fopen(filename.c_str(), "wb"); if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } } void CheckpointOutput::write_double_binary(double data) { if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } dbl_output_union temp; temp.dbl_value = data; fprintf(outputFile, "%c%c%c%c%c%c%c%c", temp.bin_value[0], temp.bin_value[1], temp.bin_value[2], temp.bin_value[3], temp.bin_value[4], temp.bin_value[5], temp.bin_value[6], temp.bin_value[7]); fflush(outputFile); } void CheckpointOutput::write_uint8_binary(int8_t data) { if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } int8_input_union temp; temp.int_value = data; fprintf(outputFile, "%c", temp.bin_value[0]); fflush(outputFile); } void CheckpointOutput::write_uint64_binary(uint64_t data) { if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } uint64_output_union temp; temp.uint_value = htof64(data); fprintf(outputFile, "%c%c%c%c%c%c%c%c", temp.bin_value[0], temp.bin_value[1], temp.bin_value[2], temp.bin_value[3], temp.bin_value[4], temp.bin_value[5], temp.bin_value[6], temp.bin_value[7]); fflush(outputFile); } void CheckpointOutput::write_uint32_binary(uint32_t data) { if(outputFile == NULL) { fprintf(stderr, "Error opening checkpoint output file %s\n", filename.c_str()); exit(EXIT_FAILURE); } uint32_output_union temp; temp.uint_value = htof32(data); fprintf(outputFile, "%c%c%c%c", temp.bin_value[0], temp.bin_value[1], temp.bin_value[2], temp.bin_value[3]); fflush(outputFile); }
print enable, freq, and file
print enable, freq, and file
C++
mit
GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC
cfd15cc8c1c004dd5da9966c8bc191b26576f450
src/coins.cpp
src/coins.cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Copyright (c) 2015-2017 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coins.h" #include "consensus/consensus.h" #include "memusage.h" #include "random.h" #include "util.h" #include <assert.h> bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; } bool CCoinsView::HaveCoin(const COutPoint &outpoint) const { return false; } uint256 CCoinsView::GetBestBlock() const { return uint256(); } bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage) { return false; } CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; } CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { } bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); } bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); } uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); } void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; } bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage) { return base->BatchWrite(mapCoins, hashBlock, nChildCachedCoinsUsage); } CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); } size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); } SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {} CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {} size_t CCoinsViewCache::DynamicMemoryUsage() const { LOCK(cs_utxo); return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage; } size_t CCoinsViewCache::ResetCachedCoinUsage() const { LOCK(cs_utxo); size_t newCachedCoinsUsage = 0; for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) newCachedCoinsUsage += it->second.coin.DynamicMemoryUsage(); if (cachedCoinsUsage != newCachedCoinsUsage) { error("Resetting: cachedCoinsUsage has drifted - before %lld after %lld", cachedCoinsUsage, newCachedCoinsUsage); cachedCoinsUsage = newCachedCoinsUsage; } return newCachedCoinsUsage; } CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const { // requires cs_utxo CCoinsMap::iterator it = cacheCoins.find(outpoint); if (it != cacheCoins.end()) return it; Coin tmp; if (!base->GetCoin(outpoint, tmp)) return cacheCoins.end(); CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first; if (ret->second.coin.IsSpent()) { // The parent only has an empty entry for this outpoint; we can consider our // version as fresh. ret->second.flags = CCoinsCacheEntry::FRESH; } cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage(); return ret; } bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it != cacheCoins.end()) { coin = it->second.coin; return true; } return false; } void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) { assert(!coin.IsSpent()); if (coin.out.scriptPubKey.IsUnspendable()) return; CCoinsMap::iterator it; bool inserted; std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>()); bool fresh = false; if (!inserted) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); } if (!possible_overwrite) { if (!it->second.coin.IsSpent()) { throw std::logic_error("Adding new coin that replaces non-pruned entry"); } fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY); } it->second.coin = std::move(coin); it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0); cachedCoinsUsage += it->second.coin.DynamicMemoryUsage(); } void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight) { bool fCoinbase = tx.IsCoinBase(); const uint256& txid = tx.GetHash(); for (size_t i = 0; i < tx.vout.size(); ++i) { // Pass fCoinbase as the possible_overwrite flag to AddCoin, in order to correctly // deal with the pre-BIP30 occurrances of duplicate coinbase transactions. cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), fCoinbase); } } void CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) { CCoinsMap::iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) return; cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); if (moveout) { *moveout = std::move(it->second.coin); } if (it->second.flags & CCoinsCacheEntry::FRESH) { cacheCoins.erase(it); } else { it->second.flags |= CCoinsCacheEntry::DIRTY; it->second.coin.Clear(); } } static const Coin coinEmpty; const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) { return coinEmpty; } else { return it->second.coin; } } bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); return (it != cacheCoins.end() && !it->second.coin.IsSpent()); } bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = cacheCoins.find(outpoint); return it != cacheCoins.end(); } uint256 CCoinsViewCache::GetBestBlock() const { LOCK(cs_utxo); if (hashBlock.IsNull()) hashBlock = base->GetBestBlock(); return hashBlock; } void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) { LOCK(cs_utxo); hashBlock = hashBlockIn; } bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn, size_t &nChildCachedCoinsUsage) { LOCK(cs_utxo); for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization). // Update usage of the chile cache before we do any swapping and deleting nChildCachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); CCoinsMap::iterator itUs = cacheCoins.find(it->first); if (itUs == cacheCoins.end()) { // The parent cache does not have an entry, while the child does // We can ignore it if it's both FRESH and pruned in the child if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) { // Otherwise we will need to create it in the parent // and move the data up and mark it as dirty CCoinsCacheEntry& entry = cacheCoins[it->first]; entry.coin = std::move(it->second.coin); cachedCoinsUsage += entry.coin.DynamicMemoryUsage(); entry.flags = CCoinsCacheEntry::DIRTY; // We can mark it FRESH in the parent if it was FRESH in the child // Otherwise it might have just been flushed from the parent's cache // and already exist in the grandparent if (it->second.flags & CCoinsCacheEntry::FRESH) entry.flags |= CCoinsCacheEntry::FRESH; } } else { // Assert that the child cache entry was not marked FRESH if the // parent cache entry has unspent outputs. If this ever happens, // it means the FRESH flag was misapplied and there is a logic // error in the calling code. if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs"); // Found the entry in the parent cache if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) { // The grandparent does not have an entry, and the child is // modified and being pruned. This means we can just delete // it from the parent. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); cacheCoins.erase(itUs); } else { // A normal modification. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); itUs->second.coin = std::move(it->second.coin); cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage(); itUs->second.flags |= CCoinsCacheEntry::DIRTY; } } CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } else it++; } hashBlock = hashBlockIn; return true; } bool CCoinsViewCache::Flush() { LOCK(cs_utxo); bool fOk = base->BatchWrite(cacheCoins, hashBlock, cachedCoinsUsage); return fOk; } void CCoinsViewCache::Trim(size_t nTrimSize) const { uint64_t nTrimmed = 0; LOCK(cs_utxo); CCoinsMap::iterator iter = cacheCoins.begin(); while (DynamicMemoryUsage() > nTrimSize) { if (iter == cacheCoins.end()) break; // Only erase entries that have not been modified if (iter->second.flags == 0) { cachedCoinsUsage -= iter->second.coin.DynamicMemoryUsage(); CCoinsMap::iterator itOld = iter++; cacheCoins.erase(itOld); nTrimmed++; } else iter++; } if (nTrimmed > 0) LogPrint("coindb", "Trimmed %ld from the CoinsViewCache, current size after trim: %ld and usage %ld bytes\n", nTrimmed, cacheCoins.size(), cachedCoinsUsage); } void CCoinsViewCache::Uncache(const COutPoint& hash) { LOCK(cs_utxo); CCoinsMap::iterator it = cacheCoins.find(hash); if (it != cacheCoins.end() && it->second.flags == 0) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); cacheCoins.erase(it); } } unsigned int CCoinsViewCache::GetCacheSize() const { LOCK(cs_utxo); return cacheCoins.size(); } CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const { LOCK(cs_utxo); if (tx.IsCoinBase()) return 0; CAmount nResult = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) nResult += AccessCoin(tx.vin[i].prevout).out.nValue; return nResult; } bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const { LOCK(cs_utxo); if (!tx.IsCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!HaveCoin(tx.vin[i].prevout)) { return false; } } } return true; } double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const { LOCK(cs_utxo); inChainInputValue = 0; if (tx.IsCoinBase()) return 0.0; double dResult = 0.0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { const Coin &coin = AccessCoin(txin.prevout); if (coin.IsSpent()) continue; if (coin.nHeight <= nHeight) { dResult += coin.out.nValue * (nHeight-coin.nHeight); inChainInputValue += coin.out.nValue; } } return tx.ComputePriority(dResult); } CCoinsViewCursor::~CCoinsViewCursor() { } static const size_t nMaxOutputsPerBlock = DEFAULT_LARGEST_TRANSACTION / ::GetSerializeSize(CTxOut(), SER_NETWORK, PROTOCOL_VERSION); const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid) { COutPoint iter(txid, 0); while (iter.n < nMaxOutputsPerBlock) { const Coin& alternate = view.AccessCoin(iter); if (!alternate.IsSpent()) return alternate; ++iter.n; } return coinEmpty; }
// Copyright (c) 2012-2015 The Bitcoin Core developers // Copyright (c) 2015-2017 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coins.h" #include "consensus/consensus.h" #include "memusage.h" #include "random.h" #include "util.h" #include <assert.h> bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; } bool CCoinsView::HaveCoin(const COutPoint &outpoint) const { return false; } uint256 CCoinsView::GetBestBlock() const { return uint256(); } bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage) { return false; } CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; } CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { } bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); } bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); } uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); } void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; } bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, size_t &nChildCachedCoinsUsage) { return base->BatchWrite(mapCoins, hashBlock, nChildCachedCoinsUsage); } CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); } size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); } SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {} CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {} size_t CCoinsViewCache::DynamicMemoryUsage() const { LOCK(cs_utxo); return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage; } size_t CCoinsViewCache::ResetCachedCoinUsage() const { LOCK(cs_utxo); size_t newCachedCoinsUsage = 0; for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) newCachedCoinsUsage += it->second.coin.DynamicMemoryUsage(); if (cachedCoinsUsage != newCachedCoinsUsage) { error("Resetting: cachedCoinsUsage has drifted - before %lld after %lld", cachedCoinsUsage, newCachedCoinsUsage); cachedCoinsUsage = newCachedCoinsUsage; } return newCachedCoinsUsage; } CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const { AssertLockHeld(cs_utxo); CCoinsMap::iterator it = cacheCoins.find(outpoint); if (it != cacheCoins.end()) return it; Coin tmp; if (!base->GetCoin(outpoint, tmp)) return cacheCoins.end(); CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first; if (ret->second.coin.IsSpent()) { // The parent only has an empty entry for this outpoint; we can consider our // version as fresh. ret->second.flags = CCoinsCacheEntry::FRESH; } cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage(); return ret; } bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const { LOCK(cs_utxo); CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it != cacheCoins.end()) { coin = it->second.coin; return true; } return false; } void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) { LOCK(cs_utxo); assert(!coin.IsSpent()); if (coin.out.scriptPubKey.IsUnspendable()) return; CCoinsMap::iterator it; bool inserted; std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>()); bool fresh = false; if (!inserted) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); } if (!possible_overwrite) { if (!it->second.coin.IsSpent()) { throw std::logic_error("Adding new coin that replaces non-pruned entry"); } fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY); } it->second.coin = std::move(coin); it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0); cachedCoinsUsage += it->second.coin.DynamicMemoryUsage(); } void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight) { bool fCoinbase = tx.IsCoinBase(); const uint256& txid = tx.GetHash(); for (size_t i = 0; i < tx.vout.size(); ++i) { // Pass fCoinbase as the possible_overwrite flag to AddCoin, in order to correctly // deal with the pre-BIP30 occurrances of duplicate coinbase transactions. cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), fCoinbase); } } void CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) { LOCK(cs_utxo); CCoinsMap::iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) return; cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); if (moveout) { *moveout = std::move(it->second.coin); } if (it->second.flags & CCoinsCacheEntry::FRESH) { cacheCoins.erase(it); } else { it->second.flags |= CCoinsCacheEntry::DIRTY; it->second.coin.Clear(); } } static const Coin coinEmpty; const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const { LOCK(cs_utxo); CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) { return coinEmpty; } else { return it->second.coin; } } bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const { LOCK(cs_utxo); CCoinsMap::const_iterator it = FetchCoin(outpoint); return (it != cacheCoins.end() && !it->second.coin.IsSpent()); } bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const { LOCK(cs_utxo); CCoinsMap::const_iterator it = cacheCoins.find(outpoint); return it != cacheCoins.end(); } uint256 CCoinsViewCache::GetBestBlock() const { LOCK(cs_utxo); if (hashBlock.IsNull()) hashBlock = base->GetBestBlock(); return hashBlock; } void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) { LOCK(cs_utxo); hashBlock = hashBlockIn; } bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn, size_t &nChildCachedCoinsUsage) { LOCK(cs_utxo); for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization). // Update usage of the chile cache before we do any swapping and deleting nChildCachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); CCoinsMap::iterator itUs = cacheCoins.find(it->first); if (itUs == cacheCoins.end()) { // The parent cache does not have an entry, while the child does // We can ignore it if it's both FRESH and pruned in the child if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) { // Otherwise we will need to create it in the parent // and move the data up and mark it as dirty CCoinsCacheEntry& entry = cacheCoins[it->first]; entry.coin = std::move(it->second.coin); cachedCoinsUsage += entry.coin.DynamicMemoryUsage(); entry.flags = CCoinsCacheEntry::DIRTY; // We can mark it FRESH in the parent if it was FRESH in the child // Otherwise it might have just been flushed from the parent's cache // and already exist in the grandparent if (it->second.flags & CCoinsCacheEntry::FRESH) entry.flags |= CCoinsCacheEntry::FRESH; } } else { // Assert that the child cache entry was not marked FRESH if the // parent cache entry has unspent outputs. If this ever happens, // it means the FRESH flag was misapplied and there is a logic // error in the calling code. if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs"); // Found the entry in the parent cache if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) { // The grandparent does not have an entry, and the child is // modified and being pruned. This means we can just delete // it from the parent. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); cacheCoins.erase(itUs); } else { // A normal modification. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); itUs->second.coin = std::move(it->second.coin); cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage(); itUs->second.flags |= CCoinsCacheEntry::DIRTY; } } CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } else it++; } hashBlock = hashBlockIn; return true; } bool CCoinsViewCache::Flush() { LOCK(cs_utxo); bool fOk = base->BatchWrite(cacheCoins, hashBlock, cachedCoinsUsage); return fOk; } void CCoinsViewCache::Trim(size_t nTrimSize) const { uint64_t nTrimmed = 0; LOCK(cs_utxo); CCoinsMap::iterator iter = cacheCoins.begin(); while (DynamicMemoryUsage() > nTrimSize) { if (iter == cacheCoins.end()) break; // Only erase entries that have not been modified if (iter->second.flags == 0) { cachedCoinsUsage -= iter->second.coin.DynamicMemoryUsage(); CCoinsMap::iterator itOld = iter++; cacheCoins.erase(itOld); nTrimmed++; } else iter++; } if (nTrimmed > 0) LogPrint("coindb", "Trimmed %ld from the CoinsViewCache, current size after trim: %ld and usage %ld bytes\n", nTrimmed, cacheCoins.size(), cachedCoinsUsage); } void CCoinsViewCache::Uncache(const COutPoint& hash) { LOCK(cs_utxo); CCoinsMap::iterator it = cacheCoins.find(hash); if (it != cacheCoins.end() && it->second.flags == 0) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); cacheCoins.erase(it); } } unsigned int CCoinsViewCache::GetCacheSize() const { LOCK(cs_utxo); return cacheCoins.size(); } CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const { LOCK(cs_utxo); if (tx.IsCoinBase()) return 0; CAmount nResult = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) nResult += AccessCoin(tx.vin[i].prevout).out.nValue; return nResult; } bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const { LOCK(cs_utxo); if (!tx.IsCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!HaveCoin(tx.vin[i].prevout)) { return false; } } } return true; } double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const { LOCK(cs_utxo); inChainInputValue = 0; if (tx.IsCoinBase()) return 0.0; double dResult = 0.0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { const Coin &coin = AccessCoin(txin.prevout); if (coin.IsSpent()) continue; if (coin.nHeight <= nHeight) { dResult += coin.out.nValue * (nHeight-coin.nHeight); inChainInputValue += coin.out.nValue; } } return tx.ComputePriority(dResult); } CCoinsViewCursor::~CCoinsViewCursor() { } static const size_t nMaxOutputsPerBlock = DEFAULT_LARGEST_TRANSACTION / ::GetSerializeSize(CTxOut(), SER_NETWORK, PROTOCOL_VERSION); const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid) { COutPoint iter(txid, 0); while (iter.n < nMaxOutputsPerBlock) { const Coin& alternate = view.AccessCoin(iter); if (!alternate.IsSpent()) return alternate; ++iter.n; } return coinEmpty; }
Add missing cs_utxo locks in coins.cpp
Add missing cs_utxo locks in coins.cpp
C++
mit
Bitcoin-com/BUcash,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Bitcoin-com/BUcash,Bitcoin-com/BUcash,BitcoinUnlimited/BitcoinUnlimited,Bitcoin-com/BUcash,BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Bitcoin-com/BUcash,Justaphf/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Bitcoin-com/BUcash,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited
db2fd9c0c3e5cad4c5a99497e226f3ec970cbcad
src/IceCompileServer.cpp
src/IceCompileServer.cpp
//===- subzero/src/IceCompileServer.cpp - Compile server ------------------===// // // The Subzero Code Generator // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// This file defines the basic commandline-based compile server. /// //===----------------------------------------------------------------------===// #include "IceCompileServer.h" #include "IceClFlags.h" #include "IceClFlagsExtra.h" #include "IceELFStreamer.h" #include "IceGlobalContext.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #include "llvm/Bitcode/NaCl/NaClBitcodeMungeUtils.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/StreamingMemoryObject.h" #pragma clang diagnostic pop #include <fstream> #include <iostream> #include <thread> namespace Ice { namespace { // Define a SmallVector backed buffer as a data stream, so that it can hold the // generated binary version of the textual bitcode in the input file. class TextDataStreamer : public llvm::DataStreamer { public: TextDataStreamer() = default; ~TextDataStreamer() final = default; static TextDataStreamer *create(const IceString &Filename, std::string *Err); size_t GetBytes(unsigned char *Buf, size_t Len) final; private: llvm::SmallVector<char, 1024> BitcodeBuffer; size_t Cursor = 0; }; TextDataStreamer *TextDataStreamer::create(const IceString &Filename, std::string *Err) { TextDataStreamer *Streamer = new TextDataStreamer(); llvm::raw_string_ostream ErrStrm(*Err); if (std::error_code EC = llvm::readNaClRecordTextAndBuildBitcode( Filename, Streamer->BitcodeBuffer, &ErrStrm)) { ErrStrm << EC.message(); ErrStrm.flush(); delete Streamer; return nullptr; } ErrStrm.flush(); return Streamer; } size_t TextDataStreamer::GetBytes(unsigned char *Buf, size_t Len) { if (Cursor >= BitcodeBuffer.size()) return 0; size_t Remaining = BitcodeBuffer.size(); Len = std::min(Len, Remaining); for (size_t i = 0; i < Len; ++i) Buf[i] = BitcodeBuffer[Cursor + i]; Cursor += Len; return Len; } std::unique_ptr<Ostream> makeStream(const IceString &Filename, std::error_code &EC) { if (Filename == "-") { return std::unique_ptr<Ostream>(new llvm::raw_os_ostream(std::cout)); } else { return std::unique_ptr<Ostream>( new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::F_None)); } } ErrorCodes getReturnValue(const Ice::ClFlagsExtra &Flags, ErrorCodes Val) { if (Flags.getAlwaysExitSuccess()) return EC_None; return Val; } } // end of anonymous namespace void CLCompileServer::run() { if (BuildDefs::dump()) { llvm::sys::PrintStackTraceOnErrorSignal(); } ClFlags::parseFlags(argc, argv); ClFlags Flags; ClFlagsExtra ExtraFlags; ClFlags::getParsedClFlags(Flags); ClFlags::getParsedClFlagsExtra(ExtraFlags); std::error_code EC; std::unique_ptr<Ostream> Ls = makeStream(ExtraFlags.getLogFilename(), EC); if (EC) { llvm::report_fatal_error("Unable to open log file"); } Ls->SetUnbuffered(); std::unique_ptr<Ostream> Os; std::unique_ptr<ELFStreamer> ELFStr; switch (Flags.getOutFileType()) { case FT_Elf: { if (ExtraFlags.getOutputFilename() == "-") { *Ls << "Error: writing binary ELF to stdout is unsupported\n"; return transferErrorCode(getReturnValue(ExtraFlags, Ice::EC_Args)); } std::unique_ptr<llvm::raw_fd_ostream> FdOs(new llvm::raw_fd_ostream( ExtraFlags.getOutputFilename(), EC, llvm::sys::fs::F_None)); if (EC) { *Ls << "Failed to open output file: " << ExtraFlags.getOutputFilename() << ":\n" << EC.message() << "\n"; return transferErrorCode(getReturnValue(ExtraFlags, Ice::EC_Args)); } ELFStr.reset(new ELFStreamer(*FdOs.get())); Os.reset(FdOs.release()); // NaCl sets st_blksize to 0, and LLVM uses that to pick the default // preferred buffer size. Set to something non-zero. Os->SetBufferSize(1 << 14); } break; case FT_Asm: case FT_Iasm: { Os = makeStream(ExtraFlags.getOutputFilename(), EC); if (EC) { *Ls << "Failed to open output file: " << ExtraFlags.getOutputFilename() << ":\n" << EC.message() << "\n"; return transferErrorCode(getReturnValue(ExtraFlags, Ice::EC_Args)); } Os->SetUnbuffered(); } break; } if (BuildDefs::minimal() && ExtraFlags.getBitcodeAsText()) llvm::report_fatal_error("Can't specify 'bitcode-as-text' flag in " "minimal build"); IceString StrError; std::unique_ptr<llvm::DataStreamer> InputStream( (!BuildDefs::minimal() && ExtraFlags.getBitcodeAsText()) ? TextDataStreamer::create(ExtraFlags.getIRFilename(), &StrError) : llvm::getDataFileStreamer(ExtraFlags.getIRFilename(), &StrError)); if (!StrError.empty() || !InputStream) { llvm::SMDiagnostic Err(ExtraFlags.getIRFilename(), llvm::SourceMgr::DK_Error, StrError); Err.print(ExtraFlags.getAppName().c_str(), *Ls); return transferErrorCode(getReturnValue(ExtraFlags, Ice::EC_Bitcode)); } Ctx.reset( new GlobalContext(Ls.get(), Os.get(), Ls.get(), ELFStr.get(), Flags)); if (Ctx->getFlags().getNumTranslationThreads() != 0) { std::thread CompileThread([this, &ExtraFlags, &InputStream]() { Ctx->initParserThread(); getCompiler().run(ExtraFlags, *Ctx.get(), std::move(InputStream)); }); CompileThread.join(); } else { getCompiler().run(ExtraFlags, *Ctx.get(), std::move(InputStream)); } transferErrorCode(getReturnValue( ExtraFlags, static_cast<ErrorCodes>(Ctx->getErrorStatus()->value()))); } } // end of namespace Ice
//===- subzero/src/IceCompileServer.cpp - Compile server ------------------===// // // The Subzero Code Generator // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// This file defines the basic commandline-based compile server. /// //===----------------------------------------------------------------------===// #include "IceCompileServer.h" #include "IceClFlags.h" #include "IceClFlagsExtra.h" #include "IceELFStreamer.h" #include "IceGlobalContext.h" #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #include "llvm/Bitcode/NaCl/NaClBitcodeMungeUtils.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/raw_os_ostream.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/StreamingMemoryObject.h" #pragma clang diagnostic pop #include <fstream> #include <iostream> #include <thread> namespace Ice { namespace { // Define a SmallVector backed buffer as a data stream, so that it can hold the // generated binary version of the textual bitcode in the input file. class TextDataStreamer : public llvm::DataStreamer { public: TextDataStreamer() = default; ~TextDataStreamer() final = default; static TextDataStreamer *create(const IceString &Filename, std::string *Err); size_t GetBytes(unsigned char *Buf, size_t Len) final; private: llvm::SmallVector<char, 1024> BitcodeBuffer; size_t Cursor = 0; }; TextDataStreamer *TextDataStreamer::create(const IceString &Filename, std::string *Err) { TextDataStreamer *Streamer = new TextDataStreamer(); llvm::raw_string_ostream ErrStrm(*Err); if (std::error_code EC = llvm::readNaClRecordTextAndBuildBitcode( Filename, Streamer->BitcodeBuffer, &ErrStrm)) { ErrStrm << EC.message(); ErrStrm.flush(); delete Streamer; return nullptr; } ErrStrm.flush(); return Streamer; } size_t TextDataStreamer::GetBytes(unsigned char *Buf, size_t Len) { if (Cursor >= BitcodeBuffer.size()) return 0; size_t Remaining = BitcodeBuffer.size(); Len = std::min(Len, Remaining); for (size_t i = 0; i < Len; ++i) Buf[i] = BitcodeBuffer[Cursor + i]; Cursor += Len; return Len; } std::unique_ptr<Ostream> makeStream(const IceString &Filename, std::error_code &EC) { if (Filename == "-") { return std::unique_ptr<Ostream>(new llvm::raw_os_ostream(std::cout)); } else { return std::unique_ptr<Ostream>( new llvm::raw_fd_ostream(Filename, EC, llvm::sys::fs::F_None)); } } ErrorCodes getReturnValue(const Ice::ClFlagsExtra &Flags, ErrorCodes Val) { if (Flags.getAlwaysExitSuccess()) return EC_None; return Val; } // Reports fatal error message, and then exits with success status 0. void reportFatalErrorThenExitSuccess(void * UserData, const std::string &Reason, bool GenCrashDag) { (void)UserData; (void)GenCrashDag; // Note: This code is (mostly) copied from llvm/lib/Support/ErrorHandling.cpp // Blast the result out to stderr. We don't try hard to make sure this // succeeds (e.g. handling EINTR) and we can't use errs() here because // raw ostreams can call report_fatal_error. llvm::SmallVector<char, 64> Buffer; llvm::raw_svector_ostream OS(Buffer); OS << "LLVM ERROR: " << Reason << "\n"; llvm::StringRef MessageStr = OS.str(); ssize_t written = ::write(2, MessageStr.data(), MessageStr.size()); (void)written; // If something went wrong, we deliberately just give up. // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. llvm::sys::RunInterruptHandlers(); exit(0); } } // end of anonymous namespace void CLCompileServer::run() { if (BuildDefs::dump()) { llvm::sys::PrintStackTraceOnErrorSignal(); } ClFlags::parseFlags(argc, argv); ClFlags Flags; ClFlagsExtra ExtraFlags; ClFlags::getParsedClFlags(Flags); ClFlags::getParsedClFlagsExtra(ExtraFlags); // Override report_fatal_error if we want to exit with 0 status. if (ExtraFlags.getAlwaysExitSuccess()) llvm::install_fatal_error_handler(reportFatalErrorThenExitSuccess, this); std::error_code EC; std::unique_ptr<Ostream> Ls = makeStream(ExtraFlags.getLogFilename(), EC); if (EC) { llvm::report_fatal_error("Unable to open log file"); } Ls->SetUnbuffered(); std::unique_ptr<Ostream> Os; std::unique_ptr<ELFStreamer> ELFStr; switch (Flags.getOutFileType()) { case FT_Elf: { if (ExtraFlags.getOutputFilename() == "-") { *Ls << "Error: writing binary ELF to stdout is unsupported\n"; return transferErrorCode(getReturnValue(ExtraFlags, Ice::EC_Args)); } std::unique_ptr<llvm::raw_fd_ostream> FdOs(new llvm::raw_fd_ostream( ExtraFlags.getOutputFilename(), EC, llvm::sys::fs::F_None)); if (EC) { *Ls << "Failed to open output file: " << ExtraFlags.getOutputFilename() << ":\n" << EC.message() << "\n"; return transferErrorCode(getReturnValue(ExtraFlags, Ice::EC_Args)); } ELFStr.reset(new ELFStreamer(*FdOs.get())); Os.reset(FdOs.release()); // NaCl sets st_blksize to 0, and LLVM uses that to pick the default // preferred buffer size. Set to something non-zero. Os->SetBufferSize(1 << 14); } break; case FT_Asm: case FT_Iasm: { Os = makeStream(ExtraFlags.getOutputFilename(), EC); if (EC) { *Ls << "Failed to open output file: " << ExtraFlags.getOutputFilename() << ":\n" << EC.message() << "\n"; return transferErrorCode(getReturnValue(ExtraFlags, Ice::EC_Args)); } Os->SetUnbuffered(); } break; } if (BuildDefs::minimal() && ExtraFlags.getBitcodeAsText()) llvm::report_fatal_error("Can't specify 'bitcode-as-text' flag in " "minimal build"); IceString StrError; std::unique_ptr<llvm::DataStreamer> InputStream( (!BuildDefs::minimal() && ExtraFlags.getBitcodeAsText()) ? TextDataStreamer::create(ExtraFlags.getIRFilename(), &StrError) : llvm::getDataFileStreamer(ExtraFlags.getIRFilename(), &StrError)); if (!StrError.empty() || !InputStream) { llvm::SMDiagnostic Err(ExtraFlags.getIRFilename(), llvm::SourceMgr::DK_Error, StrError); Err.print(ExtraFlags.getAppName().c_str(), *Ls); return transferErrorCode(getReturnValue(ExtraFlags, Ice::EC_Bitcode)); } Ctx.reset( new GlobalContext(Ls.get(), Os.get(), Ls.get(), ELFStr.get(), Flags)); if (Ctx->getFlags().getNumTranslationThreads() != 0) { std::thread CompileThread([this, &ExtraFlags, &InputStream]() { Ctx->initParserThread(); getCompiler().run(ExtraFlags, *Ctx.get(), std::move(InputStream)); }); CompileThread.join(); } else { getCompiler().run(ExtraFlags, *Ctx.get(), std::move(InputStream)); } transferErrorCode(getReturnValue( ExtraFlags, static_cast<ErrorCodes>(Ctx->getErrorStatus()->value()))); } } // end of namespace Ice
Fix pnacl-sz to return with staus 0 in report_fatal_error.
Fix pnacl-sz to return with staus 0 in report_fatal_error. Fixes pnacl-sz to return with exit status 0 in report_fatal_error, if command line flag --exit-status is specified. The importance of this is that it allows afl-fuzz to not report the mutation as a crash. In addition, afl-fuzz doesn't record crash paths in its search history. By returning success, afl-fuzz can continue to apply additional mutations to the bad input. This allows afl-fuzz to add errors that require multiple changes to occur on the input. BUG=None [email protected] Review URL: https://codereview.chromium.org/1382653002 .
C++
apache-2.0
bkaradzic/SwiftShader,bkaradzic/SwiftShader,google/swiftshader,bkaradzic/SwiftShader,bkaradzic/SwiftShader,google/swiftshader,bkaradzic/SwiftShader,google/swiftshader
d8ae4ccaaf704d78735deaeff8ddb8fb9b351229
test/ffi_tests.cc
test/ffi_tests.cc
#include <stdlib.h> #include "v8.h" #include "node.h" #include "node_buffer.h" using namespace v8; using namespace node; namespace { /* * Test struct definition used in the test harness functions below. */ typedef struct box { int width; int height; } _box; /* * Accepts a struct by value, and returns a struct by value. */ box double_box(box input) { box rtn; // modify the input box, ensure on the JS side that it's not altered input.width *= 2; input.height *= 2; rtn.width = input.width; rtn.height = input.height; return rtn; } /* * Accepts a box struct pointer, and returns a struct by value. */ box double_box_ptr(box *input) { box rtn; // modify the input box, ensure on the JS side that IT IS altered input->width *= 2; input->height *= 2; rtn.width = input->width; rtn.height = input->height; return rtn; } /* * Accepts a struct by value, and returns an int. */ int area_box(box input) { return input.width * input.height; } /* * Accepts a box pointer and returns an int. */ int area_box_ptr(box *input) { return input->width * input->height; } /* * Creates a box and returns it by value. */ box create_box(int width, int height) { box rtn = { width, height }; return rtn; } /* * Creates a box that has the sum of the width and height for its own values. */ box add_boxes(box boxes[], int num) { box rtn = { 0, 0 }; box cur; for (int i = 0; i < num; i++) { cur = boxes[i]; rtn.width += cur.width; rtn.height += cur.height; } return rtn; } /* * Reads "ints" from the "input" array until a NULL pointer is found. * Returns the number of elements in the array. */ int *int_array(int *input) { int *array = input; while (*array != -1){ *array = *array * 2; array++; } return input; } /* * Tests for passing a Struct that contains Arrays inside of it. */ struct arst { int num; double array[20]; }; struct arst array_in_struct (struct arst input) { struct arst rtn; rtn.num = input.num * 2; for (int i = 0; i < 20; i++) { rtn.array[i] = input.array[i] * 3.14; } return rtn; } /* * Tests for C function pointers. */ typedef int (*my_callback)(int); my_callback callback_func (my_callback cb) { return cb; } /* * Hard-coded `strtoul` binding, for the benchmarks. * * args[0] - the string number to convert to a real Number * args[1] - a "buffer" instance to write into (the "endptr") * args[2] - the base (0 means autodetect) */ Handle<Value> Strtoul(const Arguments &args) { HandleScope scope; char buf[128]; int base; char **endptr; args[0]->ToString()->WriteUtf8(buf); Local<Value> endptr_arg = args[0]; endptr = (char **)Buffer::Data(endptr_arg.As<Object>()); base = args[2]->Int32Value(); unsigned long val = strtoul(buf, endptr, base); return scope.Close(Integer::NewFromUnsigned(val)); } // experiments for #72 typedef void (*cb)(void); static cb callback = NULL; Handle<Value> SetCb(const Arguments &args) { HandleScope scope; char *buf = Buffer::Data(args[0].As<Object>()); callback = (cb)buf; return scope.Close(Undefined()); } Handle<Value> CallCb(const Arguments &args) { if (callback == NULL) { return ThrowException(Exception::Error(String::New("you must call \"set_cb()\" first"))); } else { callback(); } return Undefined(); } void AsyncCbCall(uv_work_t *req) { cb c = (cb)req->data; c(); } void FinishAsyncCbCall(uv_work_t *req) { // nothing delete req; } Handle<Value> CallCbAsync(const Arguments &args) { if (callback == NULL) { return ThrowException(Exception::Error(String::New("you must call \"set_cb()\" first"))); } else { uv_work_t *req = new uv_work_t; req->data = (void *)callback; uv_queue_work(uv_default_loop(), req, AsyncCbCall, FinishAsyncCbCall); } return Undefined(); } void wrap_pointer_cb(char *data, void *hint) { //fprintf(stderr, "wrap_pointer_cb\n"); } Handle<Object> WrapPointer(char *ptr) { void *user_data = NULL; size_t length = 0; Buffer *buf = Buffer::New(ptr, length, wrap_pointer_cb, user_data); return buf->handle_; } void Initialize(Handle<Object> target) { HandleScope scope; #if WIN32 // initialize "floating point support" on Windows?!?! // (this is some serious bullshit...) // http://support.microsoft.com/kb/37507 float x = 2.3f; #endif // atoi and abs here for testing purposes target->Set(String::NewSymbol("atoi"), WrapPointer((char *)atoi)); // Windows has multiple `abs` signatures, so we need to manually disambiguate int (*absPtr)(int)(abs); target->Set(String::NewSymbol("abs"), WrapPointer((char *)absPtr)); // sprintf pointer; used in the varadic tests target->Set(String::NewSymbol("sprintf"), WrapPointer((char *)sprintf)); // hard-coded `strtoul` binding, for the benchmarks NODE_SET_METHOD(target, "strtoul", Strtoul); NODE_SET_METHOD(target, "set_cb", SetCb); NODE_SET_METHOD(target, "call_cb", CallCb); NODE_SET_METHOD(target, "call_cb_async", CallCbAsync); // also need to test these custom functions target->Set(String::NewSymbol("double_box"), WrapPointer((char *)double_box)); target->Set(String::NewSymbol("double_box_ptr"), WrapPointer((char *)double_box_ptr)); target->Set(String::NewSymbol("area_box"), WrapPointer((char *)area_box)); target->Set(String::NewSymbol("area_box_ptr"), WrapPointer((char *)area_box_ptr)); target->Set(String::NewSymbol("create_box"), WrapPointer((char *)create_box)); target->Set(String::NewSymbol("add_boxes"), WrapPointer((char *)add_boxes)); target->Set(String::NewSymbol("int_array"), WrapPointer((char *)int_array)); target->Set(String::NewSymbol("array_in_struct"), WrapPointer((char *)array_in_struct)); target->Set(String::NewSymbol("callback_func"), WrapPointer((char *)callback_func)); } } // anonymous namespace NODE_MODULE(ffi_tests, Initialize);
#include <stdlib.h> #include "v8.h" #include "node.h" #include "node_buffer.h" using namespace v8; using namespace node; namespace { /* * Test struct definition used in the test harness functions below. */ typedef struct box { int width; int height; } _box; /* * Accepts a struct by value, and returns a struct by value. */ box double_box(box input) { box rtn; // modify the input box, ensure on the JS side that it's not altered input.width *= 2; input.height *= 2; rtn.width = input.width; rtn.height = input.height; return rtn; } /* * Accepts a box struct pointer, and returns a struct by value. */ box double_box_ptr(box *input) { box rtn; // modify the input box, ensure on the JS side that IT IS altered input->width *= 2; input->height *= 2; rtn.width = input->width; rtn.height = input->height; return rtn; } /* * Accepts a struct by value, and returns an int. */ int area_box(box input) { return input.width * input.height; } /* * Accepts a box pointer and returns an int. */ int area_box_ptr(box *input) { return input->width * input->height; } /* * Creates a box and returns it by value. */ box create_box(int width, int height) { box rtn = { width, height }; return rtn; } /* * Creates a box that has the sum of the width and height for its own values. */ box add_boxes(box boxes[], int num) { box rtn = { 0, 0 }; box cur; for (int i = 0; i < num; i++) { cur = boxes[i]; rtn.width += cur.width; rtn.height += cur.height; } return rtn; } /* * Reads "ints" from the "input" array until a NULL pointer is found. * Returns the number of elements in the array. */ int *int_array(int *input) { int *array = input; while (*array != -1){ *array = *array * 2; array++; } return input; } /* * Tests for passing a Struct that contains Arrays inside of it. */ struct arst { int num; double array[20]; }; struct arst array_in_struct (struct arst input) { struct arst rtn; rtn.num = input.num * 2; for (int i = 0; i < 20; i++) { rtn.array[i] = input.array[i] * 3.14; } return rtn; } /* * Tests for C function pointers. */ typedef int (*my_callback)(int); my_callback callback_func (my_callback cb) { return cb; } /* * Hard-coded `strtoul` binding, for the benchmarks. * * args[0] - the string number to convert to a real Number * args[1] - a "buffer" instance to write into (the "endptr") * args[2] - the base (0 means autodetect) */ Handle<Value> Strtoul(const Arguments &args) { HandleScope scope; char buf[128]; int base; char **endptr; args[0]->ToString()->WriteUtf8(buf); Local<Value> endptr_arg = args[0]; endptr = (char **)Buffer::Data(endptr_arg.As<Object>()); base = args[2]->Int32Value(); unsigned long val = strtoul(buf, endptr, base); return scope.Close(Integer::NewFromUnsigned(val)); } // experiments for #72 typedef void (*cb)(void); static cb callback = NULL; Handle<Value> SetCb(const Arguments &args) { HandleScope scope; char *buf = Buffer::Data(args[0].As<Object>()); callback = (cb)buf; return scope.Close(Undefined()); } Handle<Value> CallCb(const Arguments &args) { if (callback == NULL) { return ThrowException(Exception::Error(String::New("you must call \"set_cb()\" first"))); } else { callback(); } return Undefined(); } void AsyncCbCall(uv_work_t *req) { cb c = (cb)req->data; c(); } void FinishAsyncCbCall(uv_work_t *req) { // nothing delete req; } Handle<Value> CallCbAsync(const Arguments &args) { if (callback == NULL) { return ThrowException(Exception::Error(String::New("you must call \"set_cb()\" first"))); } else { uv_work_t *req = new uv_work_t; req->data = (void *)callback; uv_queue_work(uv_default_loop(), req, AsyncCbCall, (uv_after_work_cb)FinishAsyncCbCall); } return Undefined(); } void wrap_pointer_cb(char *data, void *hint) { //fprintf(stderr, "wrap_pointer_cb\n"); } Handle<Object> WrapPointer(char *ptr) { void *user_data = NULL; size_t length = 0; Buffer *buf = Buffer::New(ptr, length, wrap_pointer_cb, user_data); return buf->handle_; } void Initialize(Handle<Object> target) { HandleScope scope; #if WIN32 // initialize "floating point support" on Windows?!?! // (this is some serious bullshit...) // http://support.microsoft.com/kb/37507 float x = 2.3f; #endif // atoi and abs here for testing purposes target->Set(String::NewSymbol("atoi"), WrapPointer((char *)atoi)); // Windows has multiple `abs` signatures, so we need to manually disambiguate int (*absPtr)(int)(abs); target->Set(String::NewSymbol("abs"), WrapPointer((char *)absPtr)); // sprintf pointer; used in the varadic tests target->Set(String::NewSymbol("sprintf"), WrapPointer((char *)sprintf)); // hard-coded `strtoul` binding, for the benchmarks NODE_SET_METHOD(target, "strtoul", Strtoul); NODE_SET_METHOD(target, "set_cb", SetCb); NODE_SET_METHOD(target, "call_cb", CallCb); NODE_SET_METHOD(target, "call_cb_async", CallCbAsync); // also need to test these custom functions target->Set(String::NewSymbol("double_box"), WrapPointer((char *)double_box)); target->Set(String::NewSymbol("double_box_ptr"), WrapPointer((char *)double_box_ptr)); target->Set(String::NewSymbol("area_box"), WrapPointer((char *)area_box)); target->Set(String::NewSymbol("area_box_ptr"), WrapPointer((char *)area_box_ptr)); target->Set(String::NewSymbol("create_box"), WrapPointer((char *)create_box)); target->Set(String::NewSymbol("add_boxes"), WrapPointer((char *)add_boxes)); target->Set(String::NewSymbol("int_array"), WrapPointer((char *)int_array)); target->Set(String::NewSymbol("array_in_struct"), WrapPointer((char *)array_in_struct)); target->Set(String::NewSymbol("callback_func"), WrapPointer((char *)callback_func)); } } // anonymous namespace NODE_MODULE(ffi_tests, Initialize);
update ffi_tests.cc for node >= v0.9.4
update ffi_tests.cc for node >= v0.9.4
C++
mit
Icenium/node-ffi,node-ffi/node-ffi,paulcbetts/node-ffi,unbornchikken/node-ffi,craigcomstocks/node-ffi,unrealsolver/node-ffi,unbornchikken/node-ffi,skoky/node-ffi,lzpfmh/node-ffi,paulcbetts/node-ffi,unbornchikken/node-ffi,skoky/node-ffi,lzpfmh/node-ffi,node-ffi/node-ffi,node-ffi/node-ffi,skoky/node-ffi,paulcbetts/node-ffi,Icenium/node-ffi,pmuellr/node-ffi,paulcbetts/node-ffi,craigcomstocks/node-ffi,craigcomstocks/node-ffi,Icenium/node-ffi,unrealsolver/node-ffi,Icenium/node-ffi,pmuellr/node-ffi,node-ffi/node-ffi,pmuellr/node-ffi,craigcomstocks/node-ffi,unbornchikken/node-ffi,unrealsolver/node-ffi,lzpfmh/node-ffi,lzpfmh/node-ffi,skoky/node-ffi,unrealsolver/node-ffi,pmuellr/node-ffi
caf33a2d48b0887609e9fcbdc3cbe57c5308322a
include/forest.hpp
include/forest.hpp
#pragma once #include "data.hpp" #include "settings.hpp" #include "tree.hpp" #include "random.hpp" #include "Kabsch.hpp" #include <vector> #include <random> #include <ctime> #include <cstdint> #include <Eigen/Geometry> #include "opencv2/opencv.hpp" namespace ISUE { namespace RelocForests { class Forest { public: Forest(Data *data, Settings *settings) : data_(data), settings_(settings) { for (int i = 0; i < settings->num_trees_; ++i) forest_.push_back(new Tree()); random_ = new Random(); }; ~Forest() { delete random_; for (auto t : forest_) delete t; forest_.clear(); } void Train() { // train each tree individually int index = 1; for (auto t : forest_) { std::vector<LabeledPixel> labeled_data; std::cout << "[Tree " << index << "] " << "Generating Training Data.\n"; // randomly choose frames for (int i = 0; i < settings_->num_frames_per_tree_; ++i) { int curr_frame = random_->Next(0, data_->depth_names_.size()); // randomly sample pixels per frame for (int j = 0; j < settings_->num_pixels_per_frame_; ++j) { int row = random_->Next(0, settings_->image_height_); int col = random_->Next(0, settings_->image_width_); // calc label cv::Mat rgb_image = data_->GetRGBImage(curr_frame); cv::Mat depth_image = data_->GetDepthImage(curr_frame); float Z = (float)depth_image.at<ushort>(row, col) / (float)settings_->depth_factor_; float Y = (row - settings_->cy) * Z / settings_->fy; float X = (col - settings_->cx) * Z / settings_->fx; cv::Point3f label(X, Y, Z); // convert label to world coordinates CameraInfo pose = data_->poses_.at(curr_frame); cv::Mat R = pose.getRotation(); cv::Mat T = pose.getTranslation(); cv::Mat P(label, true); P.convertTo(P, CV_64FC2); // fix exception when doing operations with R, T cv::Mat C = R * P + T; label = cv::Point3f(C); // store labeled pixel LabeledPixel pixel(curr_frame, cv::Point2i(col, row), label); labeled_data.push_back(pixel); } } // train tree with set of pixels recursively std::cout << "[Tree " << index << "] " << "Training.\n"; std::clock_t start; double duration; start = std::clock(); t->Train(data_, labeled_data, random_, settings_); duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; std::cout << "[Tree " << index << "] " << "Train time: " << duration << " Seconds \n"; index++; } } std::vector<cv::Point3d> Eval(int row, int col, cv::Mat rgb_image, cv::Mat depth_image) { std::vector<cv::Point3d> modes; for (auto t : forest_) { auto m = t->Eval(row, col, rgb_image, depth_image); modes.insert(modes.end(), m.begin(), m.end()); } return modes; } CameraInfo Test(cv::Mat rgb_frame, cv::Mat depth_frame) { int K_init = 1024; int K = K_init; std::vector<Eigen::Affine3d> hypotheses; // sample initial hypotheses for (uint16_t i = 0; i < K_init; ++i) { // 3 points Eigen::Matrix3Xd input; Eigen::Matrix3Xd output; for (uint16_t j = 0; j < 3; ++j) { int col = random_->Next(0, settings_->image_width_); int row = random_->Next(0, settings_->image_height_); // todo: get camera space points? // add to input auto modes = Eval(row, col, rgb_frame, depth_frame); auto point = modes.at(random_->Next(0, modes.size() - 1)); // add point to output } // kabsch algorithm Eigen::Affine3d transform = Find3DAffineTransform(input, output); hypotheses.push_back(transform); } // init energies std::vector<uint32_t> energies (K, 0); while (K > 1) { // sample set of B test pixels std::vector<cv::Point2i> test_pixels; int batch_size = 500; // todo put in settings // sample points in test image for (int i = 0; i < batch_size; ++i) { int col = random_->Next(0, settings_->image_width_); int row = random_->Next(0, settings_->image_height_); test_pixels.push_back(cv::Point2i(col, row)); } for (auto p : test_pixels) { // evaluate forest to get modes (union) auto modes = Eval(p.y, p.x, rgb_frame, depth_frame); for (int i = 0; i < K; ++i) { // update energy // E_k <- E_k + e_i(H_K) } } // sort hypotheses K = K / 2; // refine hypotheses } // return best pose and energy } private: Data *data_; Settings *settings_; std::vector<Tree*> forest_; Random *random_; }; } }
#pragma once #include "data.hpp" #include "settings.hpp" #include "tree.hpp" #include "random.hpp" #include "Kabsch.hpp" #include <vector> #include <random> #include <ctime> #include <cstdint> #include <Eigen/Geometry> #include "opencv2/opencv.hpp" namespace ISUE { namespace RelocForests { class Forest { public: Forest(Data *data, Settings *settings) : data_(data), settings_(settings) { for (int i = 0; i < settings->num_trees_; ++i) forest_.push_back(new Tree()); random_ = new Random(); }; ~Forest() { delete random_; for (auto t : forest_) delete t; forest_.clear(); } void Train() { // train each tree individually int index = 1; for (auto t : forest_) { std::vector<LabeledPixel> labeled_data; std::cout << "[Tree " << index << "] " << "Generating Training Data.\n"; // randomly choose frames for (int i = 0; i < settings_->num_frames_per_tree_; ++i) { int curr_frame = random_->Next(0, data_->depth_names_.size()); // randomly sample pixels per frame for (int j = 0; j < settings_->num_pixels_per_frame_; ++j) { int row = random_->Next(0, settings_->image_height_); int col = random_->Next(0, settings_->image_width_); // calc label cv::Mat rgb_image = data_->GetRGBImage(curr_frame); cv::Mat depth_image = data_->GetDepthImage(curr_frame); float Z = (float)depth_image.at<ushort>(row, col) / (float)settings_->depth_factor_; float Y = (row - settings_->cy) * Z / settings_->fy; float X = (col - settings_->cx) * Z / settings_->fx; cv::Point3f label(X, Y, Z); // convert label to world coordinates CameraInfo pose = data_->poses_.at(curr_frame); cv::Mat R = pose.getRotation(); cv::Mat T = pose.getTranslation(); cv::Mat P(label, true); P.convertTo(P, CV_64FC2); // fix exception when doing operations with R, T cv::Mat C = R * P + T; label = cv::Point3f(C); // store labeled pixel LabeledPixel pixel(curr_frame, cv::Point2i(col, row), label); labeled_data.push_back(pixel); } } // train tree with set of pixels recursively std::cout << "[Tree " << index << "] " << "Training.\n"; std::clock_t start; double duration; start = std::clock(); t->Train(data_, labeled_data, random_, settings_); duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; std::cout << "[Tree " << index << "] " << "Train time: " << duration << " Seconds \n"; index++; } } std::vector<cv::Point3d> Eval(int row, int col, cv::Mat rgb_image, cv::Mat depth_image) { std::vector<cv::Point3d> modes; for (auto t : forest_) { auto m = t->Eval(row, col, rgb_image, depth_image); modes.insert(modes.end(), m.begin(), m.end()); } return modes; } CameraInfo Test(cv::Mat rgb_frame, cv::Mat depth_frame) { int K_init = 1024; int K = K_init; std::vector<Eigen::Affine3d> hypotheses; // sample initial hypotheses for (uint16_t i = 0; i < K_init; ++i) { // 3 points Eigen::Matrix3Xd input(3, 3); Eigen::Matrix3Xd output(3, 3); for (uint16_t j = 0; j < 3; ++j) { int col = random_->Next(0, settings_->image_width_); int row = random_->Next(0, settings_->image_height_); // todo: get camera space points? double Z = (float)depth_frame.at<ushort>(row, col) / (float)settings_->depth_factor_; double Y = (row - settings_->cy) * Z / settings_->fy; double X = (col - settings_->cx) * Z / settings_->fx; Eigen::Vector3d tmp_in(X, Y, Z); // add to input input << tmp_in; auto modes = Eval(row, col, rgb_frame, depth_frame); auto point = modes.at(random_->Next(0, modes.size() - 1)); // add point to output Eigen::Vector3d tmp_out(point.x, point.y, point.z); output << tmp_out; } // kabsch algorithm Eigen::Affine3d transform = Find3DAffineTransform(input, output); hypotheses.push_back(transform); } // init energies std::vector<uint32_t> energies (K, 0); while (K > 1) { // sample set of B test pixels std::vector<cv::Point2i> test_pixels; int batch_size = 500; // todo put in settings // sample points in test image for (int i = 0; i < batch_size; ++i) { int col = random_->Next(0, settings_->image_width_); int row = random_->Next(0, settings_->image_height_); test_pixels.push_back(cv::Point2i(col, row)); } for (auto p : test_pixels) { // evaluate forest to get modes (union) auto modes = Eval(p.y, p.x, rgb_frame, depth_frame); for (int i = 0; i < K; ++i) { // update energy // E_k <- E_k + e_i(H_K) } } // sort hypotheses K = K / 2; // refine hypotheses } // return best pose and energy } private: Data *data_; Settings *settings_; std::vector<Tree*> forest_; Random *random_; }; } }
Put points in matrices.
Put points in matrices.
C++
mit
ISUE/relocforests
a39504a2d149e2c6fe18ef82bfdd722b7d77712a
indra/llcorehttp/examples/http_texture_load.cpp
indra/llcorehttp/examples/http_texture_load.cpp
/** * @file http_texture_load.cpp * @brief Texture download example for core-http library * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include <iostream> #include <cstdio> #include <cstdlib> #include <set> #include <map> #if !defined(WIN32) #include <pthread.h> #endif #include "httpcommon.h" #include "httprequest.h" #include "httphandler.h" #include "httpresponse.h" #include "bufferarray.h" #include "_mutex.h" #include <curl/curl.h> #include <openssl/crypto.h> void init_curl(); void term_curl(); unsigned long ssl_thread_id_callback(void); void ssl_locking_callback(int mode, int type, const char * file, int line); void usage(std::ostream & out); // Default command line settings static int concurrency_limit(40); static char url_format[1024] = "http://example.com/some/path?texture_id=%s.texture"; #if defined(WIN32) #define strncpy(_a, _b, _c) strncpy_s(_a, _b, _c) #define strtok_r(_a, _b, _c) strtok_s(_a, _b, _c) int getopt(int argc, char * const argv[], const char *optstring); char *optarg(NULL); int optind(1); #endif class WorkingSet : public LLCore::HttpHandler { public: WorkingSet(); bool reload(LLCore::HttpRequest *); virtual void onCompleted(LLCore::HttpHandle handle, LLCore::HttpResponse * response); void loadTextureUuids(FILE * in); public: struct Spec { std::string mUuid; int mOffset; int mLength; }; typedef std::set<LLCore::HttpHandle> handle_set_t; typedef std::vector<Spec> texture_list_t; public: bool mVerbose; bool mRandomRange; int mMaxConcurrency; handle_set_t mHandles; int mRemaining; int mLimit; int mAt; std::string mUrl; texture_list_t mTextures; int mErrorsApi; int mErrorsHttp; int mSuccesses; long mByteCount; }; // // // int main(int argc, char** argv) { bool do_random(false); bool do_verbose(false); int option(-1); while (-1 != (option = getopt(argc, argv, "u:c:h?Rv"))) { switch (option) { case 'u': strncpy(url_format, optarg, sizeof(url_format)); url_format[sizeof(url_format) - 1] = '\0'; break; case 'c': { unsigned long value; char * end; value = strtoul(optarg, &end, 10); if (value < 1 || value > 100 || *end != '\0') { usage(std::cerr); return 1; } concurrency_limit = value; } break; case 'R': do_random = true; break; case 'v': do_verbose = true; break; case 'h': case '?': usage(std::cout); return 0; } } if ((optind + 1) != argc) { usage(std::cerr); return 1; } FILE * uuids(fopen(argv[optind], "r")); if (! uuids) { const char * errstr(strerror(errno)); std::cerr << "Couldn't open UUID file '" << argv[optind] << "'. Reason: " << errstr << std::endl; return 1; } // Initialization init_curl(); LLCore::HttpRequest::createService(); LLCore::HttpRequest::startThread(); // Get service point LLCore::HttpRequest * hr = new LLCore::HttpRequest(); // Get a handler/working set WorkingSet ws; // Fill the working set with work ws.mUrl = url_format; ws.loadTextureUuids(uuids); ws.mRandomRange = do_random; ws.mVerbose = do_verbose; ws.mMaxConcurrency = concurrency_limit; if (! ws.mTextures.size()) { std::cerr << "No UUIDs found in file '" << argv[optind] << "'." << std::endl; return 1; } // Run it while (! ws.reload(hr)) { hr->update(1000); #if defined(WIN32) Sleep(5); #else usleep(5000); #endif } // Report std::cout << "HTTP errors: " << ws.mErrorsHttp << " API errors: " << ws.mErrorsApi << " Successes: " << ws.mSuccesses << " Byte count: " << ws.mByteCount << std::endl; // Clean up delete hr; term_curl(); return 0; } void usage(std::ostream & out) { out << "\n" "usage:\thttp_texture_load [options] uuid_file\n" "\n" "This is a standalone program to drive the New Platform HTTP Library.\n" "The program is supplied with a file of texture UUIDs, one per line\n" "These are fetched sequentially using a pool of concurrent connection\n" "until all are fetched. The default URL format is only useful from\n" "within Linden Lab but this can be overriden with a printf-style\n" "URL formatting string on the command line.\n" "\n" "Options:\n" "\n" " -u <url_format> printf-style format string for URL generation\n" " Default: " << url_format << "\n" " -R Issue GETs with random Range: headers\n" " -c <limit> Maximum request concurrency. Range: [1..100]\n" " Default: " << concurrency_limit << "\n" " -v Verbose mode. Issue some chatter while running\n" " -h print this help\n" "\n" << std::endl; } WorkingSet::WorkingSet() : LLCore::HttpHandler(), mVerbose(false), mRandomRange(false), mRemaining(200), mLimit(200), mAt(0), mErrorsApi(0), mErrorsHttp(0), mSuccesses(0), mByteCount(0L) { mTextures.reserve(30000); } bool WorkingSet::reload(LLCore::HttpRequest * hr) { int to_do((std::min)(mRemaining, mMaxConcurrency - int(mHandles.size()))); for (int i(0); i < to_do; ++i) { char buffer[1024]; #if defined(WIN32) _snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, mUrl.c_str(), mTextures[mAt].mUuid.c_str()); #else snprintf(buffer, sizeof(buffer), mUrl.c_str(), mUuids[mAt].c_str()); #endif int offset(mRandomRange ? ((unsigned long) rand()) % 1000000UL : mTextures[mAt].mOffset); int length(mRandomRange ? ((unsigned long) rand()) % 1000000UL : mTextures[mAt].mLength); LLCore::HttpHandle handle; if (offset || length) { handle = hr->requestGetByteRange(0, 0, buffer, offset, length, NULL, NULL, this); } else { handle = hr->requestGet(0, 0, buffer, NULL, NULL, this); } if (! handle) { // Fatal. Couldn't queue up something. std::cerr << "Failed to queue work to HTTP Service. Reason: " << hr->getStatus().toString() << std::endl; exit(1); } else { mHandles.insert(handle); } mAt++; mRemaining--; if (mVerbose) { static int count(0); ++count; if (0 == (count %5)) std::cout << "Queued " << count << std::endl; } } // Are we done? return (! mRemaining) && mHandles.empty(); } void WorkingSet::onCompleted(LLCore::HttpHandle handle, LLCore::HttpResponse * response) { handle_set_t::iterator it(mHandles.find(handle)); if (mHandles.end() == it) { // Wha? std::cerr << "Failed to find handle in request list. Fatal." << std::endl; exit(1); } else { LLCore::HttpStatus status(response->getStatus()); if (status) { // More success LLCore::BufferArray * data(response->getBody()); mByteCount += data->size(); ++mSuccesses; } else { // Something in this library or libcurl if (status.isHttpStatus()) { ++mErrorsHttp; } else { ++mErrorsApi; } } mHandles.erase(it); } if (mVerbose) { static int count(0); ++count; if (0 == (count %5)) std::cout << "Handled " << count << std::endl; } } void WorkingSet::loadTextureUuids(FILE * in) { char buffer[1024]; while (fgets(buffer, sizeof(buffer), in)) { WorkingSet::Spec texture; char * state(NULL); char * token = strtok_r(buffer, " \t\n,", &state); if (token && 36 == strlen(token)) { // Close enough for this function texture.mUuid = token; texture.mOffset = 0; texture.mLength = 0; token = strtok_r(buffer, " \t\n,", &state); if (token) { int offset(atoi(token)); token = strtok_r(buffer, " \t\n,", &state); if (token) { int length(atoi(token)); texture.mOffset = offset; texture.mLength = length; } } mTextures.push_back(texture); } } mRemaining = mLimit = mTextures.size(); } int ssl_mutex_count(0); LLCoreInt::HttpMutex ** ssl_mutex_list = NULL; void init_curl() { curl_global_init(CURL_GLOBAL_ALL); ssl_mutex_count = CRYPTO_num_locks(); if (ssl_mutex_count > 0) { ssl_mutex_list = new LLCoreInt::HttpMutex * [ssl_mutex_count]; for (int i(0); i < ssl_mutex_count; ++i) { ssl_mutex_list[i] = new LLCoreInt::HttpMutex; } CRYPTO_set_locking_callback(ssl_locking_callback); CRYPTO_set_id_callback(ssl_thread_id_callback); } } void term_curl() { CRYPTO_set_locking_callback(NULL); for (int i(0); i < ssl_mutex_count; ++i) { delete ssl_mutex_list[i]; } delete [] ssl_mutex_list; } unsigned long ssl_thread_id_callback(void) { #if defined(WIN32) return (unsigned long) GetCurrentThread(); #else return (unsigned long) pthread_self(); #endif } void ssl_locking_callback(int mode, int type, const char * /* file */, int /* line */) { if (type >= 0 && type < ssl_mutex_count) { if (mode & CRYPTO_LOCK) { ssl_mutex_list[type]->lock(); } else { ssl_mutex_list[type]->unlock(); } } } #if defined(WIN32) // Very much a subset of posix functionality. Don't push // it too hard... int getopt(int argc, char * const argv[], const char *optstring) { static int pos(0); while (optind < argc) { if (pos == 0) { if (argv[optind][0] != '-') return -1; pos = 1; } if (! argv[optind][pos]) { ++optind; pos = 0; continue; } const char * thing(strchr(optstring, argv[optind][pos])); if (! thing) { ++optind; return -1; } if (thing[1] == ':') { optarg = argv[++optind]; ++optind; pos = 0; } else { optarg = NULL; ++pos; } return *thing; } return -1; } #endif
/** * @file http_texture_load.cpp * @brief Texture download example for core-http library * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include <iostream> #include <cstdio> #include <cstdlib> #include <set> #include <map> #if !defined(WIN32) #include <pthread.h> #endif #include "httpcommon.h" #include "httprequest.h" #include "httphandler.h" #include "httpresponse.h" #include "bufferarray.h" #include "_mutex.h" #include <curl/curl.h> #include <openssl/crypto.h> void init_curl(); void term_curl(); unsigned long ssl_thread_id_callback(void); void ssl_locking_callback(int mode, int type, const char * file, int line); void usage(std::ostream & out); // Default command line settings static int concurrency_limit(40); static char url_format[1024] = "http://example.com/some/path?texture_id=%s.texture"; #if defined(WIN32) #define strncpy(_a, _b, _c) strncpy_s(_a, _b, _c) #define strtok_r(_a, _b, _c) strtok_s(_a, _b, _c) int getopt(int argc, char * const argv[], const char *optstring); char *optarg(NULL); int optind(1); #endif class WorkingSet : public LLCore::HttpHandler { public: WorkingSet(); bool reload(LLCore::HttpRequest *); virtual void onCompleted(LLCore::HttpHandle handle, LLCore::HttpResponse * response); void loadTextureUuids(FILE * in); public: struct Spec { std::string mUuid; int mOffset; int mLength; }; typedef std::set<LLCore::HttpHandle> handle_set_t; typedef std::vector<Spec> texture_list_t; public: bool mVerbose; bool mRandomRange; int mMaxConcurrency; handle_set_t mHandles; int mRemaining; int mLimit; int mAt; std::string mUrl; texture_list_t mTextures; int mErrorsApi; int mErrorsHttp; int mSuccesses; long mByteCount; }; // // // int main(int argc, char** argv) { bool do_random(false); bool do_verbose(false); int option(-1); while (-1 != (option = getopt(argc, argv, "u:c:h?Rv"))) { switch (option) { case 'u': strncpy(url_format, optarg, sizeof(url_format)); url_format[sizeof(url_format) - 1] = '\0'; break; case 'c': { unsigned long value; char * end; value = strtoul(optarg, &end, 10); if (value < 1 || value > 100 || *end != '\0') { usage(std::cerr); return 1; } concurrency_limit = value; } break; case 'R': do_random = true; break; case 'v': do_verbose = true; break; case 'h': case '?': usage(std::cout); return 0; } } if ((optind + 1) != argc) { usage(std::cerr); return 1; } FILE * uuids(fopen(argv[optind], "r")); if (! uuids) { const char * errstr(strerror(errno)); std::cerr << "Couldn't open UUID file '" << argv[optind] << "'. Reason: " << errstr << std::endl; return 1; } // Initialization init_curl(); LLCore::HttpRequest::createService(); LLCore::HttpRequest::startThread(); // Get service point LLCore::HttpRequest * hr = new LLCore::HttpRequest(); // Get a handler/working set WorkingSet ws; // Fill the working set with work ws.mUrl = url_format; ws.loadTextureUuids(uuids); ws.mRandomRange = do_random; ws.mVerbose = do_verbose; ws.mMaxConcurrency = concurrency_limit; if (! ws.mTextures.size()) { std::cerr << "No UUIDs found in file '" << argv[optind] << "'." << std::endl; return 1; } // Run it while (! ws.reload(hr)) { hr->update(1000); #if defined(WIN32) Sleep(5); #else usleep(5000); #endif } // Report std::cout << "HTTP errors: " << ws.mErrorsHttp << " API errors: " << ws.mErrorsApi << " Successes: " << ws.mSuccesses << " Byte count: " << ws.mByteCount << std::endl; // Clean up delete hr; term_curl(); return 0; } void usage(std::ostream & out) { out << "\n" "usage:\thttp_texture_load [options] uuid_file\n" "\n" "This is a standalone program to drive the New Platform HTTP Library.\n" "The program is supplied with a file of texture UUIDs, one per line\n" "These are fetched sequentially using a pool of concurrent connection\n" "until all are fetched. The default URL format is only useful from\n" "within Linden Lab but this can be overriden with a printf-style\n" "URL formatting string on the command line.\n" "\n" "Options:\n" "\n" " -u <url_format> printf-style format string for URL generation\n" " Default: " << url_format << "\n" " -R Issue GETs with random Range: headers\n" " -c <limit> Maximum request concurrency. Range: [1..100]\n" " Default: " << concurrency_limit << "\n" " -v Verbose mode. Issue some chatter while running\n" " -h print this help\n" "\n" << std::endl; } WorkingSet::WorkingSet() : LLCore::HttpHandler(), mVerbose(false), mRandomRange(false), mRemaining(200), mLimit(200), mAt(0), mErrorsApi(0), mErrorsHttp(0), mSuccesses(0), mByteCount(0L) { mTextures.reserve(30000); } bool WorkingSet::reload(LLCore::HttpRequest * hr) { int to_do((std::min)(mRemaining, mMaxConcurrency - int(mHandles.size()))); for (int i(0); i < to_do; ++i) { char buffer[1024]; #if defined(WIN32) _snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, mUrl.c_str(), mTextures[mAt].mUuid.c_str()); #else snprintf(buffer, sizeof(buffer), mUrl.c_str(), mTextures[mAt].mUuid.c_str()); #endif int offset(mRandomRange ? ((unsigned long) rand()) % 1000000UL : mTextures[mAt].mOffset); int length(mRandomRange ? ((unsigned long) rand()) % 1000000UL : mTextures[mAt].mLength); LLCore::HttpHandle handle; if (offset || length) { handle = hr->requestGetByteRange(0, 0, buffer, offset, length, NULL, NULL, this); } else { handle = hr->requestGet(0, 0, buffer, NULL, NULL, this); } if (! handle) { // Fatal. Couldn't queue up something. std::cerr << "Failed to queue work to HTTP Service. Reason: " << hr->getStatus().toString() << std::endl; exit(1); } else { mHandles.insert(handle); } mAt++; mRemaining--; if (mVerbose) { static int count(0); ++count; if (0 == (count %5)) std::cout << "Queued " << count << std::endl; } } // Are we done? return (! mRemaining) && mHandles.empty(); } void WorkingSet::onCompleted(LLCore::HttpHandle handle, LLCore::HttpResponse * response) { handle_set_t::iterator it(mHandles.find(handle)); if (mHandles.end() == it) { // Wha? std::cerr << "Failed to find handle in request list. Fatal." << std::endl; exit(1); } else { LLCore::HttpStatus status(response->getStatus()); if (status) { // More success LLCore::BufferArray * data(response->getBody()); mByteCount += data->size(); ++mSuccesses; } else { // Something in this library or libcurl if (status.isHttpStatus()) { ++mErrorsHttp; } else { ++mErrorsApi; } } mHandles.erase(it); } if (mVerbose) { static int count(0); ++count; if (0 == (count %5)) std::cout << "Handled " << count << std::endl; } } void WorkingSet::loadTextureUuids(FILE * in) { char buffer[1024]; while (fgets(buffer, sizeof(buffer), in)) { WorkingSet::Spec texture; char * state(NULL); char * token = strtok_r(buffer, " \t\n,", &state); if (token && 36 == strlen(token)) { // Close enough for this function texture.mUuid = token; texture.mOffset = 0; texture.mLength = 0; token = strtok_r(buffer, " \t\n,", &state); if (token) { int offset(atoi(token)); token = strtok_r(buffer, " \t\n,", &state); if (token) { int length(atoi(token)); texture.mOffset = offset; texture.mLength = length; } } mTextures.push_back(texture); } } mRemaining = mLimit = mTextures.size(); } int ssl_mutex_count(0); LLCoreInt::HttpMutex ** ssl_mutex_list = NULL; void init_curl() { curl_global_init(CURL_GLOBAL_ALL); ssl_mutex_count = CRYPTO_num_locks(); if (ssl_mutex_count > 0) { ssl_mutex_list = new LLCoreInt::HttpMutex * [ssl_mutex_count]; for (int i(0); i < ssl_mutex_count; ++i) { ssl_mutex_list[i] = new LLCoreInt::HttpMutex; } CRYPTO_set_locking_callback(ssl_locking_callback); CRYPTO_set_id_callback(ssl_thread_id_callback); } } void term_curl() { CRYPTO_set_locking_callback(NULL); for (int i(0); i < ssl_mutex_count; ++i) { delete ssl_mutex_list[i]; } delete [] ssl_mutex_list; } unsigned long ssl_thread_id_callback(void) { #if defined(WIN32) return (unsigned long) GetCurrentThread(); #else return (unsigned long) pthread_self(); #endif } void ssl_locking_callback(int mode, int type, const char * /* file */, int /* line */) { if (type >= 0 && type < ssl_mutex_count) { if (mode & CRYPTO_LOCK) { ssl_mutex_list[type]->lock(); } else { ssl_mutex_list[type]->unlock(); } } } #if defined(WIN32) // Very much a subset of posix functionality. Don't push // it too hard... int getopt(int argc, char * const argv[], const char *optstring) { static int pos(0); while (optind < argc) { if (pos == 0) { if (argv[optind][0] != '-') return -1; pos = 1; } if (! argv[optind][pos]) { ++optind; pos = 0; continue; } const char * thing(strchr(optstring, argv[optind][pos])); if (! thing) { ++optind; return -1; } if (thing[1] == ':') { optarg = argv[++optind]; ++optind; pos = 0; } else { optarg = NULL; ++pos; } return *thing; } return -1; } #endif
Fix for linux/mac builds.
Fix for linux/mac builds.
C++
lgpl-2.1
gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm
73edffed5fd22a9d500be088195d32a9acf35829
functors.hpp
functors.hpp
#include <atomic> #include <map> #include <set> #include "block.hpp" #include "hash.hpp" struct processFunctor_t { virtual ~processFunctor_t () {} virtual bool initialize (const char*) { return false; } virtual void operator() (const Block&) = 0; }; struct whitelisted_t : processFunctor_t { std::set<hash256_t> whitelist; bool initialize (const char* arg) { if (strncmp(arg, "-w", 2) == 0) { const auto fileName = std::string(arg + 2); const auto file = fopen(fileName.c_str(), "r"); assert(file != nullptr); while (true) { hash256_t hash; const auto read = fread(&hash[0], 32, 1, file); // EOF? if (read == 0) break; this->whitelist.emplace(hash); } fclose(file); assert(!this->whitelist.empty()); std::cerr << "Initialized whitelist (" << this->whitelist.size() << " entries)" << std::endl; return true; } return false; } bool shouldSkip (const Block& block) const { if (this->whitelist.empty()) return false; hash256_t hash; hash256(&hash[0], block.header); return this->whitelist.find(hash) == this->whitelist.end(); } bool shouldSkip (const hash256_t& hash) const { if (this->whitelist.empty()) return false; return this->whitelist.find(hash) == this->whitelist.end(); } }; // XXX: fwrite can be used without sizeof(sbuf) < PIPE_BUF (4096 bytes) // BLOCK_HEADER > stdout struct dumpHeaders : whitelisted_t { void operator() (const Block& block) { if (this->shouldSkip(block)) return; fwrite(block.header.begin, 80, 1, stdout); } }; // SCRIPT_LENGTH | SCRIPT > stdout struct dumpScripts : whitelisted_t { void operator() (const Block& block) { if (this->shouldSkip(block)) return; uint8_t sbuf[4096]; const auto maxScriptLength = sizeof(sbuf) - sizeof(uint16_t); auto transactions = block.transactions(); while (!transactions.empty()) { const auto& transaction = transactions.front(); for (const auto& input : transaction.inputs) { if (input.script.length() > maxScriptLength) continue; const auto scriptLength = static_cast<uint16_t>(input.script.length()); Slice(sbuf, sbuf + sizeof(sbuf)).put(scriptLength); memcpy(sbuf + sizeof(uint16_t), input.script.begin, scriptLength); fwrite(sbuf, sizeof(uint16_t) + scriptLength, 1, stdout); } for (const auto& output : transaction.outputs) { if (output.script.length() > maxScriptLength) continue; const auto scriptLength = static_cast<uint16_t>(output.script.length()); Slice(sbuf, sbuf + sizeof(sbuf)).put(scriptLength); memcpy(sbuf + sizeof(uint16_t), output.script.begin, scriptLength); fwrite(sbuf, sizeof(uint16_t) + scriptLength, 1, stdout); } transactions.popFront(); } } }; struct dumpStatistics : whitelisted_t { std::atomic_ulong inputs; std::atomic_ulong outputs; std::atomic_ulong transactions; ~dumpStatistics () { std::cout << this->inputs << '\n' << this->outputs << '\n' << this->transactions << std::endl; } void operator() (const Block& block) { if (this->shouldSkip(block)) return; auto transactions = block.transactions(); this->transactions += transactions.length(); while (!transactions.empty()) { const auto& transaction = transactions.front(); this->inputs += transaction.inputs.size(); this->outputs += transaction.outputs.size(); transactions.popFront(); } } }; // SHA1(TX_HASH | VOUT) | SHA1(OUTPUT_SCRIPT) > stdout struct dumpScriptIndexMap : whitelisted_t { void operator() (const Block& block) { if (this->shouldSkip(block)) return; uint8_t sbuf[40] = {}; uint8_t tbuf[36] = {}; auto transactions = block.transactions(); while (!transactions.empty()) { const auto& transaction = transactions.front(); hash256(tbuf, transaction.data); uint32_t vout = 0; for (const auto& output : transaction.outputs) { Slice(tbuf + 32, tbuf + sizeof(tbuf)).put(vout); ++vout; sha1(sbuf, tbuf, sizeof(tbuf)); sha1(sbuf + 20, output.script); fwrite(sbuf, sizeof(sbuf), 1, stdout); } transactions.popFront(); } } }; #define READ_KV_COUNT 30000 const uint8_t COINBASE[32] = {}; // BLOCK_HASH | TX_HASH | SHA1(PREVIOUS_OUTPUT_SCRIPT) > stdout // BLOCK_HASH | TX_HASH | SHA1(OUTPUT_SCRIPT) > stdout struct dumpScriptIndex : whitelisted_t { std::map<hash160_t, hash160_t> txOuts; bool initialize (const char* arg) { if (whitelisted_t::initialize(arg)) return true; if (strncmp(arg, "-txo", 4) == 0) { const auto fileName = std::string(arg + 4); const auto file = fopen(fileName.c_str(), "r"); assert(file != nullptr); // read mapped txOuts from file until EOF while (true) { uint8_t rbuf[40 * READ_KV_COUNT]; const auto read = fread(rbuf, 40, READ_KV_COUNT, file); const auto eof = read < READ_KV_COUNT; hash160_t key, value; for (size_t i = 0; i < read; ++i) { const auto offset = i * 40; memcpy(&key[0], rbuf + offset, 20); memcpy(&value[0], rbuf + offset + 20, 20); this->txOuts.emplace(key, value); } // EOF? if (read != READ_KV_COUNT) break; } fclose(file); std::cerr << "Initialized " << this->txOuts.size() << " txOuts" << std::endl; return true; } return false; } void operator() (const Block& block) { hash256_t hash; hash256(&hash[0], block.header); if (this->shouldSkip(hash)) return; uint8_t sbuf[84] = {}; memcpy(sbuf, &hash[0], 32); auto transactions = block.transactions(); while (!transactions.empty()) { const auto& transaction = transactions.front(); hash256(sbuf + 32, transaction.data); if (!this->txOuts.empty()) { for (const auto& input : transaction.inputs) { // Coinbase input? if ( input.vout == 0xffffffff && memcmp(input.hash.begin, COINBASE, sizeof(COINBASE)) == 0 ) { sha1(&hash[0], input.script); memcpy(sbuf + 64, &hash[0], 20); fwrite(sbuf, sizeof(sbuf), 1, stdout); continue; } hash160_t hash; sha1(&hash[0], input.data.take(36)); const auto txOutsIter = this->txOuts.find(hash); assert(txOutsIter != this->txOuts.end()); memcpy(sbuf + 64, &(txOutsIter->second)[0], 20); fwrite(sbuf, sizeof(sbuf), 1, stdout); } } for (const auto& output : transaction.outputs) { sha1(sbuf + 64, output.script); fwrite(sbuf, sizeof(sbuf), 1, stdout); } transactions.popFront(); } } };
#include <atomic> #include <map> #include <set> #include "block.hpp" #include "hash.hpp" struct processFunctor_t { virtual ~processFunctor_t () {} virtual bool initialize (const char*) { return false; } virtual void operator() (const Block&) = 0; }; struct whitelisted_t : processFunctor_t { std::vector<hash256_t> whitelist; bool initialize (const char* arg) { if (strncmp(arg, "-w", 2) == 0) { const auto fileName = std::string(arg + 2); const auto file = fopen(fileName.c_str(), "r"); assert(file != nullptr); fseek(file, 0, SEEK_END); const auto fileSize = ftell(file); fseek(file, 0, SEEK_SET); assert(sizeof(hash256_t) == 32); this->whitelist.resize(fileSize / sizeof(hash256_t)); const auto read = fread(&this->whitelist[0], fileSize, 1, file); assert(read == 1); fclose(file); std::cerr << "Initialized " << this->whitelist.size() << " block hashes" << std::endl; std::sort(this->whitelist.begin(), this->whitelist.end()); std::cerr << "Sorted " << this->whitelist.size() << " block hashes" << std::endl; return true; } return false; } bool shouldSkip (const Block& block) const { if (this->whitelist.empty()) return false; hash256_t hash; hash256(&hash[0], block.header); const auto hashIter = std::lower_bound(this->whitelist.begin(), this->whitelist.end(), hash); return (hashIter != this->whitelist.end()) && !(hash < *hashIter); } bool shouldSkip (const hash256_t& hash) const { if (this->whitelist.empty()) return false; const auto hashIter = std::lower_bound(this->whitelist.begin(), this->whitelist.end(), hash); return (hashIter != this->whitelist.end()) && !(hash < *hashIter); } }; // XXX: fwrite can be used without sizeof(sbuf) < PIPE_BUF (4096 bytes) // BLOCK_HEADER > stdout struct dumpHeaders : whitelisted_t { void operator() (const Block& block) { if (this->shouldSkip(block)) return; fwrite(block.header.begin, 80, 1, stdout); } }; // SCRIPT_LENGTH | SCRIPT > stdout struct dumpScripts : whitelisted_t { void operator() (const Block& block) { if (this->shouldSkip(block)) return; uint8_t sbuf[4096]; const auto maxScriptLength = sizeof(sbuf) - sizeof(uint16_t); auto transactions = block.transactions(); while (!transactions.empty()) { const auto& transaction = transactions.front(); for (const auto& input : transaction.inputs) { if (input.script.length() > maxScriptLength) continue; const auto scriptLength = static_cast<uint16_t>(input.script.length()); Slice(sbuf, sbuf + sizeof(sbuf)).put(scriptLength); memcpy(sbuf + sizeof(uint16_t), input.script.begin, scriptLength); fwrite(sbuf, sizeof(uint16_t) + scriptLength, 1, stdout); } for (const auto& output : transaction.outputs) { if (output.script.length() > maxScriptLength) continue; const auto scriptLength = static_cast<uint16_t>(output.script.length()); Slice(sbuf, sbuf + sizeof(sbuf)).put(scriptLength); memcpy(sbuf + sizeof(uint16_t), output.script.begin, scriptLength); fwrite(sbuf, sizeof(uint16_t) + scriptLength, 1, stdout); } transactions.popFront(); } } }; struct dumpStatistics : whitelisted_t { std::atomic_ulong inputs; std::atomic_ulong outputs; std::atomic_ulong transactions; ~dumpStatistics () { std::cout << this->inputs << '\n' << this->outputs << '\n' << this->transactions << std::endl; } void operator() (const Block& block) { if (this->shouldSkip(block)) return; auto transactions = block.transactions(); this->transactions += transactions.length(); while (!transactions.empty()) { const auto& transaction = transactions.front(); this->inputs += transaction.inputs.size(); this->outputs += transaction.outputs.size(); transactions.popFront(); } } }; // SHA1(TX_HASH | VOUT) | SHA1(OUTPUT_SCRIPT) > stdout struct dumpScriptIndexMap : whitelisted_t { void operator() (const Block& block) { if (this->shouldSkip(block)) return; uint8_t sbuf[40] = {}; uint8_t tbuf[36] = {}; auto transactions = block.transactions(); while (!transactions.empty()) { const auto& transaction = transactions.front(); hash256(tbuf, transaction.data); uint32_t vout = 0; for (const auto& output : transaction.outputs) { Slice(tbuf + 32, tbuf + sizeof(tbuf)).put(vout); ++vout; sha1(sbuf, tbuf, sizeof(tbuf)); sha1(sbuf + 20, output.script); fwrite(sbuf, sizeof(sbuf), 1, stdout); } transactions.popFront(); } } }; const uint8_t COINBASE[32] = {}; // BLOCK_HASH | TX_HASH | SHA1(PREVIOUS_OUTPUT_SCRIPT) > stdout // BLOCK_HASH | TX_HASH | SHA1(OUTPUT_SCRIPT) > stdout struct dumpScriptIndex : whitelisted_t { typedef std::pair<hash160_t, hash160_t> TxOut; std::vector<TxOut> txOuts; bool initialize (const char* arg) { if (whitelisted_t::initialize(arg)) return true; if (strncmp(arg, "-txo", 4) == 0) { const auto fileName = std::string(arg + 4); const auto file = fopen(fileName.c_str(), "r"); assert(file != nullptr); fseek(file, 0, SEEK_END); const auto fileSize = ftell(file); fseek(file, 0, SEEK_SET); assert(sizeof(TxOut) == 40); this->txOuts.resize(fileSize / sizeof(TxOut)); const auto read = fread(&this->txOuts[0], fileSize, 1, file); assert(read == 1); fclose(file); std::cerr << "Initialized " << this->txOuts.size() << " txOuts" << std::endl; std::sort(this->txOuts.begin(), this->txOuts.end()); std::cerr << "Sorted " << this->txOuts.size() << " txOuts" << std::endl; return true; } return false; } void operator() (const Block& block) { hash256_t hash; hash256(&hash[0], block.header); if (this->shouldSkip(hash)) return; uint8_t sbuf[84] = {}; memcpy(sbuf, &hash[0], 32); auto transactions = block.transactions(); while (!transactions.empty()) { const auto& transaction = transactions.front(); hash256(sbuf + 32, transaction.data); if (!this->txOuts.empty()) { for (const auto& input : transaction.inputs) { // Coinbase input? if ( input.vout == 0xffffffff && memcmp(input.hash.begin, COINBASE, sizeof(COINBASE)) == 0 ) { sha1(&hash[0], input.script); memcpy(sbuf + 64, &hash[0], 20); fwrite(sbuf, sizeof(sbuf), 1, stdout); continue; } hash160_t hash; sha1(&hash[0], input.data.take(36)); const auto txOutsIter = std::lower_bound(this->txOuts.begin(), this->txOuts.end(), hash, [](const TxOut& a, const hash160_t& b) { return a.first < b; }); assert((txOutsIter != this->txOuts.end()) && !(hash < txOutsIter->first)); memcpy(sbuf + 64, &(txOutsIter->second)[0], 20); fwrite(sbuf, sizeof(sbuf), 1, stdout); } } for (const auto& output : transaction.outputs) { sha1(sbuf + 64, output.script); fwrite(sbuf, sizeof(sbuf), 1, stdout); } transactions.popFront(); } } };
use sorted vectors for high performance lookups
functors: use sorted vectors for high performance lookups
C++
isc
dcousens/fast-dat-parser,dcousens/fast-dat-parser,dcousens/fast-dat-parser
b416f6f7d139237b212909fb755c820ddff31f4b
asc/TCPString.hpp
asc/TCPString.hpp
# pragma once # include <Siv3D.hpp> namespace asc { using namespace s3d; /// <summary> /// 𑗎M”\ TCPClient, TCPServer /// </summary> /// <remarks> /// M UTF-8 ōs܂B /// </remarks> template<class Socket> class TCPString : public Socket { public: /// <summary> /// 1 ǂݍ݂܂B /// </summary> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// ǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ͐܂B /// </remarks> bool readChar(wchar& to) { std::string buffer; if (!lookahead(buffer[0])) return false; skip(sizeof(std::string::value_type)); to = FromUTF8(std::move(buffer))[0]; return true; } /// <summary> /// w肵ĕǂݍ݂܂B /// </summary> /// <param name="length"> /// ǂݍޕ /// </param> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// ǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ͐܂B /// </remarks> bool readString(size_t length, String& to) { std::string buffer; buffer.resize(length); if (!lookahead(&buffer[0], buffer.size())) return false; skip(sizeof(std::string::value_type) * buffer.size()); to = FromUTF8(std::move(buffer)); return true; } /// <summary> /// 1 sǂݍ݂܂B /// </summary> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// ǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ܂B /// </remarks> bool readLine(String& to) { return readUntil('\n', to); } /// <summary> /// w肵܂œǂݍ݂܂B /// </summary> /// <param name="end"> /// w肷镶 /// </param> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// ǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ܂B /// </remarks> bool readUntil(char end, String& to) { std::string buffer; buffer.resize(available()); if (!lookahead(&buffer[0], buffer.size())) return false; const auto pos = buffer.find(end); if (pos == buffer.npos) return false; buffer.resize(pos + 1); skip(sizeof(std::string::value_type) * buffer.size()); to = FromUTF8(std::move(buffer)); return true; } /// <summary> /// ”\Ȍǂݍ݂܂B /// </summary> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// 1 łǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ܂B /// </remarks> bool readAll(String& to) { if (!available()) return false; std::string buffer; buffer.resize(available()); if (!lookahead(&buffer[0], buffer.size())) return false; skip(sizeof(std::string::value_type) * buffer.size()); to = FromUTF8(std::move(buffer)); return true; } /// <summary> /// 𑗐M܂B /// </summary> /// <param name="data"> /// M镶 /// </param> /// <returns> /// Mɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ܂B /// </remarks> bool sendString(const String& data) { const auto str = ToUTF8(data); return send(str.data(), sizeof(decltype(str)::value_type) * str.length()); } }; using TCPStringClient = TCPString<TCPClient>; using TCPStringServer = TCPString<TCPServer>; }
# pragma once # include <Siv3D.hpp> namespace asc { using namespace s3d; /// <summary> /// 𑗎M”\ TCPClient, TCPServer /// </summary> /// <remarks> /// M UTF-8 ōs܂B /// </remarks> template<class Socket> class TCPString : public Socket { public: /// <summary> /// 1 ǂݍ݂܂B /// </summary> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// ǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ͐܂B /// </remarks> bool readChar(wchar& to) { std::string buffer; if (!lookahead(buffer[0])) return false; skip(sizeof(std::string::value_type)); to = FromUTF8(std::move(buffer))[0]; return true; } /// <summary> /// w肵ĕǂݍ݂܂B /// </summary> /// <param name="length"> /// ǂݍޕ /// </param> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// ǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ͐܂B /// </remarks> bool readString(size_t length, String& to) { std::string buffer; buffer.resize(length); if (!lookahead(&buffer[0], buffer.size())) return false; skip(sizeof(std::string::value_type) * buffer.size()); to = FromUTF8(std::move(buffer)); return true; } /// <summary> /// 1 sǂݍ݂܂B /// </summary> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// ǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ܂B /// </remarks> /// <remarks> /// EEEsERE[EhEE LF EEgEpEEE܂�EB /// </remarks> bool readLine(String& to) { return readUntil('\n', to); } /// <summary> /// w肵܂œǂݍ݂܂B /// </summary> /// <param name="end"> /// w肷镶 /// </param> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// ǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ܂B /// </remarks> bool readUntil(char end, String& to) { std::string buffer; buffer.resize(available()); if (!lookahead(&buffer[0], buffer.size())) return false; const auto pos = buffer.find(end); if (pos == buffer.npos) return false; buffer.resize(pos + 1); skip(sizeof(std::string::value_type) * buffer.size()); to = FromUTF8(std::move(buffer)); return true; } /// <summary> /// ”\Ȍǂݍ݂܂B /// </summary> /// <param name="to"> /// ǂݍݐ /// </param> /// <returns> /// 1 łǂݍ݂ɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ܂B /// </remarks> bool readAll(String& to) { if (!available()) return false; std::string buffer; buffer.resize(available()); if (!lookahead(&buffer[0], buffer.size())) return false; skip(sizeof(std::string::value_type) * buffer.size()); to = FromUTF8(std::move(buffer)); return true; } /// <summary> /// 𑗐M܂B /// </summary> /// <param name="data"> /// M镶 /// </param> /// <returns> /// Mɐ true /// </returns> /// <remarks> /// {Ȃǂ 1 oCgł͂Ȃ܂B /// </remarks> bool sendString(const String& data) { const auto str = ToUTF8(data); return send(str.data(), sizeof(decltype(str)::value_type) * str.length()); } }; using TCPStringClient = TCPString<TCPClient>; using TCPStringServer = TCPString<TCPServer>; }
Add comment.
Add comment.
C++
unlicense
ChunChunMorning/AscTCPString
ef4db6602a9ed14b500e4fd5a3fd34a6858885ee
include/ellis_private/codec/obd/pid.hpp
include/ellis_private/codec/obd/pid.hpp
/* * @file codec/elm327.hpp * * @brief Ellis ELM327 codec C++ header. */ #pragma once #ifndef ELLIS_CODEC_PID_HPP_ #define ELLIS_CODEC_PID_HPP_ #include <cstdint> #include <memory> namespace ellis { namespace obd { /** Gets a string describing a PID from a PID value. * * @param pid a PID * * @return a string description * */ const char * get_pid_string(uint16_t pid); /** Gets a string describing a PID mode from a mode value. * * @param mode a PID mode * * @return a string description */ std::string get_mode_string(uint16_t mode); /** Decodes a given value, applying the appropriate unit transformation * depending on the given PID. * * @param pid a PID * @param value an OBD II value * * @return a decoded value */ double decode_value(uint16_t pid, uint32_t val); } /* obd */ } /* ellis */ #endif /* ELLIS_CODEC_PID_HPP_ */
/* * @file codec/elm327.hpp * * @brief Ellis ELM327 codec C++ header. */ #pragma once #ifndef ELLIS_CODEC_PID_HPP_ #define ELLIS_CODEC_PID_HPP_ #include <cstdint> #include <memory> namespace ellis { namespace obd { /** Gets a string describing a PID from a PID value. * * @param pid a PID * * @return a string description * */ const char * get_pid_string(uint16_t pid); /** Gets a string describing a PID mode from a mode value. * * @param mode a PID mode * * @return a string description */ std::string get_mode_string(uint16_t mode); /** Decodes a given value, applying the appropriate unit transformation * depending on the given PID. * * @param pid a PID * @param val an OBD II value * * @return a decoded value */ double decode_value(uint16_t pid, uint32_t val); } /* obd */ } /* ellis */ #endif /* ELLIS_CODEC_PID_HPP_ */
fix doc issue
obd: fix doc issue
C++
mit
project-ellis/ellis,project-ellis/ellis
e40d14f4a9c42ed6bf93f701f6e872acadf40a6f
C++/summary-ranges.cpp
C++/summary-ranges.cpp
// Time: O(n) // Space: O(1) class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<string> ranges; if (nums.empty()) { return ranges; } int start = nums[0], end = nums[0]; for (int i = 1; i <= nums.size(); ++i) { if (i < nums.size() && nums[i] == end + 1) { end = nums[i]; } else { string range = to_string(start); if (start != end) { range.append("->" + to_string(end)); } ranges.emplace_back(range); start = end = nums[i]; } } return ranges; } };
// Time: O(n) // Space: O(1) class Solution { public: vector<string> summaryRanges(vector<int>& nums) { vector<string> ranges; if (nums.empty()) { return ranges; } int start = nums[0], end = nums[0]; for (int i = 1; i <= nums.size(); ++i) { if (i < nums.size() && nums[i] == end + 1) { end = nums[i]; } else { string range = to_string(start); if (start != end) { range.append("->" + to_string(end)); } ranges.emplace_back(range); if (i < nums.size()) { start = end = nums[i]; } } } return ranges; } };
Update summary-ranges.cpp
Update summary-ranges.cpp
C++
mit
tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,yiwen-luo/LeetCode,yiwen-luo/LeetCode,yiwen-luo/LeetCode,githubutilities/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,githubutilities/LeetCode,githubutilities/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode
15356f63203742b462cb40aed547c93c24545a39
include/mapnik/text/harfbuzz_shaper.hpp
include/mapnik/text/harfbuzz_shaper.hpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2013 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_HARFBUZZ_SHAPER_HPP #define MAPNIK_HARFBUZZ_SHAPER_HPP // mapnik #include <mapnik/text/text_properties.hpp> #include <mapnik/text/text_line.hpp> #include <mapnik/text/face.hpp> // stl #include <list> // harfbuzz #include <harfbuzz/hb.h> #include <harfbuzz/hb-ft.h> //#include <harfbuzz/hb-icu.h> namespace mapnik { static inline hb_script_t _icu_script_to_script(UScriptCode script) { if (script == USCRIPT_INVALID_CODE) return HB_SCRIPT_INVALID; return hb_script_from_string(uscript_getShortName(script), -1); } struct harfbuzz_shaper { static void shape_text(text_line & line, text_itemizer & itemizer, std::map<unsigned,double> & width_map, face_manager_freetype & font_manager, double scale_factor ) { unsigned start = line.first_char(); unsigned end = line.last_char(); size_t length = end - start; if (!length) return; line.reserve(length); std::list<text_item> const& list = itemizer.itemize(start, end); auto hb_buffer_deleter = [](hb_buffer_t * buffer) { hb_buffer_destroy(buffer);}; const std::unique_ptr<hb_buffer_t, decltype(hb_buffer_deleter)> buffer(hb_buffer_create(),hb_buffer_deleter); //hb_buffer_set_unicode_funcs(buffer.get(), hb_icu_get_unicode_funcs()); hb_buffer_pre_allocate(buffer.get(), length); mapnik::value_unicode_string const& text = itemizer.text(); for (auto const& text_item : list) { face_set_ptr face_set = font_manager.get_face_set(text_item.format->face_name, text_item.format->fontset); double size = text_item.format->text_size * scale_factor; face_set->set_unscaled_character_sizes(); std::size_t num_faces = face_set->size(); std::size_t pos = 0; for (auto const& face : *face_set) { ++pos; hb_buffer_clear_contents(buffer.get()); hb_buffer_add_utf16(buffer.get(), text.getBuffer(), text.length(), text_item.start, text_item.end - text_item.start); hb_buffer_set_direction(buffer.get(), (text_item.rtl == UBIDI_RTL)?HB_DIRECTION_RTL:HB_DIRECTION_LTR); hb_buffer_set_script(buffer.get(), _icu_script_to_script(text_item.script)); hb_font_t *font(hb_ft_font_create(face->get_face(), nullptr)); hb_shape(font, buffer.get(), nullptr, 0); hb_font_destroy(font); unsigned num_glyphs = hb_buffer_get_length(buffer.get()); hb_glyph_info_t *glyphs = hb_buffer_get_glyph_infos(buffer.get(), nullptr); hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer.get(), nullptr); bool font_has_all_glyphs = true; // Check if all glyphs are valid. for (unsigned i=0; i<num_glyphs; ++i) { if (!glyphs[i].codepoint) { font_has_all_glyphs = false; break; } } if (!font_has_all_glyphs && (pos < num_faces)) { //Try next font in fontset continue; } for (unsigned i=0; i<num_glyphs; ++i) { glyph_info tmp; tmp.glyph_index = glyphs[i].codepoint; if (face->glyph_dimensions(tmp)) { tmp.char_index = glyphs[i].cluster; tmp.face = face; tmp.format = text_item.format; tmp.scale_multiplier = size / face->get_face()->units_per_EM; //Overwrite default advance with better value provided by HarfBuzz tmp.unscaled_advance = positions[i].x_advance; tmp.offset.set(positions[i].x_offset * tmp.scale_multiplier, positions[i].y_offset * tmp.scale_multiplier); width_map[glyphs[i].cluster] += tmp.advance(); line.add_glyph(tmp, scale_factor); } } line.update_max_char_height(face->get_char_height(size)); break; //When we reach this point the current font had all glyphs. } } } }; } // namespace mapnik #endif // MAPNIK_HARFBUZZ_SHAPER_HPP
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2013 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_HARFBUZZ_SHAPER_HPP #define MAPNIK_HARFBUZZ_SHAPER_HPP // mapnik #include <mapnik/text/text_properties.hpp> #include <mapnik/text/text_line.hpp> #include <mapnik/text/face.hpp> // stl #include <list> // harfbuzz #include <harfbuzz/hb.h> #include <harfbuzz/hb-ft.h> //#include <harfbuzz/hb-icu.h> namespace mapnik { static inline hb_script_t _icu_script_to_script(UScriptCode script) { if (script == USCRIPT_INVALID_CODE) return HB_SCRIPT_INVALID; return hb_script_from_string(uscript_getShortName(script), -1); } struct harfbuzz_shaper { static void shape_text(text_line & line, text_itemizer & itemizer, std::map<unsigned,double> & width_map, face_manager_freetype & font_manager, double scale_factor ) { unsigned start = line.first_char(); unsigned end = line.last_char(); size_t length = end - start; if (!length) return; line.reserve(length); std::list<text_item> const& list = itemizer.itemize(start, end); auto hb_buffer_deleter = [](hb_buffer_t * buffer) { hb_buffer_destroy(buffer);}; const std::unique_ptr<hb_buffer_t, decltype(hb_buffer_deleter)> buffer(hb_buffer_create(),hb_buffer_deleter); //hb_buffer_set_unicode_funcs(buffer.get(), hb_icu_get_unicode_funcs()); hb_buffer_pre_allocate(buffer.get(), length); mapnik::value_unicode_string const& text = itemizer.text(); for (auto const& text_item : list) { face_set_ptr face_set = font_manager.get_face_set(text_item.format->face_name, text_item.format->fontset); double size = text_item.format->text_size * scale_factor; face_set->set_unscaled_character_sizes(); std::size_t num_faces = face_set->size(); std::size_t pos = 0; for (auto const& face : *face_set) { ++pos; hb_buffer_clear_contents(buffer.get()); hb_buffer_add_utf16(buffer.get(), reinterpret_cast<const uint16_t *>(text.getBuffer()), text.length(), text_item.start, text_item.end - text_item.start); hb_buffer_set_direction(buffer.get(), (text_item.rtl == UBIDI_RTL)?HB_DIRECTION_RTL:HB_DIRECTION_LTR); hb_buffer_set_script(buffer.get(), _icu_script_to_script(text_item.script)); hb_font_t *font(hb_ft_font_create(face->get_face(), nullptr)); hb_shape(font, buffer.get(), nullptr, 0); hb_font_destroy(font); unsigned num_glyphs = hb_buffer_get_length(buffer.get()); hb_glyph_info_t *glyphs = hb_buffer_get_glyph_infos(buffer.get(), nullptr); hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer.get(), nullptr); bool font_has_all_glyphs = true; // Check if all glyphs are valid. for (unsigned i=0; i<num_glyphs; ++i) { if (!glyphs[i].codepoint) { font_has_all_glyphs = false; break; } } if (!font_has_all_glyphs && (pos < num_faces)) { //Try next font in fontset continue; } for (unsigned i=0; i<num_glyphs; ++i) { glyph_info tmp; tmp.glyph_index = glyphs[i].codepoint; if (face->glyph_dimensions(tmp)) { tmp.char_index = glyphs[i].cluster; tmp.face = face; tmp.format = text_item.format; tmp.scale_multiplier = size / face->get_face()->units_per_EM; //Overwrite default advance with better value provided by HarfBuzz tmp.unscaled_advance = positions[i].x_advance; tmp.offset.set(positions[i].x_offset * tmp.scale_multiplier, positions[i].y_offset * tmp.scale_multiplier); width_map[glyphs[i].cluster] += tmp.advance(); line.add_glyph(tmp, scale_factor); } } line.update_max_char_height(face->get_char_height(size)); break; //When we reach this point the current font had all glyphs. } } } }; } // namespace mapnik #endif // MAPNIK_HARFBUZZ_SHAPER_HPP
handle wchar_t UChar typedef on windows
handle wchar_t UChar typedef on windows
C++
lgpl-2.1
sebastic/python-mapnik,whuaegeanse/mapnik,cjmayo/mapnik,Airphrame/mapnik,whuaegeanse/mapnik,pnorman/mapnik,lightmare/mapnik,stefanklug/mapnik,jwomeara/mapnik,sebastic/python-mapnik,yohanboniface/python-mapnik,qianwenming/mapnik,qianwenming/mapnik,Airphrame/mapnik,tomhughes/mapnik,tomhughes/mapnik,mapnik/python-mapnik,yohanboniface/python-mapnik,stefanklug/mapnik,mapycz/mapnik,Uli1/mapnik,mbrukman/mapnik,mapycz/mapnik,stefanklug/mapnik,zerebubuth/mapnik,davenquinn/python-mapnik,zerebubuth/mapnik,pramsey/mapnik,mapycz/python-mapnik,stefanklug/mapnik,tomhughes/mapnik,mbrukman/mapnik,qianwenming/mapnik,whuaegeanse/mapnik,mapnik/mapnik,tomhughes/mapnik,tomhughes/python-mapnik,mapnik/mapnik,pramsey/mapnik,qianwenming/mapnik,lightmare/mapnik,zerebubuth/mapnik,mapycz/mapnik,mbrukman/mapnik,rouault/mapnik,lightmare/mapnik,naturalatlas/mapnik,pnorman/mapnik,sebastic/python-mapnik,jwomeara/mapnik,qianwenming/mapnik,rouault/mapnik,Uli1/mapnik,mapnik/mapnik,naturalatlas/mapnik,mapnik/python-mapnik,cjmayo/mapnik,jwomeara/mapnik,manz/python-mapnik,CartoDB/mapnik,tomhughes/python-mapnik,garnertb/python-mapnik,yohanboniface/python-mapnik,Uli1/mapnik,davenquinn/python-mapnik,Uli1/mapnik,pnorman/mapnik,pramsey/mapnik,pnorman/mapnik,pramsey/mapnik,mapnik/python-mapnik,cjmayo/mapnik,Airphrame/mapnik,garnertb/python-mapnik,rouault/mapnik,lightmare/mapnik,manz/python-mapnik,mapycz/python-mapnik,CartoDB/mapnik,jwomeara/mapnik,naturalatlas/mapnik,Airphrame/mapnik,mapnik/mapnik,manz/python-mapnik,naturalatlas/mapnik,garnertb/python-mapnik,CartoDB/mapnik,whuaegeanse/mapnik,mbrukman/mapnik,cjmayo/mapnik,tomhughes/python-mapnik,davenquinn/python-mapnik,rouault/mapnik
9e203b609d53db27a4bb03df51c848e69200fb92
io/pipe_simple.cc
io/pipe_simple.cc
#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/pipe.h> #include <io/pipe_simple.h> /* * PipeSimple is a pipe which passes data through a processing function and * which provides no discipline -- it will always immediately signal that it is * ready to process more data. * * TODO: Asynchronous processing function. * * XXX Should flag error and ensure all subsequent input() and output() fail. */ PipeSimple::PipeSimple(const LogHandle& log) : log_(log), input_buffer_(), input_eos_(false), output_action_(NULL), output_callback_(NULL) { } PipeSimple::~PipeSimple() { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); } Action * PipeSimple::input(Buffer *buf, EventCallback *cb) { if (buf->empty()) { input_eos_ = true; } if (output_callback_ != NULL) { ASSERT(output_action_ == NULL); Buffer tmp; if (!process(&tmp, buf)) { output_callback_->event(Event(Event::Error, 0)); output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; cb->event(Event(Event::Error, 0)); return (EventSystem::instance()->schedule(cb)); } if (!tmp.empty() || (input_eos_ && process_eos())) { if (input_eos_ && tmp.empty()) { output_callback_->event(Event(Event::EOS, 0)); } else { output_callback_->event(Event(Event::Done, 0, tmp)); } output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } } if (!buf->empty()) { input_buffer_.append(buf); buf->clear(); } cb->event(Event(Event::Done, 0)); return (EventSystem::instance()->schedule(cb)); } Action * PipeSimple::output(EventCallback *cb) { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); if (!input_buffer_.empty() || input_eos_) { Buffer tmp; if (!process(&tmp, &input_buffer_)) { cb->event(Event(Event::Error, 0)); return (EventSystem::instance()->schedule(cb)); } if (!tmp.empty() || (input_eos_ && process_eos())) { if (input_eos_ && tmp.empty()) { ASSERT(input_buffer_.empty()); cb->event(Event(Event::EOS, 0)); } else { ASSERT(!tmp.empty()); cb->event(Event(Event::Done, 0, tmp)); } return (EventSystem::instance()->schedule(cb)); } } output_callback_ = cb; return (cancellation(this, &PipeSimple::output_cancel)); } void PipeSimple::output_cancel(void) { if (output_action_ != NULL) { ASSERT(output_callback_ == NULL); output_action_->cancel(); output_action_ = NULL; } if (output_callback_ != NULL) { delete output_callback_; output_callback_ = NULL; } } void PipeSimple::output_spontaneous(void) { if (output_callback_ == NULL) return; Buffer tmp; if (!process(&tmp, &input_buffer_)) { output_callback_->event(Event(Event::Error, 0)); output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; return; } ASSERT(input_buffer_.empty()); /* * XXX * Would prefer for this to never happen! */ if (tmp.empty() && (!input_eos_ || !process_eos())) { DEBUG(log_) << "Spontaneous output generated no output despite EOS being unset."; return; } if (tmp.empty()) { output_callback_->event(Event(Event::EOS, 0)); } else { output_callback_->event(Event(Event::Done, 0, tmp)); } output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } bool PipeSimple::process_eos(void) const { return (input_eos_); }
#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/pipe.h> #include <io/pipe_simple.h> /* * PipeSimple is a pipe which passes data through a processing function and * which provides no discipline -- it will always immediately signal that it is * ready to process more data. * * TODO: Asynchronous processing function. * * XXX Should flag error and ensure all subsequent input() and output() fail. */ PipeSimple::PipeSimple(const LogHandle& log) : log_(log), input_buffer_(), input_eos_(false), output_action_(NULL), output_callback_(NULL) { } PipeSimple::~PipeSimple() { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); } Action * PipeSimple::input(Buffer *buf, EventCallback *cb) { if (buf->empty()) { input_eos_ = true; } else { input_buffer_.append(buf); buf->clear(); } if (output_callback_ != NULL) { ASSERT(output_action_ == NULL); Buffer tmp; if (!process(&tmp, &input_buffer_)) { output_callback_->event(Event(Event::Error, 0)); output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; cb->event(Event(Event::Error, 0)); return (EventSystem::instance()->schedule(cb)); } if (!tmp.empty() || (input_eos_ && process_eos())) { if (input_eos_ && tmp.empty()) { output_callback_->event(Event(Event::EOS, 0)); } else { output_callback_->event(Event(Event::Done, 0, tmp)); } output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } } cb->event(Event(Event::Done, 0)); return (EventSystem::instance()->schedule(cb)); } Action * PipeSimple::output(EventCallback *cb) { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); if (!input_buffer_.empty() || input_eos_) { Buffer tmp; if (!process(&tmp, &input_buffer_)) { cb->event(Event(Event::Error, 0)); return (EventSystem::instance()->schedule(cb)); } if (!tmp.empty() || (input_eos_ && process_eos())) { if (input_eos_ && tmp.empty()) { ASSERT(input_buffer_.empty()); cb->event(Event(Event::EOS, 0)); } else { ASSERT(!tmp.empty()); cb->event(Event(Event::Done, 0, tmp)); } return (EventSystem::instance()->schedule(cb)); } } output_callback_ = cb; return (cancellation(this, &PipeSimple::output_cancel)); } void PipeSimple::output_cancel(void) { if (output_action_ != NULL) { ASSERT(output_callback_ == NULL); output_action_->cancel(); output_action_ = NULL; } if (output_callback_ != NULL) { delete output_callback_; output_callback_ = NULL; } } void PipeSimple::output_spontaneous(void) { if (output_callback_ == NULL) return; Buffer tmp; if (!process(&tmp, &input_buffer_)) { output_callback_->event(Event(Event::Error, 0)); output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; return; } ASSERT(input_buffer_.empty()); /* * XXX * Would prefer for this to never happen! */ if (tmp.empty() && (!input_eos_ || !process_eos())) { DEBUG(log_) << "Spontaneous output generated no output despite EOS being unset."; return; } if (tmp.empty()) { output_callback_->event(Event(Event::EOS, 0)); } else { output_callback_->event(Event(Event::Done, 0, tmp)); } output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } bool PipeSimple::process_eos(void) const { return (input_eos_); }
Fix buffering of unhandled data.
Fix buffering of unhandled data. git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@400 4068ffdb-0463-0410-8185-8cc71e3bd399
C++
bsd-2-clause
diegows/wanproxy,diegows/wanproxy,splbio/wanproxy,splbio/wanproxy,splbio/wanproxy,diegows/wanproxy
a5f72562ace8048a841b0b335f9078866093f872
implementations/MaxMSP/jcom.ramp~/jcom.ramp~.cpp
implementations/MaxMSP/jcom.ramp~/jcom.ramp~.cpp
/* * tt.ramp~ * External object for Max/MSP * * Example project for TTBlue * Copyright © 2008 by Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTClassWrapperMax.h" #include "ext.h" // Max Header #include "z_dsp.h" // MSP Header #include "ext_strings.h" // String Functions #include "commonsyms.h" // Common symbols used by the Max 4.5 API #include "ext_obex.h" // Max Object Extensions (attributes) Header #include "TTDSP.h" // TTBlue Interfaces... // Data Structure for this object typedef struct _ramp { t_pxobject obj; TTAudioObjectPtr ramp; TTAudioSignalPtr audioOut; t_symbol* attrMode; TTUInt16 maxNumChannels; TTUInt16 vs; } t_ramp; // Prototypes for methods: need a method for each incoming message type void* ramp_new(t_symbol *msg, short argc, t_atom *argv); // New Object Creation Method void ramp_free(t_ramp *x); void ramp_assist(t_ramp *x, void *b, long msg, long arg, char *dst); // Assistance Method t_int* ramp_perform(t_int *w); // An MSP Perform (signal) Method void ramp_dsp(t_ramp *x, t_signal **sp, short *count); // DSP Method void ramp_stop(t_ramp *x); void ramp_int(t_ramp *x, long newCurrentValue); void ramp_float(t_ramp *x, double newCurrentValue); void ramp_list(t_ramp *x, double endValue, double time); t_max_err ramp_setMode(t_ramp *x, void *attr, long argc, t_atom *argv); // Globals t_class *ramp_class; // Required. Global pointing to this class /************************************************************************************/ // Main() Function int TTCLASSWRAPPERMAX_EXPORT main(void) { long attrflags = 0; t_class *c; t_object *attr; TTDSPInit(); common_symbols_init(); c = class_new("jcom.ramp~",(method)ramp_new, (method)ramp_free, (short)sizeof(t_ramp), (method)0L, A_GIMME, 0); class_addmethod(c, (method)ramp_int, "int", A_FLOAT, 0L); class_addmethod(c, (method)ramp_float, "float", A_FLOAT, 0L); class_addmethod(c, (method)ramp_list, "list", A_FLOAT, A_FLOAT); class_addmethod(c, (method)ramp_stop, "stop", 0L); class_addmethod(c, (method)ramp_dsp, "dsp", A_CANT, 0L); class_addmethod(c, (method)ramp_assist, "assist", A_CANT, 0L); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); class_addmethod(c, (method)object_obex_quickref, "quickref", A_CANT, 0); attr = attr_offset_new("mode", _sym_symbol, attrflags, (method)0L, (method)ramp_setMode, calcoffset(t_ramp, attrMode)); class_addattr(c, attr); class_dspinit(c); // Setup object's class to work with MSP class_register(CLASS_BOX, c); ramp_class = c; return 0; } /************************************************************************************/ // Object Creation Method void* ramp_new(t_symbol *msg, short argc, t_atom *argv) { t_ramp *x; TTValue sr(sys_getsr()); long attrstart = attr_args_offset(argc, argv); // support normal arguments short i; x = (t_ramp *)object_alloc(ramp_class); if(x){ x->maxNumChannels = 2; // An initial argument to this object will set the maximum number of channels if(attrstart && argv) x->maxNumChannels = atom_getlong(argv); ttEnvironment->setAttributeValue(kTTSym_sampleRate, sr); //x->ramp = new TTRamp(x->maxNumChannels); TTObjectInstantiate(TT("ramp"), &x->ramp, x->maxNumChannels); TTObjectInstantiate(TT("audiosignal"), &x->audioOut, x->maxNumChannels); attr_args_process(x,argc,argv); // handle attribute args object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL)); // dumpout dsp_setup((t_pxobject *)x, x->maxNumChannels); // inlets for(i=0; i < x->maxNumChannels; i++) outlet_new((t_pxobject *)x, "signal"); // outlets x->obj.z_misc = Z_NO_INPLACE; } return (x); // Return the pointer } // Memory Deallocation void ramp_free(t_ramp *x) { dsp_free((t_pxobject *)x); TTObjectRelease(&x->ramp); TTObjectRelease(&x->audioOut); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void ramp_assist(t_ramp *x, void *b, long msg, long arg, char *dst) { if(msg==1){ // Inlets if(arg == 0) strcpy(dst, "(signal) input 1, control messages"); else snprintf(dst, 256, "(signal) input %ld", arg+1); } else if(msg==2){ // Outlets if(arg == x->maxNumChannels) strcpy(dst, "dumpout"); else snprintf(dst, 256, "(signal) Filtered output %ld", arg+1); } } void ramp_stop(t_ramp *x) { x->ramp->sendMessage(TT("stop")); } void ramp_int(t_ramp *x, long newCurrentValue) { ramp_float(x, newCurrentValue); } void ramp_float(t_ramp *x, double newCurrentValue) { x->ramp->setAttributeValue(TT("startValue"), newCurrentValue); } void ramp_list(t_ramp *x, double endValue, double time) { x->ramp->setAttributeValue(TT("destinationValue"), endValue); x->ramp->setAttributeValue(TT("rampTime"), time); } // Perform (signal) Method t_int *ramp_perform(t_int *w) { t_ramp *x = (t_ramp *)(w[1]); if(!(x->obj.z_disabled)) x->ramp->process(*x->audioOut); TTAUDIOSIGNAL_GETVECTOR32(x->audioOut, 0, x->vs, w[2]); return w+3; } // DSP Method void ramp_dsp(t_ramp *x, t_signal **sp, short *count) { x->ramp->setAttributeValue(TT("sampleRate"), sp[0]->s_sr); x->vs = sp[0]->s_n; x->audioOut->setAttributeValue(TT("numChannels"), x->maxNumChannels); x->audioOut->setAttributeValue(TT("vectorSize"), TTUInt16(sp[0]->s_n)); x->audioOut->sendMessage(TT("alloc")); dsp_add(ramp_perform, 2, x, sp[0]->s_vec); } t_max_err ramp_setMode(t_ramp *x, void *attr, long argc, t_atom *argv) { if(argc){ x->attrMode = atom_getsym(argv); if(x->attrMode == gensym("sample_accurate")) x->ramp->setAttributeValue(TT("mode"), TT("sample")); else if(x->attrMode == gensym("vector_accurate")) x->ramp->setAttributeValue(TT("mode"), TT("vector")); } return MAX_ERR_NONE; }
/* * tt.ramp~ * External object for Max/MSP * * Example project for TTBlue * Copyright © 2008 by Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTClassWrapperMax.h" #include "ext.h" // Max Header #include "z_dsp.h" // MSP Header #include "ext_strings.h" // String Functions #include "commonsyms.h" // Common symbols used by the Max 4.5 API #include "ext_obex.h" // Max Object Extensions (attributes) Header #include "TTDSP.h" // TTBlue Interfaces... // Data Structure for this object typedef struct _ramp { t_pxobject obj; TTAudioObjectPtr ramp; TTAudioSignalPtr audioOut; t_symbol* attrMode; TTUInt16 maxNumChannels; TTUInt16 vs; } t_ramp; // Prototypes for methods: need a method for each incoming message type void* ramp_new(t_symbol *msg, short argc, t_atom *argv); // New Object Creation Method void ramp_free(t_ramp *x); void ramp_assist(t_ramp *x, void *b, long msg, long arg, char *dst); // Assistance Method t_int* ramp_perform(t_int *w); // An MSP Perform (signal) Method void ramp_dsp(t_ramp *x, t_signal **sp, short *count); // DSP Method void ramp_stop(t_ramp *x); void ramp_int(t_ramp *x, long newCurrentValue); void ramp_float(t_ramp *x, double newCurrentValue); void ramp_list(t_ramp *x, double endValue, double time); t_max_err ramp_setMode(t_ramp *x, void *attr, long argc, t_atom *argv); // Globals t_class *ramp_class; // Required. Global pointing to this class /************************************************************************************/ // Main() Function int TTCLASSWRAPPERMAX_EXPORT main(void) { long attrflags = 0; t_class *c; t_object *attr; TTDSPInit(); common_symbols_init(); c = class_new("jcom.ramp~",(method)ramp_new, (method)ramp_free, (short)sizeof(t_ramp), (method)0L, A_GIMME, 0); class_addmethod(c, (method)ramp_int, "int", A_FLOAT, 0L); class_addmethod(c, (method)ramp_float, "float", A_FLOAT, 0L); class_addmethod(c, (method)ramp_list, "list", A_FLOAT, A_FLOAT); class_addmethod(c, (method)ramp_stop, "stop", 0L); class_addmethod(c, (method)ramp_dsp, "dsp", A_CANT, 0L); class_addmethod(c, (method)ramp_assist, "assist", A_CANT, 0L); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); class_addmethod(c, (method)object_obex_quickref, "quickref", A_CANT, 0); attr = attr_offset_new("mode", _sym_symbol, attrflags, (method)0L, (method)ramp_setMode, calcoffset(t_ramp, attrMode)); class_addattr(c, attr); class_dspinit(c); // Setup object's class to work with MSP class_register(CLASS_BOX, c); ramp_class = c; return 0; } /************************************************************************************/ // Object Creation Method void* ramp_new(t_symbol *msg, short argc, t_atom *argv) { t_ramp *x; TTValue sr(sys_getsr()); long attrstart = attr_args_offset(argc, argv); // support normal arguments short i; x = (t_ramp *)object_alloc(ramp_class); if(x){ x->maxNumChannels = 2; // An initial argument to this object will set the maximum number of channels if(attrstart && argv) x->maxNumChannels = atom_getlong(argv); ttEnvironment->setAttributeValue(kTTSym_sampleRate, sr); //x->ramp = new TTRamp(x->maxNumChannels); TTObjectInstantiate(TT("ramp"), &x->ramp, x->maxNumChannels); TTObjectInstantiate(TT("audiosignal"), &x->audioOut, x->maxNumChannels); attr_args_process(x,argc,argv); // handle attribute args object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL)); // dumpout dsp_setup((t_pxobject *)x, x->maxNumChannels); // inlets for(i=0; i < x->maxNumChannels; i++) outlet_new((t_pxobject *)x, "signal"); // outlets x->obj.z_misc = Z_NO_INPLACE; } return (x); // Return the pointer } // Memory Deallocation void ramp_free(t_ramp *x) { dsp_free((t_pxobject *)x); TTObjectRelease(&x->ramp); TTObjectRelease(&x->audioOut); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void ramp_assist(t_ramp *x, void *b, long msg, long arg, char *dst) { if(msg==1){ // Inlets if(arg == 0) strcpy(dst, "(signal) input 1, control messages"); else snprintf(dst, 256, "(signal) input %ld", arg+1); } else if(msg==2){ // Outlets if(arg == x->maxNumChannels) strcpy(dst, "dumpout"); else snprintf(dst, 256, "(signal) Filtered output %ld", arg+1); } } void ramp_stop(t_ramp *x) { x->ramp->sendMessage(TT("stop")); } void ramp_int(t_ramp *x, long newCurrentValue) { ramp_float(x, newCurrentValue); } void ramp_float(t_ramp *x, double newCurrentValue) { x->ramp->setAttributeValue(TT("startValue"), newCurrentValue); } void ramp_list(t_ramp *x, double endValue, double time) { x->ramp->setAttributeValue(TT("destinationValue"), endValue); x->ramp->setAttributeValue(TT("rampTime"), time); } // Perform (signal) Method t_int *ramp_perform(t_int *w) { t_ramp *x = (t_ramp *)(w[1]); if(!(x->obj.z_disabled)) x->ramp->process(*x->audioOut); //TTAUDIOSIGNAL_GETVECTOR32(x->audioOut, 0, x->vs, w[2]); x->audioOut->getVector(0, x->vs, (t_float *)(w[2])); return w+3; } // DSP Method void ramp_dsp(t_ramp *x, t_signal **sp, short *count) { x->ramp->setAttributeValue(TT("sampleRate"), sp[0]->s_sr); x->vs = sp[0]->s_n; x->audioOut->setAttributeValue(TT("numChannels"), x->maxNumChannels); x->audioOut->setAttributeValue(TT("vectorSize"), TTUInt16(sp[0]->s_n)); x->audioOut->sendMessage(TT("alloc")); dsp_add(ramp_perform, 2, x, sp[0]->s_vec); } t_max_err ramp_setMode(t_ramp *x, void *attr, long argc, t_atom *argv) { if(argc){ x->attrMode = atom_getsym(argv); if(x->attrMode == gensym("sample_accurate")) x->ramp->setAttributeValue(TT("mode"), TT("sample")); else if(x->attrMode == gensym("vector_accurate")) x->ramp->setAttributeValue(TT("mode"), TT("vector")); } return MAX_ERR_NONE; }
build fix (no longer using obsolete macro.
jcom.ramp~: build fix (no longer using obsolete macro.
C++
bsd-3-clause
jamoma/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore,jamoma/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore,eriser/JamomaCore,jamoma/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore,eriser/JamomaCore,eriser/JamomaCore,jamoma/JamomaCore,eriser/JamomaCore,eriser/JamomaCore
3753b0dd922915113bf64a03c54cd7b74e2f0d0a
src/MMGSafariPayload.hpp
src/MMGSafariPayload.hpp
// // MMGSafariPayload.hpp // // Copyright (c) 2013 MacGeneration. 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "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. // #ifndef __MMGSAFARIPAYLOAD_H__ #define __MMGSAFARIPAYLOAD_H__ #include "MMGPayload.hpp" #include <vector> class MMGSafariPayload : public MMGPayload { private: /// Notification title std::string _title; /// URL arguments std::vector<std::string> _urlArguments; public: /** * @brief Set message body, badge number, sound name to play and action button label * @param body [in] : Message body * @param actionKeyLabel [in] : Action button label * @param title [in] : Message title * @param urlArguments [in] : URL arguments for the URL to open when notification is clicked */ MMGSafariPayload(const std::string& body = "", const std::string& actionKeyLabel = "Show", const std::string& title = "", const std::vector<std::string>& urlArguments = std::vector<std::string>()); /** * @brief Destructor */ ~MMGSafariPayload(void) {} /** * @brief Get a reference to the the title * @returns title as a std::string */ const std::string& GetTitle(void)const; /** * @brief Get a reference to URL arguments * @returns URL arguments as a std::vector<std::string> */ const std::vector<std::string>& GetURLArguments(void)const; /** * @brief Set title and reconstruct the JSON payload * @param title [in] : Message body */ void SetTitle(const std::string& title); /** * @brief Set URL arguments and reconstruct the JSON payload * @param urlArguments [in] : URL arguments */ void SetURLArguments(const std::vector<std::string>& urlArguments); protected: /** * @brief Create the JSON payload according to the ivars */ void _FormatPayload(void); }; #endif /* __MMGSAFARIPAYLOAD_H__ */
// // MMGSafariPayload.hpp // // Copyright (c) 2013 MacGeneration. 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "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. // #ifndef __MMGSAFARIPAYLOAD_H__ #define __MMGSAFARIPAYLOAD_H__ #include "MMGPayload.hpp" #include <vector> class MMGSafariPayload : public MMGPayload { private: /// Notification title std::string _title; /// URL arguments std::vector<std::string> _urlArguments; public: /** * @brief Set message body, badge number, sound name to play and action button label * @param body [in] : Message body * @param actionKeyLabel [in] : Action button label * @param title [in] : Message title * @param urlArguments [in] : URL arguments for the URL to open when notification is clicked */ MMGSafariPayload(const std::string& body = "", const std::string& actionKeyLabel = "Show", const std::string& title = "", const std::vector<std::string>& urlArguments = std::vector<std::string>()); /** * @brief Destructor */ ~MMGSafariPayload(void) {} /** * @brief Get a reference to the the title * @returns title as a std::string */ const std::string& GetTitle(void)const; /** * @brief Get a reference to URL arguments * @returns URL arguments as a std::vector<std::string> */ const std::vector<std::string>& GetURLArguments(void)const; /** * @brief Set title and reconstruct the JSON payload * @param title [in] : Message body */ void SetTitle(const std::string& title); /** * @brief Set URL arguments and reconstruct the JSON payload * @param urlArguments [in] : URL arguments */ void SetURLArguments(const std::vector<std::string>& urlArguments); protected: /** * @brief Create the JSON payload according to the ivars */ void _FormatPayload(void); }; #endif /* __MMGSAFARIPAYLOAD_H__ */
Remove missing nl warning
Remove missing nl warning
C++
bsd-2-clause
gfxcc/MacGPusher,MacGeneration/MacGPusher
d5fefe2440639933bb0bf4b1083d03d2b59a9cb2
backend/utils.cpp
backend/utils.cpp
#include <cstdint> #include <stdexcept> #include <string> #include "utils.h" std::string lc3::utils::udecToBin(uint32_t value, uint32_t num_bits) { char * bits = new char[num_bits + 1]; for(uint32_t i = 0; i < num_bits; i += 1) { bits[num_bits - i - 1] = (value & 1) + '0'; value >>= 1; } bits[num_bits] = 0; return std::string(bits); } uint32_t lc3::utils::sextTo32(uint32_t value, uint32_t num_bits) { uint32_t extension = ~((1 << num_bits) - 1); if((value >> (num_bits - 1)) & 1) { return extension | value; } else { return value; } } uint32_t lc3::utils::getBit(uint32_t value, uint32_t pos) { return (value >> pos) & 1; } uint32_t lc3::utils::getBits(uint32_t value, uint32_t end, uint32_t start) { return (value >> start) & ((1 << (end - start + 1)) - 1); } uint32_t lc3::utils::computePSRCC(uint32_t value, uint32_t psr) { uint32_t cc = 0; if(value == 0) { cc = 2; } else if((value & 0x8000) != 0) { cc = 4; } else { cc = 1; } return (psr & 0xFFF8) | cc; } uint32_t lc3::utils::computeBasePlusSOffset(uint32_t base, uint32_t signed_off, uint32_t width) { return (utils::sextTo32(base, (uint32_t) 16) + lc3::utils::sextTo32(signed_off, width)) & 0xffff; } std::string lc3::utils::toLower(std::string const & str) { std::string ret = str; std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower); return ret; }
#include <algorithm> #include <cstdint> #include <stdexcept> #include <string> #include "utils.h" std::string lc3::utils::udecToBin(uint32_t value, uint32_t num_bits) { char * bits = new char[num_bits + 1]; for(uint32_t i = 0; i < num_bits; i += 1) { bits[num_bits - i - 1] = (value & 1) + '0'; value >>= 1; } bits[num_bits] = 0; return std::string(bits); } uint32_t lc3::utils::sextTo32(uint32_t value, uint32_t num_bits) { uint32_t extension = ~((1 << num_bits) - 1); if((value >> (num_bits - 1)) & 1) { return extension | value; } else { return value; } } uint32_t lc3::utils::getBit(uint32_t value, uint32_t pos) { return (value >> pos) & 1; } uint32_t lc3::utils::getBits(uint32_t value, uint32_t end, uint32_t start) { return (value >> start) & ((1 << (end - start + 1)) - 1); } uint32_t lc3::utils::computePSRCC(uint32_t value, uint32_t psr) { uint32_t cc = 0; if(value == 0) { cc = 2; } else if((value & 0x8000) != 0) { cc = 4; } else { cc = 1; } return (psr & 0xFFF8) | cc; } uint32_t lc3::utils::computeBasePlusSOffset(uint32_t base, uint32_t signed_off, uint32_t width) { return (utils::sextTo32(base, (uint32_t) 16) + lc3::utils::sextTo32(signed_off, width)) & 0xffff; } std::string lc3::utils::toLower(std::string const & str) { std::string ret = str; std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower); return ret; }
Add missing include
[back] Add missing include
C++
mit
chiragsakhuja/lc3v2,chiragsakhuja/lc3v2,chiragsakhuja/lc3v2,chiragsakhuja/lc3v2,chiragsakhuja/lc3v2,chiragsakhuja/lc3v2
b11887c6ef9e976a50d1162caefebb4bafe347d8
tree/src/TLeafL.cxx
tree/src/TLeafL.cxx
// @(#)root/tree:$Id$ // Author: Rene Brun 12/01/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A TLeaf for a 64 bit Integer data type. // ////////////////////////////////////////////////////////////////////////// #include "TLeafL.h" #include "TBranch.h" #include "TClonesArray.h" #include "Riostream.h" ClassImp(TLeafL) //______________________________________________________________________________ TLeafL::TLeafL(): TLeaf() { //*-*-*-*-*-*Default constructor for LeafI*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============================ fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafL::TLeafL(TBranch *parent, const char *name, const char *type) :TLeaf(parent, name,type) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a LeafI*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============== //*-* fLenType = sizeof(Long64_t); fMinimum = 0; fMaximum = 0; fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafL::~TLeafL() { //*-*-*-*-*-*Default destructor for a LeafI*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== if (ResetAddress(0,kTRUE)) delete [] fValue; } //______________________________________________________________________________ void TLeafL::Export(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Export element from local leaf buffer to ClonesArray*-*-*-*-* //*-* ====================================================== Long64_t *value = fValue; for (Int_t i=0;i<n;i++) { char *first = (char*)list->UncheckedAt(i); Long64_t *ii = (Long64_t*)&first[fOffset]; for (Int_t j=0;j<fLen;j++) { ii[j] = value[j]; } value += fLen; } } //______________________________________________________________________________ void TLeafL::FillBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-* //*-* ========================================= Int_t i; Int_t len = GetLen(); if (fPointer) fValue = *fPointer; if (IsRange()) { if (fValue[0] > fMaximum) fMaximum = fValue[0]; } if (IsUnsigned()) { for (i=0;i<len;i++) b << (ULong64_t)fValue[i]; } else { b.WriteFastArray(fValue,len); } } //______________________________________________________________________________ const char *TLeafL::GetTypeName() const { //*-*-*-*-*-*-*-*Returns name of leaf type*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= if (fIsUnsigned) return "ULong64_t"; return "Long64_t"; } //______________________________________________________________________________ Double_t TLeafL::GetValue(Int_t i) const { // Returns current value of leaf // if leaf is a simple type, i must be set to 0 // if leaf is an array, i is the array element number to be returned //unlikely to have unsigned long64. //cannot cast from ULong64 to Double with VC++6 //if (fIsUnsigned) return (Double_t)((ULong64_t)fValue[i]); return fValue[i]; } //______________________________________________________________________________ void TLeafL::Import(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Import element from ClonesArray into local leaf buffer*-*-*-*-* //*-* ====================================================== const Int_t kIntUndefined = -9999; Int_t j = 0; char *clone; for (Int_t i=0;i<n;i++) { clone = (char*)list->UncheckedAt(i); if (clone) memcpy(&fValue[j],clone + fOffset, 8*fLen); else memcpy(&fValue[j],&kIntUndefined, 8*fLen); j += fLen; } } //______________________________________________________________________________ void TLeafL::PrintValue(Int_t l) const { // Prints leaf value if (fIsUnsigned) { ULong64_t *uvalue = (ULong64_t*)GetValuePointer(); printf("%llu",uvalue[l]); } else { Long64_t *value = (Long64_t*)GetValuePointer(); printf("%lld",value[l]); } } //______________________________________________________________________________ void TLeafL::ReadBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Read leaf elements from Basket input buffer*-*-*-*-*-* //*-* =========================================== if (!fLeafCount && fNdata == 1) { b >> fValue[0]; } else { if (fLeafCount) { Int_t len = Int_t(fLeafCount->GetValue()); if (len > fLeafCount->GetMaximum()) { printf("ERROR leaf:%s, len=%d and max=%d\n",GetName(),len,fLeafCount->GetMaximum()); len = fLeafCount->GetMaximum(); } fNdata = len*fLen; b.ReadFastArray(fValue,len*fLen); } else { b.ReadFastArray(fValue,fLen); } } } //______________________________________________________________________________ void TLeafL::ReadBasketExport(TBuffer &b, TClonesArray *list, Int_t n) { //*-*-*-*-*-*-*-*-*-*-*Read leaf elements from Basket input buffer*-*-*-*-*-* // and export buffer to TClonesArray objects if (n*fLen == 1) { b >> fValue[0]; } else { b.ReadFastArray(fValue,n*fLen); } Long64_t *value = fValue; for (Int_t i=0;i<n;i++) { char *first = (char*)list->UncheckedAt(i); Long64_t *ii = (Long64_t*)&first[fOffset]; for (Int_t j=0;j<fLen;j++) { ii[j] = value[j]; } value += fLen; } } //______________________________________________________________________________ void TLeafL::ReadValue(ifstream &s) { // read a long integer from ifstream s and store it into the branch buffer #if defined(_MSC_VER) && (_MSC_VER<1300) printf("Due to a bug in VC++6, the function TLeafL::ReadValue is dummy\n"); #else if (fIsUnsigned) { ULong64_t *uvalue = (ULong64_t*)GetValuePointer(); for (Int_t i=0;i<fLen;i++) s >> uvalue[i]; } else { Long64_t *value = (Long64_t*)GetValuePointer(); for (Int_t i=0;i<fLen;i++) s >> value[i]; } #endif } //______________________________________________________________________________ void TLeafL::SetAddress(void *add) { //*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-* //*-* ============================ if (ResetAddress(add) && (add!=fValue)) { delete [] fValue; } if (add) { if (TestBit(kIndirectAddress)) { fPointer = (Long64_t**) add; Int_t ncountmax = fLen; if (fLeafCount) ncountmax = fLen*(fLeafCount->GetMaximum() + 1); if ((fLeafCount && ncountmax > Int_t(fLeafCount->GetValue())) || ncountmax > fNdata || *fPointer == 0) { if (*fPointer) delete [] *fPointer; if (ncountmax > fNdata) fNdata = ncountmax; *fPointer = new Long64_t[fNdata]; } fValue = *fPointer; } else { fValue = (Long64_t*)add; } } else { fValue = new Long64_t[fNdata]; fValue[0] = 0; } }
// @(#)root/tree:$Id$ // Author: Rene Brun 12/01/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A TLeaf for a 64 bit Integer data type. // ////////////////////////////////////////////////////////////////////////// #include "TLeafL.h" #include "TBranch.h" #include "TClonesArray.h" #include "Riostream.h" ClassImp(TLeafL) //______________________________________________________________________________ TLeafL::TLeafL(): TLeaf() { //*-*-*-*-*-*Default constructor for LeafI*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============================ fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafL::TLeafL(TBranch *parent, const char *name, const char *type) :TLeaf(parent, name,type) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a LeafL*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============== //*-* fLenType = sizeof(Long64_t); fMinimum = 0; fMaximum = 0; fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafL::~TLeafL() { //*-*-*-*-*-*Default destructor for a LeafL*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== if (ResetAddress(0,kTRUE)) delete [] fValue; } //______________________________________________________________________________ void TLeafL::Export(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Export element from local leaf buffer to ClonesArray*-*-*-*-* //*-* ====================================================== Long64_t *value = fValue; for (Int_t i=0;i<n;i++) { char *first = (char*)list->UncheckedAt(i); Long64_t *ii = (Long64_t*)&first[fOffset]; for (Int_t j=0;j<fLen;j++) { ii[j] = value[j]; } value += fLen; } } //______________________________________________________________________________ void TLeafL::FillBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-* //*-* ========================================= Int_t i; Int_t len = GetLen(); if (fPointer) fValue = *fPointer; if (IsRange()) { if (fValue[0] > fMaximum) fMaximum = fValue[0]; } if (IsUnsigned()) { for (i=0;i<len;i++) b << (ULong64_t)fValue[i]; } else { b.WriteFastArray(fValue,len); } } //______________________________________________________________________________ const char *TLeafL::GetTypeName() const { //*-*-*-*-*-*-*-*Returns name of leaf type*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= if (fIsUnsigned) return "ULong64_t"; return "Long64_t"; } //______________________________________________________________________________ Double_t TLeafL::GetValue(Int_t i) const { // Returns current value of leaf // if leaf is a simple type, i must be set to 0 // if leaf is an array, i is the array element number to be returned //unlikely to have unsigned long64. //cannot cast from ULong64 to Double with VC++6 //if (fIsUnsigned) return (Double_t)((ULong64_t)fValue[i]); return fValue[i]; } //______________________________________________________________________________ void TLeafL::Import(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Import element from ClonesArray into local leaf buffer*-*-*-*-* //*-* ====================================================== const Int_t kIntUndefined = -9999; Int_t j = 0; char *clone; for (Int_t i=0;i<n;i++) { clone = (char*)list->UncheckedAt(i); if (clone) memcpy(&fValue[j],clone + fOffset, 8*fLen); else memcpy(&fValue[j],&kIntUndefined, 8*fLen); j += fLen; } } //______________________________________________________________________________ void TLeafL::PrintValue(Int_t l) const { // Prints leaf value if (fIsUnsigned) { ULong64_t *uvalue = (ULong64_t*)GetValuePointer(); printf("%llu",uvalue[l]); } else { Long64_t *value = (Long64_t*)GetValuePointer(); printf("%lld",value[l]); } } //______________________________________________________________________________ void TLeafL::ReadBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Read leaf elements from Basket input buffer*-*-*-*-*-* //*-* =========================================== if (!fLeafCount && fNdata == 1) { b >> fValue[0]; } else { if (fLeafCount) { Int_t len = Int_t(fLeafCount->GetValue()); if (len > fLeafCount->GetMaximum()) { printf("ERROR leaf:%s, len=%d and max=%d\n",GetName(),len,fLeafCount->GetMaximum()); len = fLeafCount->GetMaximum(); } fNdata = len*fLen; b.ReadFastArray(fValue,len*fLen); } else { b.ReadFastArray(fValue,fLen); } } } //______________________________________________________________________________ void TLeafL::ReadBasketExport(TBuffer &b, TClonesArray *list, Int_t n) { //*-*-*-*-*-*-*-*-*-*-*Read leaf elements from Basket input buffer*-*-*-*-*-* // and export buffer to TClonesArray objects if (n*fLen == 1) { b >> fValue[0]; } else { b.ReadFastArray(fValue,n*fLen); } Long64_t *value = fValue; for (Int_t i=0;i<n;i++) { char *first = (char*)list->UncheckedAt(i); Long64_t *ii = (Long64_t*)&first[fOffset]; for (Int_t j=0;j<fLen;j++) { ii[j] = value[j]; } value += fLen; } } //______________________________________________________________________________ void TLeafL::ReadValue(ifstream &s) { // read a long integer from ifstream s and store it into the branch buffer #if defined(_MSC_VER) && (_MSC_VER<1300) printf("Due to a bug in VC++6, the function TLeafL::ReadValue is dummy\n"); #else if (fIsUnsigned) { ULong64_t *uvalue = (ULong64_t*)GetValuePointer(); for (Int_t i=0;i<fLen;i++) s >> uvalue[i]; } else { Long64_t *value = (Long64_t*)GetValuePointer(); for (Int_t i=0;i<fLen;i++) s >> value[i]; } #endif } //______________________________________________________________________________ void TLeafL::SetAddress(void *add) { //*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-* //*-* ============================ if (ResetAddress(add) && (add!=fValue)) { delete [] fValue; } if (add) { if (TestBit(kIndirectAddress)) { fPointer = (Long64_t**) add; Int_t ncountmax = fLen; if (fLeafCount) ncountmax = fLen*(fLeafCount->GetMaximum() + 1); if ((fLeafCount && ncountmax > Int_t(fLeafCount->GetValue())) || ncountmax > fNdata || *fPointer == 0) { if (*fPointer) delete [] *fPointer; if (ncountmax > fNdata) fNdata = ncountmax; *fPointer = new Long64_t[fNdata]; } fValue = *fPointer; } else { fValue = (Long64_t*)add; } } else { fValue = new Long64_t[fNdata]; fValue[0] = 0; } }
correct typo in comment
correct typo in comment git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@21655 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
bbannier/ROOT,dawehner/root,dawehner/root,dawehner/root,dawehner/root,bbannier/ROOT,bbannier/ROOT,dawehner/root,dawehner/root,bbannier/ROOT,dawehner/root,bbannier/ROOT,dawehner/root,bbannier/ROOT,bbannier/ROOT
f81e3923664c22d94c1adf2fe86f5d744cff0fd9
indra/llmessage/tests/llavatarnamecache_test.cpp
indra/llmessage/tests/llavatarnamecache_test.cpp
/** * @file llavatarnamecache_test.cpp * @author James Cook * @brief LLAvatarNameCache test cases. * * $LicenseInfo:firstyear=2010&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "../llavatarnamecache.h" #include "../test/lltut.h" namespace tut { struct avatarnamecache_data { }; typedef test_group<avatarnamecache_data> avatarnamecache_test; typedef avatarnamecache_test::object avatarnamecache_object; tut::avatarnamecache_test avatarnamecache_testcase("llavatarnamecache"); template<> template<> void avatarnamecache_object::test<1>() { bool valid = false; S32 max_age = 0; valid = max_age_from_cache_control("max-age=3600", &max_age); ensure("typical input valid", valid); ensure_equals("typical input parsed", max_age, 3600); valid = max_age_from_cache_control( " max-age=600 , no-cache,private=\"stuff\" ", &max_age); ensure("complex input valid", valid); ensure_equals("complex input parsed", max_age, 600); valid = max_age_from_cache_control( "no-cache, max-age = 123 ", &max_age); ensure("complex input 2 valid", valid); ensure_equals("complex input 2 parsed", max_age, 123); } template<> template<> void avatarnamecache_object::test<2>() { bool valid = false; S32 max_age = -1; valid = max_age_from_cache_control("", &max_age); ensure("empty input returns invalid", !valid); ensure_equals("empty input doesn't change val", max_age, -1); valid = max_age_from_cache_control("no-cache", &max_age); ensure("no max-age field returns invalid", !valid); valid = max_age_from_cache_control("max", &max_age); ensure("just 'max' returns invalid", !valid); valid = max_age_from_cache_control("max-age", &max_age); ensure("partial max-age is invalid", !valid); valid = max_age_from_cache_control("max-age=", &max_age); ensure("longer partial max-age is invalid", !valid); valid = max_age_from_cache_control("max-age=FOO", &max_age); ensure("invalid integer max-age is invalid", !valid); valid = max_age_from_cache_control("max-age 234", &max_age); ensure("space separated max-age is invalid", !valid); valid = max_age_from_cache_control("max-age=0", &max_age); ensure("zero max-age is valid", valid); // *TODO: Handle "0000" as zero //valid = max_age_from_cache_control("max-age=0000", &max_age); //ensure("multi-zero max-age is valid", valid); valid = max_age_from_cache_control("max-age=-123", &max_age); ensure("less than zero max-age is invalid", !valid); } }
/** * @file llavatarnamecache_test.cpp * @author James Cook * @brief LLAvatarNameCache test cases. * * $LicenseInfo:firstyear=2010&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "../llavatarnamecache.h" #include "../test/lltut.h" namespace tut { struct avatarnamecache_data { }; typedef test_group<avatarnamecache_data> avatarnamecache_test; typedef avatarnamecache_test::object avatarnamecache_object; tut::avatarnamecache_test avatarnamecache_testcase("LLAvatarNameCache"); template<> template<> void avatarnamecache_object::test<1>() { bool valid = false; S32 max_age = 0; valid = max_age_from_cache_control("max-age=3600", &max_age); ensure("typical input valid", valid); ensure_equals("typical input parsed", max_age, 3600); valid = max_age_from_cache_control( " max-age=600 , no-cache,private=\"stuff\" ", &max_age); ensure("complex input valid", valid); ensure_equals("complex input parsed", max_age, 600); valid = max_age_from_cache_control( "no-cache, max-age = 123 ", &max_age); ensure("complex input 2 valid", valid); ensure_equals("complex input 2 parsed", max_age, 123); } template<> template<> void avatarnamecache_object::test<2>() { bool valid = false; S32 max_age = -1; valid = max_age_from_cache_control("", &max_age); ensure("empty input returns invalid", !valid); ensure_equals("empty input doesn't change val", max_age, -1); valid = max_age_from_cache_control("no-cache", &max_age); ensure("no max-age field returns invalid", !valid); valid = max_age_from_cache_control("max", &max_age); ensure("just 'max' returns invalid", !valid); valid = max_age_from_cache_control("max-age", &max_age); ensure("partial max-age is invalid", !valid); valid = max_age_from_cache_control("max-age=", &max_age); ensure("longer partial max-age is invalid", !valid); valid = max_age_from_cache_control("max-age=FOO", &max_age); ensure("invalid integer max-age is invalid", !valid); valid = max_age_from_cache_control("max-age 234", &max_age); ensure("space separated max-age is invalid", !valid); valid = max_age_from_cache_control("max-age=0", &max_age); ensure("zero max-age is valid", valid); // *TODO: Handle "0000" as zero //valid = max_age_from_cache_control("max-age=0000", &max_age); //ensure("multi-zero max-age is valid", valid); valid = max_age_from_cache_control("max-age=-123", &max_age); ensure("less than zero max-age is invalid", !valid); } }
Standardize test name to match class name on LLAvatarNameCache
Standardize test name to match class name on LLAvatarNameCache
C++
lgpl-2.1
gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm,gabeharms/firestorm
10708c4a89241a923522897dddaa42b8a67501aa
lib/Driver/HostInfo.cpp
lib/Driver/HostInfo.cpp
//===--- HostInfo.cpp - Host specific information -----------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/HostInfo.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Option.h" #include "clang/Driver/Options.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Compiler.h" #include "ToolChains.h" #include <cassert> using namespace clang::driver; HostInfo::HostInfo(const Driver &D, const llvm::Triple &_Triple) : TheDriver(D), Triple(_Triple) { } HostInfo::~HostInfo() { } namespace { // Darwin Host Info /// DarwinHostInfo - Darwin host information implementation. class DarwinHostInfo : public HostInfo { /// Darwin version of host. unsigned DarwinVersion[3]; /// GCC version to use on this host. unsigned GCCVersion[3]; /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain *> ToolChains; public: DarwinHostInfo(const Driver &D, const llvm::Triple &Triple); ~DarwinHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { types::ID Ty = types::lookupTypeForExtension(Ext); // Darwin always preprocesses assembly files (unless -x is used // explicitly). if (Ty == types::TY_PP_Asm) return types::TY_Asm; return Ty; } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; DarwinHostInfo::DarwinHostInfo(const Driver &D, const llvm::Triple& Triple) : HostInfo(D, Triple) { assert((getArchName() == "i386" || getArchName() == "x86_64" || getArchName() == "powerpc" || getArchName() == "powerpc64") && "Unknown Darwin arch."); assert(memcmp(&getOSName()[0], "darwin", 6) == 0 && "Unknown Darwin platform."); const char *Release = &getOSName()[6]; bool HadExtra; if (!Driver::GetReleaseVersion(Release, DarwinVersion[0], DarwinVersion[1], DarwinVersion[2], HadExtra)) { D.Diag(clang::diag::err_drv_invalid_darwin_version) << Release; } // We can only call 4.2.1 for now. GCCVersion[0] = 4; GCCVersion[1] = 2; GCCVersion[2] = 1; } DarwinHostInfo::~DarwinHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool DarwinHostInfo::useDriverDriver() const { return true; } ToolChain *DarwinHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { std::string Arch; if (!ArchName) { Arch = getArchName(); ArchName = Arch.c_str(); // If no arch name is specified, infer it from the host and // -m32/-m64. if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { if (getArchName() == "i386" || getArchName() == "x86_64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "i386" : "x86_64"; } else if (getArchName() == "powerpc" || getArchName() == "powerpc64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "powerpc" : "powerpc64"; } } } else { // Normalize arch name; we shouldn't be doing this here. // // FIXME: This should be unnecessary once everything moves over to using the // ID based Triple interface. if (strcmp(ArchName, "ppc") == 0) ArchName = "powerpc"; else if (strcmp(ArchName, "ppc64") == 0) ArchName = "powerpc64"; } ToolChain *&TC = ToolChains[ArchName]; if (!TC) { llvm::Triple TCTriple(getTriple()); TCTriple.setArchName(ArchName); if (strcmp(ArchName, "i386") == 0 || strcmp(ArchName, "x86_64") == 0) TC = new toolchains::Darwin_X86(*this, TCTriple, DarwinVersion, GCCVersion); else TC = new toolchains::Darwin_GCC(*this, TCTriple); } return TC; } // Unknown Host Info /// UnknownHostInfo - Generic host information to use for unknown /// hosts. class UnknownHostInfo : public HostInfo { /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain*> ToolChains; public: UnknownHostInfo(const Driver &D, const llvm::Triple& Triple); ~UnknownHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; UnknownHostInfo::UnknownHostInfo(const Driver &D, const llvm::Triple& Triple) : HostInfo(D, Triple) { } UnknownHostInfo::~UnknownHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool UnknownHostInfo::useDriverDriver() const { return false; } ToolChain *UnknownHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { assert(!ArchName && "Unexpected arch name on platform without driver driver support."); // Automatically handle some instances of -m32/-m64 we know about. std::string Arch = getArchName(); ArchName = Arch.c_str(); if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { if (getArchName() == "i386" || getArchName() == "x86_64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "i386" : "x86_64"; } else if (getArchName() == "powerpc" || getArchName() == "powerpc64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "powerpc" : "powerpc64"; } } ToolChain *&TC = ToolChains[ArchName]; if (!TC) { llvm::Triple TCTriple(getTriple()); TCTriple.setArchName(ArchName); TC = new toolchains::Generic_GCC(*this, TCTriple); } return TC; } // FreeBSD Host Info /// FreeBSDHostInfo - FreeBSD host information implementation. class FreeBSDHostInfo : public HostInfo { /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain*> ToolChains; public: FreeBSDHostInfo(const Driver &D, const llvm::Triple& Triple) : HostInfo(D, Triple) {} ~FreeBSDHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; FreeBSDHostInfo::~FreeBSDHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool FreeBSDHostInfo::useDriverDriver() const { return false; } ToolChain *FreeBSDHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { bool Lib32 = false; assert(!ArchName && "Unexpected arch name on platform without driver driver support."); // On x86_64 we need to be able to compile 32-bits binaries as well. // Compiling 64-bit binaries on i386 is not supported. We don't have a // lib64. std::string Arch = getArchName(); ArchName = Arch.c_str(); if (Args.hasArg(options::OPT_m32) && getArchName() == "x86_64") { ArchName = "i386"; Lib32 = true; } ToolChain *&TC = ToolChains[ArchName]; if (!TC) { llvm::Triple TCTriple(getTriple()); TCTriple.setArchName(ArchName); TC = new toolchains::FreeBSD(*this, TCTriple, Lib32); } return TC; } // DragonFly Host Info /// DragonFlyHostInfo - DragonFly host information implementation. class DragonFlyHostInfo : public HostInfo { /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain*> ToolChains; public: DragonFlyHostInfo(const Driver &D, const llvm::Triple& Triple) : HostInfo(D, Triple) {} ~DragonFlyHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; DragonFlyHostInfo::~DragonFlyHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool DragonFlyHostInfo::useDriverDriver() const { return false; } ToolChain *DragonFlyHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { assert(!ArchName && "Unexpected arch name on platform without driver driver support."); ToolChain *&TC = ToolChains[getArchName()]; if (!TC) { llvm::Triple TCTriple(getTriple()); TCTriple.setArchName(getArchName()); TC = new toolchains::DragonFly(*this, TCTriple); } return TC; } } const HostInfo * clang::driver::createDarwinHostInfo(const Driver &D, const llvm::Triple& Triple){ return new DarwinHostInfo(D, Triple); } const HostInfo * clang::driver::createFreeBSDHostInfo(const Driver &D, const llvm::Triple& Triple) { return new FreeBSDHostInfo(D, Triple); } const HostInfo * clang::driver::createDragonFlyHostInfo(const Driver &D, const llvm::Triple& Triple) { return new DragonFlyHostInfo(D, Triple); } const HostInfo * clang::driver::createUnknownHostInfo(const Driver &D, const llvm::Triple& Triple) { return new UnknownHostInfo(D, Triple); }
//===--- HostInfo.cpp - Host specific information -----------------------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/HostInfo.h" #include "clang/Driver/Arg.h" #include "clang/Driver/ArgList.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Option.h" #include "clang/Driver/Options.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Compiler.h" #include "ToolChains.h" #include <cassert> using namespace clang::driver; HostInfo::HostInfo(const Driver &D, const llvm::Triple &_Triple) : TheDriver(D), Triple(_Triple) { } HostInfo::~HostInfo() { } namespace { // Darwin Host Info /// DarwinHostInfo - Darwin host information implementation. class DarwinHostInfo : public HostInfo { /// Darwin version of host. unsigned DarwinVersion[3]; /// GCC version to use on this host. unsigned GCCVersion[3]; /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain *> ToolChains; public: DarwinHostInfo(const Driver &D, const llvm::Triple &Triple); ~DarwinHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { types::ID Ty = types::lookupTypeForExtension(Ext); // Darwin always preprocesses assembly files (unless -x is used // explicitly). if (Ty == types::TY_PP_Asm) return types::TY_Asm; return Ty; } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; DarwinHostInfo::DarwinHostInfo(const Driver &D, const llvm::Triple& Triple) : HostInfo(D, Triple) { assert((getArchName() == "i386" || getArchName() == "x86_64" || getArchName() == "powerpc" || getArchName() == "powerpc64") && "Unknown Darwin arch."); assert(memcmp(&getOSName()[0], "darwin", 6) == 0 && "Unknown Darwin platform."); bool HadExtra; if (!Driver::GetReleaseVersion(&getOSName()[6], DarwinVersion[0], DarwinVersion[1], DarwinVersion[2], HadExtra)) { D.Diag(clang::diag::err_drv_invalid_darwin_version) << getOSName(); } // We can only call 4.2.1 for now. GCCVersion[0] = 4; GCCVersion[1] = 2; GCCVersion[2] = 1; } DarwinHostInfo::~DarwinHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool DarwinHostInfo::useDriverDriver() const { return true; } ToolChain *DarwinHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { std::string Arch; if (!ArchName) { Arch = getArchName(); ArchName = Arch.c_str(); // If no arch name is specified, infer it from the host and // -m32/-m64. if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { if (getArchName() == "i386" || getArchName() == "x86_64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "i386" : "x86_64"; } else if (getArchName() == "powerpc" || getArchName() == "powerpc64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "powerpc" : "powerpc64"; } } } else { // Normalize arch name; we shouldn't be doing this here. // // FIXME: This should be unnecessary once everything moves over to using the // ID based Triple interface. if (strcmp(ArchName, "ppc") == 0) ArchName = "powerpc"; else if (strcmp(ArchName, "ppc64") == 0) ArchName = "powerpc64"; } ToolChain *&TC = ToolChains[ArchName]; if (!TC) { llvm::Triple TCTriple(getTriple()); TCTriple.setArchName(ArchName); if (strcmp(ArchName, "i386") == 0 || strcmp(ArchName, "x86_64") == 0) TC = new toolchains::Darwin_X86(*this, TCTriple, DarwinVersion, GCCVersion); else TC = new toolchains::Darwin_GCC(*this, TCTriple); } return TC; } // Unknown Host Info /// UnknownHostInfo - Generic host information to use for unknown /// hosts. class UnknownHostInfo : public HostInfo { /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain*> ToolChains; public: UnknownHostInfo(const Driver &D, const llvm::Triple& Triple); ~UnknownHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; UnknownHostInfo::UnknownHostInfo(const Driver &D, const llvm::Triple& Triple) : HostInfo(D, Triple) { } UnknownHostInfo::~UnknownHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool UnknownHostInfo::useDriverDriver() const { return false; } ToolChain *UnknownHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { assert(!ArchName && "Unexpected arch name on platform without driver driver support."); // Automatically handle some instances of -m32/-m64 we know about. std::string Arch = getArchName(); ArchName = Arch.c_str(); if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { if (getArchName() == "i386" || getArchName() == "x86_64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "i386" : "x86_64"; } else if (getArchName() == "powerpc" || getArchName() == "powerpc64") { ArchName = (A->getOption().getId() == options::OPT_m32) ? "powerpc" : "powerpc64"; } } ToolChain *&TC = ToolChains[ArchName]; if (!TC) { llvm::Triple TCTriple(getTriple()); TCTriple.setArchName(ArchName); TC = new toolchains::Generic_GCC(*this, TCTriple); } return TC; } // FreeBSD Host Info /// FreeBSDHostInfo - FreeBSD host information implementation. class FreeBSDHostInfo : public HostInfo { /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain*> ToolChains; public: FreeBSDHostInfo(const Driver &D, const llvm::Triple& Triple) : HostInfo(D, Triple) {} ~FreeBSDHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; FreeBSDHostInfo::~FreeBSDHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool FreeBSDHostInfo::useDriverDriver() const { return false; } ToolChain *FreeBSDHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { bool Lib32 = false; assert(!ArchName && "Unexpected arch name on platform without driver driver support."); // On x86_64 we need to be able to compile 32-bits binaries as well. // Compiling 64-bit binaries on i386 is not supported. We don't have a // lib64. std::string Arch = getArchName(); ArchName = Arch.c_str(); if (Args.hasArg(options::OPT_m32) && getArchName() == "x86_64") { ArchName = "i386"; Lib32 = true; } ToolChain *&TC = ToolChains[ArchName]; if (!TC) { llvm::Triple TCTriple(getTriple()); TCTriple.setArchName(ArchName); TC = new toolchains::FreeBSD(*this, TCTriple, Lib32); } return TC; } // DragonFly Host Info /// DragonFlyHostInfo - DragonFly host information implementation. class DragonFlyHostInfo : public HostInfo { /// Cache of tool chains we have created. mutable llvm::StringMap<ToolChain*> ToolChains; public: DragonFlyHostInfo(const Driver &D, const llvm::Triple& Triple) : HostInfo(D, Triple) {} ~DragonFlyHostInfo(); virtual bool useDriverDriver() const; virtual types::ID lookupTypeForExtension(const char *Ext) const { return types::lookupTypeForExtension(Ext); } virtual ToolChain *getToolChain(const ArgList &Args, const char *ArchName) const; }; DragonFlyHostInfo::~DragonFlyHostInfo() { for (llvm::StringMap<ToolChain*>::iterator it = ToolChains.begin(), ie = ToolChains.end(); it != ie; ++it) delete it->second; } bool DragonFlyHostInfo::useDriverDriver() const { return false; } ToolChain *DragonFlyHostInfo::getToolChain(const ArgList &Args, const char *ArchName) const { assert(!ArchName && "Unexpected arch name on platform without driver driver support."); ToolChain *&TC = ToolChains[getArchName()]; if (!TC) { llvm::Triple TCTriple(getTriple()); TCTriple.setArchName(getArchName()); TC = new toolchains::DragonFly(*this, TCTriple); } return TC; } } const HostInfo * clang::driver::createDarwinHostInfo(const Driver &D, const llvm::Triple& Triple){ return new DarwinHostInfo(D, Triple); } const HostInfo * clang::driver::createFreeBSDHostInfo(const Driver &D, const llvm::Triple& Triple) { return new FreeBSDHostInfo(D, Triple); } const HostInfo * clang::driver::createDragonFlyHostInfo(const Driver &D, const llvm::Triple& Triple) { return new DragonFlyHostInfo(D, Triple); } const HostInfo * clang::driver::createUnknownHostInfo(const Driver &D, const llvm::Triple& Triple) { return new UnknownHostInfo(D, Triple); }
Fix use after free, found by Benjamin Kramer.
Fix use after free, found by Benjamin Kramer. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@72333 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang
81095614ffb19cdb7e8d95dee6593e32eae4e649
include/depthai-shared/datatype/RawTrackedFeatures.hpp
include/depthai-shared/datatype/RawTrackedFeatures.hpp
#pragma once #include <cstdint> #include <nlohmann/json.hpp> #include <vector> #include "DatatypeEnum.hpp" #include "RawBuffer.hpp" #include "RawFeatureTrackerConfig.hpp" #include "depthai-shared/common/Point2f.hpp" namespace dai { /** * TrackedFeatures structure * */ struct TrackedFeatures { /** * x, y position of the detected feature */ Point2f position; /** * Feature ID */ uint32_t id; /** * Feature age in frames */ uint32_t age; /** * Feature harris score */ float harrisScore; /** * Feature tracking error */ float trackingError; }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(TrackedFeatures, position, id, age, harrisScore, trackingError); /// RawTrackedFeatures structure struct RawTrackedFeatures : public RawBuffer { std::vector<TrackedFeatures> trackedFeatures; void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override { nlohmann::json j = *this; metadata = nlohmann::json::to_msgpack(j); datatype = DatatypeEnum::FeatureTrackerData; }; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawTrackedFeatures, trackedFeatures); }; } // namespace dai
#pragma once #include <cstdint> #include <nlohmann/json.hpp> #include <vector> #include "DatatypeEnum.hpp" #include "RawBuffer.hpp" #include "RawFeatureTrackerConfig.hpp" #include "depthai-shared/common/Point2f.hpp" namespace dai { /** * TrackedFeature structure * */ struct TrackedFeature { /** * x, y position of the detected feature */ Point2f position; /** * Feature ID. Persistent between frames if optical flow is enabled. */ uint32_t id; #if 0 /** * Feature age in frames */ uint32_t age; /** * Feature harris score */ float harrisScore; /** * Feature tracking error */ float trackingError; #endif }; NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(TrackedFeature, position, id); /// RawTrackedFeatures structure struct RawTrackedFeatures : public RawBuffer { std::vector<TrackedFeature> trackedFeatures; void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override { nlohmann::json j = *this; metadata = nlohmann::json::to_msgpack(j); datatype = DatatypeEnum::FeatureTrackerData; }; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawTrackedFeatures, trackedFeatures); }; } // namespace dai
Rename TrackedFeatures to TrackeFeature; disable some field due to serializer overhead
Rename TrackedFeatures to TrackeFeature; disable some field due to serializer overhead
C++
mit
luxonis/depthai-shared
a562cf75bd2dfbd8ec7954e3ebdf2dcca781e489
programs/ping/src/main.cpp
programs/ping/src/main.cpp
//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <tlib/system.hpp> #include <tlib/errors.hpp> #include <tlib/print.hpp> #include <tlib/net.hpp> #include <tlib/dns.hpp> namespace { static constexpr const size_t N = 4; static constexpr const size_t timeout_ms = 2000; } // end of anonymous namespace int main(int argc, char* argv[]) { if (argc != 2) { tlib::print_line("usage: ping address_ip"); return 1; } std::string query(argv[1]); std::string ip; if (tlib::dns::is_ip(query)) { ip = query; } else { auto resolved = tlib::dns::resolve_str(query); if(resolved){ ip = *resolved; } else { tlib::printf("ping: failed to resolve name: %s\n", std::error_message(resolved.error())); } } auto ip_parts = std::split(ip, '.'); if (ip_parts.size() != 4) { tlib::print_line("Invalid address IP"); return 1; } tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::RAW, tlib::socket_protocol::ICMP); if (!sock) { tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } sock.listen(true); if (!sock) { tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } tlib::icmp::packet_descriptor desc; desc.payload_size = 0; desc.target_ip = tlib::ip::make_address(std::atoui(ip_parts[0]), std::atoui(ip_parts[1]), std::atoui(ip_parts[2]), std::atoui(ip_parts[3])); desc.type = tlib::icmp::type::ECHO_REQUEST; desc.code = 0; for (size_t i = 0; i < N; ++i) { auto packet = sock.prepare_packet(&desc); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("Unable to resolve MAC address for target IP\n"); return 1; } tlib::printf("ping: prepare_packet error: %s\n", std::error_message(sock.error())); return 1; } auto* command_header = reinterpret_cast<tlib::icmp::echo_request_header*>(packet.payload + packet.index); command_header->identifier = 0x666; command_header->sequence = 0x1 + i; sock.finalize_packet(packet); if (!sock) { tlib::printf("ping: finalize_packet error: %s\n", std::error_message(sock.error())); return 1; } auto before = tlib::ms_time(); auto after = before; while (true) { // Make sure we don't wait for more than the timeout if (after > before + timeout_ms) { break; } auto remaining = timeout_ms - (after - before); bool handled = false; auto p = sock.wait_for_packet(remaining); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("%s unreachable\n", ip.c_str()); handled = true; sock.clear(); } else { tlib::printf("ping: wait_for_packet error: %s\n", std::error_message(sock.error())); return 1; } } else { auto* icmp_header = reinterpret_cast<tlib::icmp::header*>(p.payload + p.index); auto command_type = static_cast<tlib::icmp::type>(icmp_header->type); if (command_type == tlib::icmp::type::ECHO_REPLY) { tlib::printf("Reply received from %s\n", ip.c_str()); handled = true; } } if (handled) { break; } after = tlib::ms_time(); } if (i < N - 1) { tlib::sleep_ms(1000); } } sock.listen(false); return 0; }
//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <tlib/system.hpp> #include <tlib/errors.hpp> #include <tlib/print.hpp> #include <tlib/net.hpp> #include <tlib/dns.hpp> namespace { static constexpr const size_t N = 4; static constexpr const size_t timeout_ms = 2000; void debug_print(bool debug, const char* message){ if(debug){ tlib::print_line(message); } } } // end of anonymous namespace int main(int argc, char* argv[]) { bool debug = false; size_t i = 1; for(; i < size_t(argc); ++i){ std::string param(argv[i]); if(param == "-d"){ debug = true; } else { break; } } if (argc - i != 1) { tlib::print_line("usage: ping [options] address_ip"); return 1; } std::string query(argv[i]); std::string ip; if (tlib::dns::is_ip(query)) { ip = query; } else { debug_print(debug, "ping: Resolve name..."); auto resolved = tlib::dns::resolve_str(query); debug_print(debug, "ping: name resolved"); if(resolved){ ip = *resolved; } else { tlib::printf("ping: failed to resolve name: %s\n", std::error_message(resolved.error())); } } auto ip_parts = std::split(ip, '.'); if (ip_parts.size() != 4) { tlib::print_line("Invalid address IP"); return 1; } tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::RAW, tlib::socket_protocol::ICMP); if (!sock) { tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } sock.listen(true); if (!sock) { tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } tlib::icmp::packet_descriptor desc; desc.payload_size = 0; desc.target_ip = tlib::ip::make_address(std::atoui(ip_parts[0]), std::atoui(ip_parts[1]), std::atoui(ip_parts[2]), std::atoui(ip_parts[3])); desc.type = tlib::icmp::type::ECHO_REQUEST; desc.code = 0; for (size_t i = 0; i < N; ++i) { debug_print(debug, "ping: prepare packet..."); auto packet = sock.prepare_packet(&desc); debug_print(debug, "ping: packet prepared"); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("Unable to resolve MAC address for target IP\n"); return 1; } tlib::printf("ping: prepare_packet error: %s\n", std::error_message(sock.error())); return 1; } auto* command_header = reinterpret_cast<tlib::icmp::echo_request_header*>(packet.payload + packet.index); command_header->identifier = 0x666; command_header->sequence = 0x1 + i; debug_print(debug, "ping: finalize packet..."); sock.finalize_packet(packet); debug_print(debug, "ping: packet finalized"); if (!sock) { tlib::printf("ping: finalize_packet error: %s\n", std::error_message(sock.error())); return 1; } auto before = tlib::ms_time(); auto after = before; while (true) { // Make sure we don't wait for more than the timeout if (after > before + timeout_ms) { break; } auto remaining = timeout_ms - (after - before); bool handled = false; debug_print(debug, "ping: wait for packet..."); auto p = sock.wait_for_packet(remaining); debug_print(debug, "ping: packet received"); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("%s unreachable\n", ip.c_str()); handled = true; sock.clear(); } else { tlib::printf("ping: wait_for_packet error: %s\n", std::error_message(sock.error())); return 1; } } else { auto* icmp_header = reinterpret_cast<tlib::icmp::header*>(p.payload + p.index); auto command_type = static_cast<tlib::icmp::type>(icmp_header->type); if (command_type == tlib::icmp::type::ECHO_REPLY) { tlib::printf("Reply received from %s\n", ip.c_str()); handled = true; } } if (handled) { break; } after = tlib::ms_time(); } if (i < N - 1) { tlib::sleep_ms(1000); } } sock.listen(false); return 0; }
Add debug mode to ping
Add debug mode to ping
C++
mit
wichtounet/thor-os,wichtounet/thor-os
6ce8b01d3707dbf6c7c5399bdc068749a2a11dc7
include/traits.hpp
include/traits.hpp
#pragma once #include <type_traits> namespace aaa { template<typename Container> using value_type = typename Container::value_type; template<typename Iterator> using value_type_i = typename std::iterator_traits<Iterator>::value_type; template<typename Container> using iterator = typename Container::iterator; template<typename Container> using const_iterator = typename Container::const_iterator; template<typename T> struct sqrt_type { using type = double; }; template<> struct sqrt_type<float> { using type = float; }; template<> struct sqrt_type<long double> { using type = long double; }; template<typename T> using sqrt_type_t = typename sqrt_type<T>::type; template<typename Container> using sqrt_value_type = sqrt_type_t<value_type<Container>>; template<typename Iterator> using sqrt_value_type_i = sqrt_type_t<value_type_i<Iterator>>; // This is what we want. However, it requires Expression SFINAE, which is not // yet supported in MSVC, unless MSVC uses Clang. #if !_MSC_VER || __clang__ template<typename A, typename B, typename C> using check_sum = typename decltype(C{ A{} + B{} })*; template<typename A, typename B, typename C> using check_difference = typename decltype(C{ A{} - B{} })*; template<typename A, typename B, typename C> using check_product = typename decltype(C{ A{} * B{} })*; template<typename A, typename B, typename C> using check_ratio = typename decltype(C{ A{} / B{} })*; #else // Fallback for MSVC without Clang. template<typename A, typename B, typename C = B> using enable_if_same = typename std::enable_if< std::is_same<A, B>::value && std::is_same<B, C>::value, void*>::type; template<typename A, typename B, typename C> using check_sum = enable_if_same<A, B, C>; template<typename A, typename B, typename C> using check_difference = enable_if_same<A, B, C>; template<typename A, typename B, typename C> using check_product = enable_if_same<A, B, C>; template<typename A, typename B, typename C> using check_ratio = enable_if_same<A, B, C>; #endif } // namespace aaa
#pragma once #include <type_traits> namespace aaa { template<typename Container> using value_type = typename Container::value_type; template<typename Iterator> using value_type_i = typename std::iterator_traits<Iterator>::value_type; template<typename Container> using iterator = typename Container::iterator; template<typename Container> using const_iterator = typename Container::const_iterator; template<typename T> struct sqrt_type { using type = double; }; template<> struct sqrt_type<float> { using type = float; }; template<> struct sqrt_type<long double> { using type = long double; }; template<typename T> using sqrt_type_t = typename sqrt_type<T>::type; template<typename Container> using sqrt_value_type = sqrt_type_t<value_type<Container>>; template<typename Iterator> using sqrt_value_type_i = sqrt_type_t<value_type_i<Iterator>>; // This is what we want. However, it requires Expression SFINAE, which is not // yet supported in MSVC, unless MSVC uses Clang. #if !_MSC_VER || __clang__ template<typename A, typename B, typename C> using check_sum = decltype(C{ A{} + B{} })*; template<typename A, typename B, typename C> using check_difference = decltype(C{ A{} - B{} })*; template<typename A, typename B, typename C> using check_product = decltype(C{ A{} * B{} })*; template<typename A, typename B, typename C> using check_ratio = decltype(C{ A{} / B{} })*; #else // Fallback for MSVC without Clang. template<typename A, typename B, typename C = B> using enable_if_same = typename std::enable_if< std::is_same<A, B>::value && std::is_same<B, C>::value, void*>::type; template<typename A, typename B, typename C> using check_sum = enable_if_same<A, B, C>; template<typename A, typename B, typename C> using check_difference = enable_if_same<A, B, C>; template<typename A, typename B, typename C> using check_product = enable_if_same<A, B, C>; template<typename A, typename B, typename C> using check_ratio = enable_if_same<A, B, C>; #endif } // namespace aaa
Remove unnecessary typename
Remove unnecessary typename
C++
mit
mabur/aaa,mabur/aaa,mabur/aaa
ab9a563a28f4c085ab80e7eb73911302159f8480
input-context/glibdbusimserverproxy.cpp
input-context/glibdbusimserverproxy.cpp
/* * This file is part of meego-im-framework * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation ([email protected]) * * 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 "glibdbusimserverproxy.h" #include "minputcontext.h" #include "mdbusglibinputcontextadaptor.h" #include <QPoint> #include <QRect> #include <QString> #include <QDataStream> #include <QVariant> #include <QTimer> #include <QDateTime> #include <QDebug> #include <unistd.h> #include <sys/types.h> namespace { const char * const DBusPath("/com/meego/inputmethod/uiserver1"); const char * const DBusInterface("com.meego.inputmethod.uiserver1"); const char * const SocketPath = "unix:path=/tmp/meego-im-uiserver/imserver_dbus"; const int ConnectionRetryInterval(6*1000); // in ms const QString icAdaptorPath("/com/meego/inputmethod/inputcontext"); Maliit::DBusGLib::ConnectionRef toRef(DBusGConnection *connection) { if (!connection) return Maliit::DBusGLib::ConnectionRef(); return Maliit::DBusGLib::ConnectionRef(connection, dbus_g_connection_unref); } bool encodeVariant(GValue *dest, const QVariant &source) { switch (source.type()) { case QVariant::Bool: g_value_init(dest, G_TYPE_BOOLEAN); g_value_set_boolean(dest, source.toBool()); return true; case QVariant::Int: g_value_init(dest, G_TYPE_INT); g_value_set_int(dest, source.toInt()); return true; case QVariant::UInt: g_value_init(dest, G_TYPE_UINT); g_value_set_uint(dest, source.toUInt()); return true; case QVariant::LongLong: g_value_init(dest, G_TYPE_INT64); g_value_set_int64(dest, source.toLongLong()); return true; case QVariant::ULongLong: g_value_init(dest, G_TYPE_UINT64); g_value_set_uint64(dest, source.toULongLong()); return true; case QVariant::Double: g_value_init(dest, G_TYPE_DOUBLE); g_value_set_double(dest, source.toDouble()); return true; case QVariant::String: g_value_init(dest, G_TYPE_STRING); // string is copied by g_value_set_string g_value_set_string(dest, source.toString().toUtf8().constData()); return true; case QVariant::Rect: { // QRect is encoded as (iiii). // This is compatible with QDBusArgument encoding. see more in decoder GType structType = dbus_g_type_get_struct("GValueArray", G_TYPE_INT, G_TYPE_INT, G_TYPE_INT, G_TYPE_INT, G_TYPE_INVALID); g_value_init(dest, structType); GValueArray *array = (GValueArray*)dbus_g_type_specialized_construct(structType); if (!array) { qWarning() << Q_FUNC_INFO << "failed to initialize Rect instance"; } g_value_take_boxed(dest, array); QRect rect = source.toRect(); if (!dbus_g_type_struct_set(dest, 0, rect.left(), 1, rect.top(), 2, rect.width(), 3, rect.height(), G_MAXUINT)) { g_value_unset(dest); qWarning() << Q_FUNC_INFO << "failed to fill Rect instance"; return false; } return true; } case QMetaType::ULong: g_value_init(dest, G_TYPE_ULONG); g_value_set_ulong(dest, source.value<ulong>()); return true; default: qWarning() << Q_FUNC_INFO << "unsupported data:" << source.type() << source; return false; } } void destroyGValue(GValue *value) { g_value_unset(value); g_free(value); } GHashTable *encodeVariantMap(const QMap<QString, QVariant> &source) { GHashTable* result = g_hash_table_new_full(&g_str_hash, &g_str_equal, &g_free, GDestroyNotify(&destroyGValue)); Q_FOREACH (QString key, source.keys()) { GValue *valueVariant = g_new0(GValue, 1); if (!encodeVariant(valueVariant, source[key])) { g_free(valueVariant); g_hash_table_unref(result); return 0; } g_hash_table_insert(result, g_strdup(key.toUtf8().constData()), valueVariant); } return result; } } GlibDBusIMServerProxy::GlibDBusIMServerProxy(QObject *parent) : glibObjectProxy(NULL), connection(), active(true) { Q_UNUSED(parent); g_type_init(); MDBusGlibInputContextAdaptor *adaptor = M_DBUS_GLIB_INPUT_CONTEXT_ADAPTOR( g_object_new(M_TYPE_DBUS_GLIB_INPUT_CONTEXT_ADAPTOR, NULL)); adaptor->imServerConnection = this; inputContextAdaptor = G_OBJECT(adaptor); dbus_g_thread_init(); connectToDBus(); } GlibDBusIMServerProxy::~GlibDBusIMServerProxy() { active = false; Q_FOREACH (DBusGProxyCall *callId, pendingResetCalls) { dbus_g_proxy_cancel_call(glibObjectProxy, callId); } } // Auxiliary connection handling............................................. void GlibDBusIMServerProxy::onDisconnectionTrampoline(DBusGProxy */*proxy*/, gpointer userData) { if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__; static_cast<GlibDBusIMServerProxy *>(userData)->onDisconnection(); } void GlibDBusIMServerProxy::connectToDBus() { if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__; GError *error = NULL; connection = toRef(dbus_g_connection_open(SocketPath, &error)); if (!connection) { if (error) { qWarning("MInputContext: unable to create D-Bus connection: %s", error->message); g_error_free(error); } QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus())); return; } glibObjectProxy = dbus_g_proxy_new_for_peer(connection.get(), DBusPath, DBusInterface); if (!glibObjectProxy) { qWarning("MInputContext: unable to find the D-Bus service."); connection.reset(); QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus())); return; } g_signal_connect(G_OBJECT(glibObjectProxy), "destroy", G_CALLBACK(onDisconnectionTrampoline), this); dbus_g_connection_register_g_object(connection.get(), icAdaptorPath.toAscii().data(), inputContextAdaptor); Q_EMIT connected(); } void GlibDBusIMServerProxy::onDisconnection() { if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__; glibObjectProxy = 0; connection.reset(); Q_EMIT disconnected(); if (active) { QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus())); } } void GlibDBusIMServerProxy::resetNotifyTrampoline(DBusGProxy *proxy, DBusGProxyCall *callId, gpointer userData) { static_cast<GlibDBusIMServerProxy *>(userData)->resetNotify(proxy, callId); } void GlibDBusIMServerProxy::resetNotify(DBusGProxy *proxy, DBusGProxyCall *callId) { if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__; dbus_g_proxy_end_call(proxy, callId, 0, G_TYPE_INVALID); pendingResetCalls.remove(callId); } // Remote methods............................................................ void GlibDBusIMServerProxy::activateContext() { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "activateContext", G_TYPE_INVALID); } void GlibDBusIMServerProxy::showInputMethod() { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "showInputMethod", G_TYPE_INVALID); } void GlibDBusIMServerProxy::hideInputMethod() { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "hideInputMethod", G_TYPE_INVALID); } void GlibDBusIMServerProxy::mouseClickedOnPreedit(const QPoint &pos, const QRect &preeditRect) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "mouseClickedOnPreedit", G_TYPE_INT, pos.x(), G_TYPE_INT, pos.y(), G_TYPE_INT, preeditRect.x(), G_TYPE_INT, preeditRect.y(), G_TYPE_INT, preeditRect.width(), G_TYPE_INT, preeditRect.height(), G_TYPE_INVALID); } void GlibDBusIMServerProxy::setPreedit(const QString &text, int cursorPos) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "setPreedit", G_TYPE_STRING, text.toUtf8().data(), G_TYPE_INT, cursorPos, G_TYPE_INVALID); } void GlibDBusIMServerProxy::updateWidgetInformation(const QMap<QString, QVariant> &stateInformation, bool focusChanged) { if (!glibObjectProxy) { return; } GHashTable *encodedState = encodeVariantMap(stateInformation); if (encodedState == 0) return; GType encodedStateType = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE); dbus_g_proxy_call_no_reply(glibObjectProxy, "updateWidgetInformation", encodedStateType, encodedState, G_TYPE_BOOLEAN, focusChanged, G_TYPE_INVALID); g_hash_table_unref(encodedState); } void GlibDBusIMServerProxy::reset(bool requireSynchronization) { if (!glibObjectProxy) { return; } if (requireSynchronization) { DBusGProxyCall *resetCall = dbus_g_proxy_begin_call(glibObjectProxy, "reset", resetNotifyTrampoline, this, 0, G_TYPE_INVALID); pendingResetCalls.insert(resetCall); } else { dbus_g_proxy_call_no_reply(glibObjectProxy, "reset", G_TYPE_INVALID); } } bool GlibDBusIMServerProxy::pendingResets() { return (pendingResetCalls.size() > 0); } void GlibDBusIMServerProxy::appOrientationAboutToChange(int angle) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationAboutToChange", G_TYPE_INT, angle, G_TYPE_INVALID); } void GlibDBusIMServerProxy::appOrientationChanged(int angle) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationChanged", G_TYPE_INT, angle, G_TYPE_INVALID); } void GlibDBusIMServerProxy::setCopyPasteState(bool copyAvailable, bool pasteAvailable) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "setCopyPasteState", G_TYPE_BOOLEAN, copyAvailable, G_TYPE_BOOLEAN, pasteAvailable, G_TYPE_INVALID); } void GlibDBusIMServerProxy::processKeyEvent(QEvent::Type keyType, Qt::Key keyCode, Qt::KeyboardModifiers modifiers, const QString &text, bool autoRepeat, int count, quint32 nativeScanCode, quint32 nativeModifiers, unsigned long time) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "processKeyEvent", G_TYPE_INT, static_cast<int>(keyType), G_TYPE_INT, static_cast<int>(keyCode), G_TYPE_INT, static_cast<int>(modifiers), G_TYPE_STRING, text.toUtf8().data(), G_TYPE_BOOLEAN, autoRepeat, G_TYPE_INT, count, G_TYPE_UINT, nativeScanCode, G_TYPE_UINT, nativeModifiers, G_TYPE_ULONG, time, G_TYPE_INVALID); } void GlibDBusIMServerProxy::registerAttributeExtension(int id, const QString &fileName) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "registerAttributeExtension", G_TYPE_INT, id, G_TYPE_STRING, fileName.toUtf8().data(), G_TYPE_INVALID); } void GlibDBusIMServerProxy::unregisterAttributeExtension(int id) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "unregisterAttributeExtension", G_TYPE_INT, id, G_TYPE_INVALID); } void GlibDBusIMServerProxy::setExtendedAttribute(int id, const QString &target, const QString &targetItem, const QString &attribute, const QVariant &value) { if (!glibObjectProxy) { return; } GValue valueData = {0, {{0}, {0}}}; if (!encodeVariant(&valueData, value)) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "setExtendedAttribute", G_TYPE_INT, id, G_TYPE_STRING, target.toUtf8().data(), G_TYPE_STRING, targetItem.toUtf8().data(), G_TYPE_STRING, attribute.toUtf8().data(), G_TYPE_VALUE, &valueData, G_TYPE_INVALID); g_value_unset(&valueData); }
/* * This file is part of meego-im-framework * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation ([email protected]) * * 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 "glibdbusimserverproxy.h" #include "minputcontext.h" #include "mdbusglibinputcontextadaptor.h" #include <QPoint> #include <QRect> #include <QString> #include <QDataStream> #include <QVariant> #include <QTimer> #include <QDateTime> #include <QDebug> #include <unistd.h> #include <sys/types.h> namespace { const char * const DBusPath("/com/meego/inputmethod/uiserver1"); const char * const DBusInterface("com.meego.inputmethod.uiserver1"); const char * const SocketPath = "unix:path=/tmp/meego-im-uiserver/imserver_dbus"; const int ConnectionRetryInterval(6*1000); // in ms const QString icAdaptorPath("/com/meego/inputmethod/inputcontext"); Maliit::DBusGLib::ConnectionRef toRef(DBusGConnection *connection) { if (!connection) return Maliit::DBusGLib::ConnectionRef(); return Maliit::DBusGLib::ConnectionRef(connection, dbus_g_connection_unref); } bool encodeVariant(GValue *dest, const QVariant &source) { switch (static_cast<QMetaType::Type>(source.type())) { case QMetaType::Bool: g_value_init(dest, G_TYPE_BOOLEAN); g_value_set_boolean(dest, source.toBool()); return true; case QMetaType::Int: g_value_init(dest, G_TYPE_INT); g_value_set_int(dest, source.toInt()); return true; case QMetaType::UInt: g_value_init(dest, G_TYPE_UINT); g_value_set_uint(dest, source.toUInt()); return true; case QMetaType::LongLong: g_value_init(dest, G_TYPE_INT64); g_value_set_int64(dest, source.toLongLong()); return true; case QMetaType::ULongLong: g_value_init(dest, G_TYPE_UINT64); g_value_set_uint64(dest, source.toULongLong()); return true; case QMetaType::Double: g_value_init(dest, G_TYPE_DOUBLE); g_value_set_double(dest, source.toDouble()); return true; case QMetaType::QString: g_value_init(dest, G_TYPE_STRING); // string is copied by g_value_set_string g_value_set_string(dest, source.toString().toUtf8().constData()); return true; case QMetaType::QRect: { // QRect is encoded as (iiii). // This is compatible with QDBusArgument encoding. see more in decoder GType structType = dbus_g_type_get_struct("GValueArray", G_TYPE_INT, G_TYPE_INT, G_TYPE_INT, G_TYPE_INT, G_TYPE_INVALID); g_value_init(dest, structType); GValueArray *array = (GValueArray*)dbus_g_type_specialized_construct(structType); if (!array) { qWarning() << Q_FUNC_INFO << "failed to initialize Rect instance"; } g_value_take_boxed(dest, array); QRect rect = source.toRect(); if (!dbus_g_type_struct_set(dest, 0, rect.left(), 1, rect.top(), 2, rect.width(), 3, rect.height(), G_MAXUINT)) { g_value_unset(dest); qWarning() << Q_FUNC_INFO << "failed to fill Rect instance"; return false; } return true; } case QMetaType::ULong: g_value_init(dest, G_TYPE_ULONG); g_value_set_ulong(dest, source.value<ulong>()); return true; default: qWarning() << Q_FUNC_INFO << "unsupported data:" << source.type() << source; return false; } } void destroyGValue(GValue *value) { g_value_unset(value); g_free(value); } GHashTable *encodeVariantMap(const QMap<QString, QVariant> &source) { GHashTable* result = g_hash_table_new_full(&g_str_hash, &g_str_equal, &g_free, GDestroyNotify(&destroyGValue)); Q_FOREACH (QString key, source.keys()) { GValue *valueVariant = g_new0(GValue, 1); if (!encodeVariant(valueVariant, source[key])) { g_free(valueVariant); g_hash_table_unref(result); return 0; } g_hash_table_insert(result, g_strdup(key.toUtf8().constData()), valueVariant); } return result; } } GlibDBusIMServerProxy::GlibDBusIMServerProxy(QObject *parent) : glibObjectProxy(NULL), connection(), active(true) { Q_UNUSED(parent); g_type_init(); MDBusGlibInputContextAdaptor *adaptor = M_DBUS_GLIB_INPUT_CONTEXT_ADAPTOR( g_object_new(M_TYPE_DBUS_GLIB_INPUT_CONTEXT_ADAPTOR, NULL)); adaptor->imServerConnection = this; inputContextAdaptor = G_OBJECT(adaptor); dbus_g_thread_init(); connectToDBus(); } GlibDBusIMServerProxy::~GlibDBusIMServerProxy() { active = false; Q_FOREACH (DBusGProxyCall *callId, pendingResetCalls) { dbus_g_proxy_cancel_call(glibObjectProxy, callId); } } // Auxiliary connection handling............................................. void GlibDBusIMServerProxy::onDisconnectionTrampoline(DBusGProxy */*proxy*/, gpointer userData) { if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__; static_cast<GlibDBusIMServerProxy *>(userData)->onDisconnection(); } void GlibDBusIMServerProxy::connectToDBus() { if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__; GError *error = NULL; connection = toRef(dbus_g_connection_open(SocketPath, &error)); if (!connection) { if (error) { qWarning("MInputContext: unable to create D-Bus connection: %s", error->message); g_error_free(error); } QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus())); return; } glibObjectProxy = dbus_g_proxy_new_for_peer(connection.get(), DBusPath, DBusInterface); if (!glibObjectProxy) { qWarning("MInputContext: unable to find the D-Bus service."); connection.reset(); QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus())); return; } g_signal_connect(G_OBJECT(glibObjectProxy), "destroy", G_CALLBACK(onDisconnectionTrampoline), this); dbus_g_connection_register_g_object(connection.get(), icAdaptorPath.toAscii().data(), inputContextAdaptor); Q_EMIT connected(); } void GlibDBusIMServerProxy::onDisconnection() { if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__; glibObjectProxy = 0; connection.reset(); Q_EMIT disconnected(); if (active) { QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus())); } } void GlibDBusIMServerProxy::resetNotifyTrampoline(DBusGProxy *proxy, DBusGProxyCall *callId, gpointer userData) { static_cast<GlibDBusIMServerProxy *>(userData)->resetNotify(proxy, callId); } void GlibDBusIMServerProxy::resetNotify(DBusGProxy *proxy, DBusGProxyCall *callId) { if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__; dbus_g_proxy_end_call(proxy, callId, 0, G_TYPE_INVALID); pendingResetCalls.remove(callId); } // Remote methods............................................................ void GlibDBusIMServerProxy::activateContext() { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "activateContext", G_TYPE_INVALID); } void GlibDBusIMServerProxy::showInputMethod() { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "showInputMethod", G_TYPE_INVALID); } void GlibDBusIMServerProxy::hideInputMethod() { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "hideInputMethod", G_TYPE_INVALID); } void GlibDBusIMServerProxy::mouseClickedOnPreedit(const QPoint &pos, const QRect &preeditRect) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "mouseClickedOnPreedit", G_TYPE_INT, pos.x(), G_TYPE_INT, pos.y(), G_TYPE_INT, preeditRect.x(), G_TYPE_INT, preeditRect.y(), G_TYPE_INT, preeditRect.width(), G_TYPE_INT, preeditRect.height(), G_TYPE_INVALID); } void GlibDBusIMServerProxy::setPreedit(const QString &text, int cursorPos) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "setPreedit", G_TYPE_STRING, text.toUtf8().data(), G_TYPE_INT, cursorPos, G_TYPE_INVALID); } void GlibDBusIMServerProxy::updateWidgetInformation(const QMap<QString, QVariant> &stateInformation, bool focusChanged) { if (!glibObjectProxy) { return; } GHashTable *encodedState = encodeVariantMap(stateInformation); if (encodedState == 0) return; GType encodedStateType = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE); dbus_g_proxy_call_no_reply(glibObjectProxy, "updateWidgetInformation", encodedStateType, encodedState, G_TYPE_BOOLEAN, focusChanged, G_TYPE_INVALID); g_hash_table_unref(encodedState); } void GlibDBusIMServerProxy::reset(bool requireSynchronization) { if (!glibObjectProxy) { return; } if (requireSynchronization) { DBusGProxyCall *resetCall = dbus_g_proxy_begin_call(glibObjectProxy, "reset", resetNotifyTrampoline, this, 0, G_TYPE_INVALID); pendingResetCalls.insert(resetCall); } else { dbus_g_proxy_call_no_reply(glibObjectProxy, "reset", G_TYPE_INVALID); } } bool GlibDBusIMServerProxy::pendingResets() { return (pendingResetCalls.size() > 0); } void GlibDBusIMServerProxy::appOrientationAboutToChange(int angle) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationAboutToChange", G_TYPE_INT, angle, G_TYPE_INVALID); } void GlibDBusIMServerProxy::appOrientationChanged(int angle) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationChanged", G_TYPE_INT, angle, G_TYPE_INVALID); } void GlibDBusIMServerProxy::setCopyPasteState(bool copyAvailable, bool pasteAvailable) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "setCopyPasteState", G_TYPE_BOOLEAN, copyAvailable, G_TYPE_BOOLEAN, pasteAvailable, G_TYPE_INVALID); } void GlibDBusIMServerProxy::processKeyEvent(QEvent::Type keyType, Qt::Key keyCode, Qt::KeyboardModifiers modifiers, const QString &text, bool autoRepeat, int count, quint32 nativeScanCode, quint32 nativeModifiers, unsigned long time) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "processKeyEvent", G_TYPE_INT, static_cast<int>(keyType), G_TYPE_INT, static_cast<int>(keyCode), G_TYPE_INT, static_cast<int>(modifiers), G_TYPE_STRING, text.toUtf8().data(), G_TYPE_BOOLEAN, autoRepeat, G_TYPE_INT, count, G_TYPE_UINT, nativeScanCode, G_TYPE_UINT, nativeModifiers, G_TYPE_ULONG, time, G_TYPE_INVALID); } void GlibDBusIMServerProxy::registerAttributeExtension(int id, const QString &fileName) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "registerAttributeExtension", G_TYPE_INT, id, G_TYPE_STRING, fileName.toUtf8().data(), G_TYPE_INVALID); } void GlibDBusIMServerProxy::unregisterAttributeExtension(int id) { if (!glibObjectProxy) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "unregisterAttributeExtension", G_TYPE_INT, id, G_TYPE_INVALID); } void GlibDBusIMServerProxy::setExtendedAttribute(int id, const QString &target, const QString &targetItem, const QString &attribute, const QVariant &value) { if (!glibObjectProxy) { return; } GValue valueData = {0, {{0}, {0}}}; if (!encodeVariant(&valueData, value)) { return; } dbus_g_proxy_call_no_reply(glibObjectProxy, "setExtendedAttribute", G_TYPE_INT, id, G_TYPE_STRING, target.toUtf8().data(), G_TYPE_STRING, targetItem.toUtf8().data(), G_TYPE_STRING, attribute.toUtf8().data(), G_TYPE_VALUE, &valueData, G_TYPE_INVALID); g_value_unset(&valueData); }
Use QMetaType::Type instead of QVariant::Type.
Changes: Use QMetaType::Type instead of QVariant::Type. RevBy: Jon Nordby Details: Silences a compile warning.
C++
lgpl-2.1
jpetersen/framework,sil2100/maliit-framework,RHawkeyed/framework,RHawkeyed/framework,binlaten/framework,Elleo/framework,Elleo/framework,sil2100/maliit-framework,sil2100/maliit-framework,sil2100/maliit-framework,jpetersen/framework
b50d0ca40036a858378cf24b1f3cd7e32e8e8ec5
base/file_util.cc
base/file_util.cc
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include <stdio.h> #include <fstream> #include "base/logging.h" #include "base/string_util.h" #include "unicode/uniset.h" namespace file_util { const wchar_t kExtensionSeparator = L'.'; void PathComponents(const std::wstring& path, std::vector<std::wstring>* components) { DCHECK(components != NULL); if (components == NULL) return; std::wstring::size_type start = 0; std::wstring::size_type end = path.find(kPathSeparator, start); // Special case the "/" or "\" directory. On Windows with a drive letter, // this code path won't hit, but the right thing should still happen. // "E:\foo" will turn into "E:","foo". if (end == start) { components->push_back(std::wstring(path, 0, 1)); start = end + 1; end = path.find(kPathSeparator, start); } while (end != std::wstring::npos) { std::wstring component = std::wstring(path, start, end - start); components->push_back(component); start = end + 1; end = path.find(kPathSeparator, start); } std::wstring component = std::wstring(path, start); components->push_back(component); } bool EndsWithSeparator(std::wstring* path) { return EndsWithSeparator(*path); } bool EndsWithSeparator(const std::wstring& path) { bool is_sep = (path.length() > 0 && (path)[path.length() - 1] == kPathSeparator); return is_sep; } void TrimTrailingSeparator(std::wstring* dir) { while (dir->length() > 1 && EndsWithSeparator(dir)) dir->resize(dir->length() - 1); } void UpOneDirectory(std::wstring* dir) { TrimTrailingSeparator(dir); std::wstring::size_type last_sep = dir->find_last_of(kPathSeparator); if (last_sep != std::wstring::npos) dir->resize(last_sep); } void UpOneDirectoryOrEmpty(std::wstring* dir) { TrimTrailingSeparator(dir); std::wstring::size_type last_sep = dir->find_last_of(kPathSeparator); if (last_sep != std::wstring::npos) dir->resize(last_sep); else dir->clear(); } void TrimFilename(std::wstring* path) { if (EndsWithSeparator(path)) { TrimTrailingSeparator(path); } else { std::wstring::size_type last_sep = path->find_last_of(kPathSeparator); if (last_sep != std::wstring::npos) path->resize(last_sep); } } std::wstring GetFilenameFromPath(const std::wstring& path) { // TODO(erikkay): fix this - it's not using kPathSeparator, but win unit test // are exercising '/' as a path separator as well. std::wstring::size_type pos = path.find_last_of(L"\\/"); return std::wstring(path, pos == std::wstring::npos ? 0 : pos+1); } std::wstring GetFileExtensionFromPath(const std::wstring& path) { std::wstring file_name = GetFilenameFromPath(path); std::wstring::size_type last_dot = file_name.rfind(L'.'); return std::wstring(last_dot == std::wstring::npos? L"" : file_name, last_dot+1); } void AppendToPath(std::wstring* path, const std::wstring& new_ending) { if (!path) { NOTREACHED(); return; // Don't crash in this function in release builds. } if (!EndsWithSeparator(path)) path->push_back(kPathSeparator); path->append(new_ending); } void InsertBeforeExtension(std::wstring* path, const std::wstring& suffix) { DCHECK(path); const std::wstring::size_type last_dot = path->rfind(kExtensionSeparator); const std::wstring::size_type last_sep = path->rfind(kPathSeparator); if (last_dot == std::wstring::npos || (last_sep != std::wstring::npos && last_dot < last_sep)) { // The path looks something like "C:\pics.old\jojo" or "C:\pics\jojo". // We should just append the suffix to the entire path. path->append(suffix); return; } path->insert(last_dot, suffix); } void ReplaceIllegalCharacters(std::wstring* file_name, int replace_char) { DCHECK(file_name); // Control characters, formatting characters, non-characters, and // some printable ASCII characters regarded as dangerous ('"*/:<>?\\'). // See http://blogs.msdn.com/michkap/archive/2006/11/03/941420.aspx // and http://msdn2.microsoft.com/en-us/library/Aa365247.aspx // TODO(jungshik): Revisit the set. ZWJ and ZWNJ are excluded because they // are legitimate in Arabic and some S/SE Asian scripts. However, when used // elsewhere, they can be confusing/problematic. // Also, consider wrapping the set with our Singleton class to create and // freeze it only once. Note that there's a trade-off between memory and // speed. UErrorCode status = U_ZERO_ERROR; #if defined(WCHAR_T_IS_UTF16) UnicodeSet illegal_characters(UnicodeString( L"[[\"*/:<>?\\\\|][:Cc:][:Cf:] - [\u200c\u200d]]"), status); #else UnicodeSet illegal_characters(UNICODE_STRING_SIMPLE( "[[\"*/:<>?\\\\|][:Cc:][:Cf:] - [\\u200c\\u200d]]").unescape(), status); #endif DCHECK(U_SUCCESS(status)); // Add non-characters. If this becomes a performance bottleneck by // any chance, check |ucs4 & 0xFFFEu == 0xFFFEu|, instead. illegal_characters.add(0xFDD0, 0xFDEF); for (int i = 0; i <= 0x10; ++i) { int plane_base = 0x10000 * i; illegal_characters.add(plane_base + 0xFFFE, plane_base + 0xFFFF); } illegal_characters.freeze(); DCHECK(!illegal_characters.contains(replace_char) && replace_char < 0x10000); // Remove leading and trailing whitespace. TrimWhitespace(*file_name, TRIM_ALL, file_name); std::wstring::size_type i = 0; std::wstring::size_type length = file_name->size(); const wchar_t* wstr = file_name->data(); #if defined(WCHAR_T_IS_UTF16) // Using |span| method of UnicodeSet might speed things up a bit, but // it's not likely to matter here. std::wstring temp; temp.reserve(length); while (i < length) { UChar32 ucs4; std::wstring::size_type prev = i; U16_NEXT(wstr, i, length, ucs4); if (illegal_characters.contains(ucs4)) { temp.push_back(replace_char); } else if (ucs4 < 0x10000) { temp.push_back(ucs4); } else { temp.push_back(wstr[prev]); temp.push_back(wstr[prev + 1]); } } file_name->swap(temp); #elif defined(WCHAR_T_IS_UTF32) while (i < length) { if (illegal_characters.contains(wstr[i])) { (*file_name)[i] = replace_char; } ++i; } #else #error wchar_t* should be either UTF-16 or UTF-32 #endif } // Appends the extension to file adding a '.' if extension doesn't contain one. // This does nothing if extension is empty or '.'. This is used internally by // ReplaceExtension. static void AppendExtension(const std::wstring& extension, std::wstring* file) { if (!extension.empty() && extension != L".") { if (extension[0] != L'.') file->append(L"."); file->append(extension); } } void ReplaceExtension(std::wstring* file_name, const std::wstring& extension) { const std::wstring::size_type last_dot = file_name->rfind(L'.'); if (last_dot == std::wstring::npos) { // No extension, just append the supplied extension. AppendExtension(extension, file_name); return; } const std::wstring::size_type last_separator = file_name->rfind(kPathSeparator); if (last_separator != std::wstring::npos && last_dot < last_separator) { // File name doesn't have extension, but one of the directories does; don't // replace it, just append the supplied extension. For example // 'c:\tmp.bar\foo'. AppendExtension(extension, file_name); return; } std::wstring result = file_name->substr(0, last_dot); AppendExtension(extension, &result); file_name->swap(result); } bool ContentsEqual(const std::wstring& filename1, const std::wstring& filename2) { // We open the file in binary format even if they are text files because // we are just comparing that bytes are exactly same in both files and not // doing anything smart with text formatting. #if defined(OS_WIN) std::ifstream file1(filename1.c_str(), std::ios::in | std::ios::binary); std::ifstream file2(filename2.c_str(), std::ios::in | std::ios::binary); #elif defined(OS_POSIX) std::ifstream file1(WideToUTF8(filename1).c_str(), std::ios::in | std::ios::binary); std::ifstream file2(WideToUTF8(filename2).c_str(), std::ios::in | std::ios::binary); #endif // Even if both files aren't openable (and thus, in some sense, "equal"), // any unusable file yields a result of "false". if (!file1.is_open() || !file2.is_open()) return false; const int BUFFER_SIZE = 2056; char buffer1[BUFFER_SIZE], buffer2[BUFFER_SIZE]; do { file1.read(buffer1, BUFFER_SIZE); file2.read(buffer2, BUFFER_SIZE); if ((file1.eof() && !file2.eof()) || (!file1.eof() && file2.eof()) || (file1.gcount() != file2.gcount()) || (memcmp(buffer1, buffer2, file1.gcount()))) { file1.close(); file2.close(); return false; } } while (!file1.eof() && !file2.eof()); file1.close(); file2.close(); return true; } bool ReadFileToString(const std::wstring& path, std::string* contents) { FILE* file = OpenFile(path, "rb"); if (!file) { return false; } char buf[1 << 16]; size_t len; while ((len = fread(buf, 1, sizeof(buf), file)) > 0) { contents->append(buf, len); } CloseFile(file); return true; } bool GetFileSize(const std::wstring& file_path, int64* file_size) { FileInfo info; if (!GetFileInfo(file_path, &info)) return false; *file_size = info.size; return true; } bool CloseFile(FILE* file) { return fclose(file) == 0; } } // namespace
// 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/file_util.h" #include <stdio.h> #include <fstream> #include "base/logging.h" #include "base/string_util.h" #include "unicode/uniset.h" namespace file_util { const wchar_t kExtensionSeparator = L'.'; void PathComponents(const std::wstring& path, std::vector<std::wstring>* components) { DCHECK(components != NULL); if (components == NULL) return; std::wstring::size_type start = 0; std::wstring::size_type end = path.find(kPathSeparator, start); // Special case the "/" or "\" directory. On Windows with a drive letter, // this code path won't hit, but the right thing should still happen. // "E:\foo" will turn into "E:","foo". if (end == start) { components->push_back(std::wstring(path, 0, 1)); start = end + 1; end = path.find(kPathSeparator, start); } while (end != std::wstring::npos) { std::wstring component = std::wstring(path, start, end - start); components->push_back(component); start = end + 1; end = path.find(kPathSeparator, start); } std::wstring component = std::wstring(path, start); components->push_back(component); } bool EndsWithSeparator(std::wstring* path) { return EndsWithSeparator(*path); } bool EndsWithSeparator(const std::wstring& path) { bool is_sep = (path.length() > 0 && (path)[path.length() - 1] == kPathSeparator); return is_sep; } void TrimTrailingSeparator(std::wstring* dir) { while (dir->length() > 1 && EndsWithSeparator(dir)) dir->resize(dir->length() - 1); } void UpOneDirectory(std::wstring* dir) { TrimTrailingSeparator(dir); std::wstring::size_type last_sep = dir->find_last_of(kPathSeparator); if (last_sep != std::wstring::npos) dir->resize(last_sep); } void UpOneDirectoryOrEmpty(std::wstring* dir) { TrimTrailingSeparator(dir); std::wstring::size_type last_sep = dir->find_last_of(kPathSeparator); if (last_sep != std::wstring::npos) dir->resize(last_sep); else dir->clear(); } void TrimFilename(std::wstring* path) { if (EndsWithSeparator(path)) { TrimTrailingSeparator(path); } else { std::wstring::size_type last_sep = path->find_last_of(kPathSeparator); if (last_sep != std::wstring::npos) path->resize(last_sep); } } std::wstring GetFilenameFromPath(const std::wstring& path) { // TODO(erikkay): fix this - it's not using kPathSeparator, but win unit test // are exercising '/' as a path separator as well. std::wstring::size_type pos = path.find_last_of(L"\\/"); return std::wstring(path, pos == std::wstring::npos ? 0 : pos+1); } std::wstring GetFileExtensionFromPath(const std::wstring& path) { std::wstring file_name = GetFilenameFromPath(path); std::wstring::size_type last_dot = file_name.rfind(L'.'); return std::wstring(last_dot == std::wstring::npos? L"" : file_name, last_dot+1); } void AppendToPath(std::wstring* path, const std::wstring& new_ending) { if (!path) { NOTREACHED(); return; // Don't crash in this function in release builds. } if (!EndsWithSeparator(path)) path->push_back(kPathSeparator); path->append(new_ending); } void InsertBeforeExtension(std::wstring* path, const std::wstring& suffix) { DCHECK(path); const std::wstring::size_type last_dot = path->rfind(kExtensionSeparator); const std::wstring::size_type last_sep = path->rfind(kPathSeparator); if (last_dot == std::wstring::npos || (last_sep != std::wstring::npos && last_dot < last_sep)) { // The path looks something like "C:\pics.old\jojo" or "C:\pics\jojo". // We should just append the suffix to the entire path. path->append(suffix); return; } path->insert(last_dot, suffix); } void ReplaceIllegalCharacters(std::wstring* file_name, int replace_char) { DCHECK(file_name); // Control characters, formatting characters, non-characters, and // some printable ASCII characters regarded as dangerous ('"*/:<>?\\'). // See http://blogs.msdn.com/michkap/archive/2006/11/03/941420.aspx // and http://msdn2.microsoft.com/en-us/library/Aa365247.aspx // TODO(jungshik): Revisit the set. ZWJ and ZWNJ are excluded because they // are legitimate in Arabic and some S/SE Asian scripts. However, when used // elsewhere, they can be confusing/problematic. // Also, consider wrapping the set with our Singleton class to create and // freeze it only once. Note that there's a trade-off between memory and // speed. UErrorCode status = U_ZERO_ERROR; #if defined(WCHAR_T_IS_UTF16) UnicodeSet illegal_characters(UnicodeString( L"[[\"*/:<>?\\\\|][:Cc:][:Cf:] - [\u200c\u200d]]"), status); #else UnicodeSet illegal_characters(UNICODE_STRING_SIMPLE( "[[\"*/:<>?\\\\|][:Cc:][:Cf:] - [\\u200c\\u200d]]").unescape(), status); #endif DCHECK(U_SUCCESS(status)); // Add non-characters. If this becomes a performance bottleneck by // any chance, check |ucs4 & 0xFFFEu == 0xFFFEu|, instead. illegal_characters.add(0xFDD0, 0xFDEF); for (int i = 0; i <= 0x10; ++i) { int plane_base = 0x10000 * i; illegal_characters.add(plane_base + 0xFFFE, plane_base + 0xFFFF); } illegal_characters.freeze(); DCHECK(!illegal_characters.contains(replace_char) && replace_char < 0x10000); // Remove leading and trailing whitespace. TrimWhitespace(*file_name, TRIM_ALL, file_name); std::wstring::size_type i = 0; std::wstring::size_type length = file_name->size(); const wchar_t* wstr = file_name->data(); #if defined(WCHAR_T_IS_UTF16) // Using |span| method of UnicodeSet might speed things up a bit, but // it's not likely to matter here. std::wstring temp; temp.reserve(length); while (i < length) { UChar32 ucs4; std::wstring::size_type prev = i; U16_NEXT(wstr, i, length, ucs4); if (illegal_characters.contains(ucs4)) { temp.push_back(replace_char); } else if (ucs4 < 0x10000) { temp.push_back(ucs4); } else { temp.push_back(wstr[prev]); temp.push_back(wstr[prev + 1]); } } file_name->swap(temp); #elif defined(WCHAR_T_IS_UTF32) while (i < length) { if (illegal_characters.contains(wstr[i])) { (*file_name)[i] = replace_char; } ++i; } #else #error wchar_t* should be either UTF-16 or UTF-32 #endif } // Appends the extension to file adding a '.' if extension doesn't contain one. // This does nothing if extension is empty or '.'. This is used internally by // ReplaceExtension. static void AppendExtension(const std::wstring& extension, std::wstring* file) { if (!extension.empty() && extension != L".") { if (extension[0] != L'.') file->append(L"."); file->append(extension); } } void ReplaceExtension(std::wstring* file_name, const std::wstring& extension) { const std::wstring::size_type last_dot = file_name->rfind(L'.'); if (last_dot == std::wstring::npos) { // No extension, just append the supplied extension. AppendExtension(extension, file_name); return; } const std::wstring::size_type last_separator = file_name->rfind(kPathSeparator); if (last_separator != std::wstring::npos && last_dot < last_separator) { // File name doesn't have extension, but one of the directories does; don't // replace it, just append the supplied extension. For example // 'c:\tmp.bar\foo'. AppendExtension(extension, file_name); return; } std::wstring result = file_name->substr(0, last_dot); AppendExtension(extension, &result); file_name->swap(result); } bool ContentsEqual(const std::wstring& filename1, const std::wstring& filename2) { // We open the file in binary format even if they are text files because // we are just comparing that bytes are exactly same in both files and not // doing anything smart with text formatting. #if defined(OS_WIN) std::ifstream file1(filename1.c_str(), std::ios::in | std::ios::binary); std::ifstream file2(filename2.c_str(), std::ios::in | std::ios::binary); #elif defined(OS_POSIX) std::ifstream file1(WideToUTF8(filename1).c_str(), std::ios::in | std::ios::binary); std::ifstream file2(WideToUTF8(filename2).c_str(), std::ios::in | std::ios::binary); #endif // Even if both files aren't openable (and thus, in some sense, "equal"), // any unusable file yields a result of "false". if (!file1.is_open() || !file2.is_open()) return false; const int BUFFER_SIZE = 2056; char buffer1[BUFFER_SIZE], buffer2[BUFFER_SIZE]; do { file1.read(buffer1, BUFFER_SIZE); file2.read(buffer2, BUFFER_SIZE); if ((file1.eof() && !file2.eof()) || (!file1.eof() && file2.eof()) || (file1.gcount() != file2.gcount()) || (memcmp(buffer1, buffer2, file1.gcount()))) { file1.close(); file2.close(); return false; } } while (!file1.eof() && !file2.eof()); file1.close(); file2.close(); return true; } bool ReadFileToString(const std::wstring& path, std::string* contents) { FILE* file = OpenFile(path, "rb"); if (!file) { return false; } char buf[1 << 16]; size_t len; while ((len = fread(buf, 1, sizeof(buf), file)) > 0) { contents->append(buf, len); } CloseFile(file); return true; } bool GetFileSize(const std::wstring& file_path, int64* file_size) { FileInfo info; if (!GetFileInfo(file_path, &info)) return false; *file_size = info.size; return true; } bool CloseFile(FILE* file) { if (file == NULL) return true; return fclose(file) == 0; } } // namespace
Fix another crasher in Spell Checker related to file IO. Issue=3039 Review URL: http://codereview.chromium.org/7528
Fix another crasher in Spell Checker related to file IO. Issue=3039 Review URL: http://codereview.chromium.org/7528 git-svn-id: http://src.chromium.org/svn/trunk/src@3659 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 8112b79bdb9d79ba91212d5e64acb1b26f022c54
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
faf697d4bbccca3b646ee8d406eb13924b3cf13a
include/wrapper.hh
include/wrapper.hh
#ifndef _WRAPPER_HH_ #define _WRAPPER_HH_ #include "node.h" #include "nan.h" #include "socket.hh" class Wrapper : public Nan::ObjectWrap { static const int MAX_RECEIVE_BUFFER_SIZE = 2048; static Nan::Persistent<v8::Function> constructor; Socket *socket; explicit Wrapper(v8::Local<v8::Object> options); ~Wrapper(void); static void ParseMembershipArguments( Nan::NAN_METHOD_ARGS_TYPE info, Socket::MembershipType *type, unsigned char **address); public: static NAN_MODULE_INIT(Init); static NAN_METHOD(New); static NAN_METHOD(AddMembership); static NAN_METHOD(DropMembership); static NAN_METHOD(Send); static NAN_METHOD(Receive); }; #endif
#ifndef _WRAPPER_HH_ #define _WRAPPER_HH_ #include "node.h" #include "nan.h" #include "socket.hh" class Wrapper : public Nan::ObjectWrap { static const int MAX_RECEIVE_BUFFER_SIZE = 2048; static Nan::Persistent<v8::Function> constructor; Nan::Persistent<v8::Function> onSendCallback; Nan::Persistent<v8::Function> onRecvCallback; Socket *socket; explicit Wrapper(v8::Local<v8::Object> options); ~Wrapper(void); static void ParseMembershipArguments( Nan::NAN_METHOD_ARGS_TYPE info, Socket::MembershipType *type, unsigned char **address); public: static NAN_MODULE_INIT(Init); static NAN_METHOD(New); static NAN_METHOD(AddMembership); static NAN_METHOD(DropMembership); static NAN_METHOD(Send); static NAN_METHOD(Receive); }; #endif
Add member variables for storing onRecv and onSend callbacks
Add member variables for storing onRecv and onSend callbacks
C++
mit
piskorzj/node-packet-socket,piskorzj/node-packet-socket,piskorzj/node-packet-socket
261c41f664a2a5e887ed5df5e3f078e9bafd5054
Engine/system/api/x11api.cpp
Engine/system/api/x11api.cpp
#include "x11api.h" #ifdef __LINUX__ #include <X11/X.h> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xos.h> #include <X11/keysymdef.h> #include <X11/Xutil.h> //#include <GL/glx.h> //FIXME #include <Tempest/Event> #include <Tempest/TextCodec> #include <Tempest/Window> #include <atomic> #include <stdexcept> #include <cstring> #include <thread> #include <unordered_map> struct HWND final { ::Window wnd; HWND()=default; HWND(::Window w):wnd(w) { } HWND(Tempest::SystemApi::Window* p) { std::memcpy(&wnd,&p,sizeof(wnd)); } HWND& operator = (::Window w) { wnd = w; return *this; } operator ::Window() { return wnd; } Tempest::SystemApi::Window* ptr() { static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer"); Tempest::SystemApi::Window* ret=nullptr; std::memcpy(&ret,&wnd,sizeof(wnd)); return ret; } }; using namespace Tempest; static const char* wndClassName="Tempest.Window"; static Display* dpy = nullptr; static ::Window root = {}; static std::atomic_bool isExit{0}; static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows; static Atom& wmDeleteMessage(){ static Atom w = XInternAtom( dpy, "WM_DELETE_WINDOW", 0); return w; } static Atom& _NET_WM_STATE(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE", 0); return w; } static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0); return w; } static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0); return w; } static Atom& _NET_WM_STATE_FULLSCREEN(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0); return w; } static Event::MouseButton toButton( XButtonEvent& msg ){ if( msg.button==Button1 ) return Event::ButtonLeft; if( msg.button==Button3 ) return Event::ButtonRight; if( msg.button==Button2 ) return Event::ButtonMid; return Event::ButtonNone; } static void maximizeWindow(HWND& w) { Atom a[2]; a[0] = _NET_WM_STATE_MAXIMIZED_HORZ(); a[1] = _NET_WM_STATE_MAXIMIZED_VERT(); XChangeProperty ( dpy, w, _NET_WM_STATE(), XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2); XSync(dpy,False); } X11Api::X11Api() { dpy = XOpenDisplay(nullptr); if(dpy == nullptr) throw std::runtime_error("cannot connect to X server!"); root = DefaultRootWindow(dpy); static const TranslateKeyPair k[] = { { XK_KP_Left, Event::K_Left }, { XK_KP_Right, Event::K_Right }, { XK_KP_Up, Event::K_Up }, { XK_KP_Down, Event::K_Down }, { XK_Shift_L, Event::K_LShift }, { XK_Shift_R, Event::K_RShift }, { XK_Control_L, Event::K_LControl }, { XK_Control_R, Event::K_RControl }, { XK_Escape, Event::K_ESCAPE }, { XK_Tab, Event::K_Tab }, { XK_BackSpace, Event::K_Back }, { XK_Delete, Event::K_Delete }, { XK_Insert, Event::K_Insert }, { XK_Home, Event::K_Home }, { XK_End, Event::K_End }, { XK_Pause, Event::K_Pause }, { XK_Return, Event::K_Return }, { XK_F1, Event::K_F1 }, { 48, Event::K_0 }, { 97, Event::K_A }, { 0, Event::K_NoKey } }; setupKeyTranslate(k,24); } void *X11Api::display() { return dpy; } void X11Api::alignGeometry(SystemApi::Window *w, Tempest::Window& owner) { XWindowAttributes xwa={}; if(XGetWindowAttributes(dpy, HWND(w), &xwa)){ Tempest::SizeEvent e(xwa.width, xwa.height); SystemApi::dispatchResize(owner,e); } } SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) { //GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; //XVisualInfo * vi = glXChooseVisual(dpy, 0, att); long visualMask = VisualScreenMask; int numberOfVisuals; XVisualInfo vInfoTemplate = {}; vInfoTemplate.screen = DefaultScreen(dpy); XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals); Colormap cmap; cmap = XCreateColormap(dpy, root, vi->visual, AllocNone); XSetWindowAttributes swa={}; swa.colormap = cmap; swa.event_mask = PointerMotionMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask; HWND win = XCreateWindow( dpy, root, 0, 0, w, h, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa ); XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1); XStoreName(dpy, win, wndClassName); XFreeColormap( dpy, cmap ); XFree(vi); auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr()); windows[ret] = owner; //maximizeWindow(win); XMapWindow(dpy, win); XSync(dpy,False); alignGeometry(win.ptr(),*owner); return ret; } SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) { return implCreateWindow(owner,800,600); //TODO } void X11Api::implDestroyWindow(SystemApi::Window *w) { windows.erase(w); XDestroyWindow(dpy, HWND(w)); } bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) { return false; } bool X11Api::implIsFullscreen(SystemApi::Window *w) { return false; } void X11Api::implSetCursorPosition(int x, int y) { // TODO } void X11Api::implShowCursor(bool show) { // TODO } Rect X11Api::implWindowClientRect(SystemApi::Window *w) { XWindowAttributes xwa; XGetWindowAttributes(dpy, HWND(w), &xwa); return Rect( xwa.x, xwa.y, xwa.width, xwa.height ); } void X11Api::implExit() { isExit.store(true); } bool X11Api::implIsRunning() { return !isExit.load(); } int X11Api::implExec(SystemApi::AppCallBack &cb) { // main message loop while (!isExit.load()) { implProcessEvents(cb); } return 0; } void X11Api::implProcessEvents(SystemApi::AppCallBack &cb) { // main message loop if(XPending(dpy)>0) { XEvent xev={}; XNextEvent(dpy, &xev); HWND hWnd = xev.xclient.window; Tempest::Window* cb = windows.find(hWnd.ptr())->second; //TODO: validation switch( xev.type ) { case ClientMessage: { if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){ SystemApi::exit(); } break; } case ButtonPress: case ButtonRelease: { if(cb) { bool isWheel = false; if( xev.type==ButtonPress && XPending(dpy) && (xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){ XEvent ev; XNextEvent(dpy, &ev); isWheel = (ev.type==ButtonRelease); } if( isWheel ){ int ticks = 0; if( xev.xbutton.button == Button4 ) { ticks = 100; } else if ( xev.xbutton.button == Button5 ) { ticks = -100; } Tempest::MouseEvent e( xev.xbutton.x, xev.xbutton.y, Tempest::Event::ButtonNone, ticks, 0, Event::MouseWheel ); SystemApi::dispatchMouseWheel(*cb, e); } else { MouseEvent e( xev.xbutton.x, xev.xbutton.y, toButton( xev.xbutton ), 0, 0, xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp ); if(xev.type==ButtonPress) SystemApi::dispatchMouseDown(*cb, e); else SystemApi::dispatchMouseUp(*cb, e); } } break; } case MotionNotify: { MouseEvent e( xev.xmotion.x, xev.xmotion.y, Event::ButtonNone, 0, 0, Event::MouseMove ); SystemApi::dispatchMouseMove(*cb, e); break; } case KeyPress: case KeyRelease: { if(cb) { int keysyms_per_keycode_return = 0; KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode), 1, &keysyms_per_keycode_return ); char txt[10]={}; XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr ); auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation auto key = SystemApi::translateKey(*ksym); uint32_t scan = xev.xkey.keycode; Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),Event::M_NoModifier,(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp); if(xev.type==KeyPress) SystemApi::dispatchKeyDown(*cb,e,scan); else SystemApi::dispatchKeyUp (*cb,e,scan); } break; } } std::this_thread::yield(); } else { if(cb.onTimer()==0) std::this_thread::yield(); for(auto& i:windows) { // artificial move/resize event alignGeometry(i.first,*i.second); SystemApi::dispatchRender(*i.second); } } } #endif
#include "x11api.h" #ifdef __LINUX__ #include <X11/X.h> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xos.h> #include <X11/keysymdef.h> #include <X11/Xutil.h> //#include <GL/glx.h> //FIXME #include <Tempest/Event> #include <Tempest/TextCodec> #include <Tempest/Window> #include <atomic> #include <stdexcept> #include <cstring> #include <thread> #include <unordered_map> struct HWND final { ::Window wnd; HWND()=default; HWND(::Window w):wnd(w) { } HWND(Tempest::SystemApi::Window* p) { std::memcpy(&wnd,&p,sizeof(wnd)); } HWND& operator = (::Window w) { wnd = w; return *this; } operator ::Window() { return wnd; } Tempest::SystemApi::Window* ptr() { static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer"); Tempest::SystemApi::Window* ret=nullptr; std::memcpy(&ret,&wnd,sizeof(wnd)); return ret; } }; using namespace Tempest; static const char* wndClassName="Tempest.Window"; static Display* dpy = nullptr; static ::Window root = {}; static std::atomic_bool isExit{0}; static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows; static Atom& wmDeleteMessage(){ static Atom w = XInternAtom( dpy, "WM_DELETE_WINDOW", 0); return w; } static Atom& _NET_WM_STATE(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE", 0); return w; } static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0); return w; } static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0); return w; } static Atom& _NET_WM_STATE_FULLSCREEN(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0); return w; } static Event::MouseButton toButton( XButtonEvent& msg ){ if( msg.button==Button1 ) return Event::ButtonLeft; if( msg.button==Button3 ) return Event::ButtonRight; if( msg.button==Button2 ) return Event::ButtonMid; return Event::ButtonNone; } static void maximizeWindow(HWND& w) { Atom a[2]; a[0] = _NET_WM_STATE_MAXIMIZED_HORZ(); a[1] = _NET_WM_STATE_MAXIMIZED_VERT(); XChangeProperty ( dpy, w, _NET_WM_STATE(), XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2); XSync(dpy,False); } X11Api::X11Api() { dpy = XOpenDisplay(nullptr); if(dpy == nullptr) throw std::runtime_error("cannot connect to X server!"); root = DefaultRootWindow(dpy); static const TranslateKeyPair k[] = { { XK_KP_Left, Event::K_Left }, { XK_KP_Right, Event::K_Right }, { XK_KP_Up, Event::K_Up }, { XK_KP_Down, Event::K_Down }, { XK_Shift_L, Event::K_LShift }, { XK_Shift_R, Event::K_RShift }, { XK_Control_L, Event::K_LControl }, { XK_Control_R, Event::K_RControl }, { XK_Escape, Event::K_ESCAPE }, { XK_Tab, Event::K_Tab }, { XK_BackSpace, Event::K_Back }, { XK_Delete, Event::K_Delete }, { XK_Insert, Event::K_Insert }, { XK_Home, Event::K_Home }, { XK_End, Event::K_End }, { XK_Pause, Event::K_Pause }, { XK_Return, Event::K_Return }, { XK_F1, Event::K_F1 }, { 48, Event::K_0 }, { 97, Event::K_A }, { 0, Event::K_NoKey } }; setupKeyTranslate(k,24); } void *X11Api::display() { return dpy; } void X11Api::alignGeometry(SystemApi::Window *w, Tempest::Window& owner) { XWindowAttributes xwa={}; if(XGetWindowAttributes(dpy, HWND(w), &xwa)){ Tempest::SizeEvent e(xwa.width, xwa.height); SystemApi::dispatchResize(owner,e); } } SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) { //GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; //XVisualInfo * vi = glXChooseVisual(dpy, 0, att); long visualMask = VisualScreenMask; int numberOfVisuals; XVisualInfo vInfoTemplate = {}; vInfoTemplate.screen = DefaultScreen(dpy); XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals); Colormap cmap; cmap = XCreateColormap(dpy, root, vi->visual, AllocNone); XSetWindowAttributes swa={}; swa.colormap = cmap; swa.event_mask = PointerMotionMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask; HWND win = XCreateWindow( dpy, root, 0, 0, w, h, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa ); XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1); XStoreName(dpy, win, wndClassName); XFreeColormap( dpy, cmap ); XFree(vi); auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr()); windows[ret] = owner; //maximizeWindow(win); XMapWindow(dpy, win); XSync(dpy,False); if(owner!=nullptr) alignGeometry(win.ptr(),*owner); return ret; } SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) { return implCreateWindow(owner,800,600); //TODO } void X11Api::implDestroyWindow(SystemApi::Window *w) { windows.erase(w); XDestroyWindow(dpy, HWND(w)); } bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) { return false; } bool X11Api::implIsFullscreen(SystemApi::Window *w) { return false; } void X11Api::implSetCursorPosition(int x, int y) { // TODO } void X11Api::implShowCursor(bool show) { // TODO } Rect X11Api::implWindowClientRect(SystemApi::Window *w) { XWindowAttributes xwa; XGetWindowAttributes(dpy, HWND(w), &xwa); return Rect( xwa.x, xwa.y, xwa.width, xwa.height ); } void X11Api::implExit() { isExit.store(true); } bool X11Api::implIsRunning() { return !isExit.load(); } int X11Api::implExec(SystemApi::AppCallBack &cb) { // main message loop while (!isExit.load()) { implProcessEvents(cb); } return 0; } void X11Api::implProcessEvents(SystemApi::AppCallBack &cb) { // main message loop if(XPending(dpy)>0) { XEvent xev={}; XNextEvent(dpy, &xev); HWND hWnd = xev.xclient.window; Tempest::Window* cb = windows.find(hWnd.ptr())->second; //TODO: validation switch( xev.type ) { case ClientMessage: { if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){ SystemApi::exit(); } break; } case ButtonPress: case ButtonRelease: { if(cb) { bool isWheel = false; if( xev.type==ButtonPress && XPending(dpy) && (xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){ XEvent ev; XNextEvent(dpy, &ev); isWheel = (ev.type==ButtonRelease); } if( isWheel ){ int ticks = 0; if( xev.xbutton.button == Button4 ) { ticks = 100; } else if ( xev.xbutton.button == Button5 ) { ticks = -100; } Tempest::MouseEvent e( xev.xbutton.x, xev.xbutton.y, Tempest::Event::ButtonNone, ticks, 0, Event::MouseWheel ); SystemApi::dispatchMouseWheel(*cb, e); } else { MouseEvent e( xev.xbutton.x, xev.xbutton.y, toButton( xev.xbutton ), 0, 0, xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp ); if(xev.type==ButtonPress) SystemApi::dispatchMouseDown(*cb, e); else SystemApi::dispatchMouseUp(*cb, e); } } break; } case MotionNotify: { MouseEvent e( xev.xmotion.x, xev.xmotion.y, Event::ButtonNone, 0, 0, Event::MouseMove ); SystemApi::dispatchMouseMove(*cb, e); break; } case KeyPress: case KeyRelease: { if(cb) { int keysyms_per_keycode_return = 0; KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode), 1, &keysyms_per_keycode_return ); char txt[10]={}; XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr ); auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation auto key = SystemApi::translateKey(*ksym); uint32_t scan = xev.xkey.keycode; Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),Event::M_NoModifier,(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp); if(xev.type==KeyPress) SystemApi::dispatchKeyDown(*cb,e,scan); else SystemApi::dispatchKeyUp (*cb,e,scan); } break; } } std::this_thread::yield(); } else { if(cb.onTimer()==0) std::this_thread::yield(); for(auto& i:windows) { // artificial move/resize event alignGeometry(i.first,*i.second); SystemApi::dispatchRender(*i.second); } } } #endif
Fix crash on Linux
Fix crash on Linux Try/OpenGothic#48
C++
mit
Try/Tempest,Try/Tempest,Try/Tempest,Try/Tempest
1e967ccf9e4a10fd78058677cbca9ba7093213bf
header/CThreadPool_Ret.hpp
header/CThreadPool_Ret.hpp
#ifndef CTHREADPOOL_RET #define CTHREADPOOL_RET #include<thread> //thread::hardware_concurrency #include<type_traits> //result_of_t #include<unordered_map> #include<utility> //forward, move #include"../../lib/header/thread/CThreadRingBuf.hpp" #include"CThreadPoolItem_Ret.hpp" namespace nThread { //1. a fixed-sized threadpool //2. can return value template<class Ret> class CThreadPool_Ret { public: using size_type=std::result_of_t<decltype(std::thread::hardware_concurrency)&()>; using thread_id=IThreadPoolItemBase::id; private: CThreadRingBuf<CThreadPoolItem_Ret<Ret>*> waiting_buf_; std::unordered_map<thread_id,CThreadPoolItem_Ret<Ret>> thr_; public: CThreadPool_Ret() :CThreadPool_Ret{std::thread::hardware_concurrency()}{} //1. determine the total of usable threads //2. the value you pass will always equal to CThreadPool_Ret::size explicit CThreadPool_Ret(size_type size) :waiting_buf_{size},thr_{size} { while(size--) { CThreadPoolItem_Ret<Ret> item{&waiting_buf_}; const auto id{item.get_id()}; waiting_buf_.write(&thr_.emplace(id,std::move(item)).first->second); } } //of course, why do you need to copy or move CThreadPool_Ret? CThreadPool_Ret(const CThreadPool_Ret &)=delete; //1. block until CThreadPool_Ret::available is not zero and execute the func //2. after returning from add, CThreadPool_Ret::available will reduce 1 //3. after returning from add, CThreadPool_Ret::valid(thread_id) will return true //4. //you must call CThreadPool_Ret::get after returning from add at some moment //otherwise, CThreadPool_Ret::available cannot increase 1 template<class Func,class ... Args> thread_id add(Func &&func,Args &&...args) { auto temp{waiting_buf_.read()}; temp->assign(std::forward<Func>(func),std::forward<Args>(args)...); return temp->get_id(); } //1. return the total of usable threads at that moment //2. reduce 1 after returning from CThreadPool_Ret::add //3. increase 1 after returning from CThreadPool_Ret::get //4. non-block inline size_type available() const noexcept { return static_cast<size_type>(waiting_buf_.size()); } //1. block until the thread_id completes the func //2. after returning from get, CThreadPool_Ret::valid(thread_id) will return false //3. if the thread_id is not valid, do not get the thread_id inline Ret get(const thread_id id) { return thr_.at(id).get(); } //1. return the total of usable threads //2. is fixed after constructing //3. non-block inline size_type size() const noexcept { return static_cast<size_type>(thr_.size()); } //1. return whether the thread_id has been get yet //2. return true for the thread_id which was returned by CThreadPool_Ret::add //3. return false for the thread_id which was used by CThreadPool_Ret::get //4. non-block inline bool valid(const thread_id id) const noexcept { return thr_.at(id).is_running(); } //block until the thread_id completes the func inline void wait(const thread_id id) const { thr_.at(id).wait(); } void wait_all() const { for(const auto &val:thr_) if(valid(val.first)) wait(val.first); } //of course, why do you need to copy or move CThreadPool_Ret? CThreadPool_Ret& operator=(const CThreadPool_Ret &)=delete; //get all the threads in destructor }; } #endif
#ifndef CTHREADPOOL_RET #define CTHREADPOOL_RET #include<thread> //thread::hardware_concurrency #include<type_traits> //result_of_t #include<unordered_map> #include<utility> //forward, move #include"../../lib/header/thread/CThreadRingBuf.hpp" #include"CThreadPoolItem_Ret.hpp" namespace nThread { //1. a fixed-sized threadpool //2. can return value template<class Ret> class CThreadPool_Ret { public: using size_type=std::result_of_t<decltype(std::thread::hardware_concurrency)&()>; using thread_id=IThreadPoolItemBase::id; private: CThreadRingBuf<CThreadPoolItem_Ret<Ret>*> waiting_buf_; std::unordered_map<thread_id,CThreadPoolItem_Ret<Ret>> thr_; public: CThreadPool_Ret() :CThreadPool_Ret{std::thread::hardware_concurrency()}{} //1. determine the total of usable threads //2. the value you pass will always equal to CThreadPool_Ret::size explicit CThreadPool_Ret(size_type size) :waiting_buf_{size},thr_{size} { while(size--) { CThreadPoolItem_Ret<Ret> item{&waiting_buf_}; const auto id{item.get_id()}; waiting_buf_.write(&thr_.emplace(id,std::move(item)).first->second); } } //of course, why do you need to copy or move CThreadPool_Ret? CThreadPool_Ret(const CThreadPool_Ret &)=delete; //1. block until CThreadPool_Ret::available is not zero and execute the func //2. after returning from add, CThreadPool_Ret::available will reduce 1 //3. after returning from add, CThreadPool_Ret::valid(thread_id) will return true //4. //you must call CThreadPool_Ret::get after returning from add at some moment //otherwise, CThreadPool_Ret::available cannot increase 1 template<class Func,class ... Args> thread_id add(Func &&func,Args &&...args) { auto temp{waiting_buf_.read()}; try { temp->assign(std::forward<Func>(func),std::forward<Args>(args)...); }catch(...) { waiting_buf_.write(temp); throw ; } return temp->get_id(); } //1. return the total of usable threads at that moment //2. reduce 1 after returning from CThreadPool_Ret::add //3. increase 1 after returning from CThreadPool_Ret::get //4. non-block inline size_type available() const noexcept { return static_cast<size_type>(waiting_buf_.size()); } //1. block until the thread_id completes the func //2. after returning from get, CThreadPool_Ret::valid(thread_id) will return false //3. if the thread_id is not valid, do not get the thread_id inline Ret get(const thread_id id) { return thr_.at(id).get(); } //1. return the total of usable threads //2. is fixed after constructing //3. non-block inline size_type size() const noexcept { return static_cast<size_type>(thr_.size()); } //1. return whether the thread_id has been get yet //2. return true for the thread_id which was returned by CThreadPool_Ret::add //3. return false for the thread_id which was used by CThreadPool_Ret::get //4. non-block inline bool valid(const thread_id id) const noexcept { return thr_.at(id).is_running(); } //block until the thread_id completes the func inline void wait(const thread_id id) const { thr_.at(id).wait(); } void wait_all() const { for(const auto &val:thr_) if(valid(val.first)) wait(val.first); } //of course, why do you need to copy or move CThreadPool_Ret? CThreadPool_Ret& operator=(const CThreadPool_Ret &)=delete; //get all the threads in destructor }; } #endif
update (exception safety)
update (exception safety)
C++
mit
Fdhvdu/ThreadPool
d561ea5c852269a3945570d4f99e278a6ffeaa5a
header/tool/CAlloc_obj.hpp
header/tool/CAlloc_obj.hpp
#ifndef CALLOC_OBJ #define CALLOC_OBJ #include<memory> #include<type_traits> #include<utility> namespace nTool { template<class T,class Alloc> class CAlloc_obj { public: using allocator_type=Alloc; using value_type=T; using reference=value_type&; using const_reference=const value_type&; using pointer=typename std::allocator_traits<Alloc>::pointer; using size_type=typename std::allocator_traits<Alloc>::size_type; private: template<class S,class Arg1,class ... Args> struct First_is_ :std::integral_constant<bool,std::is_same_v<S,std::remove_cv_t<std::remove_reference_t<Arg1>>>> {}; template<class S,class ... Args> struct Only_one_parameter_:std::false_type{}; template<class S,class Arg1> struct Only_one_parameter_<S,Arg1> :std::integral_constant<bool,std::is_same_v<S,std::remove_cv_t<std::remove_reference_t<Arg1>>>> {}; allocator_type alloc_; pointer data_; bool has_not_destroy_; public: CAlloc_obj() :CAlloc_obj{allocator_type{}}{} explicit CAlloc_obj(const allocator_type &alloc) :alloc_{alloc},data_{std::allocator_traits<allocator_type>::allocate(alloc_,1)},has_not_destroy_{false}{} CAlloc_obj(const CAlloc_obj &)=delete; CAlloc_obj(CAlloc_obj &&rhs) noexcept(std::is_nothrow_move_constructible_v<allocator_type>) :alloc_{std::move(rhs.alloc_)},data_{rhs.data_},has_not_destroy_{rhs.has_not_destroy_} { rhs.data_=nullptr; } template<class ... Args,class=std::enable_if_t< !(First_is_<std::allocator_arg_t,Args...>::value ||Only_one_parameter_<allocator_type,Args...>::value ||Only_one_parameter_<CAlloc_obj,Args...>::value) >> CAlloc_obj(Args &&...args) :CAlloc_obj{std::allocator_arg,allocator_type{},std::forward<decltype(args)>(args)...}{} template<class ... Args> CAlloc_obj(std::allocator_arg_t,const allocator_type &alloc,Args &&...args) :CAlloc_obj{alloc} { construct(std::forward<decltype(args)>(args)...); } template<class ... Args> void construct(Args &&...args) { std::allocator_traits<allocator_type>::construct(alloc_,data_,std::forward<decltype(args)>(args)...); has_not_destroy_=true; } inline void destroy() { std::allocator_traits<allocator_type>::destroy(alloc_,data_); has_not_destroy_=false; } inline reference get() { return *data_; } inline const_reference get() const { return *data_; } inline bool has_not_destroy() const noexcept { return has_not_destroy_; } CAlloc_obj& operator=(const CAlloc_obj &)=delete; CAlloc_obj& operator=(CAlloc_obj &&val) noexcept { if(this!=&val) { std::swap(alloc_,val.alloc_); std::swap(data_,val.data_); std::swap(has_not_destroy_,val.has_not_destroy_); } return *this; } ~CAlloc_obj() { if(data_) { if(has_not_destroy()) destroy(); std::allocator_traits<allocator_type>::deallocate(alloc_,data_,1); } } }; } #endif
#ifndef CALLOC_OBJ #define CALLOC_OBJ #include<memory> #include<type_traits> #include<utility> namespace nTool { template<class T,class Alloc> class CAlloc_obj { public: using allocator_type=Alloc; using value_type=T; using reference=value_type&; using const_reference=const value_type&; using pointer=typename std::allocator_traits<Alloc>::pointer; using size_type=typename std::allocator_traits<Alloc>::size_type; private: template<class S,class Arg1,class ... Args> struct First_is_ :std::integral_constant<bool,std::is_same_v<S,std::remove_cv_t<std::remove_reference_t<Arg1>>>> {}; template<class S,class ... Args> struct Only_one_parameter_:std::false_type{}; template<class S,class Arg1> struct Only_one_parameter_<S,Arg1> :std::integral_constant<bool,std::is_same_v<S,std::remove_cv_t<std::remove_reference_t<Arg1>>>> {}; allocator_type alloc_; pointer data_; bool has_not_destroy_; public: CAlloc_obj() :CAlloc_obj{allocator_type{}}{} explicit CAlloc_obj(const allocator_type &alloc) :alloc_{alloc},data_{std::allocator_traits<allocator_type>::allocate(alloc_,1)},has_not_destroy_{false}{} CAlloc_obj(const CAlloc_obj &)=delete; CAlloc_obj(CAlloc_obj &&rhs) noexcept(std::is_nothrow_move_constructible_v<allocator_type>) :alloc_{std::move(rhs.alloc_)},data_{rhs.data_},has_not_destroy_{rhs.has_not_destroy_} { rhs.data_=nullptr; } template<class ... Args,class=std::enable_if_t< !(First_is_<std::allocator_arg_t,Args...>::value ||Only_one_parameter_<allocator_type,Args...>::value ||Only_one_parameter_<CAlloc_obj,Args...>::value) >> CAlloc_obj(Args &&...args) :CAlloc_obj{std::allocator_arg,allocator_type{},std::forward<decltype(args)>(args)...}{} template<class ... Args> CAlloc_obj(std::allocator_arg_t,const allocator_type &alloc,Args &&...args) :CAlloc_obj{alloc} { construct(std::forward<decltype(args)>(args)...); } template<class ... Args> void construct(Args &&...args) { std::allocator_traits<allocator_type>::construct(alloc_,data_,std::forward<decltype(args)>(args)...); has_not_destroy_=true; } inline void destroy() { std::allocator_traits<allocator_type>::destroy(alloc_,data_); has_not_destroy_=false; } inline reference get() { return *data_; } inline const_reference get() const { return *data_; } inline bool has_not_destroy() const noexcept { return has_not_destroy_; } CAlloc_obj& operator=(const CAlloc_obj &)=delete; CAlloc_obj& operator=(CAlloc_obj &&val) noexcept(std::is_nothrow_swappable_v<allocator_type>) { if(this!=&val) { std::swap(alloc_,val.alloc_); std::swap(data_,val.data_); std::swap(has_not_destroy_,val.has_not_destroy_); } return *this; } ~CAlloc_obj() { if(data_) { if(has_not_destroy()) destroy(); std::allocator_traits<allocator_type>::deallocate(alloc_,data_,1); } } }; } #endif
add noexcept
add noexcept
C++
mit
Fdhvdu/lib
7e45c901fa8988cd7352728b46579800a38a765e
Core/Debug.cc
Core/Debug.cc
/* Copyright (c) 2011-2012 Stanford University * Copyright (c) 2014 Diego Ongaro * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <cassert> #include <cstdarg> #include <cstdio> #include <cstring> #include <ctime> #include <mutex> #include <strings.h> #include <sys/types.h> #include <unistd.h> #include "Core/Debug.h" #include "Core/StringUtil.h" #include "Core/ThreadId.h" namespace LogCabin { namespace Core { namespace Debug { std::string processName = Core::StringUtil::format("%u", getpid()); namespace Internal { /** * Used to convert LogLevels into strings that will be printed. * This array must match the LogLevel enum in Core/Debug.h. */ const char* logLevelToString[] = { "SILENT", "ERROR", "WARNING", "NOTICE", "VERBOSE", NULL // must be the last element in the array }; /** * Protects #policy and #isLoggingCache. */ std::mutex mutex; /** * Specifies the log messages that should be displayed for each filename. * This first component is a pattern; the second is a log level. * A filename is matched against each pattern in order: if the filename starts * with or ends with the pattern, the corresponding log level defines the most * verbose messages that are to be displayed for the file. If a filename * matches no pattern, its log level will default to NOTICE. * * Protected by #mutex. */ std::vector<std::pair<std::string, std::string>> policy; /** * A cache of the results of getLogLevel(), since that function is slow. * This needs to be cleared when the policy changes. * The key to the map is a pointer to the absolute filename, which should be a * string literal. * * Protected by #mutex. */ std::unordered_map<const char*, LogLevel> isLoggingCache; /** * Where log messages go. */ FILE* stream = stderr; /** * Convert a string to a log level. * PANICs if the string is not a valid log level (case insensitive). */ LogLevel logLevelFromString(const std::string& level) { for (uint32_t i = 0; logLevelToString[i] != NULL; ++i) { if (strcasecmp(logLevelToString[i], level.c_str()) == 0) return LogLevel(i); } log((LogLevel::ERROR), __FILE__, __LINE__, __FUNCTION__, "'%s' is not a valid log level.\n", level.c_str()); abort(); } /** * From the policy, calculate the most verbose log level that should be * displayed for this file. * This is slow, so isLogging() caches the results in isLoggingCache. * * Must be called with #mutex held. * * \param fileName * Relative filename. */ LogLevel getLogLevel(const char* fileName) { for (auto it = policy.begin(); it != policy.end(); ++it) { const std::string& pattern = it->first; const std::string& logLevel = it->second; if (Core::StringUtil::startsWith(fileName, pattern) || Core::StringUtil::endsWith(fileName, pattern)) { return logLevelFromString(logLevel); } } return LogLevel::NOTICE; } /** * Return the number of characters of __FILE__ that make up the path prefix. * That is, __FILE__ plus this value will be the relative path from the top * directory of the code tree. */ int calculateLengthFilePrefix() { const char* start = __FILE__; const char* match = strstr(__FILE__, "Core/Debug.cc"); assert(match != NULL); return int(match - start); } /// Stores result of calculateLengthFilePrefix(). const int lengthFilePrefix = calculateLengthFilePrefix(); /** * Strip out the common prefix of a filename to get a path from the project's * root directory. * \param fileName * An absolute or relative filename, usually the value of __FILE__. * \return * A nicer way to show display 'fileName' to the user. * For example, this file would yield "Core/Debug.cc". */ const char* relativeFileName(const char* fileName) { // Remove the prefix only if it matches that of __FILE__. This check is // needed in case someone compiles different files using different paths. if (strncmp(fileName, __FILE__, lengthFilePrefix) == 0) return fileName + lengthFilePrefix; else return fileName; } } // namespace Internal using namespace Internal; // NOLINT FILE* setLogFile(FILE* newFile) { std::unique_lock<std::mutex> lockGuard(mutex); FILE* old = stream; stream = newFile; return old; } void setLogPolicy(const std::vector<std::pair<std::string, std::string>>& newPolicy) { std::unique_lock<std::mutex> lockGuard(mutex); policy = newPolicy; isLoggingCache.clear(); } void setLogPolicy(const std::initializer_list<std::pair<std::string, std::string>>& newPolicy) { setLogPolicy(std::vector<std::pair<std::string, std::string>>(newPolicy)); } std::ostream& operator<<(std::ostream& ostream, LogLevel level) { ostream << logLevelToString[uint32_t(level)]; return ostream; } bool isLogging(LogLevel level, const char* fileName) { std::unique_lock<std::mutex> lockGuard(mutex); LogLevel verbosity; auto it = isLoggingCache.find(fileName); if (it == isLoggingCache.end()) { verbosity = getLogLevel(relativeFileName(fileName)); isLoggingCache[fileName] = verbosity; } else { verbosity = it->second; } return uint32_t(level) <= uint32_t(verbosity); } void log(LogLevel level, const char* fileName, uint32_t lineNum, const char* functionName, const char* format, ...) { va_list ap; struct timespec now; clock_gettime(CLOCK_REALTIME, &now); // This ensures that output on stderr won't be interspersed with other // output. This normally happens automatically for a single call to // fprintf, but must be explicit since we're using two calls here. flockfile(stream); fprintf(stream, "%010lu.%06lu %s:%d in %s() %s[%s:%s]: ", now.tv_sec, now.tv_nsec / 1000, relativeFileName(fileName), lineNum, functionName, logLevelToString[uint32_t(level)], processName.c_str(), ThreadId::getName().c_str()); va_start(ap, format); vfprintf(stream, format, ap); va_end(ap); funlockfile(stream); fflush(stream); } } // namespace LogCabin::Core::Debug } // namespace LogCabin::Core } // namespace LogCabin
/* Copyright (c) 2011-2012 Stanford University * Copyright (c) 2014 Diego Ongaro * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <cassert> #include <cstdarg> #include <cstdio> #include <cstring> #include <ctime> #include <mutex> #include <strings.h> #include <sys/types.h> #include <unistd.h> #include "Core/Debug.h" #include "Core/StringUtil.h" #include "Core/ThreadId.h" namespace LogCabin { namespace Core { namespace Debug { std::string processName = Core::StringUtil::format("%u", getpid()); namespace Internal { /** * Used to convert LogLevels into strings that will be printed. * This array must match the LogLevel enum in Core/Debug.h. */ const char* logLevelToString[] = { "SILENT", "ERROR", "WARNING", "NOTICE", "VERBOSE", NULL // must be the last element in the array }; /** * Protects #policy and #isLoggingCache. */ std::mutex mutex; /** * Specifies the log messages that should be displayed for each filename. * This first component is a pattern; the second is a log level. * A filename is matched against each pattern in order: if the filename starts * with or ends with the pattern, the corresponding log level defines the most * verbose messages that are to be displayed for the file. If a filename * matches no pattern, its log level will default to NOTICE. * * Protected by #mutex. */ std::vector<std::pair<std::string, std::string>> policy; /** * A cache of the results of getLogLevel(), since that function is slow. * This needs to be cleared when the policy changes. * The key to the map is a pointer to the absolute filename, which should be a * string literal. * * Protected by #mutex. */ std::unordered_map<const char*, LogLevel> isLoggingCache; /** * Where log messages go. */ FILE* stream = stderr; /** * Convert a string to a log level. * PANICs if the string is not a valid log level (case insensitive). */ LogLevel logLevelFromString(const std::string& level) { for (uint32_t i = 0; logLevelToString[i] != NULL; ++i) { if (strcasecmp(logLevelToString[i], level.c_str()) == 0) return LogLevel(i); } log((LogLevel::ERROR), __FILE__, __LINE__, __FUNCTION__, "'%s' is not a valid log level.\n", level.c_str()); abort(); } /** * From the policy, calculate the most verbose log level that should be * displayed for this file. * This is slow, so isLogging() caches the results in isLoggingCache. * * Must be called with #mutex held. * * \param fileName * Relative filename. */ LogLevel getLogLevel(const char* fileName) { for (auto it = policy.begin(); it != policy.end(); ++it) { const std::string& pattern = it->first; const std::string& logLevel = it->second; if (Core::StringUtil::startsWith(fileName, pattern) || Core::StringUtil::endsWith(fileName, pattern)) { return logLevelFromString(logLevel); } } return LogLevel::NOTICE; } /** * Return the number of characters of __FILE__ that make up the path prefix. * That is, __FILE__ plus this value will be the relative path from the top * directory of the code tree. */ int calculateLengthFilePrefix() { const char* start = __FILE__; const char* match = strstr(__FILE__, "Core/Debug.cc"); assert(match != NULL); return int(match - start); } /// Stores result of calculateLengthFilePrefix(). const int lengthFilePrefix = calculateLengthFilePrefix(); /** * Strip out the common prefix of a filename to get a path from the project's * root directory. * \param fileName * An absolute or relative filename, usually the value of __FILE__. * \return * A nicer way to show display 'fileName' to the user. * For example, this file would yield "Core/Debug.cc". */ const char* relativeFileName(const char* fileName) { // Remove the prefix only if it matches that of __FILE__. This check is // needed in case someone compiles different files using different paths. if (strncmp(fileName, __FILE__, lengthFilePrefix) == 0) return fileName + lengthFilePrefix; else return fileName; } } // namespace Internal using namespace Internal; // NOLINT FILE* setLogFile(FILE* newFile) { std::unique_lock<std::mutex> lockGuard(mutex); FILE* old = stream; stream = newFile; return old; } void setLogPolicy(const std::vector<std::pair<std::string, std::string>>& newPolicy) { std::unique_lock<std::mutex> lockGuard(mutex); policy = newPolicy; isLoggingCache.clear(); } void setLogPolicy(const std::initializer_list<std::pair<std::string, std::string>>& newPolicy) { setLogPolicy(std::vector<std::pair<std::string, std::string>>(newPolicy)); } std::ostream& operator<<(std::ostream& ostream, LogLevel level) { ostream << logLevelToString[uint32_t(level)]; return ostream; } bool isLogging(LogLevel level, const char* fileName) { std::unique_lock<std::mutex> lockGuard(mutex); LogLevel verbosity; auto it = isLoggingCache.find(fileName); if (it == isLoggingCache.end()) { verbosity = getLogLevel(relativeFileName(fileName)); isLoggingCache[fileName] = verbosity; } else { verbosity = it->second; } return uint32_t(level) <= uint32_t(verbosity); } void log(LogLevel level, const char* fileName, uint32_t lineNum, const char* functionName, const char* format, ...) { va_list ap; // Don't use Core::Time here since it could potentially call PANIC. struct timespec now; clock_gettime(CLOCK_REALTIME, &now); // Failures are a little annoying here, since we can't exactly log // errors that come up. char formattedSeconds[64]; // a human-readable string now.tv_sec bool ok = false; { // First, try gmtime and strftime. struct tm calendarTime; if (gmtime_r(&now.tv_sec, &calendarTime) != NULL) { ok = (strftime(formattedSeconds, sizeof(formattedSeconds), "%F %T", &calendarTime) > 0); } } if (!ok) { // If that failed, use the raw number. snprintf(formattedSeconds, sizeof(formattedSeconds), "%010lu", now.tv_sec); formattedSeconds[sizeof(formattedSeconds) - 1] = '\0'; } // This ensures that output on stderr won't be interspersed with other // output. This normally happens automatically for a single call to // fprintf, but must be explicit since we're using two calls here. flockfile(stream); fprintf(stream, "%s.%06lu %s:%d in %s() %s[%s:%s]: ", formattedSeconds, now.tv_nsec / 1000, relativeFileName(fileName), lineNum, functionName, logLevelToString[uint32_t(level)], processName.c_str(), ThreadId::getName().c_str()); va_start(ap, format); vfprintf(stream, format, ap); va_end(ap); funlockfile(stream); fflush(stream); } } // namespace LogCabin::Core::Debug } // namespace LogCabin::Core } // namespace LogCabin
Change debug log to have human-readable dates/times
Change debug log to have human-readable dates/times was: 1423693530.354292 Server/RaftConsensus.cc:871 in init() NOTICE[1:evloop]: My server ID is 1 now: 2015-02-11 22:28:20.258285 Server/RaftConsensus.cc:871 in init() NOTICE[1:evloop]: My server ID is 1 Close #87: debug log format should have human-readable date
C++
isc
tempbottle/logcabin,gaoning777/logcabin,tempbottle/logcabin,logcabin/logcabin,logcabin/logcabin,gaoning777/logcabin,chaozh/logcabin,TigerZhang/logcabin,dankenigsberg/logcabin,dankenigsberg/logcabin,chaozh/logcabin,TigerZhang/logcabin,gaoning777/logcabin,gaoning777/logcabin,TigerZhang/logcabin,chaozh/logcabin,TigerZhang/logcabin,logcabin/logcabin,tempbottle/logcabin,dankenigsberg/logcabin,chaozh/logcabin,logcabin/logcabin,tempbottle/logcabin,dankenigsberg/logcabin
1cacd6e89a43cc070e61cff324cec8bfbcec61f9
glx/main.cpp
glx/main.cpp
/* * Code adapted from: * https://www.opengl.org/wiki/Tutorial:_OpenGL_3.0_Context_Creation_(GLX) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <GL/gl.h> #include <GL/glx.h> #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 typedef GLXContext (*glXCreateContextAttribsARBProc) (Display*, GLXFBConfig, GLXContext, Bool, const int*); // Helper to check for extension string presence. Adapted from: // http://www.opengl.org/resources/features/OGLextensions/ static bool isExtensionSupported(const char *extList, const char *extension) { const char *start; const char *where, *terminator; /* Extension names should not have spaces. */ where = strchr(extension, ' '); if (where || *extension == '\0') return false; /* It takes a bit of care to be fool-proof about parsing the OpenGL extensions string. Don't be fooled by sub-strings, etc. */ for (start=extList;;) { where = strstr(start, extension); if (!where) break; terminator = where + strlen(extension); if (where == start || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return true; start = terminator; } return false; } static bool ctxErrorOccurred = false; static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) { ctxErrorOccurred = true; return 0; } int main(int argc, char* argv[]) { Display *display = XOpenDisplay(NULL); if (!display) { printf("Failed to open X display\n"); exit(1); } // Get a matching FB config static int visual_attribs[] = { GLX_X_RENDERABLE , true, GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT, GLX_RENDER_TYPE , GLX_RGBA_BIT, GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR, GLX_RED_SIZE , 8, GLX_GREEN_SIZE , 8, GLX_BLUE_SIZE , 8, GLX_ALPHA_SIZE , 8, GLX_DEPTH_SIZE , 24, GLX_STENCIL_SIZE , 8, GLX_DOUBLEBUFFER , true, //GLX_SAMPLE_BUFFERS , 1, //GLX_SAMPLES , 4, None }; int glx_major, glx_minor; // FBConfigs were added in GLX version 1.3. if (!glXQueryVersion(display, &glx_major, &glx_minor) || ((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) { printf("Invalid GLX version"); exit(1); } printf("Getting matching framebuffer configs\n"); int fbcount; GLXFBConfig* fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount); if (!fbc) { printf("Failed to retrieve a framebuffer config\n"); exit(1); } printf("Found %d matching FB configs.\n", fbcount); // Pick the FB config/visual with the most samples per pixel printf("Getting XVisualInfos\n"); int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999; for (int i = 0; i < fbcount; ++i) { XVisualInfo *vi = glXGetVisualFromFBConfig(display, fbc[i]); if (vi) { int samp_buf, samples; glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf); glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLES, &samples); printf("\tMatching fbconfig %d, visual ID 0x%2lx: " "SAMPLE_BUFFERS = %d, SAMPLES = %d\n", i, vi -> visualid, samp_buf, samples); if (best_fbc < 0 || (samp_buf && samples) > best_num_samp) best_fbc = i, best_num_samp = samples; if (worst_fbc < 0 || !samp_buf || samples < worst_num_samp) worst_fbc = i, worst_num_samp = samples; } XFree(vi); } GLXFBConfig bestFbc = fbc[best_fbc]; // Be sure to free the FBConfig list allocated by glXChooseFBConfig() XFree(fbc); // Get a visual XVisualInfo *vi = glXGetVisualFromFBConfig(display, bestFbc); printf("Chosen visual ID = 0x%lx\n", vi->visualid); printf("Creating colormap\n"); XSetWindowAttributes swa; Colormap cmap; swa.colormap = cmap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone); swa.background_pixmap = None ; swa.border_pixel = 0; swa.event_mask = StructureNotifyMask; printf("Creating window\n"); Window win = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, 100, 100, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa); if (!win) { printf("Failed to create window.\n"); exit(1); } // Done with the visual info data XFree(vi); XStoreName(display, win, "GL 3.0 Window"); printf("Mapping window\n"); XMapWindow(display, win); // Get the default screen's GLX extension list const char *glxExts = glXQueryExtensionsString(display, DefaultScreen(display)); // NOTE: It is not necessary to create or make current to a context before // calling glXGetProcAddressARB glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0; glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddressARB((const GLubyte *) "glXCreateContextAttribsARB"); GLXContext ctx = 0; // Install an X error handler so the application won't exit if GL 3.0 // context allocation fails. // // Note this error handler is global. All display connections in all // threads of a process use the same error handler, so be sure to guard // against other threads issuing X commands while this code is running. ctxErrorOccurred = false; int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler); // Check for the GLX_ARB_create_context extension string and the function. // If either is not present, use GLX 1.3 context creation method. if (!isExtensionSupported(glxExts, "GLX_ARB_create_context") || !glXCreateContextAttribsARB) { printf("glXCreateContextAttribsARB() not found" " ... using old-style GLX context\n"); ctx = glXCreateNewContext(display, bestFbc, GLX_RGBA_TYPE, 0, true); } // If it does, try to get a GL 3.0 context! else { int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 0, //GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, None }; printf("Creating context\n"); ctx = glXCreateContextAttribsARB(display, bestFbc, 0, true, context_attribs); // Sync to ensure any errors generated are processed. XSync(display, false); if (!ctxErrorOccurred && ctx) printf("Created GL 3.0 context\n"); else { // Couldn't create GL 3.0 context. Fall back to old-style 2.x // context. When a context version below 3.0 is requested, // implementations will return the newest context version // compatible with OpenGL versions less than version 3.0. // GLX_CONTEXT_MAJOR_VERSION_ARB = 1 context_attribs[1] = 1; // GLX_CONTEXT_MINOR_VERSION_ARB = 0 context_attribs[3] = 0; ctxErrorOccurred = false; printf("Failed to create GL 3.0 context" " ... using old-style GLX context\n"); ctx = glXCreateContextAttribsARB(display, bestFbc, 0, true, context_attribs); } } // Sync to ensure any errors generated are processed. XSync(display, false); // Restore the original error handler XSetErrorHandler(oldHandler); if (ctxErrorOccurred || !ctx) { printf("Failed to create an OpenGL context\n"); exit(1); } // Verifying that context is a direct context if (! glXIsDirect (display, ctx)) { printf("Indirect GLX rendering context obtained\n"); } else { printf("Direct GLX rendering context obtained\n"); } printf("Making context current\n"); glXMakeCurrent(display, win, ctx); glClearColor(0, 0.5, 1, 1); glClear(GL_COLOR_BUFFER_BIT); glXSwapBuffers(display, win); sleep(1); glClearColor (1, 0.5, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glXSwapBuffers(display, win); sleep(1); glXMakeCurrent(display, 0, 0); glXDestroyContext(display, ctx); XDestroyWindow(display, win); XFreeColormap(display, cmap); XCloseDisplay(display); return 0; }
/* * Code adapted from: * https://www.opengl.org/wiki/Tutorial:_OpenGL_3.0_Context_Creation_(GLX) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <GL/gl.h> #include <GL/glx.h> #include "common/error.h" #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 typedef GLXContext (*glXCreateContextAttribsARBProc) (Display*, GLXFBConfig, GLXContext, Bool, const int*); // Helper to check for extension string presence. Adapted from: // http://www.opengl.org/resources/features/OGLextensions/ static bool isExtensionSupported(const char *extList, const char *extension) { const char *start; const char *where, *terminator; /* Extension names should not have spaces. */ where = strchr(extension, ' '); if (where || *extension == '\0') return false; /* It takes a bit of care to be fool-proof about parsing the OpenGL extensions string. Don't be fooled by sub-strings, etc. */ for (start=extList;;) { where = strstr(start, extension); if (!where) break; terminator = where + strlen(extension); if (where == start || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return true; start = terminator; } return false; } static bool ctxErrorOccurred = false; static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) { ctxErrorOccurred = true; return 0; } int main(int argc, char* argv[]) { Display *display = XOpenDisplay(NULL); if (!display) fail("Failed to open X display\n"); // Get a matching FB config static int visual_attribs[] = { GLX_X_RENDERABLE , true, GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT, GLX_RENDER_TYPE , GLX_RGBA_BIT, GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR, GLX_RED_SIZE , 8, GLX_GREEN_SIZE , 8, GLX_BLUE_SIZE , 8, GLX_ALPHA_SIZE , 8, GLX_DEPTH_SIZE , 24, GLX_STENCIL_SIZE , 8, GLX_DOUBLEBUFFER , true, //GLX_SAMPLE_BUFFERS , 1, //GLX_SAMPLES , 4, None }; int glx_major, glx_minor; // FBConfigs were added in GLX version 1.3. if (!glXQueryVersion(display, &glx_major, &glx_minor) || ((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) fail("Invalid GLX version"); printf("Getting matching framebuffer configs\n"); int fbcount; GLXFBConfig* fbc = glXChooseFBConfig(display, DefaultScreen(display), visual_attribs, &fbcount); if (!fbc) fail("Failed to retrieve a framebuffer config\n"); printf("Found %d matching FB configs.\n", fbcount); // Pick the FB config/visual with the most samples per pixel printf("Getting XVisualInfos\n"); int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999; for (int i = 0; i < fbcount; ++i) { XVisualInfo *vi = glXGetVisualFromFBConfig(display, fbc[i]); if (vi) { int samp_buf, samples; glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf); glXGetFBConfigAttrib(display, fbc[i], GLX_SAMPLES, &samples); printf("\tMatching fbconfig %d, visual ID 0x%2lx: " "SAMPLE_BUFFERS = %d, SAMPLES = %d\n", i, vi -> visualid, samp_buf, samples); if (best_fbc < 0 || (samp_buf && samples) > best_num_samp) best_fbc = i, best_num_samp = samples; if (worst_fbc < 0 || !samp_buf || samples < worst_num_samp) worst_fbc = i, worst_num_samp = samples; } XFree(vi); } GLXFBConfig bestFbc = fbc[best_fbc]; // Be sure to free the FBConfig list allocated by glXChooseFBConfig() XFree(fbc); // Get a visual XVisualInfo *vi = glXGetVisualFromFBConfig(display, bestFbc); printf("Chosen visual ID = 0x%lx\n", vi->visualid); printf("Creating colormap\n"); XSetWindowAttributes swa; Colormap cmap; swa.colormap = cmap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone); swa.background_pixmap = None ; swa.border_pixel = 0; swa.event_mask = StructureNotifyMask; printf("Creating window\n"); Window win = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, 100, 100, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa); if (!win) fail("Failed to create window.\n"); // Done with the visual info data XFree(vi); XStoreName(display, win, "GL 3.0 Window"); printf("Mapping window\n"); XMapWindow(display, win); // Get the default screen's GLX extension list const char *glxExts = glXQueryExtensionsString(display, DefaultScreen(display)); // NOTE: It is not necessary to create or make current to a context before // calling glXGetProcAddressARB glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0; glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc) glXGetProcAddressARB((const GLubyte *) "glXCreateContextAttribsARB"); GLXContext ctx = 0; // Install an X error handler so the application won't exit if GL 3.0 // context allocation fails. // // Note this error handler is global. All display connections in all // threads of a process use the same error handler, so be sure to guard // against other threads issuing X commands while this code is running. ctxErrorOccurred = false; int (*oldHandler)(Display*, XErrorEvent*) = XSetErrorHandler(&ctxErrorHandler); // Check for the GLX_ARB_create_context extension string and the function. // If either is not present, use GLX 1.3 context creation method. if (!isExtensionSupported(glxExts, "GLX_ARB_create_context") || !glXCreateContextAttribsARB) { printf("glXCreateContextAttribsARB() not found" " ... using old-style GLX context\n"); ctx = glXCreateNewContext(display, bestFbc, GLX_RGBA_TYPE, 0, true); } // If it does, try to get a GL 3.0 context! else { int context_attribs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 0, //GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, None }; printf("Creating context\n"); ctx = glXCreateContextAttribsARB(display, bestFbc, 0, true, context_attribs); // Sync to ensure any errors generated are processed. XSync(display, false); if (!ctxErrorOccurred && ctx) printf("Created GL 3.0 context\n"); else { // Couldn't create GL 3.0 context. Fall back to old-style 2.x // context. When a context version below 3.0 is requested, // implementations will return the newest context version // compatible with OpenGL versions less than version 3.0. // GLX_CONTEXT_MAJOR_VERSION_ARB = 1 context_attribs[1] = 1; // GLX_CONTEXT_MINOR_VERSION_ARB = 0 context_attribs[3] = 0; ctxErrorOccurred = false; printf("Failed to create GL 3.0 context" " ... using old-style GLX context\n"); ctx = glXCreateContextAttribsARB(display, bestFbc, 0, true, context_attribs); } } // Sync to ensure any errors generated are processed. XSync(display, false); // Restore the original error handler XSetErrorHandler(oldHandler); if (ctxErrorOccurred || !ctx) fail("Failed to create an OpenGL context\n"); // Verifying that context is a direct context if (! glXIsDirect (display, ctx)) { printf("Indirect GLX rendering context obtained\n"); } else { printf("Direct GLX rendering context obtained\n"); } printf("Making context current\n"); glXMakeCurrent(display, win, ctx); glClearColor(0, 0.5, 1, 1); glClear(GL_COLOR_BUFFER_BIT); glXSwapBuffers(display, win); sleep(1); glClearColor (1, 0.5, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glXSwapBuffers(display, win); sleep(1); glXMakeCurrent(display, 0, 0); glXDestroyContext(display, ctx); XDestroyWindow(display, win); XFreeColormap(display, cmap); XCloseDisplay(display); return 0; }
use fail() for error handling
glx: use fail() for error handling
C++
apache-2.0
mkollaro/opengl_snippets
d2e413e8abe3d1f48ac2a229c69bb075fe94041f
EXP1/Draw.cxx
EXP1/Draw.cxx
void Draw(string s_Exo, string s_Run) { gStyle->SetOptStat(0); string s_TFile_Cyclus = s_Exo + "/" + s_Run + "/cyclus.root"; string s_TFile_Class = s_Exo + "/" + s_Run + "/Scenario.root"; cout<<s_TFile_Cyclus<<endl; cout<<s_TFile_Class<<endl; TFile *FCy = new TFile(s_TFile_Cyclus.c_str()); TFile *FCl = new TFile(s_TFile_Class.c_str()); TTree *TCy = (TTree *) FCy->Get("TT"); TTree *TCl = (TTree *) FCl->Get("TreeScenario"); TCy->SetLineColor(kRed); TCy->SetMarkerColor(kRed); TCy->SetLineWidth(3); TCl->SetLineColor(kBlue); TCl->SetMarkerColor(kBlue); TCl->SetLineWidth(3); // ################################################################################ // Legend // ################################################################################ TLegend *L01 = new TLegend(0.75,0.10,0.90,0.25); L01->AddEntry(TCy, "Cyclus", "L"); L01->AddEntry(TCl, "CLASS", "L"); // ################################################################################ // ENERGY // ################################################################################ TCanvas *C00 = new TCanvas("C00","C00",700,500); TCy->Draw("P:T","","L"); TCl->Draw("P:T","","Lsame"); TH1F *tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Thermal Power"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Power (W)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); // ################################################################################ // Plutonium // ################################################################################ TCanvas *C0 = new TCanvas("C0","Pu",1500,900); C0->Divide(2,2,0.01,0.01); C0->cd(1); TCy->Draw("B93/1000:T","","L"); TCl->Draw("B93:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C0->cd(2); TCy->Draw("B3/1000:T","","L"); TCl->Draw("B3:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu in Stock"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C0->cd(3); TCy->Draw("B98/1000:T","","L"); TCl->Draw("B98:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu9"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C0->cd(4); TCy->Draw("B8/1000:T","","L"); TCl->Draw("B8:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu9 in Stock"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); // ################################################################################ // MA // ################################################################################ TCanvas *C1 = new TCanvas("C1","MA",1500,900); C1->Divide(2,2,0.01,0.01); C1->cd(1); TCy->Draw("B96/1000:T","","L"); TCl->Draw("B96:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total MA"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C1->cd(2); TCy->Draw("B94/1000:T","","L"); TCl->Draw("B94:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Am"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C1->cd(3); TCy->Draw("B92/1000:T","","L"); TCl->Draw("B92:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Np"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C1->cd(4); TCy->Draw("B95/1000:T","","L"); TCl->Draw("B95:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Cm"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); }
int Draw(string s_Code1, string s_Code2, string s_Exo1, string s_Exo2, string s_Run1, string s_Run2) { gROOT->Reset() gStyle->SetOptStat(0); cout<<endl<<"----------------------------------"<<endl; cout<<"USAGE : "<<endl; cout<<".x Draw.cxx(\"code1\",\"code2\",\"Ex1\",\"Ex2\",\"Run1\",\"Run2\")"<<endl; cout<<"EXAMPLE : "<<endl; cout<<".x Draw.cxx(\"class\",\"class\",\"EX1\",\"EX1\",\"1\",\"1\")"<<endl; cout<<"----------------------------------"<<endl<<endl; string Code1 = s_Code1; string Code2 = s_Code2; string Exo1 = s_Exo1; string Exo2 = s_Exo2; string Run1 = s_Run1; string Run2 = s_Run2; string s_TFile_1; string s_TFile_2; TTree *TC1; TTree *TC2; if (Code1 == "class") s_TFile_1 = Exo1 + "/" + Run1 + "/Scenario.root"; else if (Code1 == "cyclus") s_TFile_1 = Exo1 + "/" + Run1 + "/cyclus.root"; else { cout<<endl<<"code 1 should be \"class\" or \"cyclus\""<<endl<<endl; return 1; } if (Code2 == "class") s_TFile_2 = Exo2 + "/" + Run2 + "/Scenario.root"; else if (Code2 == "cyclus") s_TFile_2 = Exo2 + "/" + Run2 + "/cyclus.root"; else { cout<<endl<<"code 2 should be \"class\" or \"cyclus\""<<endl<<endl; return 1; } cout<<s_TFile_1<<endl; cout<<s_TFile_2<<endl; TFile *FC1 = new TFile(s_TFile_1.c_str()); TFile *FC2 = new TFile(s_TFile_2.c_str()); string s_TTreeName_Cyclus = "TT"; string s_TTreeName_Class = "TreeScenario"; if (Code1 == "cyclus") TC1 = (TTree *) FC1->Get("TT"); if (Code1 == "class") TC1 = (TTree *) FC1->Get("TreeScenario"); if (Code2 == "cyclus") TC2 = (TTree *) FC2->Get("TT"); if (Code2 == "class") TC2 = (TTree *) FC2->Get("TreeScenario"); TC1->SetLineColor(kRed); TC1->SetMarkerColor(kRed); TC1->SetLineWidth(4); TC2->SetLineColor(kBlue); TC2->SetMarkerColor(kBlue); TC2->SetLineWidth(2); // ################################################################################ // Legend // ################################################################################ TLegend *L01 = new TLegend(0.75,0.10,0.90,0.25); L01->AddEntry(TC1, s_Code1.c_str(), "L"); L01->AddEntry(TC2, s_Code2.c_str(), "L"); // ################################################################################ // ENERGY // ################################################################################ TCanvas *C00 = new TCanvas("C00","C00",700,500); TC1->Draw("P:T","","L"); TC2->Draw("P:T","","Lsame"); TH1F *tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Thermal Power"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Power (W)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); // ################################################################################ // Plutonium // ################################################################################ TCanvas *C0 = new TCanvas("C0","Pu",1500,900); C0->Divide(2,2,0.01,0.01); C0->cd(1); TC1->Draw("B93:T","","L"); TC2->Draw("B93:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C0->cd(2); TC1->Draw("B3:T","","L"); TC2->Draw("B3:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu in Stock"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C0->cd(3); TC1->Draw("B98:T","","L"); TC2->Draw("B98:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Pu9"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C0->cd(4); TC1->Draw("B8:T","","L"); TC2->Draw("B8:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Pu9 in Stock"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); // ################################################################################ // U // ################################################################################ TCanvas *C1 = new TCanvas("C1","U",1500,900); C1->Divide(2,2,0.01,0.01); C1->cd(1); TC1->Draw("B102:T","","L"); TC2->Draw("B102:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total U5"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C1->cd(2); TC1->Draw("B12:T","","L"); TC2->Draw("B12:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("U5 in Stock"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C1->cd(3); TC1->Draw("B66:T","","L"); TC2->Draw("B66:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("U5 in Reactors"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C1->cd(4); TC1->Draw("B91:T","","L"); TC2->Draw("B91:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total U"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); // ################################################################################ // MA // ################################################################################ TCanvas *C2 = new TCanvas("C2","MA",1500,900); C2->Divide(2,2,0.01,0.01); C2->cd(1); TC1->Draw("B96:T","","L"); TC2->Draw("B96:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total MA"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C2->cd(2); TC1->Draw("B94:T","","L"); TC2->Draw("B94:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Am"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C2->cd(3); TC1->Draw("B92:T","","L"); TC2->Draw("B92:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Np"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); C2->cd(4); TC1->Draw("B95:T","","L"); TC2->Draw("B95:T","","Lsame"); tmp0 = (TH1F*)gPad->GetPrimitive("htemp"); tmp0->SetTitle("Total Cm"); tmp0->GetXaxis()->SetTitle("Time (y)"); tmp0->GetXaxis()->CenterTitle(); tmp0->GetXaxis()->SetTitleOffset(0.8); tmp0->GetXaxis()->SetTitleSize(0.05); tmp0->GetYaxis()->SetTitle("Mass (tons)"); tmp0->GetYaxis()->CenterTitle(); tmp0->GetYaxis()->SetTitleOffset(0.8); tmp0->GetYaxis()->SetTitleSize(0.05); gPad->Update(); L01->Draw(); return 0; }
Update Draw script
Update Draw script
C++
bsd-3-clause
fcci2017/exercice
d31b0de6d463a9381f82ac4c82244fb1f0de2f02
projects/src/simbicycle.hh
projects/src/simbicycle.hh
#include <cmath> #include <type_traits> #include <boost/math/special_functions/round.hpp> #include "bicycle/kinematic.h" #include "kalman.h" /* * Member function definitions of sim::Bicycle template class. * See simbicycle.h for template class declaration. */ namespace sim { #define OBSERVER_FUNCTION(return_type) \ template <typename T> \ typename std::enable_if<std::is_base_of<observer::ObserverBase, T>::value, return_type>::type #define NULL_OBSERVER_FUNCTION(return_type) \ template <typename T> \ typename std::enable_if<!std::is_base_of<observer::ObserverBase, T>::value, return_type>::type #define BICYCLE_TYPE Bicycle<Model, Observer> template <typename Model, typename Observer> template <typename T> Bicycle<Model, Observer>::Bicycle(typename std::enable_if<std::is_base_of<observer::ObserverBase, T>::value, real_t>::type v, real_t dt) : m_model(v, dt), m_observer(m_model), m_full_state(full_state_t::Zero()), m_pose(BicyclePoseMessage_init_zero), m_input(input_t::Zero()), m_measurement(measurement_t::Zero()) { // Note: User must initialize Kalman matrices in application. chBSemObjectInit(&m_state_sem, false); // initialize to not taken static_assert((!std::is_same<Model, model::BicycleKinematic>::value) || std::is_same<Observer, std::nullptr_t>::value, "Only std::nullptr_t observer type can be used with BicycleKinematic model type."); } template <typename Model, typename Observer> template <typename T> Bicycle<Model, Observer>::Bicycle(typename std::enable_if<!std::is_base_of<observer::ObserverBase, T>::value, real_t>::type v, real_t dt) : m_model(v, dt), m_observer(nullptr), m_full_state(full_state_t::Zero()), m_pose(BicyclePoseMessage_init_zero), m_input(input_t::Zero()), m_measurement(measurement_t::Zero()) { // Note: User must initialize Kalman matrices in application. chBSemObjectInit(&m_state_sem, false); // initialize to not taken static_assert((!std::is_same<Model, model::BicycleKinematic>::value) || std::is_same<Observer, std::nullptr_t>::value, "Only std::nullptr_t observer type can be used with BicycleKinematic model type."); } template <typename Model, typename Observer> void Bicycle<Model, Observer>::set_v(real_t v) { using namespace boost::math::policies; using quantize_policy = policy<rounding_error<ignore_error>>; static constexpr quantize_policy policy; real_t v_quantized = v_quantization_resolution * boost::math::round(v/v_quantization_resolution, policy); if (v_quantized != this->v()) { m_model.set_v_dt(v_quantized, m_model.dt()); } } template <typename Model, typename Observer> void Bicycle<Model, Observer>::set_dt(real_t dt) { if (dt != this->dt()) { m_model.set_v_dt(m_model.v(), dt); } } template <typename Model, typename Observer> OBSERVER_FUNCTION(void) Bicycle<Model, Observer>::reset() { m_observer.reset(); m_full_state = full_state_t::Zero(); } template <typename Model, typename Observer> NULL_OBSERVER_FUNCTION(void) Bicycle<Model, Observer>::reset() { m_full_state = full_state_t::Zero(); } template <typename Model, typename Observer> void Bicycle<Model, Observer>::update_dynamics(real_t roll_torque_input, real_t steer_torque_input, real_t yaw_angle_measurement, real_t steer_angle_measurement, real_t rear_wheel_angle_measurement) { // While the rear wheel angle measurement can be used to determine velocity, // it is assumed that velocity is determined outside this class and passed as // an input. This allows the velocity resolution, and thus the model update // frequency, to be determined by a filter unrelated to the bicycle model. // // This could also be used to determine the wheel angles, as we assume // no-slip conditions. However, we calculate the wheel angles during the // kinematic update and solely from bicycle velocity. (void)rear_wheel_angle_measurement; m_input = input_t::Zero(); model_t::set_input_element(m_input, model_t::input_index_t::roll_torque, roll_torque_input); model_t::set_input_element(m_input, model_t::input_index_t::steer_torque, steer_torque_input); m_measurement = measurement_t::Zero(); model_t::set_output_element(m_measurement, model_t::output_index_t::yaw_angle, yaw_angle_measurement); model_t::set_output_element(m_measurement, model_t::output_index_t::steer_angle, steer_angle_measurement); // do full state update which is observer specific chBSemWait(&m_state_sem); full_state_t full_state_copy = m_full_state; chBSemSignal(&m_state_sem); full_state_t full_state_next = do_full_state_update(full_state_copy); chBSemWait(&m_state_sem); m_full_state = full_state_next; chBSemSignal(&m_state_sem); } template <typename Model, typename Observer> void Bicycle<Model, Observer>::update_kinematics() { chBSemWait(&m_state_sem); full_state_t full_state_copy = m_full_state; chBSemSignal(&m_state_sem); // solve for pitch as this does not get integrated const real_t roll = model_t::get_full_state_element(full_state_copy, full_state_index_t::roll_angle); const real_t steer = model_t::get_full_state_element(full_state_copy, full_state_index_t::steer_angle); real_t pitch = model_t::get_full_state_element(full_state_copy, full_state_index_t::pitch_angle); pitch = m_model.solve_constraint_pitch(roll, steer, pitch); // update full state with newest computed pitch angle chBSemWait(&m_state_sem); model_t::set_full_state_element(m_full_state, full_state_index_t::pitch_angle, pitch); // mod rear wheel angle so it does not grow beyond all bounds model_t::set_full_state_element(m_full_state, full_state_index_t::rear_wheel_angle, std::fmod(model_t::get_full_state_element(full_state_copy, full_state_index_t::rear_wheel_angle), constants::two_pi)), chBSemSignal(&m_state_sem); m_pose.timestamp = chVTGetSystemTime(); m_pose.x = model_t::get_full_state_element(full_state_copy, full_state_index_t::x); m_pose.y = model_t::get_full_state_element(full_state_copy, full_state_index_t::y); m_pose.rear_wheel = model_t::get_full_state_element(full_state_copy, full_state_index_t::rear_wheel_angle); m_pose.pitch = pitch; m_pose.yaw = model_t::get_full_state_element(full_state_copy, full_state_index_t::yaw_angle); m_pose.roll = roll; m_pose.steer = steer; } template <typename Model, typename Observer> OBSERVER_FUNCTION(void) Bicycle<Model, Observer>::prime_observer() { // define a non-zero initial state, this is selected arbitrarily for now state_t x = state_t::Zero(); model::Bicycle::set_state_element(x, model_t::state_index_t::steer_angle, 0.1f); // in radians static constexpr real_t observer_prime_period = 3.0; // seconds real_t t = 0; while (t < observer_prime_period) { x = m_model.update_state(x); m_observer.update_state(input_t::Zero(), m_model.calculate_output(x)); t += m_model.dt(); } } template <typename Model, typename Observer> NULL_OBSERVER_FUNCTION(void) Bicycle<Model, Observer>::prime_observer() { // do nothing } template <typename Model, typename Observer> const BicyclePoseMessage& Bicycle<Model, Observer>::pose() const { return m_pose; } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::input_t& Bicycle<Model, Observer>::input() const { return m_input; } template <typename Model, typename Observer> typename Bicycle<Model, Observer>::model_t& Bicycle<Model, Observer>::model() { return m_model; }; template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::model_t& Bicycle<Model, Observer>::model() const { return m_model; }; template <typename Model, typename Observer> typename Bicycle<Model, Observer>::observer_t& Bicycle<Model, Observer>::observer() { return m_observer; }; template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::observer_t& Bicycle<Model, Observer>::observer() const { return m_observer; }; template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::second_order_matrix_t& Bicycle<Model, Observer>::M() const { return m_model.M(); } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::second_order_matrix_t& Bicycle<Model, Observer>::C1() const { return m_model.C1(); } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::second_order_matrix_t& Bicycle<Model, Observer>::K0() const { return m_model.K0(); } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::second_order_matrix_t& Bicycle<Model, Observer>::K2() const { return m_model.K2(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::wheelbase() const { return m_model.wheelbase(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::trail() const { return m_model.trail(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::steer_axis_tilt() const { return m_model.steer_axis_tilt(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::rear_wheel_radius() const { return m_model.rear_wheel_radius(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::front_wheel_radius() const { return m_model.front_wheel_radius(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::v() const { return m_model.v(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::dt() const { return m_model.dt(); } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::full_state_t& Bicycle<Model, Observer>::full_state() const { return m_full_state; } template <typename Model, typename Observer> OBSERVER_FUNCTION(typename BICYCLE_TYPE::full_state_t) Bicycle<Model, Observer>::do_full_state_update(const full_state_t& full_state) { // The auxiliary states _must_ also be integrated at the same time as the // dynamic state. After the observer update, we "merge" dynamic states together. full_state_t state_full = m_model.integrate_full_state( full_state, m_input, m_model.dt(), m_measurement); m_observer.update_state(m_input, m_measurement); if (!m_observer.state().allFinite()) { chSysHalt("state elements with non finite values"); } { // limit allowed bicycle state state_t x = m_observer.state(); auto limit_state_element = [&x](model::Bicycle::state_index_t index, real_t limit) { const real_t value = model::Bicycle::get_state_element(x, index); if (std::abs(value) > limit) { model::Bicycle::set_state_element(x, index, std::copysign(limit, value)); } }; real_t roll_angle = model_t::get_state_element(m_observer.state(), model_t::state_index_t::roll_angle); if (std::abs(roll_angle) > constants::pi) { // state normalization limits angles to the range [-2*pi, 2*pi] // and here we constrain it further to [-pi, pi] chDbgAssert((roll_angle <= constants::two_pi) && (roll_angle >= -constants::two_pi), "roll angle not model normalized"); roll_angle += std::copysign(constants::two_pi, -1*roll_angle); } limit_state_element(model_t::state_index_t::roll_rate, roll_rate_limit); limit_state_element(model_t::state_index_t::steer_rate, steer_rate_limit); m_observer.set_state(x); } // Merge observer and model states // // We simply copy the observer state estimate to the full state vector // this may result in accumulated error in the auxiliary states but // convergence of the observer estimate should keep it low. // Also, we have no way to correct auxiliary states as there are no sensors // to measure them and that's because they are _purely_ virtual. return model_t::make_full_state(model_t::get_auxiliary_state_part(state_full), m_observer.state()); } template <typename Model, typename Observer> NULL_OBSERVER_FUNCTION(typename BICYCLE_TYPE::full_state_t) Bicycle<Model, Observer>::do_full_state_update(const full_state_t& full_state) { // REMOVE ME: No limiting is done but that is removed in a different commit return m_model.integrate_full_state(full_state, m_input, m_model.dt(), m_measurement); } } // namespace sim
#include <cmath> #include <type_traits> #include <boost/math/special_functions/round.hpp> #include "bicycle/kinematic.h" #include "kalman.h" /* * Member function definitions of sim::Bicycle template class. * See simbicycle.h for template class declaration. */ namespace sim { #define OBSERVER_FUNCTION(return_type) \ template <typename T> \ typename std::enable_if<std::is_base_of<observer::ObserverBase, T>::value, return_type>::type #define NULL_OBSERVER_FUNCTION(return_type) \ template <typename T> \ typename std::enable_if<!std::is_base_of<observer::ObserverBase, T>::value, return_type>::type #define BICYCLE_TYPE Bicycle<Model, Observer> template <typename Model, typename Observer> template <typename T> Bicycle<Model, Observer>::Bicycle(typename std::enable_if<std::is_base_of<observer::ObserverBase, T>::value, real_t>::type v, real_t dt) : m_model(v, dt), m_observer(m_model), m_full_state(full_state_t::Zero()), m_pose(BicyclePoseMessage_init_zero), m_input(input_t::Zero()), m_measurement(measurement_t::Zero()) { // Note: User must initialize Kalman matrices in application. chBSemObjectInit(&m_state_sem, false); // initialize to not taken static_assert((!std::is_same<Model, model::BicycleKinematic>::value) || std::is_same<Observer, std::nullptr_t>::value, "Only std::nullptr_t observer type can be used with BicycleKinematic model type."); } template <typename Model, typename Observer> template <typename T> Bicycle<Model, Observer>::Bicycle(typename std::enable_if<!std::is_base_of<observer::ObserverBase, T>::value, real_t>::type v, real_t dt) : m_model(v, dt), m_observer(nullptr), m_full_state(full_state_t::Zero()), m_pose(BicyclePoseMessage_init_zero), m_input(input_t::Zero()), m_measurement(measurement_t::Zero()) { // Note: User must initialize Kalman matrices in application. chBSemObjectInit(&m_state_sem, false); // initialize to not taken static_assert((!std::is_same<Model, model::BicycleKinematic>::value) || std::is_same<Observer, std::nullptr_t>::value, "Only std::nullptr_t observer type can be used with BicycleKinematic model type."); } template <typename Model, typename Observer> void Bicycle<Model, Observer>::set_v(real_t v) { using namespace boost::math::policies; using quantize_policy = policy<rounding_error<ignore_error>>; static constexpr quantize_policy policy; real_t v_quantized = v_quantization_resolution * boost::math::round(v/v_quantization_resolution, policy); if (v_quantized != this->v()) { m_model.set_v_dt(v_quantized, m_model.dt()); } } template <typename Model, typename Observer> void Bicycle<Model, Observer>::set_dt(real_t dt) { if (dt != this->dt()) { m_model.set_v_dt(m_model.v(), dt); } } template <typename Model, typename Observer> OBSERVER_FUNCTION(void) Bicycle<Model, Observer>::reset() { m_observer.reset(); m_full_state = full_state_t::Zero(); } template <typename Model, typename Observer> NULL_OBSERVER_FUNCTION(void) Bicycle<Model, Observer>::reset() { m_full_state = full_state_t::Zero(); } template <typename Model, typename Observer> void Bicycle<Model, Observer>::update_dynamics(real_t roll_torque_input, real_t steer_torque_input, real_t yaw_angle_measurement, real_t steer_angle_measurement, real_t rear_wheel_angle_measurement) { // While the rear wheel angle measurement can be used to determine velocity, // it is assumed that velocity is determined outside this class and passed as // an input. This allows the velocity resolution, and thus the model update // frequency, to be determined by a filter unrelated to the bicycle model. // // This could also be used to determine the wheel angles, as we assume // no-slip conditions. However, we calculate the wheel angles during the // kinematic update and solely from bicycle velocity. (void)rear_wheel_angle_measurement; m_input = input_t::Zero(); model_t::set_input_element(m_input, model_t::input_index_t::roll_torque, roll_torque_input); model_t::set_input_element(m_input, model_t::input_index_t::steer_torque, steer_torque_input); m_measurement = measurement_t::Zero(); model_t::set_output_element(m_measurement, model_t::output_index_t::yaw_angle, yaw_angle_measurement); model_t::set_output_element(m_measurement, model_t::output_index_t::steer_angle, steer_angle_measurement); // do full state update which is observer specific chBSemWait(&m_state_sem); full_state_t full_state_copy = m_full_state; chBSemSignal(&m_state_sem); full_state_t full_state_next = do_full_state_update(full_state_copy); chBSemWait(&m_state_sem); m_full_state = full_state_next; chBSemSignal(&m_state_sem); } template <typename Model, typename Observer> void Bicycle<Model, Observer>::update_kinematics() { chBSemWait(&m_state_sem); full_state_t full_state_copy = m_full_state; chBSemSignal(&m_state_sem); // solve for pitch as this does not get integrated const real_t roll = model_t::get_full_state_element(full_state_copy, full_state_index_t::roll_angle); const real_t steer = model_t::get_full_state_element(full_state_copy, full_state_index_t::steer_angle); real_t pitch = model_t::get_full_state_element(full_state_copy, full_state_index_t::pitch_angle); pitch = m_model.solve_constraint_pitch(roll, steer, pitch); // update full state with newest computed pitch angle chBSemWait(&m_state_sem); model_t::set_full_state_element(m_full_state, full_state_index_t::pitch_angle, pitch); // mod rear wheel angle so it does not grow beyond all bounds model_t::set_full_state_element(m_full_state, full_state_index_t::rear_wheel_angle, std::fmod(model_t::get_full_state_element(full_state_copy, full_state_index_t::rear_wheel_angle), constants::two_pi)), chBSemSignal(&m_state_sem); m_pose.timestamp = chVTGetSystemTime(); m_pose.x = model_t::get_full_state_element(full_state_copy, full_state_index_t::x); m_pose.y = model_t::get_full_state_element(full_state_copy, full_state_index_t::y); m_pose.rear_wheel = model_t::get_full_state_element(full_state_copy, full_state_index_t::rear_wheel_angle); m_pose.pitch = pitch; m_pose.yaw = model_t::get_full_state_element(full_state_copy, full_state_index_t::yaw_angle); m_pose.roll = roll; m_pose.steer = steer; } template <typename Model, typename Observer> OBSERVER_FUNCTION(void) Bicycle<Model, Observer>::prime_observer() { // define a non-zero initial state, this is selected arbitrarily for now state_t x = state_t::Zero(); model::Bicycle::set_state_element(x, model_t::state_index_t::steer_angle, 0.1f); // in radians static constexpr real_t observer_prime_period = 3.0; // seconds real_t t = 0; while (t < observer_prime_period) { x = m_model.update_state(x); m_observer.update_state(input_t::Zero(), m_model.calculate_output(x)); t += m_model.dt(); } } template <typename Model, typename Observer> NULL_OBSERVER_FUNCTION(void) Bicycle<Model, Observer>::prime_observer() { // do nothing } template <typename Model, typename Observer> const BicyclePoseMessage& Bicycle<Model, Observer>::pose() const { return m_pose; } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::input_t& Bicycle<Model, Observer>::input() const { return m_input; } template <typename Model, typename Observer> typename Bicycle<Model, Observer>::model_t& Bicycle<Model, Observer>::model() { return m_model; }; template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::model_t& Bicycle<Model, Observer>::model() const { return m_model; }; template <typename Model, typename Observer> typename Bicycle<Model, Observer>::observer_t& Bicycle<Model, Observer>::observer() { return m_observer; }; template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::observer_t& Bicycle<Model, Observer>::observer() const { return m_observer; }; template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::second_order_matrix_t& Bicycle<Model, Observer>::M() const { return m_model.M(); } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::second_order_matrix_t& Bicycle<Model, Observer>::C1() const { return m_model.C1(); } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::second_order_matrix_t& Bicycle<Model, Observer>::K0() const { return m_model.K0(); } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::second_order_matrix_t& Bicycle<Model, Observer>::K2() const { return m_model.K2(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::wheelbase() const { return m_model.wheelbase(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::trail() const { return m_model.trail(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::steer_axis_tilt() const { return m_model.steer_axis_tilt(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::rear_wheel_radius() const { return m_model.rear_wheel_radius(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::front_wheel_radius() const { return m_model.front_wheel_radius(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::v() const { return m_model.v(); } template <typename Model, typename Observer> model::real_t Bicycle<Model, Observer>::dt() const { return m_model.dt(); } template <typename Model, typename Observer> const typename Bicycle<Model, Observer>::full_state_t& Bicycle<Model, Observer>::full_state() const { return m_full_state; } template <typename Model, typename Observer> OBSERVER_FUNCTION(typename BICYCLE_TYPE::full_state_t) Bicycle<Model, Observer>::do_full_state_update(const full_state_t& full_state) { // The auxiliary states _must_ also be integrated at the same time as the // dynamic state. After the observer update, we "merge" dynamic states together. full_state_t state_full = m_model.integrate_full_state( full_state, m_input, m_model.dt(), m_measurement); m_observer.update_state(m_input, m_measurement); if (!m_observer.state().allFinite()) { chSysHalt("state elements with non finite values"); } { // limit allowed bicycle state state_t x = m_observer.state(); auto limit_state_element = [&x](model::Bicycle::state_index_t index, real_t limit) { const real_t value = model::Bicycle::get_state_element(x, index); if (std::abs(value) > limit) { model::Bicycle::set_state_element(x, index, std::copysign(limit, value)); } }; const real_t roll_angle = model_t::get_state_element(x, model_t::state_index_t::roll_angle); if (std::abs(roll_angle) > constants::pi) { // state normalization limits angles to the range [-2*pi, 2*pi] // and here we constrain it further to [-pi, pi] chDbgAssert((roll_angle <= constants::two_pi) && (roll_angle >= -constants::two_pi), "roll angle not model normalized"); model_t::set_state_element(x, model_t::state_index_t::roll_angle, roll_angle + std::copysign(constants::two_pi, -1*roll_angle)); } limit_state_element(model_t::state_index_t::roll_rate, roll_rate_limit); limit_state_element(model_t::state_index_t::steer_rate, steer_rate_limit); m_observer.set_state(x); } // Merge observer and model states // // We simply copy the observer state estimate to the full state vector // this may result in accumulated error in the auxiliary states but // convergence of the observer estimate should keep it low. // Also, we have no way to correct auxiliary states as there are no sensors // to measure them and that's because they are _purely_ virtual. return model_t::make_full_state(model_t::get_auxiliary_state_part(state_full), m_observer.state()); } template <typename Model, typename Observer> NULL_OBSERVER_FUNCTION(typename BICYCLE_TYPE::full_state_t) Bicycle<Model, Observer>::do_full_state_update(const full_state_t& full_state) { // REMOVE ME: No limiting is done but that is removed in a different commit return m_model.integrate_full_state(full_state, m_input, m_model.dt(), m_measurement); } } // namespace sim
Set roll angle after normalization
Set roll angle after normalization
C++
bsd-2-clause
oliverlee/phobos,oliverlee/phobos,oliverlee/phobos,oliverlee/phobos
0126bf2a7819f287f05a566772cb522d4ad504e0
cvmfs/publish/repository_transaction.cc
cvmfs/publish/repository_transaction.cc
/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include "publish/repository.h" #include <string> #include "backoff.h" #include "catalog_mgr_ro.h" #include "catalog_mgr_rw.h" #include "directory_entry.h" #include "logging.h" #include "manifest.h" #include "publish/except.h" #include "publish/repository_util.h" #include "publish/settings.h" #include "util/pointer.h" #include "util/posix.h" namespace publish { void Publisher::CheckTransactionStatus() { // The process that opens the transaction does not stay alive for the life // time of the transaction const std::string transaction_lock = settings_.transaction().spool_area().transaction_lock(); in_transaction_ = ServerLockFile::IsLocked(transaction_lock, true /* ignore_stale */); const std::string publishing_lock = settings_.transaction().spool_area().publishing_lock(); is_publishing_ = ServerLockFile::IsLocked(publishing_lock, false /* ignore_stale */); session_ = new Session(settings_, llvl_); } void Publisher::TransactionRetry() { if (managed_node_) { int rvi = managed_node_->Check(false /* is_quiet */); if (rvi != 0) throw EPublish("cannot establish writable mountpoint"); } BackoffThrottle throttle(500, 5000, 10000); // Negative timeouts (i.e.: no retry) will result in a deadline that has // already passed and thus has the correct effect uint64_t deadline = platform_monotonic_time() + settings_.transaction().GetTimeoutS(); if (settings_.transaction().GetTimeoutS() == 0) deadline = uint64_t(-1); while (true) { try { TransactionImpl(); break; } catch (const publish::EPublish& e) { if (e.failure() != EPublish::kFailTransactionState) { session_->Drop(); ServerLockFile::Release( settings_.transaction().spool_area().transaction_lock()); } if ((e.failure() == EPublish::kFailTransactionState) || (e.failure() == EPublish::kFailLeaseBusy)) { if (platform_monotonic_time() > deadline) throw; LogCvmfs(kLogCvmfs, kLogStdout, "repository busy, retrying"); throttle.Throttle(); CheckTransactionStatus(); continue; } throw; } // try-catch } // while (true) if (managed_node_) managed_node_->Open(); } void Publisher::TransactionImpl() { if (in_transaction_) { throw EPublish("another transaction is already open", EPublish::kFailTransactionState); } InitSpoolArea(); // On error, Transaction() will release the transaction lock and drop // the session const std::string transaction_lock = settings_.transaction().spool_area().transaction_lock(); ServerLockFile::Acquire(transaction_lock, true /* ignore_stale */); if (session_->has_lease()) { LogCvmfs(kLogCvmfs, kLogStdout | kLogSyslogWarn, "Warning: stale lease found for %s", settings_.fqrn().c_str()); } session_->Acquire(); // We might have a valid lease for a non-existing path. Nevertheless, we run // run into problems when merging catalogs later, so for the time being we // disallow transactions on non-existing paths. if (!settings_.transaction().lease_path().empty()) { std::string path = GetParentPath( "/" + settings_.transaction().lease_path()); catalog::SimpleCatalogManager *catalog_mgr = GetSimpleCatalogManager(); catalog::DirectoryEntry dirent; bool retval = catalog_mgr->LookupPath(path, catalog::kLookupSole, &dirent); if (!retval) { throw EPublish("cannot open transaction on non-existing path " + path, EPublish::kFailLeaseNoEntry); } if (!dirent.IsDirectory()) { throw EPublish( "cannot open transaction on " + path + ", which is not a directory", EPublish::kFailLeaseNoDir); } } ConstructSpoolers(); UniquePtr<CheckoutMarker> marker(CheckoutMarker::CreateFrom( settings_.transaction().spool_area().checkout_marker())); // TODO(jblomer): take root hash from r/o mountpoint? if (marker.IsValid()) settings_.GetTransaction()->SetBaseHash(marker->hash()); else settings_.GetTransaction()->SetBaseHash(manifest_->catalog_hash()); if (settings_.transaction().HasTemplate()) { LogCvmfs(kLogCvmfs, llvl_ | kLogStdout | kLogNoLinebreak, "CernVM-FS: cloning template %s --> %s ... ", settings_.transaction().template_from().c_str(), settings_.transaction().template_to().c_str()); ConstructSyncManagers(); catalog_mgr_->CloneTree(settings_.transaction().template_from(), settings_.transaction().template_to()); Sync(); SendTalkCommand(settings_.transaction().spool_area().readonly_talk_socket(), "chroot " + settings_.transaction().base_hash().ToString() + "\n"); LogCvmfs(kLogCvmfs, llvl_ | kLogStdout, "[done]"); // TODO(jblomer): fix-me // PushReflog(); } in_transaction_ = true; LogCvmfs(kLogCvmfs, llvl_ | kLogDebug | kLogSyslog, "(%s) opened transaction", settings_.fqrn().c_str()); } } // namespace publish
/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include "publish/repository.h" #include <string> #include "backoff.h" #include "catalog_mgr_ro.h" #include "catalog_mgr_rw.h" #include "directory_entry.h" #include "logging.h" #include "manifest.h" #include "publish/except.h" #include "publish/repository_util.h" #include "publish/settings.h" #include "util/pointer.h" #include "util/posix.h" namespace publish { void Publisher::CheckTransactionStatus() { // The process that opens the transaction does not stay alive for the life // time of the transaction const std::string transaction_lock = settings_.transaction().spool_area().transaction_lock(); in_transaction_ = ServerLockFile::IsLocked(transaction_lock, true /* ignore_stale */); const std::string publishing_lock = settings_.transaction().spool_area().publishing_lock(); is_publishing_ = ServerLockFile::IsLocked(publishing_lock, false /* ignore_stale */); session_ = new Session(settings_, llvl_); } void Publisher::TransactionRetry() { if (managed_node_) { int rvi = managed_node_->Check(false /* is_quiet */); if (rvi != 0) throw EPublish("cannot establish writable mountpoint"); } BackoffThrottle throttle(500, 5000, 10000); // Negative timeouts (i.e.: no retry) will result in a deadline that has // already passed and thus has the correct effect uint64_t deadline = platform_monotonic_time() + settings_.transaction().GetTimeoutS(); if (settings_.transaction().GetTimeoutS() == 0) deadline = uint64_t(-1); while (true) { try { TransactionImpl(); break; } catch (const publish::EPublish& e) { if (e.failure() != EPublish::kFailTransactionState) { session_->Drop(); ServerLockFile::Release( settings_.transaction().spool_area().transaction_lock()); } if ((e.failure() == EPublish::kFailTransactionState) || (e.failure() == EPublish::kFailLeaseBusy)) { if (platform_monotonic_time() > deadline) throw; LogCvmfs(kLogCvmfs, kLogStdout, "repository busy, retrying"); throttle.Throttle(); CheckTransactionStatus(); continue; } throw; } // try-catch } // while (true) if (managed_node_) managed_node_->Open(); } void Publisher::TransactionImpl() { if (in_transaction_) { throw EPublish("another transaction is already open", EPublish::kFailTransactionState); } InitSpoolArea(); // On error, Transaction() will release the transaction lock and drop // the session const std::string transaction_lock = settings_.transaction().spool_area().transaction_lock(); ServerLockFile::Acquire(transaction_lock, true /* ignore_stale */); session_->Acquire(); // We might have a valid lease for a non-existing path. Nevertheless, we run // run into problems when merging catalogs later, so for the time being we // disallow transactions on non-existing paths. if (!settings_.transaction().lease_path().empty()) { std::string path = GetParentPath( "/" + settings_.transaction().lease_path()); catalog::SimpleCatalogManager *catalog_mgr = GetSimpleCatalogManager(); catalog::DirectoryEntry dirent; bool retval = catalog_mgr->LookupPath(path, catalog::kLookupSole, &dirent); if (!retval) { throw EPublish("cannot open transaction on non-existing path " + path, EPublish::kFailLeaseNoEntry); } if (!dirent.IsDirectory()) { throw EPublish( "cannot open transaction on " + path + ", which is not a directory", EPublish::kFailLeaseNoDir); } } ConstructSpoolers(); UniquePtr<CheckoutMarker> marker(CheckoutMarker::CreateFrom( settings_.transaction().spool_area().checkout_marker())); // TODO(jblomer): take root hash from r/o mountpoint? if (marker.IsValid()) settings_.GetTransaction()->SetBaseHash(marker->hash()); else settings_.GetTransaction()->SetBaseHash(manifest_->catalog_hash()); if (settings_.transaction().HasTemplate()) { LogCvmfs(kLogCvmfs, llvl_ | kLogStdout | kLogNoLinebreak, "CernVM-FS: cloning template %s --> %s ... ", settings_.transaction().template_from().c_str(), settings_.transaction().template_to().c_str()); ConstructSyncManagers(); catalog_mgr_->CloneTree(settings_.transaction().template_from(), settings_.transaction().template_to()); Sync(); SendTalkCommand(settings_.transaction().spool_area().readonly_talk_socket(), "chroot " + settings_.transaction().base_hash().ToString() + "\n"); LogCvmfs(kLogCvmfs, llvl_ | kLogStdout, "[done]"); // TODO(jblomer): fix-me // PushReflog(); } in_transaction_ = true; LogCvmfs(kLogCvmfs, llvl_ | kLogDebug | kLogSyslog, "(%s) opened transaction", settings_.fqrn().c_str()); } } // namespace publish
Remove spurious warning on transaction
[publish] Remove spurious warning on transaction
C++
bsd-3-clause
DrDaveD/cvmfs,DrDaveD/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,DrDaveD/cvmfs,cvmfs/cvmfs
5529b7dccc13af9021a7e8e99a683ee3048c3ef3
gm/gamma.cpp
gm/gamma.cpp
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkGradientShader.h" DEF_SIMPLE_GM(gamma, canvas, 500, 200) { SkPaint p; const SkScalar sz = 50.0f; const int szInt = SkScalarTruncToInt(sz); const SkScalar tx = sz + 5.0f; const SkRect r = SkRect::MakeXYWH(0, 0, sz, sz); SkShader::TileMode rpt = SkShader::kRepeat_TileMode; SkBitmap ditherBmp; ditherBmp.allocN32Pixels(2, 2); SkPMColor* pixels = reinterpret_cast<SkPMColor*>(ditherBmp.getPixels()); pixels[0] = pixels[3] = SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF); pixels[1] = pixels[2] = SkPackARGB32(0xFF, 0, 0, 0); SkBitmap linearGreyBmp; SkImageInfo linearGreyInfo = SkImageInfo::MakeN32(szInt, szInt, kOpaque_SkAlphaType, kLinear_SkColorProfileType); linearGreyBmp.allocPixels(linearGreyInfo); linearGreyBmp.eraseARGB(0xFF, 0x7F, 0x7F, 0x7F); SkBitmap srgbGreyBmp; SkImageInfo srgbGreyInfo = SkImageInfo::MakeN32(szInt, szInt, kOpaque_SkAlphaType, kSRGB_SkColorProfileType); srgbGreyBmp.allocPixels(srgbGreyInfo); srgbGreyBmp.eraseARGB(0xFF, 0xBC, 0xBC, 0xBC); SkPaint textPaint; textPaint.setColor(SK_ColorWHITE); // Helpers: auto advance = [&]() { canvas->translate(tx, 0); p.reset(); }; auto nextRect = [&](const char* label, const char* label2) { canvas->drawRect(r, p); canvas->drawText(label, strlen(label), 0, sz + textPaint.getFontSpacing(), textPaint); if (label2) { canvas->drawText(label2, strlen(label2), 0, sz + 2 * textPaint.getFontSpacing(), textPaint); } advance(); }; auto nextBitmap = [&](const SkBitmap& bmp, const char* label) { canvas->drawBitmap(bmp, 0, 0); canvas->drawText(label, strlen(label), 0, sz + textPaint.getFontSpacing(), textPaint); advance(); }; auto nextXferRect = [&](SkColor srcColor, SkXfermode::Mode mode, SkColor dstColor) { p.setColor(dstColor); canvas->drawRect(r, p); p.setColor(srcColor); p.setXfermodeMode(mode); canvas->drawRect(r, p); SkString srcText = SkStringPrintf("%08X", srcColor); SkString dstText = SkStringPrintf("%08X", dstColor); canvas->drawText(srcText.c_str(), srcText.size(), 0, sz + textPaint.getFontSpacing(), textPaint); const char* modeName = SkXfermode::ModeName(mode); canvas->drawText(modeName, strlen(modeName), 0, sz + 2 * textPaint.getFontSpacing(), textPaint); canvas->drawText(dstText.c_str(), dstText.size(), 0, sz + 3 * textPaint.getFontSpacing(), textPaint); advance(); }; // Necessary for certain Xfermode tests to work (ie some of them output white @ 50% alpha): canvas->clear(SK_ColorBLACK); // *Everything* should be perceptually 50% grey. Only the first rectangle // is guaranteed to draw that way, though. canvas->save(); // Black/white dither, pixel perfect. This is ground truth. p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kNone_SkFilterQuality); nextRect("Dither", "Reference"); // Black/white dither, sampled at half-texel offset. Tests bilerp. // NOTE: We need to apply a non-identity scale and/or rotation to trick // the raster pipeline into *not* snapping to nearest. SkMatrix offsetMatrix = SkMatrix::Concat( SkMatrix::MakeScale(-1.0f), SkMatrix::MakeTrans(0.5f, 0.0f)); p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt, &offsetMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Dither", "Bilerp"); // Black/white dither, scaled down by 2x. Tests minification. SkMatrix scaleMatrix = SkMatrix::MakeScale(0.5f); p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt, &scaleMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Dither", "Scale"); // 50% grey via paint color. p.setColor(0xff7f7f7f); nextRect("Color", 0); // Black -> White gradient, scaled to sample just the middle. // Tests gradient interpolation. SkPoint points[2] = { SkPoint::Make(0 - (sz * 10), 0), SkPoint::Make(sz + (sz * 10), 0) }; SkColor colors[2] = { SK_ColorBLACK, SK_ColorWHITE }; p.setShader(SkGradientShader::MakeLinear(points, colors, nullptr, 2, SkShader::kClamp_TileMode)); nextRect("Gradient", 0); // 50% grey from linear bitmap, with drawBitmap nextBitmap(linearGreyBmp, "Lnr BMP"); // 50% grey from sRGB bitmap, with drawBitmap nextBitmap(srgbGreyBmp, "sRGB BMP"); // Bitmap wrapped in a shader (linear): p.setShader(SkShader::MakeBitmapShader(linearGreyBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Lnr BMP", "Shader"); // Bitmap wrapped in a shader (sRGB): p.setShader(SkShader::MakeBitmapShader(srgbGreyBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("sRGB BMP", "Shader"); // Carriage return. canvas->restore(); canvas->translate(0, 2 * sz); const U8CPU sqrtHalf = 0xB4; const SkColor sqrtHalfAlpha = SkColorSetARGB(sqrtHalf, 0, 0, 0); const SkColor sqrtHalfWhite = SkColorSetARGB(0xFF, sqrtHalf, sqrtHalf, sqrtHalf); // Xfermode tests, all done off-screen so certain modes work... canvas->saveLayer(nullptr, nullptr); nextXferRect(0x7fffffff, SkXfermode::kSrcOver_Mode, SK_ColorBLACK); nextXferRect(0x7f000000, SkXfermode::kSrcOver_Mode, SK_ColorWHITE); nextXferRect(SK_ColorBLACK, SkXfermode::kDstOver_Mode, 0x7fffffff); nextXferRect(SK_ColorWHITE, SkXfermode::kSrcIn_Mode, 0x7fff00ff); nextXferRect(0x7fff00ff, SkXfermode::kDstIn_Mode, SK_ColorWHITE); nextXferRect(sqrtHalfWhite, SkXfermode::kSrcIn_Mode, sqrtHalfAlpha); nextXferRect(sqrtHalfAlpha, SkXfermode::kDstIn_Mode, sqrtHalfWhite); nextXferRect(0xff3f3f3f, SkXfermode::kPlus_Mode, 0xff3f3f3f); nextXferRect(sqrtHalfWhite, SkXfermode::kModulate_Mode, sqrtHalfWhite); canvas->restore(); canvas->restore(); }
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "Resources.h" #include "SkGradientShader.h" DEF_SIMPLE_GM(gamma, canvas, 500, 200) { SkPaint p; const SkScalar sz = 50.0f; const int szInt = SkScalarTruncToInt(sz); const SkScalar tx = sz + 5.0f; const SkRect r = SkRect::MakeXYWH(0, 0, sz, sz); SkShader::TileMode rpt = SkShader::kRepeat_TileMode; SkBitmap ditherBmp; ditherBmp.allocN32Pixels(2, 2); SkPMColor* pixels = reinterpret_cast<SkPMColor*>(ditherBmp.getPixels()); pixels[0] = pixels[3] = SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF); pixels[1] = pixels[2] = SkPackARGB32(0xFF, 0, 0, 0); SkBitmap linearGreyBmp; SkImageInfo linearGreyInfo = SkImageInfo::MakeN32(szInt, szInt, kOpaque_SkAlphaType, kLinear_SkColorProfileType); linearGreyBmp.allocPixels(linearGreyInfo); linearGreyBmp.eraseARGB(0xFF, 0x7F, 0x7F, 0x7F); SkBitmap srgbGreyBmp; SkImageInfo srgbGreyInfo = SkImageInfo::MakeN32(szInt, szInt, kOpaque_SkAlphaType, kSRGB_SkColorProfileType); srgbGreyBmp.allocPixels(srgbGreyInfo); srgbGreyBmp.eraseARGB(0xFF, 0xBC, 0xBC, 0xBC); SkPaint textPaint; textPaint.setColor(SK_ColorWHITE); // Helpers: auto advance = [&]() { canvas->translate(tx, 0); p.reset(); }; auto nextRect = [&](const char* label, const char* label2) { canvas->drawRect(r, p); canvas->drawText(label, strlen(label), 0, sz + textPaint.getFontSpacing(), textPaint); if (label2) { canvas->drawText(label2, strlen(label2), 0, sz + 2 * textPaint.getFontSpacing(), textPaint); } advance(); }; auto nextBitmap = [&](const SkBitmap& bmp, const char* label) { canvas->drawBitmap(bmp, 0, 0); canvas->drawText(label, strlen(label), 0, sz + textPaint.getFontSpacing(), textPaint); advance(); }; auto nextXferRect = [&](SkColor srcColor, SkXfermode::Mode mode, SkColor dstColor) { p.setColor(dstColor); canvas->drawRect(r, p); p.setColor(srcColor); p.setXfermodeMode(mode); canvas->drawRect(r, p); SkString srcText = SkStringPrintf("%08X", srcColor); SkString dstText = SkStringPrintf("%08X", dstColor); canvas->drawText(srcText.c_str(), srcText.size(), 0, sz + textPaint.getFontSpacing(), textPaint); const char* modeName = SkXfermode::ModeName(mode); canvas->drawText(modeName, strlen(modeName), 0, sz + 2 * textPaint.getFontSpacing(), textPaint); canvas->drawText(dstText.c_str(), dstText.size(), 0, sz + 3 * textPaint.getFontSpacing(), textPaint); advance(); }; // Necessary for certain Xfermode tests to work (ie some of them output white @ 50% alpha): canvas->clear(SK_ColorBLACK); // *Everything* should be perceptually 50% grey. Only the first rectangle // is guaranteed to draw that way, though. canvas->save(); // Black/white dither, pixel perfect. This is ground truth. p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kNone_SkFilterQuality); nextRect("Dither", "Reference"); // Black/white dither, sampled at half-texel offset. Tests bilerp. // NOTE: We need to apply a non-identity scale and/or rotation to trick // the raster pipeline into *not* snapping to nearest. SkMatrix offsetMatrix = SkMatrix::Concat( SkMatrix::MakeScale(-1.0f), SkMatrix::MakeTrans(0.5f, 0.0f)); p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt, &offsetMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Dither", "Bilerp"); // Black/white dither, scaled down by 2x. Tests minification. SkMatrix scaleMatrix = SkMatrix::MakeScale(0.5f); p.setShader(SkShader::MakeBitmapShader(ditherBmp, rpt, rpt, &scaleMatrix)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Dither", "Scale"); // 50% grey via paint color. p.setColor(0xff7f7f7f); nextRect("Color", 0); // Black -> White gradient, scaled to sample just the middle. // Tests gradient interpolation. SkPoint points[2] = { SkPoint::Make(0 - (sz * 10), 0), SkPoint::Make(sz + (sz * 10), 0) }; SkColor colors[2] = { SK_ColorBLACK, SK_ColorWHITE }; p.setShader(SkGradientShader::MakeLinear(points, colors, nullptr, 2, SkShader::kClamp_TileMode)); nextRect("Gradient", 0); // 50% grey from linear bitmap, with drawBitmap nextBitmap(linearGreyBmp, "Lnr BMP"); // 50% grey from sRGB bitmap, with drawBitmap nextBitmap(srgbGreyBmp, "sRGB BMP"); // Bitmap wrapped in a shader (linear): p.setShader(SkShader::MakeBitmapShader(linearGreyBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("Lnr BMP", "Shader"); // Bitmap wrapped in a shader (sRGB): p.setShader(SkShader::MakeBitmapShader(srgbGreyBmp, rpt, rpt)); p.setFilterQuality(SkFilterQuality::kMedium_SkFilterQuality); nextRect("sRGB BMP", "Shader"); // Carriage return. canvas->restore(); canvas->translate(0, 2 * sz); const U8CPU sqrtHalf = 0xB4; const SkColor sqrtHalfAlpha = SkColorSetARGB(sqrtHalf, 0, 0, 0); const SkColor sqrtHalfWhite = SkColorSetARGB(0xFF, sqrtHalf, sqrtHalf, sqrtHalf); // Xfermode tests, all done off-screen so certain modes work... canvas->saveLayer(nullptr, nullptr); nextXferRect(0x7fffffff, SkXfermode::kSrcOver_Mode, SK_ColorBLACK); nextXferRect(0x7f000000, SkXfermode::kSrcOver_Mode, SK_ColorWHITE); nextXferRect(SK_ColorBLACK, SkXfermode::kDstOver_Mode, 0x7fffffff); nextXferRect(SK_ColorWHITE, SkXfermode::kSrcIn_Mode, 0x7fff00ff); nextXferRect(0x7fff00ff, SkXfermode::kDstIn_Mode, SK_ColorWHITE); nextXferRect(sqrtHalfWhite, SkXfermode::kSrcIn_Mode, sqrtHalfAlpha); nextXferRect(sqrtHalfAlpha, SkXfermode::kDstIn_Mode, sqrtHalfWhite); nextXferRect(0xff3f3f3f, SkXfermode::kPlus_Mode, 0xff3f3f3f); nextXferRect(sqrtHalfWhite, SkXfermode::kModulate_Mode, sqrtHalfWhite); canvas->restore(); }
Remove unmatched restore call in gamma GM
Remove unmatched restore call in gamma GM BUG=skia: GOLD_TRYBOT_URL= https://gold.skia.org/search2?unt=true&query=source_type%3Dgm&master=false&issue=1917303002 Review URL: https://codereview.chromium.org/1917303002
C++
bsd-3-clause
HalCanary/skia-hc,tmpvar/skia.cc,google/skia,google/skia,tmpvar/skia.cc,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,google/skia,HalCanary/skia-hc,tmpvar/skia.cc,aosp-mirror/platform_external_skia,rubenvb/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,rubenvb/skia,google/skia,google/skia,google/skia,tmpvar/skia.cc,rubenvb/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,tmpvar/skia.cc,rubenvb/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,tmpvar/skia.cc,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,tmpvar/skia.cc,HalCanary/skia-hc,tmpvar/skia.cc,google/skia,google/skia,rubenvb/skia,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,google/skia,HalCanary/skia-hc,tmpvar/skia.cc,rubenvb/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,rubenvb/skia
ec0b326272cc52f8f6f297cd6e44dd75245cadb8
src/delta.hpp
src/delta.hpp
#ifndef __DELTA_HPP_INCLUDED__ #define __DELTA_HPP_INCLUDED__ #include <string> namespace dafs { struct Delta { std::string filename; std::string difference; }; } #endif
#ifndef __DELTA_HPP_INCLUDED__ #define __DELTA_HPP_INCLUDED__ #include <string> namespace dafs { // // Edits to files are represented by delta objects. It contains all the // necessary data to update the file from one version to the next. // struct Delta { std::string filename; std::string difference; }; } #endif
Add delta struct comment
Add delta struct comment
C++
mit
dgkimura/dafs,dgkimura/dafs
9d0ecbdb31d9745bddb1a4f486dd9df825e9fc3e
lib/SIL/MemLocation.cpp
lib/SIL/MemLocation.cpp
//===------------------------- MemLocation.cpp ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-memlocation" #include "swift/SIL/MemLocation.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Utility Functions //===----------------------------------------------------------------------===// static inline void removeMemLocations(MemLocationValueMap &Values, MemLocationList &FirstLevel) { for (auto &X : FirstLevel) Values.erase(X); } //===----------------------------------------------------------------------===// // SILValue Projection //===----------------------------------------------------------------------===// void SILValueProjection::print() const { llvm::outs() << Base; llvm::outs() << Path.getValue(); } //===----------------------------------------------------------------------===// // Load Store Value //===----------------------------------------------------------------------===// SILValue LoadStoreValue::createExtract(SILValue Base, Optional<ProjectionPath> &Path, SILInstruction *Inst) { // If we found a projection path, but there are no projections, then the two // loads must be the same, return PrevLI. if (!Path || Path->empty()) return Base; // Ok, at this point we know that we can construct our aggregate projections // from our list of address projections. SILValue LastExtract = Base; SILBuilder Builder(Inst); // Construct the path! for (auto PI = Path->rbegin(), PE = Path->rend(); PI != PE; ++PI) { LastExtract = PI->createValueProjection(Builder, Inst->getLoc(), LastExtract).get(); continue; } // Return the last extract we created. return LastExtract; } //===----------------------------------------------------------------------===// // Memory Location //===----------------------------------------------------------------------===// void MemLocation::initialize(SILValue Dest) { Base = getUnderlyingObject(Dest); Path = ProjectionPath::getAddrProjectionPath(Base, Dest); } bool MemLocation::isMustAliasMemLocation(const MemLocation &RHS, AliasAnalysis *AA) { // If the bases are not must-alias, the locations may not alias. if (!AA->isMustAlias(Base, RHS.getBase())) return false; // If projection paths are different, then the locations can not alias. if (!hasIdenticalProjectionPath(RHS)) return false; return true; } bool MemLocation::isMayAliasMemLocation(const MemLocation &RHS, AliasAnalysis *AA) { // If the bases do not alias, then the locations can not alias. if (AA->isNoAlias(Base, RHS.getBase())) return false; // If one projection path is a prefix of another, then the locations // could alias. if (hasNonEmptySymmetricPathDifference(RHS)) return false; return true; } void MemLocation::getFirstLevelMemLocations(MemLocationList &Locs, SILModule *Mod) { SILType Ty = getType(); llvm::SmallVector<Projection, 8> Out; Projection::getFirstLevelAddrProjections(Ty, *Mod, Out); for (auto &X : Out) { ProjectionPath P; P.append(X); P.append(Path.getValue()); Locs.push_back(MemLocation(Base, P)); } } void MemLocation::expand(MemLocation &Base, SILModule *M, MemLocationList &Locs, TypeExpansionMap &TECache) { // To expand a memory location to its indivisible parts, we first get the // address projection paths from the accessed type to each indivisible field, // i.e. leaf nodes, then we append these projection paths to the Base. SILType BaseTy = Base.getType(); if (TECache.find(BaseTy) == TECache.end()) { // There is no cached expansion for this type, build and cache it now. ProjectionPathList Paths; ProjectionPath::expandTypeIntoNodeProjectionPaths(BaseTy, M, Paths); for (auto &P : Paths) { TECache[BaseTy].push_back(std::move(P.getValue())); } } // Construct the MemLocation by appending the projection path from the // accessed node to the leaf nodes. ProjectionPath &BasePath = Base.getPath().getValue(); for (auto &P : TECache[BaseTy]) { Locs.push_back(MemLocation(Base.getBase(), P.getValue(), BasePath)); } } void MemLocation::reduce(MemLocation &Base, SILModule *M, MemLocationSet &Locs) { // First, construct the MemLocation by appending the projection path from the // accessed node to the leaf nodes. MemLocationList Nodes; ProjectionPathList Paths; ProjectionPath::expandTypeIntoNodeProjectionPaths(Base.getType(), M, Paths); ProjectionPath &BasePath = Base.getPath().getValue(); for (auto &X : Paths) { Nodes.push_back(MemLocation(Base.getBase(), X.getValue(), BasePath)); } // Second, go from leaf nodes to their parents. This guarantees that at the // point the parent is processed, its children have been processed already. for (auto I = Nodes.rbegin(), E = Nodes.rend(); I != E; ++I) { MemLocationList FirstLevel; I->getFirstLevelMemLocations(FirstLevel, M); // Reached the end of the projection tree, this is a leaf node. if (FirstLevel.empty()) continue; // If this is a class reference type, we have reached end of the type tree. if (I->getType().getClassOrBoundGenericClass()) continue; // This is NOT a leaf node, check whether all its first level children are // alive. bool Alive = true; for (auto &X : FirstLevel) { Alive &= Locs.find(X) != Locs.end(); } // All first level locations are alive, create the new aggregated location. if (Alive) { for (auto &X : FirstLevel) Locs.erase(X); Locs.insert(*I); } } } void MemLocation::expandWithValues(MemLocation &Base, SILValue &Val, SILModule *Mod, MemLocationList &Locs, LoadStoreValueList &Vals) { // To expand a memory location to its indivisible parts, we first get the // projection paths from the accessed type to each indivisible field, i.e. // leaf nodes, then we append these projection paths to the Base. ProjectionPathList Paths; ProjectionPath::expandTypeIntoNodeProjectionPaths(Base.getType(), Mod, Paths); // Construct the MemLocation and LoadStoreValues by appending the projection // path // from the accessed node to the leaf nodes. ProjectionPath &BasePath = Base.getPath().getValue(); for (auto &X : Paths) { Locs.push_back(MemLocation(Base.getBase(), X.getValue(), BasePath)); Vals.push_back(LoadStoreValue(Val, X.getValue())); } } SILValue MemLocation::reduceWithValues(MemLocation &Base, SILModule *Mod, MemLocationValueMap &Values, SILInstruction *InsertPt) { // Walk bottom up the projection tree, try to reason about how to construct // a single SILValue out of all the available values for all the memory // locations. // // First, get a list of all the leaf nodes and intermediate nodes for the // Base memory location. MemLocationList ALocs; ProjectionPathList Paths; ProjectionPath::expandTypeIntoNodeProjectionPaths(Base.getType(), Mod, Paths); ProjectionPath &BasePath = Base.getPath().getValue(); for (auto &X : Paths) { ALocs.push_back(MemLocation(Base.getBase(), X.getValue(), BasePath)); } // Second, go from leaf nodes to their parents. This guarantees that at the // point the parent is processed, its children have been processed already. for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) { // This is a leaf node, we have a value for it. // // Reached the end of the projection tree, this is a leaf node. MemLocationList FirstLevel; I->getFirstLevelMemLocations(FirstLevel, Mod); if (FirstLevel.empty()) continue; // If this is a class reference type, we have reached end of the type tree. if (I->getType().getClassOrBoundGenericClass()) continue; // This is NOT a leaf node, we need to construct a value for it. // // If there are more than 1 children and all the children nodes have // LoadStoreValues with the same base. we can get away by not extracting // value // for every single field. // // Simply create a new node with all the aggregated base value, i.e. // stripping off the last level projection. // bool HasIdenticalValueBase = true; auto Iter = FirstLevel.begin(); LoadStoreValue &FirstVal = Values[*Iter]; SILValue FirstBase = FirstVal.getBase(); Iter = std::next(Iter); for (auto EndIter = FirstLevel.end(); Iter != EndIter; ++Iter) { LoadStoreValue &V = Values[*Iter]; HasIdenticalValueBase &= (FirstBase == V.getBase()); } if (HasIdenticalValueBase && (FirstLevel.size() > 1 || !FirstVal.hasEmptyProjectionPath())) { Values[*I] = FirstVal.stripLastLevelProjection(); // We have a value for the parent, remove all the values for children. removeMemLocations(Values, FirstLevel); continue; } // In 2 cases do we need aggregation. // // 1. If there is only 1 child and we can not strip off any projections, // that means we need to create an aggregation. // // 2. Children have values from different bases, We need to create // extractions and aggregation in this case. // llvm::SmallVector<SILValue, 8> Vals; for (auto &X : FirstLevel) { Vals.push_back(Values[X].materialize(InsertPt)); } SILBuilder Builder(InsertPt); NullablePtr<swift::SILInstruction> AI = Projection::createAggFromFirstLevelProjections( Builder, InsertPt->getLoc(), I->getType(), Vals); // This is the Value for the current node. ProjectionPath P; Values[*I] = LoadStoreValue(SILValue(AI.get()), P); removeMemLocations(Values, FirstLevel); // Keep iterating until we have reach the top-most level of the projection // tree. // i.e. the memory location represented by the Base. } assert(Values.size() == 1 && "Should have a single location this point"); // Finally materialize and return the forwarding SILValue. return Values.begin()->second.materialize(InsertPt); } void MemLocation::enumerateMemLocation(SILModule *M, SILValue Mem, std::vector<MemLocation> &LV, MemLocationIndexMap &BM, TypeExpansionMap &TV) { // Construct a Location to represent the memory written by this instruction. MemLocation L(Mem); // If we cant figure out the Base or Projection Path for the memory location, // simply ignore it for now. if (!L.isValid()) return; // Expand the given Mem into individual fields and add them to the // locationvault. MemLocationList Locs; MemLocation::expand(L, M, Locs, TV); for (auto &Loc : Locs) { BM[Loc] = LV.size(); LV.push_back(Loc); } } void MemLocation::enumerateMemLocations(SILFunction &F, std::vector<MemLocation> &LV, MemLocationIndexMap &BM, TypeExpansionMap &TV) { // Enumerate all locations accessed by the loads or stores. // // TODO: process more instructions as we process more instructions in // processInstruction. // SILValue Op; for (auto &B : F) { for (auto &I : B) { if (auto *LI = dyn_cast<LoadInst>(&I)) { enumerateMemLocation(&I.getModule(), LI->getOperand(), LV, BM, TV); } else if (auto *SI = dyn_cast<StoreInst>(&I)) { enumerateMemLocation(&I.getModule(), SI->getDest(), LV, BM, TV); } } } }
//===------------------------- MemLocation.cpp ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-memlocation" #include "swift/SIL/MemLocation.h" #include "llvm/Support/Debug.h" using namespace swift; //===----------------------------------------------------------------------===// // Utility Functions //===----------------------------------------------------------------------===// static inline void removeMemLocations(MemLocationValueMap &Values, MemLocationList &FirstLevel) { for (auto &X : FirstLevel) Values.erase(X); } //===----------------------------------------------------------------------===// // SILValue Projection //===----------------------------------------------------------------------===// void SILValueProjection::print() const { llvm::outs() << Base; llvm::outs() << Path.getValue(); } //===----------------------------------------------------------------------===// // Load Store Value //===----------------------------------------------------------------------===// SILValue LoadStoreValue::createExtract(SILValue Base, Optional<ProjectionPath> &Path, SILInstruction *Inst) { // If we found a projection path, but there are no projections, then the two // loads must be the same, return PrevLI. if (!Path || Path->empty()) return Base; // Ok, at this point we know that we can construct our aggregate projections // from our list of address projections. SILValue LastExtract = Base; SILBuilder Builder(Inst); // Construct the path! for (auto PI = Path->rbegin(), PE = Path->rend(); PI != PE; ++PI) { LastExtract = PI->createValueProjection(Builder, Inst->getLoc(), LastExtract).get(); continue; } // Return the last extract we created. return LastExtract; } //===----------------------------------------------------------------------===// // Memory Location //===----------------------------------------------------------------------===// void MemLocation::initialize(SILValue Dest) { Base = getUnderlyingObject(Dest); Path = ProjectionPath::getAddrProjectionPath(Base, Dest); } bool MemLocation::isMustAliasMemLocation(const MemLocation &RHS, AliasAnalysis *AA) { // If the bases are not must-alias, the locations may not alias. if (!AA->isMustAlias(Base, RHS.getBase())) return false; // If projection paths are different, then the locations can not alias. if (!hasIdenticalProjectionPath(RHS)) return false; return true; } bool MemLocation::isMayAliasMemLocation(const MemLocation &RHS, AliasAnalysis *AA) { // If the bases do not alias, then the locations can not alias. if (AA->isNoAlias(Base, RHS.getBase())) return false; // If one projection path is a prefix of another, then the locations // could alias. if (hasNonEmptySymmetricPathDifference(RHS)) return false; return true; } void MemLocation::getFirstLevelMemLocations(MemLocationList &Locs, SILModule *Mod) { SILType Ty = getType(); llvm::SmallVector<Projection, 8> Out; Projection::getFirstLevelAddrProjections(Ty, *Mod, Out); for (auto &X : Out) { ProjectionPath P; P.append(X); P.append(Path.getValue()); Locs.push_back(MemLocation(Base, P)); } } void MemLocation::expand(MemLocation &Base, SILModule *M, MemLocationList &Locs, TypeExpansionMap &TECache) { // To expand a memory location to its indivisible parts, we first get the // address projection paths from the accessed type to each indivisible field, // i.e. leaf nodes, then we append these projection paths to the Base. SILType BaseTy = Base.getType(); if (TECache.find(BaseTy) == TECache.end()) { // There is no cached expansion for this type, build and cache it now. ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(BaseTy, M, Paths); for (auto &P : Paths) { TECache[BaseTy].push_back(std::move(P.getValue())); } } // Construct the MemLocation by appending the projection path from the // accessed node to the leaf nodes. ProjectionPath &BasePath = Base.getPath().getValue(); for (auto &P : TECache[BaseTy]) { Locs.push_back(MemLocation(Base.getBase(), P.getValue(), BasePath)); } } void MemLocation::reduce(MemLocation &Base, SILModule *M, MemLocationSet &Locs) { // First, construct the MemLocation by appending the projection path from the // accessed node to the leaf nodes. MemLocationList Nodes; ProjectionPathList Paths; ProjectionPath::expandTypeIntoNodeProjectionPaths(Base.getType(), M, Paths); ProjectionPath &BasePath = Base.getPath().getValue(); for (auto &X : Paths) { Nodes.push_back(MemLocation(Base.getBase(), X.getValue(), BasePath)); } // Second, go from leaf nodes to their parents. This guarantees that at the // point the parent is processed, its children have been processed already. for (auto I = Nodes.rbegin(), E = Nodes.rend(); I != E; ++I) { MemLocationList FirstLevel; I->getFirstLevelMemLocations(FirstLevel, M); // Reached the end of the projection tree, this is a leaf node. if (FirstLevel.empty()) continue; // If this is a class reference type, we have reached end of the type tree. if (I->getType().getClassOrBoundGenericClass()) continue; // This is NOT a leaf node, check whether all its first level children are // alive. bool Alive = true; for (auto &X : FirstLevel) { Alive &= Locs.find(X) != Locs.end(); } // All first level locations are alive, create the new aggregated location. if (Alive) { for (auto &X : FirstLevel) Locs.erase(X); Locs.insert(*I); } } } void MemLocation::expandWithValues(MemLocation &Base, SILValue &Val, SILModule *Mod, MemLocationList &Locs, LoadStoreValueList &Vals) { // To expand a memory location to its indivisible parts, we first get the // projection paths from the accessed type to each indivisible field, i.e. // leaf nodes, then we append these projection paths to the Base. ProjectionPathList Paths; ProjectionPath::expandTypeIntoLeafProjectionPaths(Base.getType(), Mod, Paths); // Construct the MemLocation and LoadStoreValues by appending the projection // path // from the accessed node to the leaf nodes. ProjectionPath &BasePath = Base.getPath().getValue(); for (auto &X : Paths) { Locs.push_back(MemLocation(Base.getBase(), X.getValue(), BasePath)); Vals.push_back(LoadStoreValue(Val, X.getValue())); } } SILValue MemLocation::reduceWithValues(MemLocation &Base, SILModule *Mod, MemLocationValueMap &Values, SILInstruction *InsertPt) { // Walk bottom up the projection tree, try to reason about how to construct // a single SILValue out of all the available values for all the memory // locations. // // First, get a list of all the leaf nodes and intermediate nodes for the // Base memory location. MemLocationList ALocs; ProjectionPathList Paths; ProjectionPath::expandTypeIntoNodeProjectionPaths(Base.getType(), Mod, Paths); ProjectionPath &BasePath = Base.getPath().getValue(); for (auto &X : Paths) { ALocs.push_back(MemLocation(Base.getBase(), X.getValue(), BasePath)); } // Second, go from leaf nodes to their parents. This guarantees that at the // point the parent is processed, its children have been processed already. for (auto I = ALocs.rbegin(), E = ALocs.rend(); I != E; ++I) { // This is a leaf node, we have a value for it. // // Reached the end of the projection tree, this is a leaf node. MemLocationList FirstLevel; I->getFirstLevelMemLocations(FirstLevel, Mod); if (FirstLevel.empty()) continue; // If this is a class reference type, we have reached end of the type tree. if (I->getType().getClassOrBoundGenericClass()) continue; // This is NOT a leaf node, we need to construct a value for it. // // If there are more than 1 children and all the children nodes have // LoadStoreValues with the same base. we can get away by not extracting // value // for every single field. // // Simply create a new node with all the aggregated base value, i.e. // stripping off the last level projection. // bool HasIdenticalValueBase = true; auto Iter = FirstLevel.begin(); LoadStoreValue &FirstVal = Values[*Iter]; SILValue FirstBase = FirstVal.getBase(); Iter = std::next(Iter); for (auto EndIter = FirstLevel.end(); Iter != EndIter; ++Iter) { LoadStoreValue &V = Values[*Iter]; HasIdenticalValueBase &= (FirstBase == V.getBase()); } if (HasIdenticalValueBase && (FirstLevel.size() > 1 || !FirstVal.hasEmptyProjectionPath())) { Values[*I] = FirstVal.stripLastLevelProjection(); // We have a value for the parent, remove all the values for children. removeMemLocations(Values, FirstLevel); continue; } // In 2 cases do we need aggregation. // // 1. If there is only 1 child and we can not strip off any projections, // that means we need to create an aggregation. // // 2. Children have values from different bases, We need to create // extractions and aggregation in this case. // llvm::SmallVector<SILValue, 8> Vals; for (auto &X : FirstLevel) { Vals.push_back(Values[X].materialize(InsertPt)); } SILBuilder Builder(InsertPt); NullablePtr<swift::SILInstruction> AI = Projection::createAggFromFirstLevelProjections( Builder, InsertPt->getLoc(), I->getType(), Vals); // This is the Value for the current node. ProjectionPath P; Values[*I] = LoadStoreValue(SILValue(AI.get()), P); removeMemLocations(Values, FirstLevel); // Keep iterating until we have reach the top-most level of the projection // tree. // i.e. the memory location represented by the Base. } assert(Values.size() == 1 && "Should have a single location this point"); // Finally materialize and return the forwarding SILValue. return Values.begin()->second.materialize(InsertPt); } void MemLocation::enumerateMemLocation(SILModule *M, SILValue Mem, std::vector<MemLocation> &LV, MemLocationIndexMap &BM, TypeExpansionMap &TV) { // Construct a Location to represent the memory written by this instruction. MemLocation L(Mem); // If we cant figure out the Base or Projection Path for the memory location, // simply ignore it for now. if (!L.isValid()) return; // Expand the given Mem into individual fields and add them to the // locationvault. MemLocationList Locs; MemLocation::expand(L, M, Locs, TV); for (auto &Loc : Locs) { BM[Loc] = LV.size(); LV.push_back(Loc); } } void MemLocation::enumerateMemLocations(SILFunction &F, std::vector<MemLocation> &LV, MemLocationIndexMap &BM, TypeExpansionMap &TV) { // Enumerate all locations accessed by the loads or stores. // // TODO: process more instructions as we process more instructions in // processInstruction. // SILValue Op; for (auto &B : F) { for (auto &I : B) { if (auto *LI = dyn_cast<LoadInst>(&I)) { enumerateMemLocation(&I.getModule(), LI->getOperand(), LV, BM, TV); } else if (auto *SI = dyn_cast<StoreInst>(&I)) { enumerateMemLocation(&I.getModule(), SI->getDest(), LV, BM, TV); } } } }
Correct the wrongly used function in MemLocation
Correct the wrongly used function in MemLocation
C++
apache-2.0
khizkhiz/swift,khizkhiz/swift,khizkhiz/swift,khizkhiz/swift,khizkhiz/swift,khizkhiz/swift,khizkhiz/swift
c10281e01394521592ae7d45c8098935c7ef0ed5
src/cpp/session/modules/SessionPlumberViewer.cpp
src/cpp/session/modules/SessionPlumberViewer.cpp
/* * SessionPlumberViewer.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionPlumberViewer.hpp" #include <boost/format.hpp> #include <boost/algorithm/string/predicate.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <r/RSexp.hpp> #include <r/RRoutines.hpp> #include <r/RUtil.hpp> #include <r/ROptions.hpp> #include <r/session/RSessionUtils.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionUserSettings.hpp> #include "plumber/SessionPlumber.hpp" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace plumber_viewer { namespace { void enqueueStartEvent(const std::string& url, const std::string& path, int viewerType, int options) { FilePath plumberPath(path); // enque the event json::Object dataJson; dataJson["url"] = module_context::mapUrlPorts(url); dataJson["path"] = module_context::createAliasedPath(plumberPath); dataJson["state"] = "started"; dataJson["viewer"] = viewerType; dataJson["options"] = options; ClientEvent event(client_events::kPlumberViewer, dataJson); module_context::enqueClientEvent(event); } SEXP rs_plumberviewer(SEXP urlSEXP, SEXP pathSEXP, SEXP viewerSEXP) { try { if (!r::sexp::isString(urlSEXP) || (r::sexp::length(urlSEXP) != 1)) { throw r::exec::RErrorException( "url must be a single element character vector."); } if (!r::sexp::isString(pathSEXP) || (r::sexp::length(pathSEXP) != 1)) { throw r::exec::RErrorException( "path must be a single element character vector."); } int viewertype = r::sexp::asInteger(viewerSEXP); // in desktop mode make sure we have the right version of httpuv if (options().programMode() == kSessionProgramModeDesktop) { if (!module_context::isPackageVersionInstalled("httpuv", "1.2")) { module_context::consoleWriteError("\nWARNING: To view Plumber " "APIs inside RStudio, you need to " "install the latest version of the httpuv package from " "CRAN (version 1.2 or higher is required).\n\n"); } } std::string path = r::sexp::safeAsString(pathSEXP); enqueueStartEvent(r::sexp::safeAsString(urlSEXP), path, viewertype, PLUMBER_VIEWER_OPTIONS_NONE); } catch(const r::exec::RErrorException& e) { r::exec::error(e.message()); } return R_NilValue; } void setPlumberViewerType(int viewerType) { Error error = r::exec::RFunction(".rs.setPlumberViewerType", viewerType).call(); if (error) LOG_ERROR(error); } void onUserSettingsChanged(boost::shared_ptr<int> pPlumberViewerType) { int plumberViewerType = userSettings().plumberViewerType(); if (plumberViewerType != *pPlumberViewerType) { setPlumberViewerType(plumberViewerType); *pPlumberViewerType = plumberViewerType; } } Error setPlumberViewer(boost::shared_ptr<int> pPlumberViewerType, const json::JsonRpcRequest& request, json::JsonRpcResponse*) { int viewerType = 0; Error error = json::readParams(request.params, &viewerType); if (error) return error; if (viewerType != *pPlumberViewerType) { setPlumberViewerType(viewerType); *pPlumberViewerType = viewerType; } return Success(); } Error getPlumberRunCmd(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string targetPath, extendedType; Error error = json::readParams(request.params, &targetPath, &extendedType); if (error) return error; FilePath plumberPath = module_context::resolveAliasedPath(targetPath); // filename "entrypoint.R" has special meaning when running locally or publishing to rsConnect; // won't necessarily have any annotations bool hasEntrypointFile = false; if (plumberPath.stem() == "entrypoint") { hasEntrypointFile = true; } else { // if the folder contains entrypoint.R, use it, even if not the currently loaded file FilePath searchFolder = plumberPath.isDirectory() ? plumberPath : plumberPath.parent(); FilePath entryPointPath = searchFolder.complete("entrypoint.R"); if (entryPointPath.exists() && !entryPointPath.isDirectory()) hasEntrypointFile = true; } if (hasEntrypointFile) { // entrypoint.R mode operates on the folder if (!plumberPath.isDirectory()) plumberPath = plumberPath.parent(); } std::string plumberRunPath = module_context::pathRelativeTo( module_context::safeCurrentPath(), plumberPath); // check to see if Plumber is attached to the search path bool isPlumberAttached = false; SEXP namespaces = R_NilValue; r::sexp::Protect protect; error = r::exec::RFunction("search").call(&namespaces, &protect); if (error) { // not fatal; we'll just presume Plumber is not on the path LOG_ERROR(error); } else { int len = r::sexp::length(namespaces); for (int i = 0; i < len; i++) { std::string ns = r::sexp::safeAsString(STRING_ELT(namespaces, i), ""); if (ns == "package:plumber") { isPlumberAttached = true; break; } } } std::string runCmd; if (!isPlumberAttached) runCmd = "plumber::"; if (!hasEntrypointFile) { runCmd.append(R"RCODE(plumb(file=')RCODE"); runCmd.append(plumberRunPath); runCmd.append(R"RCODE(')$run())RCODE"); } else { runCmd.append(R"RCODE(plumb(dir=')RCODE"); runCmd.append(plumberRunPath); runCmd.append(R"RCODE(')$run())RCODE"); } json::Object dataJson; dataJson["run_cmd"] = runCmd; pResponse->setResult(dataJson); return Success(); } Error initPlumberViewerPref(boost::shared_ptr<int> pPlumberViewerType) { SEXP plumberBrowser = r::options::getOption("plumber.launch.browser"); *pPlumberViewerType = userSettings().plumberViewerType(); if (plumberBrowser == R_NilValue) { setPlumberViewerType(*pPlumberViewerType); } return Success(); } } // anonymous namespace Error initialize() { using boost::bind; using namespace module_context; boost::shared_ptr<int> pPlumberViewerType = boost::make_shared<int>(PLUMBER_VIEWER_NONE); json::JsonRpcFunction setPlumberViewerTypeRpc = boost::bind(setPlumberViewer, pPlumberViewerType, _1, _2); R_CallMethodDef methodDefViewer; methodDefViewer.name = "rs_plumberviewer"; methodDefViewer.fun = (DL_FUNC) rs_plumberviewer; methodDefViewer.numArgs = 3; r::routines::addCallMethod(methodDefViewer); userSettings().onChanged.connect(bind(onUserSettingsChanged, pPlumberViewerType)); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionPlumberViewer.R")) (bind(registerRpcMethod, "get_plumber_run_cmd", getPlumberRunCmd)) (bind(registerRpcMethod, "set_plumber_viewer_type", setPlumberViewerTypeRpc)) (bind(initPlumberViewerPref, pPlumberViewerType)); return initBlock.execute(); } } // namespace plumber_viewer } // namespace modules } // namespace session } // namespace rstudio
/* * SessionPlumberViewer.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionPlumberViewer.hpp" #include <boost/format.hpp> #include <boost/algorithm/string/predicate.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <r/RSexp.hpp> #include <r/RRoutines.hpp> #include <r/RUtil.hpp> #include <r/ROptions.hpp> #include <r/session/RSessionUtils.hpp> #include <session/SessionModuleContext.hpp> #include <session/SessionUserSettings.hpp> #include "plumber/SessionPlumber.hpp" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace plumber_viewer { namespace { void enqueueStartEvent(const std::string& url, const std::string& path, int viewerType, int options) { FilePath plumberPath(path); // enque the event json::Object dataJson; dataJson["url"] = module_context::mapUrlPorts(url); dataJson["path"] = module_context::createAliasedPath(plumberPath); dataJson["state"] = "started"; dataJson["viewer"] = viewerType; dataJson["options"] = options; ClientEvent event(client_events::kPlumberViewer, dataJson); module_context::enqueClientEvent(event); } SEXP rs_plumberviewer(SEXP urlSEXP, SEXP pathSEXP, SEXP viewerSEXP) { try { if (!r::sexp::isString(urlSEXP) || (r::sexp::length(urlSEXP) != 1)) { throw r::exec::RErrorException( "url must be a single element character vector."); } if (!r::sexp::isString(pathSEXP) || (r::sexp::length(pathSEXP) != 1)) { throw r::exec::RErrorException( "path must be a single element character vector."); } int viewertype = r::sexp::asInteger(viewerSEXP); // in desktop mode make sure we have the right version of httpuv if (options().programMode() == kSessionProgramModeDesktop) { if (!module_context::isPackageVersionInstalled("httpuv", "1.2")) { module_context::consoleWriteError("\nWARNING: To view Plumber " "APIs inside RStudio, you need to " "install the latest version of the httpuv package from " "CRAN (version 1.2 or higher is required).\n\n"); } } std::string path = r::sexp::safeAsString(pathSEXP); enqueueStartEvent(r::sexp::safeAsString(urlSEXP), path, viewertype, PLUMBER_VIEWER_OPTIONS_NONE); } catch(const r::exec::RErrorException& e) { r::exec::error(e.message()); } return R_NilValue; } void setPlumberViewerType(int viewerType) { Error error = r::exec::RFunction(".rs.setPlumberViewerType", viewerType).call(); if (error) LOG_ERROR(error); } void onUserSettingsChanged(boost::shared_ptr<int> pPlumberViewerType) { int plumberViewerType = userSettings().plumberViewerType(); if (plumberViewerType != *pPlumberViewerType) { setPlumberViewerType(plumberViewerType); *pPlumberViewerType = plumberViewerType; } } Error setPlumberViewer(boost::shared_ptr<int> pPlumberViewerType, const json::JsonRpcRequest& request, json::JsonRpcResponse*) { int viewerType = 0; Error error = json::readParams(request.params, &viewerType); if (error) return error; if (viewerType != *pPlumberViewerType) { setPlumberViewerType(viewerType); *pPlumberViewerType = viewerType; } return Success(); } Error getPlumberRunCmd(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { std::string targetPath, extendedType; Error error = json::readParams(request.params, &targetPath, &extendedType); if (error) return error; FilePath plumberPath = module_context::resolveAliasedPath(targetPath); // filename "entrypoint.R" has special meaning when running locally or publishing to rsConnect; // won't necessarily have any annotations bool hasEntrypointFile = false; if (plumberPath.stem() == "entrypoint") { hasEntrypointFile = true; } else { // if the folder contains entrypoint.R, use it, even if not the currently loaded file FilePath searchFolder = plumberPath.isDirectory() ? plumberPath : plumberPath.parent(); FilePath entryPointPath = searchFolder.complete("entrypoint.R"); if (entryPointPath.exists() && !entryPointPath.isDirectory()) hasEntrypointFile = true; } if (hasEntrypointFile) { // entrypoint.R mode operates on the folder if (!plumberPath.isDirectory()) plumberPath = plumberPath.parent(); } std::string plumberRunPath = module_context::pathRelativeTo( module_context::safeCurrentPath(), plumberPath); // check to see if Plumber is attached to the search path bool isPlumberAttached = false; SEXP namespaces = R_NilValue; r::sexp::Protect protect; error = r::exec::RFunction("search").call(&namespaces, &protect); if (error) { // not fatal; we'll just presume Plumber is not on the path LOG_ERROR(error); } else { int len = r::sexp::length(namespaces); for (int i = 0; i < len; i++) { std::string ns = r::sexp::safeAsString(STRING_ELT(namespaces, i), ""); if (ns == "package:plumber") { isPlumberAttached = true; break; } } } std::string runCmd; if (!isPlumberAttached) runCmd = "plumber::"; if (!hasEntrypointFile) { runCmd.append(R"RCODE(plumb(file=')RCODE"); runCmd.append(plumberRunPath); runCmd.append(R"RCODE(')$run())RCODE"); } else { runCmd.append(R"RCODE(plumb(dir=')RCODE"); runCmd.append(plumberRunPath); runCmd.append(R"RCODE(')$run())RCODE"); } json::Object dataJson; dataJson["run_cmd"] = runCmd; pResponse->setResult(dataJson); return Success(); } Error initPlumberViewerPref(boost::shared_ptr<int> pPlumberViewerType) { SEXP plumberBrowser = r::options::getOption("plumber.swagger.url"); *pPlumberViewerType = userSettings().plumberViewerType(); if (plumberBrowser == R_NilValue) { setPlumberViewerType(*pPlumberViewerType); } return Success(); } } // anonymous namespace Error initialize() { using boost::bind; using namespace module_context; boost::shared_ptr<int> pPlumberViewerType = boost::make_shared<int>(PLUMBER_VIEWER_NONE); json::JsonRpcFunction setPlumberViewerTypeRpc = boost::bind(setPlumberViewer, pPlumberViewerType, _1, _2); R_CallMethodDef methodDefViewer; methodDefViewer.name = "rs_plumberviewer"; methodDefViewer.fun = (DL_FUNC) rs_plumberviewer; methodDefViewer.numArgs = 3; r::routines::addCallMethod(methodDefViewer); userSettings().onChanged.connect(bind(onUserSettingsChanged, pPlumberViewerType)); ExecBlock initBlock; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionPlumberViewer.R")) (bind(registerRpcMethod, "get_plumber_run_cmd", getPlumberRunCmd)) (bind(registerRpcMethod, "set_plumber_viewer_type", setPlumberViewerTypeRpc)) (bind(initPlumberViewerPref, pPlumberViewerType)); return initBlock.execute(); } } // namespace plumber_viewer } // namespace modules } // namespace session } // namespace rstudio
fix option for current plumber viewer type
fix option for current plumber viewer type
C++
agpl-3.0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
b6f3769c7098ac010914b44040c1d7975bb919ac
ui/gfx/skia_util.cc
ui/gfx/skia_util.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/skia_util.h" #include "base/i18n/char_iterator.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkColorPriv.h" #include "third_party/skia/include/core/SkUnPreMultiply.h" #include "third_party/skia/include/effects/SkBlurMaskFilter.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "third_party/skia/include/effects/SkLayerDrawLooper.h" #include "ui/gfx/image/image_skia_rep.h" #include "ui/gfx/rect.h" #include "ui/gfx/shadow_value.h" namespace gfx { SkRect RectToSkRect(const gfx::Rect& rect) { SkRect r; r.iset(rect.x(), rect.y(), rect.right(), rect.bottom()); return r; } SkIRect RectToSkIRect(const gfx::Rect& rect) { SkIRect r = { rect.x(), rect.y(), rect.right(), rect.bottom() }; return r; } gfx::Rect SkRectToRect(const SkRect& rect) { return gfx::Rect(static_cast<int>(rect.left()), static_cast<int>(rect.top()), static_cast<int>(rect.width()), static_cast<int>(rect.height())); } SkShader* CreateImageRepShader(const gfx::ImageSkiaRep& image_rep, SkShader::TileMode tile_mode, const SkMatrix& local_matrix) { SkShader* shader = SkShader::CreateBitmapShader(image_rep.sk_bitmap(), tile_mode, tile_mode); SkScalar scale_x = local_matrix.getScaleX(); SkScalar scale_y = local_matrix.getScaleY(); SkScalar bitmap_scale = SkFloatToScalar(image_rep.GetScale()); // Unscale matrix by |bitmap_scale| such that the bitmap is drawn at the // correct density. // Convert skew and translation to pixel coordinates. // Thus, for |bitmap_scale| = 2: // x scale = 2, x translation = 1 DIP, // should be converted to // x scale = 1, x translation = 2 pixels. SkMatrix shader_scale = local_matrix; shader_scale.preScale(bitmap_scale, bitmap_scale); shader_scale.setScaleX(SkScalarDiv(scale_x, bitmap_scale)); shader_scale.setScaleY(SkScalarDiv(scale_y, bitmap_scale)); shader->setLocalMatrix(shader_scale); return shader; } SkShader* CreateGradientShader(int start_point, int end_point, SkColor start_color, SkColor end_color) { SkColor grad_colors[2] = { start_color, end_color}; SkPoint grad_points[2]; grad_points[0].iset(0, start_point); grad_points[1].iset(0, end_point); return SkGradientShader::CreateLinear( grad_points, grad_colors, NULL, 2, SkShader::kRepeat_TileMode); } SkDrawLooper* CreateShadowDrawLooper(const std::vector<ShadowValue>& shadows) { if (shadows.empty()) return NULL; SkLayerDrawLooper* looper = new SkLayerDrawLooper; looper->addLayer(); // top layer of the original. SkLayerDrawLooper::LayerInfo layer_info; layer_info.fPaintBits |= SkLayerDrawLooper::kMaskFilter_Bit; layer_info.fPaintBits |= SkLayerDrawLooper::kColorFilter_Bit; layer_info.fColorMode = SkXfermode::kSrc_Mode; for (size_t i = 0; i < shadows.size(); ++i) { const ShadowValue& shadow = shadows[i]; layer_info.fOffset.set(SkIntToScalar(shadow.x()), SkIntToScalar(shadow.y())); // SkBlurMaskFilter's blur radius defines the range to extend the blur from // original mask, which is half of blur amount as defined in ShadowValue. SkMaskFilter* blur_mask = SkBlurMaskFilter::Create( SkDoubleToScalar(shadow.blur() / 2), SkBlurMaskFilter::kNormal_BlurStyle, SkBlurMaskFilter::kHighQuality_BlurFlag); SkColorFilter* color_filter = SkColorFilter::CreateModeFilter( shadow.color(), SkXfermode::kSrcIn_Mode); SkPaint* paint = looper->addLayer(layer_info); SkSafeUnref(paint->setMaskFilter(blur_mask)); SkSafeUnref(paint->setColorFilter(color_filter)); } return looper; } bool BitmapsAreEqual(const SkBitmap& bitmap1, const SkBitmap& bitmap2) { void* addr1 = NULL; void* addr2 = NULL; size_t size1 = 0; size_t size2 = 0; bitmap1.lockPixels(); addr1 = bitmap1.getAddr32(0, 0); size1 = bitmap1.getSize(); bitmap1.unlockPixels(); bitmap2.lockPixels(); addr2 = bitmap2.getAddr32(0, 0); size2 = bitmap2.getSize(); bitmap2.unlockPixels(); return (size1 == size2) && (0 == memcmp(addr1, addr2, bitmap1.getSize())); } string16 RemoveAcceleratorChar(const string16& s, char16 accelerator_char, int* accelerated_char_pos, int* accelerated_char_span) { bool escaped = false; int last_char_pos = -1; int last_char_span = 0; base::i18n::UTF16CharIterator chars(&s); string16 accelerator_removed; accelerator_removed.reserve(s.size()); while (!chars.end()) { int32 c = chars.get(); int array_pos = chars.array_pos(); chars.Advance(); if (c != accelerator_char || escaped) { int span = chars.array_pos() - array_pos; if (escaped && c != accelerator_char) { last_char_pos = accelerator_removed.size(); last_char_span = span; } for (int i = 0; i < span; i++) accelerator_removed.push_back(s[array_pos + i]); escaped = false; } else { escaped = true; } } if (accelerated_char_pos) *accelerated_char_pos = last_char_pos; if (accelerated_char_span) *accelerated_char_span = last_char_span; return accelerator_removed; } void ConvertSkiaToRGBA(const unsigned char* skia, int pixel_width, unsigned char* rgba) { int total_length = pixel_width * 4; for (int i = 0; i < total_length; i += 4) { const uint32_t pixel_in = *reinterpret_cast<const uint32_t*>(&skia[i]); // Pack the components here. int alpha = SkGetPackedA32(pixel_in); if (alpha != 0 && alpha != 255) { SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel_in); rgba[i + 0] = SkColorGetR(unmultiplied); rgba[i + 1] = SkColorGetG(unmultiplied); rgba[i + 2] = SkColorGetB(unmultiplied); rgba[i + 3] = alpha; } else { rgba[i + 0] = SkGetPackedR32(pixel_in); rgba[i + 1] = SkGetPackedG32(pixel_in); rgba[i + 2] = SkGetPackedB32(pixel_in); rgba[i + 3] = alpha; } } } } // namespace gfx
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/skia_util.h" #include "base/i18n/char_iterator.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkColorPriv.h" #include "third_party/skia/include/core/SkUnPreMultiply.h" #include "third_party/skia/include/effects/SkBlurMaskFilter.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "third_party/skia/include/effects/SkLayerDrawLooper.h" #include "ui/gfx/image/image_skia_rep.h" #include "ui/gfx/rect.h" #include "ui/gfx/shadow_value.h" namespace gfx { SkRect RectToSkRect(const gfx::Rect& rect) { SkRect r; r.iset(rect.x(), rect.y(), rect.right(), rect.bottom()); return r; } SkIRect RectToSkIRect(const gfx::Rect& rect) { return SkIRect::MakeXYWH(rect.x(), rect.y(), rect.width(), rect.height()); } gfx::Rect SkRectToRect(const SkRect& rect) { return gfx::Rect(static_cast<int>(rect.left()), static_cast<int>(rect.top()), static_cast<int>(rect.width()), static_cast<int>(rect.height())); } SkShader* CreateImageRepShader(const gfx::ImageSkiaRep& image_rep, SkShader::TileMode tile_mode, const SkMatrix& local_matrix) { SkShader* shader = SkShader::CreateBitmapShader(image_rep.sk_bitmap(), tile_mode, tile_mode); SkScalar scale_x = local_matrix.getScaleX(); SkScalar scale_y = local_matrix.getScaleY(); SkScalar bitmap_scale = SkFloatToScalar(image_rep.GetScale()); // Unscale matrix by |bitmap_scale| such that the bitmap is drawn at the // correct density. // Convert skew and translation to pixel coordinates. // Thus, for |bitmap_scale| = 2: // x scale = 2, x translation = 1 DIP, // should be converted to // x scale = 1, x translation = 2 pixels. SkMatrix shader_scale = local_matrix; shader_scale.preScale(bitmap_scale, bitmap_scale); shader_scale.setScaleX(SkScalarDiv(scale_x, bitmap_scale)); shader_scale.setScaleY(SkScalarDiv(scale_y, bitmap_scale)); shader->setLocalMatrix(shader_scale); return shader; } SkShader* CreateGradientShader(int start_point, int end_point, SkColor start_color, SkColor end_color) { SkColor grad_colors[2] = { start_color, end_color}; SkPoint grad_points[2]; grad_points[0].iset(0, start_point); grad_points[1].iset(0, end_point); return SkGradientShader::CreateLinear( grad_points, grad_colors, NULL, 2, SkShader::kRepeat_TileMode); } SkDrawLooper* CreateShadowDrawLooper(const std::vector<ShadowValue>& shadows) { if (shadows.empty()) return NULL; SkLayerDrawLooper* looper = new SkLayerDrawLooper; looper->addLayer(); // top layer of the original. SkLayerDrawLooper::LayerInfo layer_info; layer_info.fPaintBits |= SkLayerDrawLooper::kMaskFilter_Bit; layer_info.fPaintBits |= SkLayerDrawLooper::kColorFilter_Bit; layer_info.fColorMode = SkXfermode::kSrc_Mode; for (size_t i = 0; i < shadows.size(); ++i) { const ShadowValue& shadow = shadows[i]; layer_info.fOffset.set(SkIntToScalar(shadow.x()), SkIntToScalar(shadow.y())); // SkBlurMaskFilter's blur radius defines the range to extend the blur from // original mask, which is half of blur amount as defined in ShadowValue. SkMaskFilter* blur_mask = SkBlurMaskFilter::Create( SkDoubleToScalar(shadow.blur() / 2), SkBlurMaskFilter::kNormal_BlurStyle, SkBlurMaskFilter::kHighQuality_BlurFlag); SkColorFilter* color_filter = SkColorFilter::CreateModeFilter( shadow.color(), SkXfermode::kSrcIn_Mode); SkPaint* paint = looper->addLayer(layer_info); SkSafeUnref(paint->setMaskFilter(blur_mask)); SkSafeUnref(paint->setColorFilter(color_filter)); } return looper; } bool BitmapsAreEqual(const SkBitmap& bitmap1, const SkBitmap& bitmap2) { void* addr1 = NULL; void* addr2 = NULL; size_t size1 = 0; size_t size2 = 0; bitmap1.lockPixels(); addr1 = bitmap1.getAddr32(0, 0); size1 = bitmap1.getSize(); bitmap1.unlockPixels(); bitmap2.lockPixels(); addr2 = bitmap2.getAddr32(0, 0); size2 = bitmap2.getSize(); bitmap2.unlockPixels(); return (size1 == size2) && (0 == memcmp(addr1, addr2, bitmap1.getSize())); } string16 RemoveAcceleratorChar(const string16& s, char16 accelerator_char, int* accelerated_char_pos, int* accelerated_char_span) { bool escaped = false; int last_char_pos = -1; int last_char_span = 0; base::i18n::UTF16CharIterator chars(&s); string16 accelerator_removed; accelerator_removed.reserve(s.size()); while (!chars.end()) { int32 c = chars.get(); int array_pos = chars.array_pos(); chars.Advance(); if (c != accelerator_char || escaped) { int span = chars.array_pos() - array_pos; if (escaped && c != accelerator_char) { last_char_pos = accelerator_removed.size(); last_char_span = span; } for (int i = 0; i < span; i++) accelerator_removed.push_back(s[array_pos + i]); escaped = false; } else { escaped = true; } } if (accelerated_char_pos) *accelerated_char_pos = last_char_pos; if (accelerated_char_span) *accelerated_char_span = last_char_span; return accelerator_removed; } void ConvertSkiaToRGBA(const unsigned char* skia, int pixel_width, unsigned char* rgba) { int total_length = pixel_width * 4; for (int i = 0; i < total_length; i += 4) { const uint32_t pixel_in = *reinterpret_cast<const uint32_t*>(&skia[i]); // Pack the components here. int alpha = SkGetPackedA32(pixel_in); if (alpha != 0 && alpha != 255) { SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel_in); rgba[i + 0] = SkColorGetR(unmultiplied); rgba[i + 1] = SkColorGetG(unmultiplied); rgba[i + 2] = SkColorGetB(unmultiplied); rgba[i + 3] = alpha; } else { rgba[i + 0] = SkGetPackedR32(pixel_in); rgba[i + 1] = SkGetPackedG32(pixel_in); rgba[i + 2] = SkGetPackedB32(pixel_in); rgba[i + 3] = alpha; } } } } // namespace gfx
Simplify the implementation of RectToSkIRect() function.
gfx: Simplify the implementation of RectToSkIRect() function. [email protected] [email protected] Review URL: https://codereview.chromium.org/10943023 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@157686 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
dednal/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,ondra-novak/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,dednal/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,dednal/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,ltilve/chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,nacl-webkit/chrome_deps,patrickm/chromium.src,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,jaruba/chromium.src,markYoungH/chromium.src,zcbenz/cefode-chromium,patrickm/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,littlstar/chromium.src,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,dushu1203/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,nacl-webkit/chrome_deps,Chilledheart/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,Just-D/chromium-1,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,ltilve/chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,ondra-novak/chromium.src,ltilve/chromium,littlstar/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,M4sse/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,Just-D/chromium-1,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,patrickm/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,markYoungH/chromium.src,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,littlstar/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,Jonekee/chromium.src,dednal/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,nacl-webkit/chrome_deps,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,dushu1203/chromium.src,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,mogoweb/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,Chilledheart/chromium,ltilve/chromium,jaruba/chromium.src,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,patrickm/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,anirudhSK/chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk
e2769ac10a86fcfb588824166fc16c36dcfc5c2c
test/msan/fork.cc
test/msan/fork.cc
// Test that chained origins are fork-safe. // Run a number of threads that create new chained origins, then fork // and verify that origin reads do not deadlock in the child process. // RUN: %clangxx_msan -std=c++11 -fsanitize-memory-track-origins=2 -g -m64 -O3 %s -o %t // RUN: MSAN_OPTIONS=store_context_size=1000,origin_history_size=0,origin_history_per_stack_limit=0 %run %t |& FileCheck %s // Fun fact: if test output is redirected to a file (as opposed to // being piped directly to FileCheck), we may lose some "done"s due to // a kernel bug: // https://lkml.org/lkml/2014/2/17/324 #include <pthread.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <signal.h> #include <errno.h> #include <atomic> #include <sanitizer/msan_interface.h> std::atomic<bool> done; void copy_uninit_thread2() { volatile int x; volatile int v; while (true) { v = x; x = v; if (done.load()) return; } } void copy_uninit_thread1(int level) { if (!level) copy_uninit_thread2(); else copy_uninit_thread1(level - 1); } void *copy_uninit_thread(void *id) { copy_uninit_thread1((long)id); return 0; } // Run through stackdepot in the child process. // If any of the hash table cells are locked, this may deadlock. void child() { volatile int x; volatile int v; for (int i = 0; i < 10000; ++i) { v = x; x = v; } write(2, "done\n", 5); } void test() { done.store(false); const int kThreads = 10; pthread_t t[kThreads]; for (int i = 0; i < kThreads; ++i) pthread_create(&t[i], NULL, copy_uninit_thread, (void*)(long)i); usleep(100000); pid_t pid = fork(); if (pid) { // parent done.store(true); usleep(1000000); kill(pid, SIGKILL); } else { // child child(); } } int main() { const int kChildren = 20; for (int i = 0; i < kChildren; ++i) { pid_t pid = fork(); if (pid) { // parent } else { test(); exit(0); } } for (int i = 0; i < kChildren; ++i) { pid_t p; while ((p = wait(NULL)) == -1) { } } return 0; } // Expect 20 (== kChildren) "done" messages. // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done
// Test that chained origins are fork-safe. // Run a number of threads that create new chained origins, then fork // and verify that origin reads do not deadlock in the child process. // RUN: %clangxx_msan -std=c++11 -fsanitize-memory-track-origins=2 -g -m64 -O3 %s -o %t // RUN: MSAN_OPTIONS=store_context_size=1000,origin_history_size=0,origin_history_per_stack_limit=0 %run %t |& FileCheck %s // Fun fact: if test output is redirected to a file (as opposed to // being piped directly to FileCheck), we may lose some "done"s due to // a kernel bug: // https://lkml.org/lkml/2014/2/17/324 #include <pthread.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <signal.h> #include <errno.h> #include <sanitizer/msan_interface.h> int done; void copy_uninit_thread2() { volatile int x; volatile int v; while (true) { v = x; x = v; if (__atomic_load_n(&done, __ATOMIC_RELAXED)) return; } } void copy_uninit_thread1(int level) { if (!level) copy_uninit_thread2(); else copy_uninit_thread1(level - 1); } void *copy_uninit_thread(void *id) { copy_uninit_thread1((long)id); return 0; } // Run through stackdepot in the child process. // If any of the hash table cells are locked, this may deadlock. void child() { volatile int x; volatile int v; for (int i = 0; i < 10000; ++i) { v = x; x = v; } write(2, "done\n", 5); } void test() { const int kThreads = 10; pthread_t t[kThreads]; for (int i = 0; i < kThreads; ++i) pthread_create(&t[i], NULL, copy_uninit_thread, (void*)(long)i); usleep(100000); pid_t pid = fork(); if (pid) { // parent __atomic_store_n(&done, 1, __ATOMIC_RELAXED); usleep(1000000); kill(pid, SIGKILL); } else { // child child(); } } int main() { const int kChildren = 20; for (int i = 0; i < kChildren; ++i) { pid_t pid = fork(); if (pid) { // parent } else { test(); exit(0); } } for (int i = 0; i < kChildren; ++i) { pid_t p; while ((p = wait(NULL)) == -1) { } } return 0; } // Expect 20 (== kChildren) "done" messages. // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done // CHECK: done
Fix fork test on centos-6.5.
[msan] Fix fork test on centos-6.5. Missing <atomic> header. git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@217142 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
2f9041b84244e5b0039ef4901c20b646f2ceaaf0
src/editor.cc
src/editor.cc
#include "editor.hh" #include "exception.hh" #include "utils.hh" #include "register.hh" #include "register_manager.hh" #include "utf8_iterator.hh" #include <array> namespace Kakoune { Editor::Editor(Buffer& buffer) : m_buffer(&buffer), m_edition_level(0), m_selections(buffer) { m_selections.push_back(Selection(buffer.begin(), buffer.begin())); } void Editor::erase() { scoped_edition edition(*this); for (auto& sel : m_selections) { m_buffer->erase(sel.begin(), sel.end()); sel.avoid_eol(); } } static BufferIterator prepare_insert(Buffer& buffer, const Selection& sel, InsertMode mode) { switch (mode) { case InsertMode::Insert: return sel.begin(); case InsertMode::Replace: { BufferIterator pos = sel.begin(); buffer.erase(sel.begin(), sel.end()); return pos; } case InsertMode::Append: { // special case for end of lines, append to current line instead auto pos = std::max(sel.first(), sel.last()); if (pos.column() == buffer.line_length(pos.line()) - 1) return pos; else return pos+1; } case InsertMode::InsertAtLineBegin: return buffer.iterator_at_line_begin(sel.begin()); case InsertMode::AppendAtLineEnd: return buffer.iterator_at_line_end(sel.end()-1)-1; case InsertMode::InsertAtNextLineBegin: return buffer.iterator_at_line_end(sel.end()-1); case InsertMode::OpenLineBelow: { LineCount line = (sel.end() - 1).line(); buffer.insert(buffer.iterator_at_line_end(line), "\n"); return buffer.iterator_at_line_begin(line + 1); } case InsertMode::OpenLineAbove: { auto pos = buffer.iterator_at_line_begin(sel.begin()); buffer.insert(pos, "\n"); return pos; } } assert(false); return BufferIterator{}; } void Editor::insert(const String& string, InsertMode mode) { scoped_edition edition(*this); for (auto& sel : m_selections) { BufferIterator pos = prepare_insert(*m_buffer, sel, mode); m_buffer->insert(pos, string); if (mode == InsertMode::Replace) { sel.first() = pos; sel.last() = pos + (string.empty() ? 0 : string.length() - 1 ); } sel.avoid_eol(); } } void Editor::insert(const memoryview<String>& strings, InsertMode mode) { scoped_edition edition(*this); if (strings.empty()) return; for (size_t i = 0; i < selections().size(); ++i) { auto& sel = m_selections[i]; BufferIterator pos = prepare_insert(*m_buffer, sel, mode); const String& str = strings[std::min(i, strings.size()-1)]; m_buffer->insert(pos, str); if (mode == InsertMode::Replace) { sel.first() = pos; sel.last() = pos + (str.empty() ? 0 : str.length() - 1); } sel.avoid_eol(); } } std::vector<String> Editor::selections_content() const { std::vector<String> contents; for (auto& sel : m_selections) contents.push_back(m_buffer->string(sel.begin(), sel.end())); return contents; } static bool compare_selections(const Selection& lhs, const Selection& rhs) { return lhs.begin() < rhs.begin(); } static void sort_and_merge_overlapping(SelectionList& selections) { if (selections.size() == 1) return; Range back = selections.back(); auto back_rank = std::count_if(selections.begin(), selections.end(), [&](const Selection& sel) { return sel.begin() <= back.begin(); }); std::stable_sort(selections.begin(), selections.end(), compare_selections); if (back_rank < selections.size()) std::rotate(selections.begin(), selections.begin() + back_rank, selections.end()); assert(selections.back() == back); for (size_t i = 0; i < selections.size() and selections.size() > 1;) { size_t next = (i + 1) % selections.size(); if (overlaps(selections[i], selections[next])) { selections[i].merge_with(selections[next]); selections.erase(selections.begin() + next); } else ++i; } } void Editor::move_selections(CharCount offset, SelectMode mode) { assert(mode == SelectMode::Replace or mode == SelectMode::Extend); for (auto& sel : m_selections) { auto last = sel.last(); auto limit = offset < 0 ? buffer().iterator_at_line_begin(last) : utf8::previous(buffer().iterator_at_line_end(last)); last = utf8::advance(last, limit, offset); sel.first() = mode == SelectMode::Extend ? sel.first() : last; sel.last() = last; sel.avoid_eol(); } sort_and_merge_overlapping(m_selections); } void Editor::move_selections(LineCount offset, SelectMode mode) { assert(mode == SelectMode::Replace or mode == SelectMode::Extend); for (auto& sel : m_selections) { BufferCoord pos = sel.last().coord(); pos.line += offset; BufferIterator last = utf8::finish(m_buffer->iterator_at(pos, true)); sel.first() = mode == SelectMode::Extend ? sel.first() : last; sel.last() = last; sel.avoid_eol(); } sort_and_merge_overlapping(m_selections); } void Editor::clear_selections() { auto& sel = m_selections.back(); auto& pos = sel.last(); if (*pos == '\n' and not pos.is_begin() and *utf8::previous(pos) != '\n') pos = utf8::previous(pos); sel.first() = pos; m_selections.erase(m_selections.begin(), m_selections.end() - 1); check_invariant(); } void Editor::flip_selections() { for (auto& sel : m_selections) std::swap(sel.first(), sel.last()); check_invariant(); } void Editor::keep_selection(int index) { if (index < m_selections.size()) m_selections = SelectionList{ std::move(m_selections[index]) }; check_invariant(); } void Editor::remove_selection(int index) { if (m_selections.size() > 1 and index < m_selections.size()) m_selections.erase(m_selections.begin() + index); check_invariant(); } void Editor::select(const Selection& selection, SelectMode mode) { if (mode == SelectMode::Replace) m_selections = SelectionList{ selection }; else if (mode == SelectMode::Extend) { for (auto& sel : m_selections) sel.merge_with(selection); sort_and_merge_overlapping(m_selections); } else if (mode == SelectMode::Append) { m_selections.push_back(selection); sort_and_merge_overlapping(m_selections); } else assert(false); check_invariant(); } void Editor::select(SelectionList selections) { if (selections.empty()) throw runtime_error("no selections"); m_selections = std::move(selections); check_invariant(); } void Editor::select(const Selector& selector, SelectMode mode) { if (mode == SelectMode::Append) { auto& sel = m_selections.back(); auto res = selector(sel); if (res.captures().empty()) res.captures() = sel.captures(); m_selections.push_back(res); } else if (mode == SelectMode::ReplaceLast) { auto& sel = m_selections.back(); auto res = selector(sel); sel.first() = res.first(); sel.last() = res.last(); if (not res.captures().empty()) sel.captures() = std::move(res.captures()); } else { for (auto& sel : m_selections) { auto res = selector(sel); if (mode == SelectMode::Extend) sel.merge_with(res); else { sel.first() = res.first(); sel.last() = res.last(); } if (not res.captures().empty()) sel.captures() = std::move(res.captures()); } } sort_and_merge_overlapping(m_selections); check_invariant(); } struct nothing_selected : public runtime_error { nothing_selected() : runtime_error("nothing was selected") {} }; void Editor::multi_select(const MultiSelector& selector) { SelectionList new_selections; for (auto& sel : m_selections) { SelectionList res = selector(sel); for (auto& new_sel : res) { // preserve captures when selectors captures nothing. if (new_sel.captures().empty()) new_selections.emplace_back(new_sel.first(), new_sel.last(), sel.captures()); else new_selections.push_back(std::move(new_sel)); } } if (new_selections.empty()) throw nothing_selected(); sort_and_merge_overlapping(new_selections); m_selections = std::move(new_selections); check_invariant(); } class LastModifiedRangeListener : public BufferChangeListener { public: LastModifiedRangeListener(Buffer& buffer) : m_buffer(buffer) { m_buffer.change_listeners().insert(this); } ~LastModifiedRangeListener() { m_buffer.change_listeners().erase(this); } void on_insert(const BufferIterator& begin, const BufferIterator& end) { assert(begin.is_valid()); assert(end.is_valid()); m_first = begin; m_last = utf8::previous(end); } void on_erase(const BufferIterator& begin, const BufferIterator& end) { assert(begin.is_valid()); m_first = begin; if (m_first >= m_buffer.end()) m_first = utf8::previous(m_buffer.end()); m_last = m_first; } const BufferIterator& first() const { return m_first; } const BufferIterator& last() const { return m_last; } private: BufferIterator m_first; BufferIterator m_last; Buffer& m_buffer; }; bool Editor::undo() { LastModifiedRangeListener listener(buffer()); bool res = m_buffer->undo(); if (res) m_selections = SelectionList{ {listener.first(), listener.last()} }; check_invariant(); return res; } bool Editor::redo() { LastModifiedRangeListener listener(buffer()); bool res = m_buffer->redo(); if (res) m_selections = SelectionList{ {listener.first(), listener.last()} }; check_invariant(); return res; } void Editor::check_invariant() const { assert(not m_selections.empty()); m_selections.check_invariant(); auto it = ++std::max_element(m_selections.begin(), m_selections.end(), compare_selections); assert(std::is_sorted(m_selections.begin(), it, compare_selections)); assert(std::is_sorted(it, m_selections.end(), compare_selections)); } void Editor::begin_edition() { ++m_edition_level; if (m_edition_level == 1) m_buffer->begin_undo_group(); } void Editor::end_edition() { assert(m_edition_level > 0); if (m_edition_level == 1) m_buffer->end_undo_group(); --m_edition_level; } using utf8_it = utf8::utf8_iterator<BufferIterator, utf8::InvalidBytePolicy::Pass>; IncrementalInserter::IncrementalInserter(Editor& editor, InsertMode mode) : m_editor(editor), m_edition(editor), m_mode(mode) { Buffer& buffer = *editor.m_buffer; for (auto& sel : m_editor.m_selections) { utf8_it first, last; switch (mode) { case InsertMode::Insert: first = utf8_it(sel.end()) - 1; last = sel.begin(); break; case InsertMode::Replace: { buffer.erase(sel.begin(), sel.end()); first = last = sel.begin(); break; } case InsertMode::Append: { first = sel.begin(); last = std::max(sel.first(), sel.last()); // special case for end of lines, append to current line instead auto coord = last.underlying_iterator().coord(); if (coord.column != buffer.line_length(coord.line) - 1) ++last; break; } case InsertMode::OpenLineBelow: case InsertMode::AppendAtLineEnd: first = utf8_it(buffer.iterator_at_line_end(utf8::previous(sel.end()))) - 1; last = first; break; case InsertMode::OpenLineAbove: case InsertMode::InsertAtLineBegin: first = buffer.iterator_at_line_begin(sel.begin()); if (mode == InsertMode::OpenLineAbove) --first; else { auto first_non_blank = first; while (*first_non_blank == ' ' or *first_non_blank == '\t') ++first_non_blank; if (*first_non_blank != '\n') first = first_non_blank; } last = first; break; } if (first.underlying_iterator().is_end()) --first; if (last.underlying_iterator().is_end()) --last; sel.first() = first.underlying_iterator(); sel.last() = last.underlying_iterator(); } if (mode == InsertMode::OpenLineBelow or mode == InsertMode::OpenLineAbove) { insert("\n"); if (mode == InsertMode::OpenLineAbove) { for (auto& sel : m_editor.m_selections) { // special case, the --first line above did nothing, so we need to compensate now if (sel.first() == utf8::next(buffer.begin())) sel.first() = sel.last() = buffer.begin(); } } } editor.check_invariant(); } IncrementalInserter::~IncrementalInserter() { for (auto& sel : m_editor.m_selections) { if (m_mode == InsertMode::Append and sel.last().column() > 0) sel.last() = utf8::previous(sel.last()); sel.avoid_eol(); } } void IncrementalInserter::insert(String content) { Buffer& buffer = m_editor.buffer(); for (auto& sel : m_editor.m_selections) { m_editor.filters()(buffer, sel, content); buffer.insert(sel.last(), content); } } void IncrementalInserter::insert(const memoryview<String>& strings) { for (size_t i = 0; i < m_editor.m_selections.size(); ++i) { size_t index = std::min(i, strings.size()-1); m_editor.buffer().insert(m_editor.m_selections[i].last(), strings[index]); } } void IncrementalInserter::erase() { for (auto& sel : m_editor.m_selections) { BufferIterator pos = sel.last(); m_editor.buffer().erase(utf8::previous(pos), pos); } } void IncrementalInserter::move_cursors(CharCount move) { m_editor.move_selections(move, SelectMode::Replace); } void IncrementalInserter::move_cursors(LineCount move) { m_editor.move_selections(move, SelectMode::Replace); } }
#include "editor.hh" #include "exception.hh" #include "utils.hh" #include "register.hh" #include "register_manager.hh" #include "utf8_iterator.hh" #include <array> namespace Kakoune { Editor::Editor(Buffer& buffer) : m_buffer(&buffer), m_edition_level(0), m_selections(buffer) { m_selections.push_back(Selection(buffer.begin(), buffer.begin())); } void Editor::erase() { scoped_edition edition(*this); for (auto& sel : m_selections) { m_buffer->erase(sel.begin(), sel.end()); sel.avoid_eol(); } } static BufferIterator prepare_insert(Buffer& buffer, const Selection& sel, InsertMode mode) { switch (mode) { case InsertMode::Insert: return sel.begin(); case InsertMode::Replace: { BufferIterator pos = sel.begin(); buffer.erase(sel.begin(), sel.end()); return pos; } case InsertMode::Append: { // special case for end of lines, append to current line instead auto pos = std::max(sel.first(), sel.last()); if (pos.column() == buffer.line_length(pos.line()) - 1) return pos; else return pos+1; } case InsertMode::InsertAtLineBegin: return buffer.iterator_at_line_begin(sel.begin()); case InsertMode::AppendAtLineEnd: return buffer.iterator_at_line_end(sel.end()-1)-1; case InsertMode::InsertAtNextLineBegin: return buffer.iterator_at_line_end(sel.end()-1); case InsertMode::OpenLineBelow: { LineCount line = (sel.end() - 1).line(); buffer.insert(buffer.iterator_at_line_end(line), "\n"); return buffer.iterator_at_line_begin(line + 1); } case InsertMode::OpenLineAbove: { auto pos = buffer.iterator_at_line_begin(sel.begin()); buffer.insert(pos, "\n"); return pos; } } assert(false); return BufferIterator{}; } void Editor::insert(const String& string, InsertMode mode) { scoped_edition edition(*this); for (auto& sel : m_selections) { BufferIterator pos = prepare_insert(*m_buffer, sel, mode); m_buffer->insert(pos, string); if (mode == InsertMode::Replace) { sel.first() = pos; sel.last() = pos + (string.empty() ? 0 : string.length() - 1 ); } sel.avoid_eol(); } } void Editor::insert(const memoryview<String>& strings, InsertMode mode) { scoped_edition edition(*this); if (strings.empty()) return; for (size_t i = 0; i < selections().size(); ++i) { auto& sel = m_selections[i]; BufferIterator pos = prepare_insert(*m_buffer, sel, mode); const String& str = strings[std::min(i, strings.size()-1)]; m_buffer->insert(pos, str); if (mode == InsertMode::Replace) { sel.first() = pos; sel.last() = pos + (str.empty() ? 0 : str.length() - 1); } sel.avoid_eol(); } } std::vector<String> Editor::selections_content() const { std::vector<String> contents; for (auto& sel : m_selections) contents.push_back(m_buffer->string(sel.begin(), sel.end())); return contents; } static bool compare_selections(const Selection& lhs, const Selection& rhs) { return lhs.begin() < rhs.begin(); } static void sort_and_merge_overlapping(SelectionList& selections) { if (selections.size() == 1) return; Range back = selections.back(); auto back_rank = std::count_if(selections.begin(), selections.end(), [&](const Selection& sel) { return sel.begin() <= back.begin(); }); std::stable_sort(selections.begin(), selections.end(), compare_selections); if (back_rank < selections.size()) std::rotate(selections.begin(), selections.begin() + back_rank, selections.end()); assert(selections.back() == back); for (size_t i = 0; i < selections.size() and selections.size() > 1;) { size_t next = (i + 1) % selections.size(); if (overlaps(selections[i], selections[next])) { selections[i].merge_with(selections[next]); selections.erase(selections.begin() + next); } else ++i; } } void Editor::move_selections(CharCount offset, SelectMode mode) { assert(mode == SelectMode::Replace or mode == SelectMode::Extend); for (auto& sel : m_selections) { auto last = sel.last(); auto limit = offset < 0 ? buffer().iterator_at_line_begin(last) : utf8::previous(buffer().iterator_at_line_end(last)); last = utf8::advance(last, limit, offset); sel.first() = mode == SelectMode::Extend ? sel.first() : last; sel.last() = last; sel.avoid_eol(); } sort_and_merge_overlapping(m_selections); } void Editor::move_selections(LineCount offset, SelectMode mode) { assert(mode == SelectMode::Replace or mode == SelectMode::Extend); for (auto& sel : m_selections) { BufferCoord pos = sel.last().coord(); pos.line += offset; BufferIterator last = utf8::finish(m_buffer->iterator_at(pos, true)); sel.first() = mode == SelectMode::Extend ? sel.first() : last; sel.last() = last; sel.avoid_eol(); } sort_and_merge_overlapping(m_selections); } void Editor::clear_selections() { auto& sel = m_selections.back(); auto& pos = sel.last(); if (*pos == '\n' and not pos.is_begin() and *utf8::previous(pos) != '\n') pos = utf8::previous(pos); sel.first() = pos; m_selections.erase(m_selections.begin(), m_selections.end() - 1); check_invariant(); } void Editor::flip_selections() { for (auto& sel : m_selections) std::swap(sel.first(), sel.last()); check_invariant(); } void Editor::keep_selection(int index) { if (index < m_selections.size()) m_selections = SelectionList{ std::move(m_selections[index]) }; check_invariant(); } void Editor::remove_selection(int index) { if (m_selections.size() > 1 and index < m_selections.size()) m_selections.erase(m_selections.begin() + index); check_invariant(); } void Editor::select(const Selection& selection, SelectMode mode) { if (mode == SelectMode::Replace) m_selections = SelectionList{ selection }; else if (mode == SelectMode::Extend) { for (auto& sel : m_selections) sel.merge_with(selection); sort_and_merge_overlapping(m_selections); } else if (mode == SelectMode::Append) { m_selections.push_back(selection); sort_and_merge_overlapping(m_selections); } else assert(false); check_invariant(); } void Editor::select(SelectionList selections) { if (selections.empty()) throw runtime_error("no selections"); m_selections = std::move(selections); check_invariant(); } void Editor::select(const Selector& selector, SelectMode mode) { if (mode == SelectMode::Append) { auto& sel = m_selections.back(); auto res = selector(sel); if (res.captures().empty()) res.captures() = sel.captures(); m_selections.push_back(res); } else if (mode == SelectMode::ReplaceLast) { auto& sel = m_selections.back(); auto res = selector(sel); sel.first() = res.first(); sel.last() = res.last(); if (not res.captures().empty()) sel.captures() = std::move(res.captures()); } else { for (auto& sel : m_selections) { auto res = selector(sel); if (mode == SelectMode::Extend) sel.merge_with(res); else { sel.first() = res.first(); sel.last() = res.last(); } if (not res.captures().empty()) sel.captures() = std::move(res.captures()); } } sort_and_merge_overlapping(m_selections); check_invariant(); } struct nothing_selected : public runtime_error { nothing_selected() : runtime_error("nothing was selected") {} }; void Editor::multi_select(const MultiSelector& selector) { SelectionList new_selections; for (auto& sel : m_selections) { SelectionList res = selector(sel); for (auto& new_sel : res) { // preserve captures when selectors captures nothing. if (new_sel.captures().empty()) new_selections.emplace_back(new_sel.first(), new_sel.last(), sel.captures()); else new_selections.push_back(std::move(new_sel)); } } if (new_selections.empty()) throw nothing_selected(); sort_and_merge_overlapping(new_selections); m_selections = std::move(new_selections); check_invariant(); } class LastModifiedRangeListener : public BufferChangeListener { public: LastModifiedRangeListener(Buffer& buffer) : m_buffer(buffer) { m_buffer.change_listeners().insert(this); } ~LastModifiedRangeListener() { m_buffer.change_listeners().erase(this); } void on_insert(const BufferIterator& begin, const BufferIterator& end) { assert(begin.is_valid()); assert(end.is_valid()); m_first = begin; m_last = utf8::previous(end); } void on_erase(const BufferIterator& begin, const BufferIterator& end) { assert(begin.is_valid()); m_first = begin; if (m_first >= m_buffer.end()) m_first = utf8::previous(m_buffer.end()); m_last = m_first; } const BufferIterator& first() const { return m_first; } const BufferIterator& last() const { return m_last; } private: BufferIterator m_first; BufferIterator m_last; Buffer& m_buffer; }; bool Editor::undo() { LastModifiedRangeListener listener(buffer()); bool res = m_buffer->undo(); if (res) m_selections = SelectionList{ {listener.first(), listener.last()} }; check_invariant(); return res; } bool Editor::redo() { LastModifiedRangeListener listener(buffer()); bool res = m_buffer->redo(); if (res) m_selections = SelectionList{ {listener.first(), listener.last()} }; check_invariant(); return res; } void Editor::check_invariant() const { assert(not m_selections.empty()); m_selections.check_invariant(); auto it = ++std::max_element(m_selections.begin(), m_selections.end(), compare_selections); assert(std::is_sorted(m_selections.begin(), it, compare_selections)); assert(std::is_sorted(it, m_selections.end(), compare_selections)); } void Editor::begin_edition() { ++m_edition_level; if (m_edition_level == 1) m_buffer->begin_undo_group(); } void Editor::end_edition() { assert(m_edition_level > 0); if (m_edition_level == 1) m_buffer->end_undo_group(); --m_edition_level; } using utf8_it = utf8::utf8_iterator<BufferIterator, utf8::InvalidBytePolicy::Pass>; IncrementalInserter::IncrementalInserter(Editor& editor, InsertMode mode) : m_editor(editor), m_edition(editor), m_mode(mode) { Buffer& buffer = *editor.m_buffer; for (auto& sel : m_editor.m_selections) { utf8_it first, last; switch (mode) { case InsertMode::Insert: first = utf8_it(sel.end()) - 1; last = sel.begin(); break; case InsertMode::Replace: { buffer.erase(sel.begin(), sel.end()); first = last = sel.begin(); break; } case InsertMode::Append: { first = sel.begin(); last = std::max(sel.first(), sel.last()); // special case for end of lines, append to current line instead auto coord = last.underlying_iterator().coord(); if (coord.column != buffer.line_length(coord.line) - 1) ++last; break; } case InsertMode::OpenLineBelow: case InsertMode::AppendAtLineEnd: first = utf8_it(buffer.iterator_at_line_end(utf8::previous(sel.end()))) - 1; last = first; break; case InsertMode::OpenLineAbove: case InsertMode::InsertAtLineBegin: first = buffer.iterator_at_line_begin(sel.begin()); if (mode == InsertMode::OpenLineAbove) --first; else { auto first_non_blank = first; while (*first_non_blank == ' ' or *first_non_blank == '\t') ++first_non_blank; if (*first_non_blank != '\n') first = first_non_blank; } last = first; break; case InsertMode::InsertAtNextLineBegin: assert(false); // not implemented break; } if (first.underlying_iterator().is_end()) --first; if (last.underlying_iterator().is_end()) --last; sel.first() = first.underlying_iterator(); sel.last() = last.underlying_iterator(); } if (mode == InsertMode::OpenLineBelow or mode == InsertMode::OpenLineAbove) { insert("\n"); if (mode == InsertMode::OpenLineAbove) { for (auto& sel : m_editor.m_selections) { // special case, the --first line above did nothing, so we need to compensate now if (sel.first() == utf8::next(buffer.begin())) sel.first() = sel.last() = buffer.begin(); } } } editor.check_invariant(); } IncrementalInserter::~IncrementalInserter() { for (auto& sel : m_editor.m_selections) { if (m_mode == InsertMode::Append and sel.last().column() > 0) sel.last() = utf8::previous(sel.last()); sel.avoid_eol(); } } void IncrementalInserter::insert(String content) { Buffer& buffer = m_editor.buffer(); for (auto& sel : m_editor.m_selections) { m_editor.filters()(buffer, sel, content); buffer.insert(sel.last(), content); } } void IncrementalInserter::insert(const memoryview<String>& strings) { for (size_t i = 0; i < m_editor.m_selections.size(); ++i) { size_t index = std::min(i, strings.size()-1); m_editor.buffer().insert(m_editor.m_selections[i].last(), strings[index]); } } void IncrementalInserter::erase() { for (auto& sel : m_editor.m_selections) { BufferIterator pos = sel.last(); m_editor.buffer().erase(utf8::previous(pos), pos); } } void IncrementalInserter::move_cursors(CharCount move) { m_editor.move_selections(move, SelectMode::Replace); } void IncrementalInserter::move_cursors(LineCount move) { m_editor.move_selections(move, SelectMode::Replace); } }
fix warning
Editor: fix warning
C++
unlicense
jjthrash/kakoune,rstacruz/kakoune,jkonecny12/kakoune,lenormf/kakoune,Somasis/kakoune,danielma/kakoune,danielma/kakoune,casimir/kakoune,jkonecny12/kakoune,alexherbo2/kakoune,occivink/kakoune,jjthrash/kakoune,jjthrash/kakoune,elegios/kakoune,danr/kakoune,Asenar/kakoune,zakgreant/kakoune,alexherbo2/kakoune,occivink/kakoune,mawww/kakoune,ekie/kakoune,danielma/kakoune,Asenar/kakoune,rstacruz/kakoune,zakgreant/kakoune,danr/kakoune,Asenar/kakoune,xificurC/kakoune,mawww/kakoune,xificurC/kakoune,Somasis/kakoune,casimir/kakoune,alpha123/kakoune,flavius/kakoune,flavius/kakoune,danr/kakoune,lenormf/kakoune,rstacruz/kakoune,jkonecny12/kakoune,alexherbo2/kakoune,jjthrash/kakoune,occivink/kakoune,mawww/kakoune,Somasis/kakoune,zakgreant/kakoune,alpha123/kakoune,casimir/kakoune,jkonecny12/kakoune,mawww/kakoune,elegios/kakoune,lenormf/kakoune,elegios/kakoune,ekie/kakoune,occivink/kakoune,alpha123/kakoune,alexherbo2/kakoune,casimir/kakoune,danielma/kakoune,ekie/kakoune,Asenar/kakoune,flavius/kakoune,alpha123/kakoune,lenormf/kakoune,flavius/kakoune,xificurC/kakoune,Somasis/kakoune,xificurC/kakoune,rstacruz/kakoune,danr/kakoune,ekie/kakoune,elegios/kakoune,zakgreant/kakoune
49d20aebb203e49c870cdab30a4d64a6eaf5e6dc
src/app/pluginloader.cpp
src/app/pluginloader.cpp
/* * Copyright (C) 2008-2014 The Communi Project * * This example is free, and not covered by the LGPL license. There is no * restriction applied to their modification, redistribution, using and so on. * You can study them, modify them, use them in your own program - either * completely or partially. */ #include "pluginloader.h" #include <QDir> #include <QApplication> #include <QtPlugin> #include "bufferview.h" #include "bufferplugin.h" #include "connectionplugin.h" #include "documentplugin.h" #include "viewplugin.h" static QObjectList loadPlugins(const QStringList& paths) { QObjectList instances; foreach (const QString& path, paths) { QDir dir(path); foreach (const QFileInfo& file, dir.entryInfoList(QDir::Files)) { // blacklisted obsolete plugin if (file.baseName() == "monitorplugin" || file.baseName() == "libmonitorplugin") continue; QPluginLoader loader(file.absoluteFilePath()); if (loader.load()) instances += loader.instance(); } } return instances; } static QObjectList pluginInstances() { static QObjectList instances = loadPlugins(QApplication::libraryPaths()); return instances; } QStringList PluginLoader::paths() { QStringList lst; lst += COMMUNI_INSTALL_PLUGINS; #ifdef Q_OS_MAC QDir dir(QApplication::applicationFilePath()); if (dir.cd("../../PlugIns")) lst += dir.absolutePath(); #endif return lst; } PluginLoader::PluginLoader(QObject* parent) : QObject(parent) { qRegisterMetaType<BufferView*>(); } PluginLoader* PluginLoader::instance() { static PluginLoader loader; return &loader; } void PluginLoader::bufferAdded(IrcBuffer* buffer) { foreach (QObject* instance, pluginInstances()) { BufferPlugin* plugin = qobject_cast<BufferPlugin*>(instance); if (plugin) plugin->bufferAdded(buffer); } } void PluginLoader::bufferRemoved(IrcBuffer* buffer) { foreach (QObject* instance, pluginInstances()) { BufferPlugin* plugin = qobject_cast<BufferPlugin*>(instance); if (plugin) plugin->bufferRemoved(buffer); } } void PluginLoader::connectionAdded(IrcConnection* connection) { foreach (QObject* instance, pluginInstances()) { ConnectionPlugin* plugin = qobject_cast<ConnectionPlugin*>(instance); if (plugin) plugin->connectionAdded(connection); } } void PluginLoader::connectionRemoved(IrcConnection* connection) { foreach (QObject* instance, pluginInstances()) { ConnectionPlugin* plugin = qobject_cast<ConnectionPlugin*>(instance); if (plugin) plugin->connectionRemoved(connection); } } void PluginLoader::viewAdded(BufferView* view) { foreach (QObject* instance, pluginInstances()) { ViewPlugin* plugin = qobject_cast<ViewPlugin*>(instance); if (plugin) plugin->viewAdded(view); } } void PluginLoader::viewRemoved(BufferView* view) { foreach (QObject* instance, pluginInstances()) { ViewPlugin* plugin = qobject_cast<ViewPlugin*>(instance); if (plugin) plugin->viewRemoved(view); } } void PluginLoader::documentAdded(TextDocument* doc) { foreach (QObject* instance, pluginInstances()) { DocumentPlugin* plugin = qobject_cast<DocumentPlugin*>(instance); if (plugin) plugin->documentAdded(doc); } } void PluginLoader::documentRemoved(TextDocument* doc) { foreach (QObject* instance, pluginInstances()) { DocumentPlugin* plugin = qobject_cast<DocumentPlugin*>(instance); if (plugin) plugin->documentRemoved(doc); } }
/* * Copyright (C) 2008-2014 The Communi Project * * This example is free, and not covered by the LGPL license. There is no * restriction applied to their modification, redistribution, using and so on. * You can study them, modify them, use them in your own program - either * completely or partially. */ #include "pluginloader.h" #include <QDir> #include <QApplication> #include <QtPlugin> #include "bufferview.h" #include "bufferplugin.h" #include "connectionplugin.h" #include "documentplugin.h" #include "viewplugin.h" static QObjectList loadPlugins(const QStringList& paths) { QObjectList instances; foreach (const QString& path, paths) { foreach (const QFileInfo& file, QDir(path).entryInfoList(QDir::Files)) { const QString base = file.baseName(); // blacklisted obsolete plugin if (base.startsWith("monitorplugin") || base.startsWith("libmonitorplugin")) continue; #ifdef Q_OS_WIN // avoid loading undesired files from %QTDIR%\bin if (base.startsWith("Qt5") || base.startsWith("Irc") || base.startsWith("Enginio") || base.startsWith("icu") || file.suffix() != "dll") continue; #endif QPluginLoader loader(file.absoluteFilePath()); if (loader.load()) instances += loader.instance(); } } return instances; } static QObjectList pluginInstances() { static QObjectList instances = loadPlugins(QApplication::libraryPaths()); return instances; } QStringList PluginLoader::paths() { QStringList lst; lst += COMMUNI_INSTALL_PLUGINS; #ifdef Q_OS_MAC QDir dir(QApplication::applicationFilePath()); if (dir.cd("../../PlugIns")) lst += dir.absolutePath(); #endif return lst; } PluginLoader::PluginLoader(QObject* parent) : QObject(parent) { qRegisterMetaType<BufferView*>(); } PluginLoader* PluginLoader::instance() { static PluginLoader loader; return &loader; } void PluginLoader::bufferAdded(IrcBuffer* buffer) { foreach (QObject* instance, pluginInstances()) { BufferPlugin* plugin = qobject_cast<BufferPlugin*>(instance); if (plugin) plugin->bufferAdded(buffer); } } void PluginLoader::bufferRemoved(IrcBuffer* buffer) { foreach (QObject* instance, pluginInstances()) { BufferPlugin* plugin = qobject_cast<BufferPlugin*>(instance); if (plugin) plugin->bufferRemoved(buffer); } } void PluginLoader::connectionAdded(IrcConnection* connection) { foreach (QObject* instance, pluginInstances()) { ConnectionPlugin* plugin = qobject_cast<ConnectionPlugin*>(instance); if (plugin) plugin->connectionAdded(connection); } } void PluginLoader::connectionRemoved(IrcConnection* connection) { foreach (QObject* instance, pluginInstances()) { ConnectionPlugin* plugin = qobject_cast<ConnectionPlugin*>(instance); if (plugin) plugin->connectionRemoved(connection); } } void PluginLoader::viewAdded(BufferView* view) { foreach (QObject* instance, pluginInstances()) { ViewPlugin* plugin = qobject_cast<ViewPlugin*>(instance); if (plugin) plugin->viewAdded(view); } } void PluginLoader::viewRemoved(BufferView* view) { foreach (QObject* instance, pluginInstances()) { ViewPlugin* plugin = qobject_cast<ViewPlugin*>(instance); if (plugin) plugin->viewRemoved(view); } } void PluginLoader::documentAdded(TextDocument* doc) { foreach (QObject* instance, pluginInstances()) { DocumentPlugin* plugin = qobject_cast<DocumentPlugin*>(instance); if (plugin) plugin->documentAdded(doc); } } void PluginLoader::documentRemoved(TextDocument* doc) { foreach (QObject* instance, pluginInstances()) { DocumentPlugin* plugin = qobject_cast<DocumentPlugin*>(instance); if (plugin) plugin->documentRemoved(doc); } }
Fix plugin loading on Windows
Fix plugin loading on Windows
C++
bsd-3-clause
jpnurmi/communi-desktop,gdamjan/communi-desktop,sevanteri/communi-desktop,communi/communi-desktop,communi/communi-desktop
d9214750877b212f73d25f769a432e63d0bf4538
src/bicycle/kinematic.cc
src/bicycle/kinematic.cc
#include <cmath> #include "bicycle/kinematic.h" #include "constants.h" namespace { template <typename E> constexpr uint8_t index(E e) { return static_cast<uint8_t>(e); } } // namespace namespace model { BicycleKinematic::BicycleKinematic(const second_order_matrix_t& M, const second_order_matrix_t& C1, const second_order_matrix_t& K0, const second_order_matrix_t& K2, real_t wheelbase, real_t trail, real_t steer_axis_tilt, real_t rear_wheel_radius, real_t front_wheel_radius, real_t v, real_t dt) : Bicycle(M, C1, K0, K2, wheelbase, trail, steer_axis_tilt, rear_wheel_radius, front_wheel_radius, v, dt) { set_K(); } BicycleKinematic::BicycleKinematic(const char* param_file, real_t v, real_t dt) : Bicycle(param_file, v, dt) { set_K(); } BicycleKinematic::BicycleKinematic(real_t v, real_t dt) : Bicycle(v, dt) { set_K(); } BicycleKinematic::state_t BicycleKinematic::update_state(const BicycleKinematic::state_t& x, const BicycleKinematic::input_t& u, const BicycleKinematic::measurement_t& z) const { /* * Simplified equations of motion are used to simulate the bicycle dynamics. * Roll/steer rate and acceleration terms are ignored resulting in: * (g*K0 + v^2*K2) [phi ] = [T_phi ] * [delta] = [T_delta] * */ (void)u; const real_t yaw_angle_measurement = get_output_element(z, output_index_t::yaw_angle); const real_t steer_angle_measurement = get_output_element(z, output_index_t::steer_angle); const real_t next_roll = -m_K(0, 1)/m_K(0, 0) * steer_angle_measurement; state_t next_x = state_t::Zero(); set_state_element(next_x, state_index_t::yaw_angle, yaw_angle_measurement); set_state_element(next_x, state_index_t::steer_rate, (steer_angle_measurement - get_state_element(x, state_index_t::steer_angle))/m_dt); set_state_element(next_x, state_index_t::roll_rate, (next_roll - get_state_element(x, state_index_t::roll_angle))/m_dt); set_state_element(next_x, state_index_t::steer_angle, steer_angle_measurement); set_state_element(next_x, state_index_t::roll_angle, next_roll); return next_x; } BicycleKinematic::full_state_t BicycleKinematic::integrate_full_state(const BicycleKinematic::full_state_t& xf, const BicycleKinematic::input_t& u, real_t t, const BicycleKinematic::measurement_t& z) const { /* * As this class is already a simplification, we integrate the auxiliary state part separately, using the state at * the previous time. After, integration of the auxiliary state, the dynamic state is updated. */ static constexpr auto x_index = index(full_state_index_t::x); static constexpr auto y_index = index(full_state_index_t::y); static constexpr auto rear_wheel_index = index(full_state_index_t::rear_wheel_angle); static constexpr auto pitch_index = index(full_state_index_t::pitch_angle); const real_t v = m_v; const real_t rr = m_rr; const real_t yaw_angle = get_full_state_element(xf, full_state_index_t::yaw_angle); auxiliary_state_t x_aux_out = get_auxiliary_state_part(xf); m_stepper.do_step([v, rr, yaw_angle](const auxiliary_state_t& x, auxiliary_state_t& dxdt, const real_t t) -> void { (void)t; // system is time-independent; (void)x; // auxiliary state fields only dxdt[x_index] = v*std::cos(yaw_angle); dxdt[y_index] = v*std::sin(yaw_angle); dxdt[rear_wheel_index] = -v/rr; dxdt[pitch_index] = 0; // pitch angle is not integrated and must be obtained using solve_pitch_constraint() }, x_aux_out, static_cast<real_t>(0), t); const state_t x_out = update_state(get_state_part(xf), u, z); return make_full_state(x_aux_out, x_out); } void BicycleKinematic::set_state_space() { Bicycle::set_state_space(); set_K(); } void BicycleKinematic::set_K() { m_K = constants::g*m_K0 + m_v*m_v*m_K2; } } // namespace model
#include <cmath> #include "bicycle/kinematic.h" #include "constants.h" namespace { template <typename E> constexpr uint8_t index(E e) { return static_cast<uint8_t>(e); } } // namespace namespace model { BicycleKinematic::BicycleKinematic(const second_order_matrix_t& M, const second_order_matrix_t& C1, const second_order_matrix_t& K0, const second_order_matrix_t& K2, real_t wheelbase, real_t trail, real_t steer_axis_tilt, real_t rear_wheel_radius, real_t front_wheel_radius, real_t v, real_t dt) : Bicycle(M, C1, K0, K2, wheelbase, trail, steer_axis_tilt, rear_wheel_radius, front_wheel_radius, v, dt) { set_K(); } BicycleKinematic::BicycleKinematic(const char* param_file, real_t v, real_t dt) : Bicycle(param_file, v, dt) { set_K(); } BicycleKinematic::BicycleKinematic(real_t v, real_t dt) : Bicycle(v, dt) { set_K(); } BicycleKinematic::state_t BicycleKinematic::update_state(const BicycleKinematic::state_t& x, const BicycleKinematic::input_t& u, const BicycleKinematic::measurement_t& z) const { /* * Simplified equations of motion are used to simulate the bicycle dynamics. * Roll/steer rate and acceleration terms are ignored resulting in: * (g*K0 + v^2*K2) [phi ] = [T_phi ] * [delta] = [T_delta] * */ (void)u; const real_t steer_angle_measurement = get_output_element(z, output_index_t::steer_angle); static constexpr auto yaw_index_A = index(state_index_t::yaw_angle); static constexpr auto steer_index_A = index(state_index_t::steer_angle); static constexpr auto steer_rate_index_A = index(state_index_t::steer_rate); const real_t yaw_rate = m_A(yaw_index_A, steer_index_A)*get_state_element(x, state_index_t::steer_angle) + m_A(yaw_index_A, steer_rate_index_A)*get_state_element(x, state_index_t::steer_rate); const real_t yaw_angle = get_output_element(z, output_index_t::yaw_angle); const real_t next_roll = -m_K(0, 1)/m_K(0, 0) * steer_angle_measurement; state_t next_x = state_t::Zero(); set_state_element(next_x, state_index_t::yaw_angle, yaw_rate*m_dt + yaw_angle); set_state_element(next_x, state_index_t::steer_rate, (steer_angle_measurement - get_state_element(x, state_index_t::steer_angle))/m_dt); set_state_element(next_x, state_index_t::roll_rate, (next_roll - get_state_element(x, state_index_t::roll_angle))/m_dt); set_state_element(next_x, state_index_t::steer_angle, steer_angle_measurement); set_state_element(next_x, state_index_t::roll_angle, next_roll); return next_x; } BicycleKinematic::full_state_t BicycleKinematic::integrate_full_state(const BicycleKinematic::full_state_t& xf, const BicycleKinematic::input_t& u, real_t t, const BicycleKinematic::measurement_t& z) const { /* * As this class is already a simplification, we integrate the auxiliary state part separately, using the state at * the previous time. After, integration of the auxiliary state, the dynamic state is updated. */ static constexpr auto x_index = index(full_state_index_t::x); static constexpr auto y_index = index(full_state_index_t::y); static constexpr auto rear_wheel_index = index(full_state_index_t::rear_wheel_angle); static constexpr auto pitch_index = index(full_state_index_t::pitch_angle); const real_t v = m_v; const real_t rr = m_rr; const real_t yaw_angle = get_full_state_element(xf, full_state_index_t::yaw_angle); auxiliary_state_t x_aux_out = get_auxiliary_state_part(xf); m_stepper.do_step([v, rr, yaw_angle](const auxiliary_state_t& x, auxiliary_state_t& dxdt, const real_t t) -> void { (void)t; // system is time-independent; (void)x; // auxiliary state fields only dxdt[x_index] = v*std::cos(yaw_angle); dxdt[y_index] = v*std::sin(yaw_angle); dxdt[rear_wheel_index] = -v/rr; dxdt[pitch_index] = 0; // pitch angle is not integrated and must be obtained using solve_pitch_constraint() }, x_aux_out, static_cast<real_t>(0), t); const state_t x_out = update_state(get_state_part(xf), u, z); return make_full_state(x_aux_out, x_out); } void BicycleKinematic::set_state_space() { Bicycle::set_state_space(); set_K(); } void BicycleKinematic::set_K() { m_K = constants::g*m_K0 + m_v*m_v*m_K2; } } // namespace model
Fix yaw update in kinematic bicycle state update
Fix yaw update in kinematic bicycle state update
C++
bsd-2-clause
oliverlee/bicycle,oliverlee/bicycle
15a8eac238bbb308a2ef1b42294bb60cc795ab11
test/src/main.cpp
test/src/main.cpp
#include <Arduino.h> #include "lcd.h" #include "xpins.h" const uint32_t kDebounceMs = 100; const uint32_t kFlashMs = 1000; const uint16_t kToneHz = 1000; const uint32_t kToneMs = 300; DECLARE_KBUTTON_PINS(); DECLARE_KLED_PINS(); DECLARE_KSPEAKER_PIN(); DECLARE_LCD(); #if USE_LAMP DECLARE_KLAMP_PIN(); #endif bool buttons[BUTTON_COUNT] = { false }; bool buttonsBefore[BUTTON_COUNT] = { false }; uint32_t lastPressedMs[BUTTON_COUNT] = { 0 }; uint32_t flashStartMs[PLAYER_COUNT] = { 0 }; void setup() { for (const int buttonPin : kButtonPins) { xPinMode(buttonPin, INPUT_PULLUP); } for (const int ledPin : kLedPins) { xPinMode(ledPin, OUTPUT); xDigitalWrite(ledPin, LOW); } xPinMode(kSpeakerPin, OUTPUT); #if USE_LAMP xPinMode(kLampPin, OUTPUT); #endif initLcd(&lcd); lcd.print("Hello!"); flushLcd(&lcd); tone(kSpeakerPin, kToneHz, kToneMs); } void loop() { uint32_t now = millis(); for (int i = 0; i < BUTTON_COUNT; ++i) { buttonsBefore[i] = buttons[i]; if (now - lastPressedMs[i] > kDebounceMs) { if (xDigitalRead(kButtonPins[i]) == LOW) { buttons[i] = true; lastPressedMs[i] = now; } else { buttons[i] = false; } } if (buttons[i] && !buttonsBefore[i]) { lcd.clear(); lcd.print("Pressed "); lcd.print(i); flushLcd(&lcd); tone(kSpeakerPin, kToneHz, kToneMs); if (FIRST_PLAYER_BUTTON <= i && i <= LAST_PLAYER_BUTTON) { int playerNumber = i - FIRST_PLAYER_BUTTON; int ledPin = kLedPins[playerNumber]; digitalWrite(ledPin, HIGH); digitalWrite(kLampPin, HIGH); flashStartMs[playerNumber] = now; } } } for (int i = 0; i < PLAYER_COUNT; ++i) { if (flashStartMs[i] != 0 && now - flashStartMs[i] > kFlashMs) { digitalWrite(kLedPins[i], LOW); digitalWrite(kLampPin, LOW); } } }
#include <Arduino.h> #include "lcd.h" #include "xpins.h" const uint32_t kDebounceMs = 100; const uint32_t kFlashMs = 1000; const uint16_t kToneHz = 1000; const uint32_t kToneMs = 300; DECLARE_KBUTTON_PINS(); DECLARE_KLED_PINS(); DECLARE_KSPEAKER_PIN(); DECLARE_LCD(); #if USE_LAMP DECLARE_KLAMP_PIN(); #endif bool buttons[BUTTON_COUNT] = { false }; bool buttonsBefore[BUTTON_COUNT] = { false }; uint32_t lastPressedMs[BUTTON_COUNT] = { 0 }; uint32_t flashStartMs[PLAYER_COUNT] = { 0 }; void setup() { for (const int buttonPin : kButtonPins) { xPinMode(buttonPin, INPUT_PULLUP); } for (const int ledPin : kLedPins) { xPinMode(ledPin, OUTPUT); xDigitalWrite(ledPin, LOW); } xPinMode(kSpeakerPin, OUTPUT); #if USE_LAMP xPinMode(kLampPin, OUTPUT); #endif initLcd(&lcd); lcd.print("Hello!"); flushLcd(&lcd); tone(kSpeakerPin, kToneHz, kToneMs); } void loop() { uint32_t now = millis(); for (int i = 0; i < BUTTON_COUNT; ++i) { buttonsBefore[i] = buttons[i]; if (now - lastPressedMs[i] > kDebounceMs) { if (xDigitalRead(kButtonPins[i]) == LOW) { buttons[i] = true; lastPressedMs[i] = now; } else { buttons[i] = false; } } if (buttons[i] && !buttonsBefore[i]) { lcd.clear(); lcd.print("Pressed "); lcd.print(i); flushLcd(&lcd); tone(kSpeakerPin, kToneHz, kToneMs); if (FIRST_PLAYER_BUTTON <= i && i <= LAST_PLAYER_BUTTON) { int playerNumber = i - FIRST_PLAYER_BUTTON; int ledPin = kLedPins[playerNumber]; digitalWrite(ledPin, HIGH); #if USE_LAMP digitalWrite(kLampPin, HIGH); #endif flashStartMs[playerNumber] = now; } } } for (int i = 0; i < PLAYER_COUNT; ++i) { if (flashStartMs[i] != 0 && now - flashStartMs[i] > kFlashMs) { digitalWrite(kLedPins[i], LOW); #if USE_LAMP digitalWrite(kLampPin, LOW); #endif } } }
Fix v0 build
Fix v0 build
C++
mit
iley/kamaji,iley/kamaji,iley/kamaji,iley/kamaji,iley/kamaji
8f82e73206c2707be84631aefdc188319931b844
deal.II/lac/source/petsc_matrix_base.cc
deal.II/lac/source/petsc_matrix_base.cc
//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2004, 2005 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <lac/petsc_matrix_base.h> #include <lac/petsc_full_matrix.h> #include <lac/petsc_sparse_matrix.h> #include <lac/petsc_parallel_sparse_matrix.h> #include <lac/petsc_vector.h> #ifdef DEAL_II_USE_PETSC namespace PETScWrappers { namespace MatrixIterators { void MatrixBase::const_iterator::Accessor:: visit_present_row () { // if we are asked to visit the // past-the-end line, then simply // release all our caches and go on // with life if (this->a_row == matrix->m()) { colnum_cache.reset (); value_cache.reset (); return; } // otherwise first flush PETSc caches matrix->compress (); // get a representation of the present // row int ncols; #if (PETSC_VERSION_MAJOR <= 2) && \ ((PETSC_VERSION_MINOR < 2) || \ ((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0))) int *colnums; PetscScalar *values; #else const int *colnums; const PetscScalar *values; #endif int ierr; ierr = MatGetRow(*matrix, this->a_row, &ncols, &colnums, &values); AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr)); // copy it into our caches if the line // isn't empty. if it is, then we've // done something wrong, since we // shouldn't have initialized an // iterator for an empty line (what // would it point to?) Assert (ncols != 0, ExcInternalError()); colnum_cache.reset (new std::vector<unsigned int> (colnums, colnums+ncols)); value_cache.reset (new std::vector<PetscScalar> (values, values+ncols)); // and finally restore the matrix ierr = MatRestoreRow(*matrix, this->a_row, &ncols, &colnums, &values); AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr)); } } MatrixBase::MatrixBase () : last_action (LastAction::none) {} MatrixBase::~MatrixBase () { const int ierr = MatDestroy (matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void MatrixBase::clear () { // destroy the matrix... int ierr = MatDestroy (matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); // ...and replace it by an empty // sequential matrix const int m=0, n=0, n_nonzero_per_row=0; ierr = MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, n_nonzero_per_row, 0, &matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); } MatrixBase & MatrixBase::operator = (const double d) { Assert (d==0, ExcScalarAssignmentOnlyForZeroValue()); // flush previously cached elements. this // seems to be necessary since petsc // 2.2.1, at least for parallel vectors // (see test bits/petsc_64) compress (); const int ierr = MatZeroEntries (matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); return *this; } void MatrixBase::set (const unsigned int i, const unsigned int j, const PetscScalar value) { if (last_action != LastAction::insert) { int ierr; ierr = MatAssemblyBegin(matrix,MAT_FLUSH_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = MatAssemblyEnd(matrix,MAT_FLUSH_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); } const signed int petsc_i = i; const signed int petsc_j = j; const int ierr = MatSetValues (matrix, 1, &petsc_i, 1, &petsc_j, &value, INSERT_VALUES); AssertThrow (ierr == 0, ExcPETScError(ierr)); last_action = LastAction::insert; } void MatrixBase::add (const unsigned int i, const unsigned int j, const PetscScalar value) { if (last_action != LastAction::add) { int ierr; ierr = MatAssemblyBegin(matrix,MAT_FLUSH_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = MatAssemblyEnd(matrix,MAT_FLUSH_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); last_action = LastAction::add; } // we have to do above actions in any // case to be consistent with the MPI // communication model (see the // comments in the documentation of // PETScWrappers::MPI::Vector), but we // can save some work if the addend is // zero if (value == 0) return; const signed int petsc_i = i; const signed int petsc_j = j; const int ierr = MatSetValues (matrix, 1, &petsc_i, 1, &petsc_j, &value, ADD_VALUES); AssertThrow (ierr == 0, ExcPETScError(ierr)); } PetscScalar MatrixBase::el (const unsigned int i, const unsigned int j) const { const signed int petsc_i = i; const signed int petsc_j = j; PetscScalar value; const int ierr = MatGetValues (matrix, 1, &petsc_i, 1, &petsc_j, &value); AssertThrow (ierr == 0, ExcPETScError(ierr)); return value; } PetscScalar MatrixBase::diag_element (const unsigned int i) const { Assert (m() == n(), ExcNotQuadratic()); // this doesn't seem to work any // different than any other element return el(i,i); } void MatrixBase::compress () { // flush buffers int ierr; ierr = MatAssemblyBegin (matrix,MAT_FINAL_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = MatAssemblyEnd (matrix,MAT_FINAL_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); // try to compress the representation ierr = MatCompress (matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); } unsigned int MatrixBase::m () const { int n_rows, n_cols; int ierr = MatGetSize (matrix, &n_rows, &n_cols); AssertThrow (ierr == 0, ExcPETScError(ierr)); return n_rows; } unsigned int MatrixBase::n () const { int n_rows, n_cols; int ierr = MatGetSize (matrix, &n_rows, &n_cols); AssertThrow (ierr == 0, ExcPETScError(ierr)); return n_cols; } unsigned int MatrixBase::local_size () const { int n_rows, n_cols; int ierr = MatGetLocalSize (matrix, &n_rows, &n_cols); AssertThrow (ierr == 0, ExcPETScError(ierr)); return n_rows; } std::pair<unsigned int, unsigned int> MatrixBase::local_range () const { int begin, end; const int ierr = MatGetOwnershipRange (static_cast<const Mat &>(matrix), &begin, &end); AssertThrow (ierr == 0, ExcPETScError(ierr)); return std::make_pair (begin, end); } unsigned int MatrixBase::n_nonzero_elements () const { MatInfo mat_info; const int ierr = MatGetInfo (matrix, MAT_GLOBAL_SUM, &mat_info); AssertThrow (ierr == 0, ExcPETScError(ierr)); return static_cast<unsigned int>(mat_info.nz_used); } unsigned int MatrixBase:: row_length (const unsigned int row) const { //TODO: this function will probably only work if compress() was called on the //matrix previously. however, we can't do this here, since it would impose //global communication and one would have to make sure that this function is //called the same number of times from all processors, something that is //unreasonable. there should simply be a way in PETSc to query the number of //entries in a row bypassing the call to compress(), but I can't find one Assert (row < m(), ExcInternalError()); // get a representation of the present // row int ncols; #if (PETSC_VERSION_MAJOR <= 2) && \ ((PETSC_VERSION_MINOR < 2) || \ ((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0))) int *colnums; PetscScalar *values; #else const int *colnums; const PetscScalar *values; #endif //TODO: this is probably horribly inefficient; we should lobby for a way to //query this information from PETSc int ierr; ierr = MatGetRow(*this, row, &ncols, &colnums, &values); Assert (ierr == 0, MatrixBase::ExcPETScError(ierr)); // then restore the matrix and return the // number of columns in this row as // queried previously ierr = MatRestoreRow(*this, row, &ncols, &colnums, &values); AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr)); return ncols; } PetscReal MatrixBase::l1_norm () const { PetscReal result; const int ierr = MatNorm (matrix, NORM_1, &result); AssertThrow (ierr == 0, ExcPETScError(ierr)); return result; } PetscReal MatrixBase::linfty_norm () const { PetscReal result; const int ierr = MatNorm (matrix, NORM_INFINITY, &result); AssertThrow (ierr == 0, ExcPETScError(ierr)); return result; } PetscReal MatrixBase::frobenius_norm () const { PetscReal result; const int ierr = MatNorm (matrix, NORM_FROBENIUS, &result); AssertThrow (ierr == 0, ExcPETScError(ierr)); return result; } MatrixBase & MatrixBase::operator *= (const PetscScalar a) { const int ierr = MatScale (&a, matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); return *this; } MatrixBase & MatrixBase::operator /= (const PetscScalar a) { const PetscScalar factor = 1./a; const int ierr = MatScale (&factor, matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); return *this; } void MatrixBase::vmult (VectorBase &dst, const VectorBase &src) const { Assert (&src != &dst, ExcSourceEqualsDestination()); const int ierr = MatMult (matrix, src, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void MatrixBase::Tvmult (VectorBase &dst, const VectorBase &src) const { Assert (&src != &dst, ExcSourceEqualsDestination()); const int ierr = MatMultTranspose (matrix, src, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void MatrixBase::vmult_add (VectorBase &dst, const VectorBase &src) const { Assert (&src != &dst, ExcSourceEqualsDestination()); const int ierr = MatMultAdd (matrix, src, dst, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void MatrixBase::Tvmult_add (VectorBase &dst, const VectorBase &src) const { Assert (&src != &dst, ExcSourceEqualsDestination()); const int ierr = MatMultTransposeAdd (matrix, src, dst, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } PetscScalar MatrixBase::matrix_norm_square (const VectorBase &v) const { Vector tmp(v.size()); vmult (tmp, v); return tmp*v; } PetscScalar MatrixBase::matrix_scalar_product (const VectorBase &u, const VectorBase &v) const { Vector tmp(v.size()); vmult (tmp, v); return u*tmp; } PetscScalar MatrixBase::residual (VectorBase &dst, const VectorBase &x, const VectorBase &b) const { // avoid the use of a temporary, and // rather do one negation pass more than // necessary vmult (dst, x); dst -= b; dst *= -1; return dst.l2_norm(); } MatrixBase::operator const Mat () const { return matrix; } } #else // On gcc2.95 on Alpha OSF1, the native assembler does not like empty // files, so provide some dummy code namespace { void dummy () {} } #endif // DEAL_II_USE_PETSC
//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2004, 2005 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <lac/petsc_matrix_base.h> #include <lac/petsc_full_matrix.h> #include <lac/petsc_sparse_matrix.h> #include <lac/petsc_parallel_sparse_matrix.h> #include <lac/petsc_vector.h> #ifdef DEAL_II_USE_PETSC namespace PETScWrappers { namespace MatrixIterators { void MatrixBase::const_iterator::Accessor:: visit_present_row () { // if we are asked to visit the // past-the-end line, then simply // release all our caches and go on // with life if (this->a_row == matrix->m()) { colnum_cache.reset (); value_cache.reset (); return; } // otherwise first flush PETSc caches matrix->compress (); // get a representation of the present // row int ncols; #if (PETSC_VERSION_MAJOR <= 2) && \ ((PETSC_VERSION_MINOR < 2) || \ ((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0))) int *colnums; PetscScalar *values; #else const int *colnums; const PetscScalar *values; #endif int ierr; ierr = MatGetRow(*matrix, this->a_row, &ncols, &colnums, &values); AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr)); // copy it into our caches if the line // isn't empty. if it is, then we've // done something wrong, since we // shouldn't have initialized an // iterator for an empty line (what // would it point to?) Assert (ncols != 0, ExcInternalError()); colnum_cache.reset (new std::vector<unsigned int> (colnums, colnums+ncols)); value_cache.reset (new std::vector<PetscScalar> (values, values+ncols)); // and finally restore the matrix ierr = MatRestoreRow(*matrix, this->a_row, &ncols, &colnums, &values); AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr)); } } MatrixBase::MatrixBase () : last_action (LastAction::none) {} MatrixBase::~MatrixBase () { const int ierr = MatDestroy (matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void MatrixBase::clear () { // destroy the matrix... int ierr = MatDestroy (matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); // ...and replace it by an empty // sequential matrix const int m=0, n=0, n_nonzero_per_row=0; ierr = MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, n_nonzero_per_row, 0, &matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); } MatrixBase & MatrixBase::operator = (const double d) { Assert (d==0, ExcScalarAssignmentOnlyForZeroValue()); // flush previously cached elements. this // seems to be necessary since petsc // 2.2.1, at least for parallel vectors // (see test bits/petsc_64) compress (); const int ierr = MatZeroEntries (matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); return *this; } void MatrixBase::set (const unsigned int i, const unsigned int j, const PetscScalar value) { if (last_action != LastAction::insert) { int ierr; ierr = MatAssemblyBegin(matrix,MAT_FLUSH_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = MatAssemblyEnd(matrix,MAT_FLUSH_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); } const signed int petsc_i = i; const signed int petsc_j = j; const int ierr = MatSetValues (matrix, 1, &petsc_i, 1, &petsc_j, &value, INSERT_VALUES); AssertThrow (ierr == 0, ExcPETScError(ierr)); last_action = LastAction::insert; } void MatrixBase::add (const unsigned int i, const unsigned int j, const PetscScalar value) { if (last_action != LastAction::add) { int ierr; ierr = MatAssemblyBegin(matrix,MAT_FLUSH_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = MatAssemblyEnd(matrix,MAT_FLUSH_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); last_action = LastAction::add; } // we have to do above actions in any // case to be consistent with the MPI // communication model (see the // comments in the documentation of // PETScWrappers::MPI::Vector), but we // can save some work if the addend is // zero if (value == 0) return; const signed int petsc_i = i; const signed int petsc_j = j; const int ierr = MatSetValues (matrix, 1, &petsc_i, 1, &petsc_j, &value, ADD_VALUES); AssertThrow (ierr == 0, ExcPETScError(ierr)); } PetscScalar MatrixBase::el (const unsigned int i, const unsigned int j) const { const signed int petsc_i = i; const signed int petsc_j = j; PetscScalar value; const int ierr = MatGetValues (matrix, 1, &petsc_i, 1, &petsc_j, &value); AssertThrow (ierr == 0, ExcPETScError(ierr)); return value; } PetscScalar MatrixBase::diag_element (const unsigned int i) const { Assert (m() == n(), ExcNotQuadratic()); // this doesn't seem to work any // different than any other element return el(i,i); } void MatrixBase::compress () { // flush buffers int ierr; ierr = MatAssemblyBegin (matrix,MAT_FINAL_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); ierr = MatAssemblyEnd (matrix,MAT_FINAL_ASSEMBLY); AssertThrow (ierr == 0, ExcPETScError(ierr)); // try to compress the representation ierr = MatCompress (matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); } unsigned int MatrixBase::m () const { int n_rows, n_cols; int ierr = MatGetSize (matrix, &n_rows, &n_cols); AssertThrow (ierr == 0, ExcPETScError(ierr)); return n_rows; } unsigned int MatrixBase::n () const { int n_rows, n_cols; int ierr = MatGetSize (matrix, &n_rows, &n_cols); AssertThrow (ierr == 0, ExcPETScError(ierr)); return n_cols; } unsigned int MatrixBase::local_size () const { int n_rows, n_cols; int ierr = MatGetLocalSize (matrix, &n_rows, &n_cols); AssertThrow (ierr == 0, ExcPETScError(ierr)); return n_rows; } std::pair<unsigned int, unsigned int> MatrixBase::local_range () const { int begin, end; const int ierr = MatGetOwnershipRange (static_cast<const Mat &>(matrix), &begin, &end); AssertThrow (ierr == 0, ExcPETScError(ierr)); return std::make_pair (begin, end); } unsigned int MatrixBase::n_nonzero_elements () const { MatInfo mat_info; const int ierr = MatGetInfo (matrix, MAT_GLOBAL_SUM, &mat_info); AssertThrow (ierr == 0, ExcPETScError(ierr)); return static_cast<unsigned int>(mat_info.nz_used); } unsigned int MatrixBase:: row_length (const unsigned int row) const { //TODO: this function will probably only work if compress() was called on the //matrix previously. however, we can't do this here, since it would impose //global communication and one would have to make sure that this function is //called the same number of times from all processors, something that is //unreasonable. there should simply be a way in PETSc to query the number of //entries in a row bypassing the call to compress(), but I can't find one Assert (row < m(), ExcInternalError()); // get a representation of the present // row int ncols; #if (PETSC_VERSION_MAJOR <= 2) && \ ((PETSC_VERSION_MINOR < 2) || \ ((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0))) int *colnums; PetscScalar *values; #else const int *colnums; const PetscScalar *values; #endif //TODO: this is probably horribly inefficient; we should lobby for a way to //query this information from PETSc int ierr; ierr = MatGetRow(*this, row, &ncols, &colnums, &values); AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr)); // then restore the matrix and return the // number of columns in this row as // queried previously ierr = MatRestoreRow(*this, row, &ncols, &colnums, &values); AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr)); return ncols; } PetscReal MatrixBase::l1_norm () const { PetscReal result; const int ierr = MatNorm (matrix, NORM_1, &result); AssertThrow (ierr == 0, ExcPETScError(ierr)); return result; } PetscReal MatrixBase::linfty_norm () const { PetscReal result; const int ierr = MatNorm (matrix, NORM_INFINITY, &result); AssertThrow (ierr == 0, ExcPETScError(ierr)); return result; } PetscReal MatrixBase::frobenius_norm () const { PetscReal result; const int ierr = MatNorm (matrix, NORM_FROBENIUS, &result); AssertThrow (ierr == 0, ExcPETScError(ierr)); return result; } MatrixBase & MatrixBase::operator *= (const PetscScalar a) { const int ierr = MatScale (&a, matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); return *this; } MatrixBase & MatrixBase::operator /= (const PetscScalar a) { const PetscScalar factor = 1./a; const int ierr = MatScale (&factor, matrix); AssertThrow (ierr == 0, ExcPETScError(ierr)); return *this; } void MatrixBase::vmult (VectorBase &dst, const VectorBase &src) const { Assert (&src != &dst, ExcSourceEqualsDestination()); const int ierr = MatMult (matrix, src, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void MatrixBase::Tvmult (VectorBase &dst, const VectorBase &src) const { Assert (&src != &dst, ExcSourceEqualsDestination()); const int ierr = MatMultTranspose (matrix, src, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void MatrixBase::vmult_add (VectorBase &dst, const VectorBase &src) const { Assert (&src != &dst, ExcSourceEqualsDestination()); const int ierr = MatMultAdd (matrix, src, dst, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } void MatrixBase::Tvmult_add (VectorBase &dst, const VectorBase &src) const { Assert (&src != &dst, ExcSourceEqualsDestination()); const int ierr = MatMultTransposeAdd (matrix, src, dst, dst); AssertThrow (ierr == 0, ExcPETScError(ierr)); } PetscScalar MatrixBase::matrix_norm_square (const VectorBase &v) const { Vector tmp(v.size()); vmult (tmp, v); return tmp*v; } PetscScalar MatrixBase::matrix_scalar_product (const VectorBase &u, const VectorBase &v) const { Vector tmp(v.size()); vmult (tmp, v); return u*tmp; } PetscScalar MatrixBase::residual (VectorBase &dst, const VectorBase &x, const VectorBase &b) const { // avoid the use of a temporary, and // rather do one negation pass more than // necessary vmult (dst, x); dst -= b; dst *= -1; return dst.l2_norm(); } MatrixBase::operator const Mat () const { return matrix; } } #else // On gcc2.95 on Alpha OSF1, the native assembler does not like empty // files, so provide some dummy code namespace { void dummy () {} } #endif // DEAL_II_USE_PETSC
Make something an AssertThrow again that needs to be.
Make something an AssertThrow again that needs to be. git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@10605 0785d39b-7218-0410-832d-ea1e28bc413d
C++
lgpl-2.1
naliboff/dealii,pesser/dealii,sriharisundar/dealii,maieneuro/dealii,andreamola/dealii,kalj/dealii,pesser/dealii,natashasharma/dealii,lpolster/dealii,naliboff/dealii,ESeNonFossiIo/dealii,flow123d/dealii,kalj/dealii,maieneuro/dealii,maieneuro/dealii,shakirbsm/dealii,pesser/dealii,JaeryunYim/dealii,mtezzele/dealii,angelrca/dealii,YongYang86/dealii,sriharisundar/dealii,jperryhouts/dealii,shakirbsm/dealii,lue/dealii,lue/dealii,gpitton/dealii,lue/dealii,nicolacavallini/dealii,gpitton/dealii,ESeNonFossiIo/dealii,mac-a/dealii,Arezou-gh/dealii,sriharisundar/dealii,rrgrove6/dealii,ibkim11/dealii,shakirbsm/dealii,EGP-CIG-REU/dealii,danshapero/dealii,nicolacavallini/dealii,YongYang86/dealii,EGP-CIG-REU/dealii,sriharisundar/dealii,danshapero/dealii,Arezou-gh/dealii,mac-a/dealii,pesser/dealii,Arezou-gh/dealii,naliboff/dealii,nicolacavallini/dealii,Arezou-gh/dealii,maieneuro/dealii,flow123d/dealii,sairajat/dealii,natashasharma/dealii,lue/dealii,lpolster/dealii,flow123d/dealii,maieneuro/dealii,rrgrove6/dealii,flow123d/dealii,flow123d/dealii,ESeNonFossiIo/dealii,johntfoster/dealii,YongYang86/dealii,EGP-CIG-REU/dealii,maieneuro/dealii,msteigemann/dealii,jperryhouts/dealii,natashasharma/dealii,YongYang86/dealii,lpolster/dealii,rrgrove6/dealii,rrgrove6/dealii,JaeryunYim/dealii,jperryhouts/dealii,angelrca/dealii,pesser/dealii,sairajat/dealii,natashasharma/dealii,mtezzele/dealii,sairajat/dealii,kalj/dealii,EGP-CIG-REU/dealii,msteigemann/dealii,ESeNonFossiIo/dealii,angelrca/dealii,adamkosik/dealii,mac-a/dealii,JaeryunYim/dealii,sairajat/dealii,spco/dealii,flow123d/dealii,spco/dealii,jperryhouts/dealii,EGP-CIG-REU/dealii,rrgrove6/dealii,naliboff/dealii,shakirbsm/dealii,ESeNonFossiIo/dealii,nicolacavallini/dealii,lue/dealii,mtezzele/dealii,adamkosik/dealii,spco/dealii,JaeryunYim/dealii,JaeryunYim/dealii,andreamola/dealii,danshapero/dealii,kalj/dealii,lue/dealii,kalj/dealii,adamkosik/dealii,mac-a/dealii,msteigemann/dealii,ibkim11/dealii,spco/dealii,gpitton/dealii,rrgrove6/dealii,johntfoster/dealii,nicolacavallini/dealii,shakirbsm/dealii,ibkim11/dealii,johntfoster/dealii,danshapero/dealii,naliboff/dealii,pesser/dealii,angelrca/dealii,lpolster/dealii,johntfoster/dealii,EGP-CIG-REU/dealii,jperryhouts/dealii,nicolacavallini/dealii,sriharisundar/dealii,gpitton/dealii,mtezzele/dealii,natashasharma/dealii,JaeryunYim/dealii,andreamola/dealii,flow123d/dealii,msteigemann/dealii,ESeNonFossiIo/dealii,Arezou-gh/dealii,adamkosik/dealii,lue/dealii,ibkim11/dealii,EGP-CIG-REU/dealii,mtezzele/dealii,naliboff/dealii,lpolster/dealii,lpolster/dealii,naliboff/dealii,adamkosik/dealii,ESeNonFossiIo/dealii,ibkim11/dealii,pesser/dealii,sairajat/dealii,angelrca/dealii,sairajat/dealii,andreamola/dealii,johntfoster/dealii,spco/dealii,angelrca/dealii,sairajat/dealii,msteigemann/dealii,mac-a/dealii,mtezzele/dealii,johntfoster/dealii,jperryhouts/dealii,johntfoster/dealii,Arezou-gh/dealii,andreamola/dealii,Arezou-gh/dealii,nicolacavallini/dealii,shakirbsm/dealii,rrgrove6/dealii,mac-a/dealii,danshapero/dealii,maieneuro/dealii,gpitton/dealii,kalj/dealii,danshapero/dealii,spco/dealii,ibkim11/dealii,msteigemann/dealii,angelrca/dealii,kalj/dealii,YongYang86/dealii,gpitton/dealii,andreamola/dealii,danshapero/dealii,JaeryunYim/dealii,natashasharma/dealii,jperryhouts/dealii,natashasharma/dealii,sriharisundar/dealii,adamkosik/dealii,lpolster/dealii,andreamola/dealii,msteigemann/dealii,adamkosik/dealii,gpitton/dealii,shakirbsm/dealii,YongYang86/dealii,sriharisundar/dealii,mtezzele/dealii,YongYang86/dealii,mac-a/dealii,ibkim11/dealii,spco/dealii
d9ae637306b20374cb237303116517d7cb48acef
xchainer/python/array.cc
xchainer/python/array.cc
#include "xchainer/python/array.h" #include <algorithm> #include <cstdint> #include <string> #include <vector> #include <pybind11/numpy.h> #include <pybind11/operators.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_index.h" #include "xchainer/constant.h" #include "xchainer/context.h" #include "xchainer/device.h" #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/indexable_array.h" #include "xchainer/indexer.h" #include "xchainer/slice.h" #include "xchainer/python/array_index.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; namespace { // TODO(beam2d): The current binding has an overhead on wrapping ArrayBodyPtr by Array, which copies shared_ptr. One // simple way to avoid this overhead is to use reinterpret_cast<Array&>(ptr). This cast is valid if ArrayBodyPtr (i.e., // shared_ptr) satisfies "standard layout" conditions. We can test if ArrayBodyPtr satisfies these conditions by // std::is_standard_layout (see http://en.cppreference.com/w/cpp/types/is_standard_layout#Notes). using ArrayBodyPtr = std::shared_ptr<internal::ArrayBody>; using ConstArrayBodyPtr = std::shared_ptr<const internal::ArrayBody>; Dtype NumpyDtypeToDtype(const py::dtype& npdtype) { switch (npdtype.kind()) { case 'b': return Dtype::kBool; case 'i': switch (npdtype.itemsize()) { case 1: return Dtype::kInt8; case 2: return Dtype::kInt16; case 4: return Dtype::kInt32; case 8: return Dtype::kInt64; default: break; } break; case 'u': switch (npdtype.itemsize()) { case 1: return Dtype::kUInt8; default: break; } break; case 'f': switch (npdtype.itemsize()) { case 4: return Dtype::kFloat32; case 8: return Dtype::kFloat64; default: break; } break; default: break; } throw DtypeError("unsupported NumPy dtype"); } Device& GetDevice(const nonstd::optional<std::string>& device_id) { return device_id.has_value() ? GetDefaultContext().GetDevice(device_id.value()) : GetDefaultDevice(); } ArrayBodyPtr MakeArray(const Shape& shape, Dtype dtype, py::list list, const nonstd::optional<std::string>& device_id) { auto total_size = shape.GetTotalSize(); auto bytes = GetElementSize(dtype) * total_size; if (static_cast<size_t>(total_size) != list.size()) { throw DimensionError("Invalid data length"); } // Allocate a buffer and copy data std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes); VisitDtype(dtype, [&](auto pt) { using T = typename decltype(pt)::type; std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); }); }); return Array::FromBuffer(shape, dtype, ptr, GetDevice(device_id)).move_body(); } ArrayBodyPtr MakeArray(py::array array, const nonstd::optional<std::string>& device_id) { if ((array.flags() & py::array::c_style) == 0) { throw DimensionError("cannot convert non-contiguous NumPy array to Array"); } Dtype dtype = NumpyDtypeToDtype(array.dtype()); py::buffer_info info = array.request(); Shape shape(info.shape); // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released void* underlying_data = array.mutable_data(); std::shared_ptr<void> data{std::make_shared<py::array>(std::move(array)), underlying_data}; return Array::FromBuffer(shape, dtype, data, GetDevice(device_id)).move_body(); } py::buffer_info MakeNumpyArrayFromArray(internal::ArrayBody& self) { // Used as a temporary accessor Array array{std::move(ArrayBodyPtr(&self, [](internal::ArrayBody* ptr) { (void)ptr; // unused }))}; return py::buffer_info( array.data().get(), array.element_bytes(), std::string(1, GetCharCode(array.dtype())), array.ndim(), array.shape(), array.strides()); } } // namespace void InitXchainerArray(pybind11::module& m) { py::class_<internal::ArrayBody, ArrayBodyPtr>{m, "Array", py::buffer_protocol()} .def(py::init(py::overload_cast<const Shape&, Dtype, py::list, const nonstd::optional<std::string>&>(&MakeArray)), py::arg("shape"), py::arg("dtype"), py::arg("data"), py::arg("device") = nullptr) .def(py::init(py::overload_cast<py::array, const nonstd::optional<std::string>&>(&MakeArray)), py::arg("data"), py::arg("device") = nullptr) .def_buffer(&MakeNumpyArrayFromArray) .def("view", [](const ArrayBodyPtr& self) { // Duplicate the array body return std::make_shared<internal::ArrayBody>(*self); }) .def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); }) .def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); }) .def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); }) .def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); }) .def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); }) .def("__getitem__", [](const ArrayBodyPtr& self, py::handle handle) { return Array{self}.At(python::internal::MakeArrayIndices(handle)).move_body(); }) .def("to_device", [](const ArrayBodyPtr& self, Device& device) { return Array{self}.ToDevice(device).move_body(); }) .def("to_device", [](const ArrayBodyPtr& self, const std::string& device_name) { Device& device = GetDefaultContext().GetDevice({device_name}); return Array{self}.ToDevice(device).move_body(); }) .def("to_device", [](const ArrayBodyPtr& self, const std::string& backend_name, int index) { Device& device = GetDefaultContext().GetDevice({backend_name, index}); return Array{self}.ToDevice(device).move_body(); }) .def("transpose", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); }) .def("reshape", [](const ArrayBodyPtr& self, const Shape& shape) { return Array{self}.Reshape(shape).move_body(); }) .def("reshape", [](const ArrayBodyPtr& self, const std::vector<int64_t>& shape) { return Array{self}.Reshape({shape.begin(), shape.end()}).move_body(); }) .def("reshape", [](const ArrayBodyPtr& self, py::args args) { auto shape = py::cast<std::vector<int64_t>>(args); return Array{self}.Reshape({shape.begin(), shape.end()}).move_body(); }) .def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); }) .def("as_constant", [](const ArrayBodyPtr& self, bool copy) { return Array{self}.AsConstant(copy ? CopyKind::kCopy : CopyKind::kView).move_body(); }, py::arg("copy") = false) .def("as_constant", [](const ArrayBodyPtr& self, const std::vector<GraphId>& graph_ids, bool copy) { return Array{self}.AsConstant(graph_ids, copy ? CopyKind::kCopy : CopyKind::kView).move_body(); }, py::arg().noconvert(), py::arg("copy") = false) .def("require_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.RequireGrad(graph_id).move_body(); }, py::arg("graph_id") = kDefaultGraphId) .def("is_grad_required", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); }, py::arg("graph_id") = kDefaultGraphId) .def("get_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr { const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id); if (!grad.has_value()) { return nullptr; } return grad->body(); }, py::arg("graph_id") = kDefaultGraphId) .def("set_grad", [](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) { Array{self}.SetGrad(Array{grad}, graph_id); }, py::arg("grad"), py::arg("graph_id") = kDefaultGraphId) .def_property( "grad", [](const ArrayBodyPtr& self) -> ConstArrayBodyPtr { const nonstd::optional<Array>& grad = Array{self}.GetGrad(kDefaultGraphId); if (!grad.has_value()) { return nullptr; } return grad->body(); }, [](const ArrayBodyPtr& self, const ArrayBodyPtr& grad) { auto array = Array{self}; if (grad) { array.SetGrad(Array{grad}, kDefaultGraphId); } else { array.ClearGrad(kDefaultGraphId); } }) .def("cleargrad", [](const ArrayBodyPtr& self, const GraphId& graph_id) { Array{self}.ClearGrad(graph_id); }, py::arg("graph_id") = kDefaultGraphId) .def_property_readonly( "device", [](const ArrayBodyPtr& self) -> Device& { return Array{self}.device(); }, py::return_value_policy::reference) .def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); }) .def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); }) .def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.IsContiguous(); }) .def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); }) .def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); }) .def_property_readonly("shape", [](const ArrayBodyPtr& self) { return Array{self}.shape(); }) .def_property_readonly("strides", [](const ArrayBodyPtr& self) { return Array{self}.strides(); }) .def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalBytes(); }) .def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalSize(); }) .def_property_readonly("T", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); }) .def_property_readonly( "_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing [](const ArrayBodyPtr& self) -> intptr_t { const void* ptr = Array{self}.data().get(); return reinterpret_cast<intptr_t>(ptr); // NOLINT: reinterpret_cast }) .def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) { py::list list; Array array{self}; // Copy data into the list VisitDtype(array.dtype(), [&array, &list](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{array}; Indexer<> indexer{array.shape()}; for (int64_t i = 0; i < indexer.total_size(); ++i) { indexer.Set(i); list.append(iarray[indexer]); } }); return list; }); m.def("empty", [](const Shape& shape, Dtype dtype, const nonstd::optional<std::string>& device_id) { return Array::Empty(shape, dtype, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("dtype"), py::arg("device") = nullptr) .def("full", [](const Shape& shape, Scalar value, Dtype dtype, const nonstd::optional<std::string>& device_id) { return Array::Full(shape, value, dtype, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("value"), py::arg("dtype"), py::arg("device") = nullptr) .def("full", [](const Shape& shape, Scalar value, const nonstd::optional<std::string>& device_id) { return Array::Full(shape, value, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("value"), py::arg("device") = nullptr) .def("zeros", [](const Shape& shape, Dtype dtype, const nonstd::optional<std::string>& device_id) { return Array::Zeros(shape, dtype, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("dtype"), py::arg("device") = nullptr) .def("ones", [](const Shape& shape, Dtype dtype, const nonstd::optional<std::string>& device_id) { return Array::Ones(shape, dtype, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("dtype"), py::arg("device") = nullptr) .def("empty_like", [](const ArrayBodyPtr& other, const nonstd::optional<std::string>& device_id) { return Array::EmptyLike(Array{other}, GetDevice(device_id)).move_body(); }, py::arg("other"), py::arg("device") = nullptr) .def("full_like", [](const ArrayBodyPtr& other, Scalar value, const nonstd::optional<std::string>& device_id) { return Array::FullLike(Array{other}, value, GetDevice(device_id)).move_body(); }, py::arg("other"), py::arg("value"), py::arg("device") = nullptr) .def("zeros_like", [](const ArrayBodyPtr& other, const nonstd::optional<std::string>& device_id) { return Array::ZerosLike(Array{other}, GetDevice(device_id)).move_body(); }, py::arg("other"), py::arg("device") = nullptr) .def("ones_like", [](const ArrayBodyPtr& other, const nonstd::optional<std::string>& device_id) { return Array::OnesLike(Array{other}, GetDevice(device_id)).move_body(); }, py::arg("other"), py::arg("device") = nullptr); } } // namespace xchainer
#include "xchainer/python/array.h" #include <algorithm> #include <cstdint> #include <string> #include <vector> #include <pybind11/numpy.h> #include <pybind11/operators.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/array_index.h" #include "xchainer/constant.h" #include "xchainer/context.h" #include "xchainer/device.h" #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/indexable_array.h" #include "xchainer/indexer.h" #include "xchainer/slice.h" #include "xchainer/python/array_index.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; namespace { // TODO(beam2d): The current binding has an overhead on wrapping ArrayBodyPtr by Array, which copies shared_ptr. One // simple way to avoid this overhead is to use reinterpret_cast<Array&>(ptr). This cast is valid if ArrayBodyPtr (i.e., // shared_ptr) satisfies "standard layout" conditions. We can test if ArrayBodyPtr satisfies these conditions by // std::is_standard_layout (see http://en.cppreference.com/w/cpp/types/is_standard_layout#Notes). using ArrayBodyPtr = std::shared_ptr<internal::ArrayBody>; using ConstArrayBodyPtr = std::shared_ptr<const internal::ArrayBody>; Dtype NumpyDtypeToDtype(const py::dtype& npdtype) { switch (npdtype.kind()) { case 'b': return Dtype::kBool; case 'i': switch (npdtype.itemsize()) { case 1: return Dtype::kInt8; case 2: return Dtype::kInt16; case 4: return Dtype::kInt32; case 8: return Dtype::kInt64; default: break; } break; case 'u': switch (npdtype.itemsize()) { case 1: return Dtype::kUInt8; default: break; } break; case 'f': switch (npdtype.itemsize()) { case 4: return Dtype::kFloat32; case 8: return Dtype::kFloat64; default: break; } break; default: break; } throw DtypeError("unsupported NumPy dtype"); } Device& GetDevice(const nonstd::optional<std::string>& device_id) { return device_id.has_value() ? GetDefaultContext().GetDevice(device_id.value()) : GetDefaultDevice(); } ArrayBodyPtr MakeArray(const Shape& shape, Dtype dtype, py::list list, const nonstd::optional<std::string>& device_id) { auto total_size = shape.GetTotalSize(); auto bytes = GetElementSize(dtype) * total_size; if (static_cast<size_t>(total_size) != list.size()) { throw DimensionError("Invalid data length"); } // Allocate a buffer and copy data std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes); VisitDtype(dtype, [&](auto pt) { using T = typename decltype(pt)::type; std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); }); }); return Array::FromBuffer(shape, dtype, ptr, GetDevice(device_id)).move_body(); } ArrayBodyPtr MakeArray(py::array array, const nonstd::optional<std::string>& device_id) { if ((array.flags() & py::array::c_style) == 0) { throw DimensionError("cannot convert non-contiguous NumPy array to Array"); } Dtype dtype = NumpyDtypeToDtype(array.dtype()); py::buffer_info info = array.request(); Shape shape(info.shape); // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released void* underlying_data = array.mutable_data(); std::shared_ptr<void> data{std::make_shared<py::array>(std::move(array)), underlying_data}; return Array::FromBuffer(shape, dtype, data, GetDevice(device_id)).move_body(); } py::buffer_info MakeNumpyArrayFromArray(internal::ArrayBody& self) { // Used as a temporary accessor Array array{std::move(ArrayBodyPtr(&self, [](internal::ArrayBody* ptr) { (void)ptr; // unused }))}; return py::buffer_info( array.data().get(), array.element_bytes(), std::string(1, GetCharCode(array.dtype())), array.ndim(), array.shape(), array.strides()); } } // namespace void InitXchainerArray(pybind11::module& m) { py::class_<internal::ArrayBody, ArrayBodyPtr>{m, "Array", py::buffer_protocol()} .def(py::init(py::overload_cast<const Shape&, Dtype, py::list, const nonstd::optional<std::string>&>(&MakeArray)), py::arg("shape"), py::arg("dtype"), py::arg("data"), py::arg("device") = nullptr) .def(py::init(py::overload_cast<py::array, const nonstd::optional<std::string>&>(&MakeArray)), py::arg("data"), py::arg("device") = nullptr) .def_buffer(&MakeNumpyArrayFromArray) .def("view", [](const ArrayBodyPtr& self) { // Duplicate the array body return std::make_shared<internal::ArrayBody>(*self); }) .def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); }) .def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); }) .def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); }) .def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); }) .def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); }) .def("__getitem__", [](const ArrayBodyPtr& self, py::handle handle) { return Array{self}.At(python::internal::MakeArrayIndices(handle)).move_body(); }) .def("to_device", [](const ArrayBodyPtr& self, Device& device) { return Array{self}.ToDevice(device).move_body(); }) .def("to_device", [](const ArrayBodyPtr& self, const std::string& device_name) { Device& device = GetDefaultContext().GetDevice({device_name}); return Array{self}.ToDevice(device).move_body(); }) .def("to_device", [](const ArrayBodyPtr& self, const std::string& backend_name, int index) { Device& device = GetDefaultContext().GetDevice({backend_name, index}); return Array{self}.ToDevice(device).move_body(); }) .def("transpose", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); }) .def("reshape", [](const ArrayBodyPtr& self, const Shape& shape) { return Array{self}.Reshape(shape).move_body(); }) .def("reshape", [](const ArrayBodyPtr& self, const std::vector<int64_t>& shape) { return Array{self}.Reshape({shape.begin(), shape.end()}).move_body(); }) .def("reshape", [](const ArrayBodyPtr& self, py::args args) { auto shape = py::cast<std::vector<int64_t>>(args); return Array{self}.Reshape({shape.begin(), shape.end()}).move_body(); }) .def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); }) .def("as_constant", [](const ArrayBodyPtr& self, bool copy) { return Array{self}.AsConstant(copy ? CopyKind::kCopy : CopyKind::kView).move_body(); }, py::arg("copy") = false) .def("as_constant", [](const ArrayBodyPtr& self, const std::vector<GraphId>& graph_ids, bool copy) { return Array{self}.AsConstant(graph_ids, copy ? CopyKind::kCopy : CopyKind::kView).move_body(); }, py::arg().noconvert(), py::arg("copy") = false) .def("require_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.RequireGrad(graph_id).move_body(); }, py::arg("graph_id") = kDefaultGraphId) .def("is_grad_required", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); }, py::arg("graph_id") = kDefaultGraphId) .def("get_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr { const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id); if (!grad.has_value()) { return nullptr; } return grad->body(); }, py::arg("graph_id") = kDefaultGraphId) .def("set_grad", [](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) { auto array = Array{self}; if (grad) { array.SetGrad(Array{grad}, graph_id); } else { array.ClearGrad(graph_id); } }, py::arg("grad"), py::arg("graph_id") = kDefaultGraphId) .def_property( "grad", [](const ArrayBodyPtr& self) -> ConstArrayBodyPtr { const nonstd::optional<Array>& grad = Array{self}.GetGrad(kDefaultGraphId); if (!grad.has_value()) { return nullptr; } return grad->body(); }, [](const ArrayBodyPtr& self, const ArrayBodyPtr& grad) { auto array = Array{self}; if (grad) { array.SetGrad(Array{grad}, kDefaultGraphId); } else { array.ClearGrad(kDefaultGraphId); } }) .def("cleargrad", [](const ArrayBodyPtr& self, const GraphId& graph_id) { Array{self}.ClearGrad(graph_id); }, py::arg("graph_id") = kDefaultGraphId) .def_property_readonly( "device", [](const ArrayBodyPtr& self) -> Device& { return Array{self}.device(); }, py::return_value_policy::reference) .def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); }) .def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); }) .def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.IsContiguous(); }) .def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); }) .def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); }) .def_property_readonly("shape", [](const ArrayBodyPtr& self) { return Array{self}.shape(); }) .def_property_readonly("strides", [](const ArrayBodyPtr& self) { return Array{self}.strides(); }) .def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalBytes(); }) .def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.GetTotalSize(); }) .def_property_readonly("T", [](const ArrayBodyPtr& self) { return Array{self}.Transpose().move_body(); }) .def_property_readonly( "_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing [](const ArrayBodyPtr& self) -> intptr_t { const void* ptr = Array{self}.data().get(); return reinterpret_cast<intptr_t>(ptr); // NOLINT: reinterpret_cast }) .def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) { py::list list; Array array{self}; // Copy data into the list VisitDtype(array.dtype(), [&array, &list](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T> iarray{array}; Indexer<> indexer{array.shape()}; for (int64_t i = 0; i < indexer.total_size(); ++i) { indexer.Set(i); list.append(iarray[indexer]); } }); return list; }); m.def("empty", [](const Shape& shape, Dtype dtype, const nonstd::optional<std::string>& device_id) { return Array::Empty(shape, dtype, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("dtype"), py::arg("device") = nullptr) .def("full", [](const Shape& shape, Scalar value, Dtype dtype, const nonstd::optional<std::string>& device_id) { return Array::Full(shape, value, dtype, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("value"), py::arg("dtype"), py::arg("device") = nullptr) .def("full", [](const Shape& shape, Scalar value, const nonstd::optional<std::string>& device_id) { return Array::Full(shape, value, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("value"), py::arg("device") = nullptr) .def("zeros", [](const Shape& shape, Dtype dtype, const nonstd::optional<std::string>& device_id) { return Array::Zeros(shape, dtype, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("dtype"), py::arg("device") = nullptr) .def("ones", [](const Shape& shape, Dtype dtype, const nonstd::optional<std::string>& device_id) { return Array::Ones(shape, dtype, GetDevice(device_id)).move_body(); }, py::arg("shape"), py::arg("dtype"), py::arg("device") = nullptr) .def("empty_like", [](const ArrayBodyPtr& other, const nonstd::optional<std::string>& device_id) { return Array::EmptyLike(Array{other}, GetDevice(device_id)).move_body(); }, py::arg("other"), py::arg("device") = nullptr) .def("full_like", [](const ArrayBodyPtr& other, Scalar value, const nonstd::optional<std::string>& device_id) { return Array::FullLike(Array{other}, value, GetDevice(device_id)).move_body(); }, py::arg("other"), py::arg("value"), py::arg("device") = nullptr) .def("zeros_like", [](const ArrayBodyPtr& other, const nonstd::optional<std::string>& device_id) { return Array::ZerosLike(Array{other}, GetDevice(device_id)).move_body(); }, py::arg("other"), py::arg("device") = nullptr) .def("ones_like", [](const ArrayBodyPtr& other, const nonstd::optional<std::string>& device_id) { return Array::OnesLike(Array{other}, GetDevice(device_id)).move_body(); }, py::arg("other"), py::arg("device") = nullptr); } } // namespace xchainer
Add old behavior back
Add old behavior back
C++
mit
pfnet/chainer,ktnyt/chainer,keisuke-umezawa/chainer,hvy/chainer,niboshi/chainer,jnishi/chainer,wkentaro/chainer,ktnyt/chainer,niboshi/chainer,niboshi/chainer,jnishi/chainer,chainer/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,hvy/chainer,wkentaro/chainer,jnishi/chainer,chainer/chainer,niboshi/chainer,hvy/chainer,ktnyt/chainer,tkerola/chainer,okuta/chainer,keisuke-umezawa/chainer,okuta/chainer,chainer/chainer,hvy/chainer,okuta/chainer,wkentaro/chainer,chainer/chainer,okuta/chainer,jnishi/chainer,wkentaro/chainer,ktnyt/chainer
c4e1851f4284e21d65177185382bfbfc173070c5
util/ddv_socket.cpp
util/ddv_socket.cpp
#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h> bool socketError = false; int DDV_Listen(int port){ int s = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port);//port 8888 inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port if (ret == 0){ ret = listen(s, 100);//start listening, backlog of 100 allowed if (ret == 0){ return s; }else{ printf("Listen failed! Error: %s\n", strerror(errno)); close(s); return 0; } }else{ printf("Binding failed! Error: %s\n", strerror(errno)); close(s); return 0; } } int DDV_Accept(int sock){ return accept(sock, 0, 0); } bool DDV_write(void * buffer, int width, int count, int sock){ int sofar = 0; int todo = width*count; while (sofar != todo){ int r = send(sock, (char*)buffer + sofar, todo-sofar, 0); if (r < 0){ socketError = true; printf("Could not write! %s\n", strerror(errno)); return false; } sofar += r; } return true; } bool DDV_read(void * buffer, int width, int count, int sock){ int sofar = 0; int todo = width*count; while (sofar != todo){ int r = recv(sock, (char*)buffer + sofar, todo-sofar, 0); if (r < 0){ socketError = true; printf("Could not read! %s\n", strerror(errno)); return false; } sofar += r; } return true; }
#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h> bool socketError = false; int DDV_Listen(int port){ int s = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port);//port 8888 inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);//listen on all interfaces int ret = bind(s, (sockaddr*)&addr, sizeof(addr));//bind to all interfaces, chosen port if (ret == 0){ ret = listen(s, 100);//start listening, backlog of 100 allowed if (ret == 0){ return s; }else{ printf("Listen failed! Error: %s\n", strerror(errno)); close(s); return 0; } }else{ printf("Binding failed! Error: %s\n", strerror(errno)); close(s); return 0; } } int DDV_Accept(int sock){ return accept(sock, 0, 0); } bool DDV_write(void * buffer, int width, int count, int sock){ int sofar = 0; int todo = width*count; while (sofar != todo){ int r = send(sock, (char*)buffer + sofar, todo-sofar, 0); if (r <= 0){ socketError = true; printf("Could not write! %s\n", strerror(errno)); return false; } sofar += r; } return true; } bool DDV_read(void * buffer, int width, int count, int sock){ int sofar = 0; int todo = width*count; while (sofar != todo){ int r = recv(sock, (char*)buffer + sofar, todo-sofar, 0); if (r <= 0){ socketError = true; printf("Could not read! %s\n", strerror(errno)); return false; } sofar += r; } return true; }
Fix voor afsluiten verbinding...
Fix voor afsluiten verbinding...
C++
unlicense
rbouqueau/mistserver,rbouqueau/mistserver,DDVTECH/mistserver,rbouqueau/mistserver,DDVTECH/mistserver,rbouqueau/mistserver,DDVTECH/mistserver,rbouqueau/mistserver,DDVTECH/mistserver,DDVTECH/mistserver
1903c56ef8386f9692ec96c7efff5a9f5a91681b
xchainer/python/array.cc
xchainer/python/array.cc
#include "xchainer/python/array.h" #include <algorithm> #include <cstdint> #include <pybind11/numpy.h> #include <pybind11/operators.h> #include "xchainer/array.h" #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; namespace { using ArrayBodyPtr = std::shared_ptr<internal::ArrayBody>; using ConstArrayBodyPtr = std::shared_ptr<const internal::ArrayBody>; Dtype NumpyDtypeToDtype(const py::dtype& npdtype) { switch (npdtype.kind()) { case 'b': return Dtype::kBool; case 'i': switch (npdtype.itemsize()) { case 1: return Dtype::kInt8; case 2: return Dtype::kInt16; case 4: return Dtype::kInt32; case 8: return Dtype::kInt64; default: break; } break; case 'u': switch (npdtype.itemsize()) { case 1: return Dtype::kUInt8; default: break; } break; case 'f': switch (npdtype.itemsize()) { case 4: return Dtype::kFloat32; case 8: return Dtype::kFloat64; default: break; } break; default: break; } throw DtypeError("unsupported NumPy dtype"); } ArrayBodyPtr MakeArray(const Shape& shape, Dtype dtype, py::list list) { auto total_size = shape.total_size(); auto bytes = GetElementSize(dtype) * total_size; if (static_cast<size_t>(total_size) != list.size()) { throw DimensionError("Invalid data length"); } // Allocate a buffer and copy data std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes); VisitDtype(dtype, [&](auto pt) { using T = typename decltype(pt)::type; std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); }); }); return Array::FromBuffer(shape, dtype, ptr).move_body(); } ArrayBodyPtr MakeArray(py::array array) { if ((array.flags() & py::array::c_style) == 0) { throw DimensionError("cannot convert non-contiguous NumPy array to Array"); } Dtype dtype = NumpyDtypeToDtype(array.dtype()); py::buffer_info info = array.request(); Shape shape(info.shape); // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data()); return Array::FromBuffer(shape, dtype, data).move_body(); } py::buffer_info MakeNumpyArrayFromArray(internal::ArrayBody& self) { // Used as a temporary accessor Array array{std::move(ArrayBodyPtr(&self, [](internal::ArrayBody* ptr) { (void)ptr; // unused }))}; if (!array.is_contiguous()) { throw DimensionError("cannot convert non-contiguous Array to NumPy array"); } int64_t itemsize{GetElementSize(array.dtype())}; const Shape& shape = array.shape(); // compute C-contiguous strides size_t ndim = array.ndim(); std::vector<size_t> strides(ndim); if (ndim > 0) { std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>()); strides.back() = 1; std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; }); } return py::buffer_info(array.data().get(), itemsize, std::string(1, GetCharCode(array.dtype())), ndim, shape, strides); } } // namespace void InitXchainerArray(pybind11::module& m) { py::class_<internal::ArrayBody, ArrayBodyPtr>{m, "Array", py::buffer_protocol()} .def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray))) .def(py::init(py::overload_cast<py::array>(&MakeArray))) .def_buffer(&MakeNumpyArrayFromArray) .def("view", [](const ArrayBodyPtr& self) { // Duplicate the array body return std::make_shared<internal::ArrayBody>(*self); }) .def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); }) .def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); }) .def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); }) .def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); }) .def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); }) .def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); }) .def("require_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{Array{self}.RequireGrad(graph_id)}.move_body(); }, py::arg("graph_id") = "") .def("is_grad_required", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); }, py::arg("graph_id") = "") .def("get_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr { if (self->HasNode(graph_id)) { return Array{self}.GetGrad(graph_id)->body(); } else { return nullptr; } }, py::arg("graph_id") = "") .def("set_grad", [](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) { if (grad) { if (self->HasNode(graph_id)) { Array{self}.SetGrad(Array{grad}, graph_id); } else { Array{self}.RequireGrad(graph_id).SetGrad(Array{grad}, graph_id); } } else { Array{self}.ClearGrad(graph_id); } }, py::arg("grad"), py::arg("graph_id") = "") .def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); }) .def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); }) .def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.is_contiguous(); }) .def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); }) .def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); }) .def_property_readonly("shape", [](const ArrayBodyPtr& self) { return Array{self}.shape(); }) .def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.total_bytes(); }) .def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.total_size(); }) .def_property_readonly("_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing [](const ArrayBodyPtr& self) { return reinterpret_cast<std::uintptr_t>(Array{self}.data().get()); }) .def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) { py::list list; Array array{self}; // Copy data into the list VisitDtype(array.dtype(), [&array, &list](auto pt) { using T = typename decltype(pt)::type; auto size = array.total_size(); const T& data = *std::static_pointer_cast<const T>(array.data()); for (int64_t i = 0; i < size; ++i) { list.append((&data)[i]); } }); return list; }); } } // namespace xchainer
#include "xchainer/python/array.h" #include <algorithm> #include <cstdint> #include <pybind11/numpy.h> #include <pybind11/operators.h> #include "xchainer/array.h" #include "xchainer/dtype.h" #include "xchainer/error.h" #include "xchainer/python/common.h" namespace xchainer { namespace py = pybind11; namespace { using ArrayBodyPtr = std::shared_ptr<internal::ArrayBody>; using ConstArrayBodyPtr = std::shared_ptr<const internal::ArrayBody>; Dtype NumpyDtypeToDtype(const py::dtype& npdtype) { switch (npdtype.kind()) { case 'b': return Dtype::kBool; case 'i': switch (npdtype.itemsize()) { case 1: return Dtype::kInt8; case 2: return Dtype::kInt16; case 4: return Dtype::kInt32; case 8: return Dtype::kInt64; default: break; } break; case 'u': switch (npdtype.itemsize()) { case 1: return Dtype::kUInt8; default: break; } break; case 'f': switch (npdtype.itemsize()) { case 4: return Dtype::kFloat32; case 8: return Dtype::kFloat64; default: break; } break; default: break; } throw DtypeError("unsupported NumPy dtype"); } ArrayBodyPtr MakeArray(const Shape& shape, Dtype dtype, py::list list) { auto total_size = shape.total_size(); auto bytes = GetElementSize(dtype) * total_size; if (static_cast<size_t>(total_size) != list.size()) { throw DimensionError("Invalid data length"); } // Allocate a buffer and copy data std::shared_ptr<void> ptr = std::make_unique<uint8_t[]>(bytes); VisitDtype(dtype, [&](auto pt) { using T = typename decltype(pt)::type; std::transform(list.begin(), list.end(), static_cast<T*>(ptr.get()), [](auto& item) { return py::cast<T>(item); }); }); return Array::FromBuffer(shape, dtype, ptr).move_body(); } ArrayBodyPtr MakeArray(py::array array) { if ((array.flags() & py::array::c_style) == 0) { throw DimensionError("cannot convert non-contiguous NumPy array to Array"); } Dtype dtype = NumpyDtypeToDtype(array.dtype()); py::buffer_info info = array.request(); Shape shape(info.shape); // data holds the copy of py::array which in turn references the NumPy array and the buffer is therefore not released std::shared_ptr<void> data(std::make_shared<py::array>(std::move(array)), array.mutable_data()); return Array::FromBuffer(shape, dtype, data).move_body(); } py::buffer_info MakeNumpyArrayFromArray(internal::ArrayBody& self) { // Used as a temporary accessor Array array{std::move(ArrayBodyPtr(&self, [](internal::ArrayBody* ptr) { (void)ptr; // unused }))}; if (!array.is_contiguous()) { throw DimensionError("cannot convert non-contiguous Array to NumPy array"); } int64_t itemsize{GetElementSize(array.dtype())}; const Shape& shape = array.shape(); // compute C-contiguous strides size_t ndim = array.ndim(); std::vector<size_t> strides(ndim); if (ndim > 0) { std::partial_sum(shape.crbegin(), shape.crend() - 1, strides.rbegin() + 1, std::multiplies<size_t>()); strides.back() = 1; std::transform(strides.crbegin(), strides.crend(), strides.rbegin(), [&itemsize](size_t item) { return item * itemsize; }); } return py::buffer_info(array.data().get(), itemsize, std::string(1, GetCharCode(array.dtype())), ndim, shape, strides); } } // namespace void InitXchainerArray(pybind11::module& m) { py::class_<internal::ArrayBody, ArrayBodyPtr>{m, "Array", py::buffer_protocol()} .def(py::init(py::overload_cast<const Shape&, Dtype, py::list>(&MakeArray))) .def(py::init(py::overload_cast<py::array>(&MakeArray))) .def_buffer(&MakeNumpyArrayFromArray) .def("view", [](const ArrayBodyPtr& self) { // Duplicate the array body return std::make_shared<internal::ArrayBody>(*self); }) .def("__iadd__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} += Array{rhs}).move_body(); }) .def("__imul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} *= Array{rhs}).move_body(); }) .def("__add__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} + Array{rhs}).move_body(); }) .def("__mul__", [](const ArrayBodyPtr& self, const ArrayBodyPtr& rhs) { return (Array{self} * Array{rhs}).move_body(); }) .def("__repr__", [](const ArrayBodyPtr& self) { return Array{self}.ToString(); }) .def("copy", [](const ArrayBodyPtr& self) { return Array{self}.Copy().move_body(); }) .def("require_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{Array{self}.RequireGrad(graph_id)}.move_body(); }, py::arg("graph_id") = "") .def("is_grad_required", [](const ArrayBodyPtr& self, const GraphId& graph_id) { return Array{self}.IsGradRequired(graph_id); }, py::arg("graph_id") = "") .def("get_grad", [](const ArrayBodyPtr& self, const GraphId& graph_id) -> ConstArrayBodyPtr { if (self->HasNode(graph_id)) { const nonstd::optional<Array>& grad = Array{self}.GetGrad(graph_id); if (grad.has_value()) { return grad->body(); } else { return nullptr; } } else { return nullptr; } }, py::arg("graph_id") = "") .def("set_grad", [](const ArrayBodyPtr& self, const ArrayBodyPtr& grad, const GraphId& graph_id) { if (grad) { if (self->HasNode(graph_id)) { Array{self}.SetGrad(Array{grad}, graph_id); } else { Array{self}.RequireGrad(graph_id).SetGrad(Array{grad}, graph_id); } } else { Array{self}.ClearGrad(graph_id); } }, py::arg("grad"), py::arg("graph_id") = "") .def_property_readonly("dtype", [](const ArrayBodyPtr& self) { return Array{self}.dtype(); }) .def_property_readonly("element_bytes", [](const ArrayBodyPtr& self) { return Array{self}.element_bytes(); }) .def_property_readonly("is_contiguous", [](const ArrayBodyPtr& self) { return Array{self}.is_contiguous(); }) .def_property_readonly("ndim", [](const ArrayBodyPtr& self) { return Array{self}.ndim(); }) .def_property_readonly("offset", [](const ArrayBodyPtr& self) { return Array{self}.offset(); }) .def_property_readonly("shape", [](const ArrayBodyPtr& self) { return Array{self}.shape(); }) .def_property_readonly("total_bytes", [](const ArrayBodyPtr& self) { return Array{self}.total_bytes(); }) .def_property_readonly("total_size", [](const ArrayBodyPtr& self) { return Array{self}.total_size(); }) .def_property_readonly("_debug_data_memory_address", // These methods starting with `_debug_` are stubs for testing [](const ArrayBodyPtr& self) { return reinterpret_cast<std::uintptr_t>(Array{self}.data().get()); }) .def_property_readonly("_debug_flat_data", [](const ArrayBodyPtr& self) { py::list list; Array array{self}; // Copy data into the list VisitDtype(array.dtype(), [&array, &list](auto pt) { using T = typename decltype(pt)::type; auto size = array.total_size(); const T& data = *std::static_pointer_cast<const T>(array.data()); for (int64_t i = 0; i < size; ++i) { list.append((&data)[i]); } }); return list; }); } } // namespace xchainer
Fix get_grad()
Fix get_grad()
C++
mit
ktnyt/chainer,hvy/chainer,hvy/chainer,okuta/chainer,okuta/chainer,jnishi/chainer,wkentaro/chainer,chainer/chainer,keisuke-umezawa/chainer,ktnyt/chainer,pfnet/chainer,keisuke-umezawa/chainer,niboshi/chainer,okuta/chainer,wkentaro/chainer,okuta/chainer,ktnyt/chainer,jnishi/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,niboshi/chainer,hvy/chainer,ktnyt/chainer,hvy/chainer,chainer/chainer,jnishi/chainer,wkentaro/chainer,wkentaro/chainer,chainer/chainer,tkerola/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,niboshi/chainer
561bd2c5be72b54718ab02048381ed7b37c606d4
xcodec/xcodec_decoder.cc
xcodec/xcodec_decoder.cc
#include <common/buffer.h> #include <common/endian.h> #include <xcodec/xcdb.h> #include <xcodec/xchash.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_decoder.h> XCodecDecoder::XCodecDecoder(XCodec *codec) : log_("/xcodec/decoder"), database_(codec->database_), backref_() { } XCodecDecoder::~XCodecDecoder() { } /* * Decode an XCodec-encoded stream. Returns false if there was an * inconsistency in the stream or something malformed. Returns true * if we were able to process the stream or expect to be able to * once more data arrives. The input buffer is cleared of anything * we can process right now. */ bool XCodecDecoder::decode(Buffer *output, Buffer *input) { BufferSegment *seg, *oseg; uint64_t hash; size_t inlen; uint8_t ch; inlen = input->length(); while (inlen != 0) { ch = input->peek(); while (!XCODEC_CHAR_SPECIAL(ch)) { inlen--; input->skip(1); output->append(ch); if (inlen == 0) break; ch = input->peek(); } ASSERT(inlen == input->length()); if (inlen == 0) break; switch (ch) { /* * A reference to a hash we are expected to have * in our database. */ case XCODEC_HASHREF_CHAR: if (inlen < 9) return (true); input->moveout((uint8_t *)&hash, 1, sizeof hash); hash = LittleEndian::decode(hash); seg = database_->lookup(hash); if (seg == NULL) { ERROR(log_) << "Stream referenced unseen hash: " << hash; return (false); } backref_.declare(hash, seg); output->append(seg); inlen -= 9; break; /* * A literal character will follow that would * otherwise have seemed magic. */ case XCODEC_ESCAPE_CHAR: if (inlen < 2) return (true); input->skip(1); output->append(input->peek()); input->skip(1); inlen -= 2; break; /* * A learning opportunity -- a hash we should put * into our database for future use and the data * it will be used in reference to next time. */ case XCODEC_DECLARE_CHAR: if (inlen < 9 + XCODEC_SEGMENT_LENGTH) return (true); input->moveout((uint8_t *)&hash, 1, sizeof hash); hash = LittleEndian::decode(hash); input->copyout(&seg, XCODEC_SEGMENT_LENGTH); input->skip(XCODEC_SEGMENT_LENGTH); uint64_t shash = XCHash<XCODEC_SEGMENT_LENGTH>::hash(seg->data()); if (shash != hash) { seg->unref(); ERROR(log_) << "Data in stream does not have expected hash. (stream " << shash << " expected " << hash << ")"; return (false); } /* * Chech whether we already know a hash by this name. */ oseg = database_->lookup(hash); if (oseg != NULL) { /* * We already know a hash by this name. Check * whether it is for the same data. That would * be nice. In that case all we need to do is * update the backreference window. */ if (seg->match(oseg)) { seg->unref(); /* * NB: Use the existing segment since * it's nice to share. */ backref_.declare(hash, oseg); oseg->unref(); } else { seg->unref(); oseg->unref(); ERROR(log_) << "Stream includes hash with different local data."; return (false); } } else { /* * This is a brand new hash. Enter it into the * database and the backref window. */ database_->enter(hash, seg); backref_.declare(hash, seg); seg->unref(); } inlen -= 9 + XCODEC_SEGMENT_LENGTH; break; /* * A reference to a recently-used hash. We expect * to see a lot of these whenever we see declarations * since the declarations are desorted in the stream * and are not literally inserted. */ case XCODEC_BACKREF_CHAR: if (inlen < 2) return (true); input->skip(1); ch = input->peek(); input->skip(1); seg = backref_.dereference(ch); if (seg == NULL) { ERROR(log_) << "Stream included invalid backref."; return (false); } output->append(seg); inlen -= 2; break; default: NOTREACHED(); } } return (true); }
#include <common/buffer.h> #include <common/endian.h> #include <xcodec/xcdb.h> #include <xcodec/xchash.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_decoder.h> XCodecDecoder::XCodecDecoder(XCodec *codec) : log_("/xcodec/decoder"), database_(codec->database_), backref_() { } XCodecDecoder::~XCodecDecoder() { } /* * Decode an XCodec-encoded stream. Returns false if there was an * inconsistency in the stream or something malformed. Returns true * if we were able to process the stream or expect to be able to * once more data arrives. The input buffer is cleared of anything * we can process right now. */ bool XCodecDecoder::decode(Buffer *output, Buffer *input) { BufferSegment *seg, *oseg; uint64_t hash; size_t inlen; uint8_t ch; inlen = input->length(); while (inlen != 0) { ch = input->peek(); while (!XCODEC_CHAR_SPECIAL(ch)) { inlen--; input->skip(1); output->append(ch); if (inlen == 0) break; ch = input->peek(); } ASSERT(inlen == input->length()); if (inlen == 0) break; switch (ch) { /* * A reference to a hash we are expected to have * in our database. */ case XCODEC_HASHREF_CHAR: if (inlen < 9) return (true); input->moveout((uint8_t *)&hash, 1, sizeof hash); hash = LittleEndian::decode(hash); seg = database_->lookup(hash); if (seg == NULL) { ERROR(log_) << "Stream referenced unseen hash: " << hash; return (false); } backref_.declare(hash, seg); output->append(seg); inlen -= 9; break; /* * A literal character will follow that would * otherwise have seemed magic. */ case XCODEC_ESCAPE_CHAR: if (inlen < 2) return (true); input->skip(1); output->append(input->peek()); input->skip(1); inlen -= 2; break; /* * A learning opportunity -- a hash we should put * into our database for future use and the data * it will be used in reference to next time. */ case XCODEC_DECLARE_CHAR: if (inlen < 9 + XCODEC_SEGMENT_LENGTH) return (true); input->moveout((uint8_t *)&hash, 1, sizeof hash); hash = LittleEndian::decode(hash); input->copyout(&seg, XCODEC_SEGMENT_LENGTH); input->skip(XCODEC_SEGMENT_LENGTH); if (XCHash<XCODEC_SEGMENT_LENGTH>::hash(seg->data()) != hash) { seg->unref(); ERROR(log_) << "Data in stream does not have expected hash."; return (false); } /* * Chech whether we already know a hash by this name. */ oseg = database_->lookup(hash); if (oseg != NULL) { /* * We already know a hash by this name. Check * whether it is for the same data. That would * be nice. In that case all we need to do is * update the backreference window. */ if (seg->match(oseg)) { seg->unref(); /* * NB: Use the existing segment since * it's nice to share. */ backref_.declare(hash, oseg); oseg->unref(); } else { seg->unref(); oseg->unref(); ERROR(log_) << "Stream includes hash with different local data."; return (false); } } else { /* * This is a brand new hash. Enter it into the * database and the backref window. */ database_->enter(hash, seg); backref_.declare(hash, seg); seg->unref(); } inlen -= 9 + XCODEC_SEGMENT_LENGTH; break; /* * A reference to a recently-used hash. We expect * to see a lot of these whenever we see declarations * since the declarations are desorted in the stream * and are not literally inserted. */ case XCODEC_BACKREF_CHAR: if (inlen < 2) return (true); input->skip(1); ch = input->peek(); input->skip(1); seg = backref_.dereference(ch); if (seg == NULL) { ERROR(log_) << "Stream included invalid backref."; return (false); } output->append(seg); inlen -= 2; break; default: NOTREACHED(); } } return (true); }
Remove hash printing code.
Remove hash printing code.
C++
bsd-2-clause
wanproxy/wanproxy,wanproxy/wanproxy,wanproxy/wanproxy
ee76c4fc3ee512f25ec17fa75152a0d93494fd01
xcodec/xcodec_encoder.cc
xcodec/xcodec_encoder.cc
#include <common/buffer.h> #include <common/endian.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_cache.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_hash.h> struct candidate_symbol { bool set_; unsigned offset_; uint64_t symbol_; }; XCodecEncoder::XCodecEncoder(XCodecCache *cache) : log_("/xcodec/encoder"), cache_(cache), window_() { } XCodecEncoder::~XCodecEncoder() { } /* * This takes a view of a data stream and turns it into a series of references * to other data, declarations of data to be referenced, and data that needs * escaped. */ void XCodecEncoder::encode(Buffer *output, Buffer *input) { if (input->empty()) return; if (input->length() < XCODEC_SEGMENT_LENGTH) { encode_escape(output, input, input->length()); return; } XCodecHash xcodec_hash; candidate_symbol candidate; Buffer outq; unsigned o = 0; candidate.set_ = false; /* * While there is input. */ while (!input->empty()) { /* * If we cannot acquire a complete hash within this segment, * stop looking. */ if (o + input->length() < XCODEC_SEGMENT_LENGTH) { DEBUG(log_) << "Buffer couldn't yield a hash."; outq.append(input); input->clear(); break; } /* * Take the first BufferSegment out of the input Buffer. */ BufferSegment *seg; input->moveout(&seg); /* * And add it to a temporary Buffer where input is queued. */ outq.append(seg); /* * And for every byte in this BufferSegment. */ const uint8_t *p, *q = seg->end(); for (p = seg->data(); p < q; p++) { /* * If we cannot acquire a complete hash within this segment. */ if (o + (q - p) < XCODEC_SEGMENT_LENGTH) { /* * Hash all of the bytes from it and continue. */ o += q - p; while (p < q) xcodec_hash.add(*p++); break; } /* * If we don't have a complete hash. */ if (o < XCODEC_SEGMENT_LENGTH) { for (;;) { /* * Add bytes to the hash. */ xcodec_hash.add(*p); /* * Until we have a complete hash. */ if (++o == XCODEC_SEGMENT_LENGTH) break; /* * Go to the next byte. */ p++; } ASSERT(o == XCODEC_SEGMENT_LENGTH); } else { /* * Roll it into the rolling hash. */ xcodec_hash.roll(*p); o++; } ASSERT(o >= XCODEC_SEGMENT_LENGTH); ASSERT(p != q); /* * And then mix the hash's internal state into a * uint64_t that we can use to refer to that data * and to look up possible past occurances of that * data in the XCodecCache. */ unsigned start = o - XCODEC_SEGMENT_LENGTH; uint64_t hash = xcodec_hash.mix(); /* * If there is a pending candidate hash that wouldn't * overlap with the data that the rolling hash presently * covers, declare it now. */ if (candidate.set_ && candidate.offset_ + XCODEC_SEGMENT_LENGTH <= start) { BufferSegment *nseg; encode_declaration(output, &outq, candidate.offset_, candidate.symbol_, &nseg); o -= candidate.offset_ + XCODEC_SEGMENT_LENGTH; start = o - XCODEC_SEGMENT_LENGTH; candidate.set_ = false; /* * If, on top of that, the just-declared hash is * the same as the current hash, consider referencing * it immediately. */ if (hash == candidate.symbol_) { /* * If it's a hash collision, though, nevermind. * Skip trying to use this hash as a reference, * too, and go on to the next one. */ if (!encode_reference(output, &outq, start, hash, nseg)) { nseg->unref(); DEBUG(log_) << "Collision in adjacent-declare pass."; continue; } nseg->unref(); /* * But if there's no collection, then we can move * on to looking for the *next* hash/data to declare * or reference. */ o = 0; xcodec_hash.reset(); DEBUG(log_) << "Hit in adjacent-declare pass."; continue; } nseg->unref(); } /* * Now attempt to encode this hash as a reference if it * has been defined before. */ BufferSegment *oseg = cache_->lookup(hash); if (oseg != NULL) { /* * This segment already exists. If it's * identical to this chunk of data, then that's * positively fantastic. */ if (encode_reference(output, &outq, start, hash, oseg)) { oseg->unref(); o = 0; xcodec_hash.reset(); /* * We have output any data before this hash * in escaped form, so any candidate hash * before it is invalid now. */ candidate.set_ = false; continue; } /* * This hash isn't usable because it collides * with another, so keep looking for something * viable. */ oseg->unref(); DEBUG(log_) << "Collision in first pass."; continue; } /* * Not defined before, it's a candidate for declaration if * we don't already have one. */ if (candidate.set_) { /* * We already have a hash that occurs earlier, * isn't a collision and includes data that's * covered by this hash, so don't remember it * and keep going. */ ASSERT(candidate.offset_ + XCODEC_SEGMENT_LENGTH > start); continue; } /* * The hash at this offset doesn't collide with any * other and is the first viable hash we've seen so far * in the stream, so remember it so that if we don't * find something to reference we can declare this one * for future use. */ candidate.offset_ = start; candidate.symbol_ = hash; candidate.set_ = true; } seg->unref(); } /* * Done processing input. If there's still data in the outq Buffer, * then we need to declare any candidate hashes and escape any data * after them. */ /* * There's a hash we can declare, do it. */ if (candidate.set_) { ASSERT(!outq.empty()); encode_declaration(output, &outq, candidate.offset_, candidate.symbol_, NULL); candidate.set_ = false; } /* * There's data after that hash or no candidate hash, so * just escape it. */ if (!outq.empty()) { encode_escape(output, &outq, outq.length()); } ASSERT(!candidate.set_); ASSERT(outq.empty()); ASSERT(input->empty()); } void XCodecEncoder::encode_declaration(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment **segp) { if (offset != 0) { encode_escape(output, input, offset); } BufferSegment *nseg; input->copyout(&nseg, XCODEC_SEGMENT_LENGTH); cache_->enter(hash, nseg); output->append(XCODEC_MAGIC); output->append(XCODEC_OP_EXTRACT); output->append(nseg); window_.declare(hash, nseg); if (segp == NULL) nseg->unref(); /* * Skip to the end. */ input->skip(XCODEC_SEGMENT_LENGTH); if (segp != NULL) *segp = nseg; } void XCodecEncoder::encode_escape(Buffer *output, Buffer *input, unsigned length) { ASSERT(length != 0); do { unsigned offset; if (!input->find(XCODEC_MAGIC, &offset, length)) { output->append(input, length); input->skip(length); return; } if (offset != 0) { output->append(input, offset); length -= offset; input->skip(offset); } output->append(XCODEC_MAGIC); output->append(XCODEC_OP_ESCAPE); length -= sizeof XCODEC_MAGIC; input->skip(sizeof XCODEC_MAGIC); } while (length != 0); } bool XCodecEncoder::encode_reference(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment *oseg) { uint8_t data[XCODEC_SEGMENT_LENGTH]; input->copyout(data, offset, sizeof data); if (!oseg->equal(data, sizeof data)) return (false); if (offset != 0) { encode_escape(output, input, offset); } /* * Skip to the end. */ input->skip(XCODEC_SEGMENT_LENGTH); /* * And output a reference. */ uint8_t b; if (window_.present(hash, &b)) { output->append(XCODEC_MAGIC); output->append(XCODEC_OP_BACKREF); output->append(b); } else { output->append(XCODEC_MAGIC); output->append(XCODEC_OP_REF); uint64_t behash = BigEndian::encode(hash); output->append(&behash); window_.declare(hash, oseg); } return (true); }
#include <common/buffer.h> #include <common/endian.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_cache.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_hash.h> struct candidate_symbol { bool set_; unsigned offset_; uint64_t symbol_; }; XCodecEncoder::XCodecEncoder(XCodecCache *cache) : log_("/xcodec/encoder"), cache_(cache), window_() { } XCodecEncoder::~XCodecEncoder() { } /* * This takes a view of a data stream and turns it into a series of references * to other data, declarations of data to be referenced, and data that needs * escaped. */ void XCodecEncoder::encode(Buffer *output, Buffer *input) { if (input->empty()) return; if (input->length() < XCODEC_SEGMENT_LENGTH) { encode_escape(output, input, input->length()); return; } XCodecHash xcodec_hash; candidate_symbol candidate; Buffer outq; unsigned o = 0; candidate.set_ = false; /* * While there is input. */ while (!input->empty()) { /* * If we cannot acquire a complete hash within this segment, * stop looking. */ if (o + input->length() < XCODEC_SEGMENT_LENGTH) { DEBUG(log_) << "Buffer couldn't yield a hash."; outq.append(input); input->clear(); break; } /* * Take the first BufferSegment out of the input Buffer. */ BufferSegment *seg; input->moveout(&seg); /* * And add it to a temporary Buffer where input is queued. */ outq.append(seg); /* * And for every byte in this BufferSegment. */ const uint8_t *p, *q = seg->end(); for (p = seg->data(); p < q; p++) { /* * If we cannot acquire a complete hash within this segment. */ if (o + (q - p) < XCODEC_SEGMENT_LENGTH) { /* * Hash all of the bytes from it and continue. */ o += q - p; while (p < q) xcodec_hash.add(*p++); break; } /* * If we don't have a complete hash. */ if (o < XCODEC_SEGMENT_LENGTH) { for (;;) { /* * Add bytes to the hash. */ xcodec_hash.add(*p); /* * Until we have a complete hash. */ if (++o == XCODEC_SEGMENT_LENGTH) break; /* * Go to the next byte. */ p++; } ASSERT(o == XCODEC_SEGMENT_LENGTH); } else { /* * Roll it into the rolling hash. */ xcodec_hash.roll(*p); o++; } ASSERT(o >= XCODEC_SEGMENT_LENGTH); ASSERT(p != q); /* * And then mix the hash's internal state into a * uint64_t that we can use to refer to that data * and to look up possible past occurances of that * data in the XCodecCache. */ unsigned start = o - XCODEC_SEGMENT_LENGTH; uint64_t hash = xcodec_hash.mix(); /* * If there is a pending candidate hash that wouldn't * overlap with the data that the rolling hash presently * covers, declare it now. */ if (candidate.set_ && candidate.offset_ + XCODEC_SEGMENT_LENGTH <= start) { BufferSegment *nseg; encode_declaration(output, &outq, candidate.offset_, candidate.symbol_, &nseg); o -= candidate.offset_ + XCODEC_SEGMENT_LENGTH; start = o - XCODEC_SEGMENT_LENGTH; candidate.set_ = false; /* * If, on top of that, the just-declared hash is * the same as the current hash, consider referencing * it immediately. */ if (hash == candidate.symbol_) { /* * If it's a hash collision, though, nevermind. * Skip trying to use this hash as a reference, * too, and go on to the next one. */ if (!encode_reference(output, &outq, start, hash, nseg)) { nseg->unref(); DEBUG(log_) << "Collision in adjacent-declare pass."; continue; } nseg->unref(); /* * But if there's no collection, then we can move * on to looking for the *next* hash/data to declare * or reference. */ o = 0; xcodec_hash.reset(); DEBUG(log_) << "Hit in adjacent-declare pass."; continue; } nseg->unref(); } /* * Now attempt to encode this hash as a reference if it * has been defined before. */ BufferSegment *oseg = cache_->lookup(hash); if (oseg != NULL) { /* * This segment already exists. If it's * identical to this chunk of data, then that's * positively fantastic. */ if (encode_reference(output, &outq, start, hash, oseg)) { oseg->unref(); o = 0; xcodec_hash.reset(); /* * We have output any data before this hash * in escaped form, so any candidate hash * before it is invalid now. */ candidate.set_ = false; continue; } /* * This hash isn't usable because it collides * with another, so keep looking for something * viable. * * XXX * If this is the first hash (i.e. * !candidate.set_) then we can adjust the * start of the current window and escape the * first byte right away. Does that help? */ oseg->unref(); DEBUG(log_) << "Collision in first pass."; continue; } /* * Not defined before, it's a candidate for declaration * if we don't already have one. */ if (candidate.set_) { /* * We already have a hash that occurs earlier, * isn't a collision and includes data that's * covered by this hash, so don't remember it * and keep going. */ ASSERT(candidate.offset_ + XCODEC_SEGMENT_LENGTH > start); continue; } /* * The hash at this offset doesn't collide with any * other and is the first viable hash we've seen so far * in the stream, so remember it so that if we don't * find something to reference we can declare this one * for future use. */ candidate.offset_ = start; candidate.symbol_ = hash; candidate.set_ = true; } seg->unref(); } /* * Done processing input. If there's still data in the outq Buffer, * then we need to declare any candidate hashes and escape any data * after them. */ /* * There's a hash we can declare, do it. */ if (candidate.set_) { ASSERT(!outq.empty()); encode_declaration(output, &outq, candidate.offset_, candidate.symbol_, NULL); candidate.set_ = false; } /* * There's data after that hash or no candidate hash, so * just escape it. */ if (!outq.empty()) { encode_escape(output, &outq, outq.length()); } ASSERT(!candidate.set_); ASSERT(outq.empty()); ASSERT(input->empty()); } void XCodecEncoder::encode_declaration(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment **segp) { if (offset != 0) { encode_escape(output, input, offset); } BufferSegment *nseg; input->copyout(&nseg, XCODEC_SEGMENT_LENGTH); cache_->enter(hash, nseg); output->append(XCODEC_MAGIC); output->append(XCODEC_OP_EXTRACT); output->append(nseg); window_.declare(hash, nseg); if (segp == NULL) nseg->unref(); /* * Skip to the end. */ input->skip(XCODEC_SEGMENT_LENGTH); if (segp != NULL) *segp = nseg; } void XCodecEncoder::encode_escape(Buffer *output, Buffer *input, unsigned length) { ASSERT(length != 0); do { unsigned offset; if (!input->find(XCODEC_MAGIC, &offset, length)) { output->append(input, length); input->skip(length); return; } if (offset != 0) { output->append(input, offset); length -= offset; input->skip(offset); } output->append(XCODEC_MAGIC); output->append(XCODEC_OP_ESCAPE); length -= sizeof XCODEC_MAGIC; input->skip(sizeof XCODEC_MAGIC); } while (length != 0); } bool XCodecEncoder::encode_reference(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment *oseg) { uint8_t data[XCODEC_SEGMENT_LENGTH]; input->copyout(data, offset, sizeof data); if (!oseg->equal(data, sizeof data)) return (false); if (offset != 0) { encode_escape(output, input, offset); } /* * Skip to the end. */ input->skip(XCODEC_SEGMENT_LENGTH); /* * And output a reference. */ uint8_t b; if (window_.present(hash, &b)) { output->append(XCODEC_MAGIC); output->append(XCODEC_OP_BACKREF); output->append(b); } else { output->append(XCODEC_MAGIC); output->append(XCODEC_OP_REF); uint64_t behash = BigEndian::encode(hash); output->append(&behash); window_.declare(hash, oseg); } return (true); }
Add a comment and reformat a nearby one.
Add a comment and reformat a nearby one. git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@760 4068ffdb-0463-0410-8185-8cc71e3bd399
C++
bsd-2-clause
splbio/wanproxy,diegows/wanproxy,diegows/wanproxy,diegows/wanproxy,splbio/wanproxy,splbio/wanproxy
18fc2d6fcd8458d6f06b5eb521da90319ee457e5
chrome/browser/extensions/default_apps.cc
chrome/browser/extensions/default_apps.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/default_apps.h" #include "base/command_line.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" const int DefaultApps::kAppsPromoCounterMax = 10; // static void DefaultApps::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kDefaultAppsInstalled, false); prefs->RegisterIntegerPref(prefs::kAppsPromoCounter, 0); } DefaultApps::DefaultApps(PrefService* prefs) : prefs_(prefs) { // gmail, calendar, docs ids_.insert("pjkljhegncpnkpknbcohdijeoejaedia"); ids_.insert("ejjicmeblgpmajnghnpcppodonldlgfn"); ids_.insert("apdfllckaahabafndbhieahigkjlhalf"); } DefaultApps::~DefaultApps() {} const ExtensionIdSet* DefaultApps::GetAppsToInstall() const { if (GetDefaultAppsInstalled()) return NULL; else return &ids_; } const ExtensionIdSet* DefaultApps::GetDefaultApps() const { return &ids_; } void DefaultApps::DidInstallApp(const ExtensionIdSet& installed_ids) { // If all the default apps have been installed, stop trying to install them. // Note that we use std::includes here instead of == because apps might have // been manually installed while the the default apps were installing and we // wouldn't want to keep trying to install them in that case. if (!GetDefaultAppsInstalled() && std::includes(installed_ids.begin(), installed_ids.end(), ids_.begin(), ids_.end())) { SetDefaultAppsInstalled(true); } } bool DefaultApps::ShouldShowPromo(const ExtensionIdSet& installed_ids) { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceAppsPromoVisible)) { return true; } if (GetDefaultAppsInstalled() && GetPromoCounter() < kAppsPromoCounterMax) { // If we have the exact set of default apps, show the promo. If we don't // have the exact set of default apps, this means that the user manually // installed one. The promo doesn't make sense if it shows apps the user // manually installed, so expire it immediately in that situation. if (installed_ids == ids_) return true; else SetPromoHidden(); } return false; } void DefaultApps::DidShowPromo() { if (!GetDefaultAppsInstalled()) { NOTREACHED() << "Should not show promo until default apps are installed."; return; } int promo_counter = GetPromoCounter(); if (promo_counter == kAppsPromoCounterMax) { NOTREACHED() << "Promo has already been shown the maximum number of times."; return; } if (promo_counter < kAppsPromoCounterMax) SetPromoCounter(++promo_counter); else SetPromoHidden(); } void DefaultApps::SetPromoHidden() { SetPromoCounter(kAppsPromoCounterMax); } int DefaultApps::GetPromoCounter() const { return prefs_->GetInteger(prefs::kAppsPromoCounter); } void DefaultApps::SetPromoCounter(int val) { prefs_->SetInteger(prefs::kAppsPromoCounter, val); prefs_->ScheduleSavePersistentPrefs(); } bool DefaultApps::GetDefaultAppsInstalled() const { return prefs_->GetBoolean(prefs::kDefaultAppsInstalled); } void DefaultApps::SetDefaultAppsInstalled(bool val) { prefs_->SetBoolean(prefs::kDefaultAppsInstalled, val); prefs_->ScheduleSavePersistentPrefs(); }
// 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/extensions/default_apps.h" #include "base/command_line.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" const int DefaultApps::kAppsPromoCounterMax = 10; // static void DefaultApps::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kDefaultAppsInstalled, false); prefs->RegisterIntegerPref(prefs::kAppsPromoCounter, 0); } DefaultApps::DefaultApps(PrefService* prefs) : prefs_(prefs) { #if !defined(OS_CHROMEOS) // gmail, calendar, docs ids_.insert("pjkljhegncpnkpknbcohdijeoejaedia"); ids_.insert("ejjicmeblgpmajnghnpcppodonldlgfn"); ids_.insert("apdfllckaahabafndbhieahigkjlhalf"); #endif // OS_CHROMEOS } DefaultApps::~DefaultApps() {} const ExtensionIdSet* DefaultApps::GetAppsToInstall() const { if (GetDefaultAppsInstalled()) return NULL; else return &ids_; } const ExtensionIdSet* DefaultApps::GetDefaultApps() const { return &ids_; } void DefaultApps::DidInstallApp(const ExtensionIdSet& installed_ids) { // If all the default apps have been installed, stop trying to install them. // Note that we use std::includes here instead of == because apps might have // been manually installed while the the default apps were installing and we // wouldn't want to keep trying to install them in that case. if (!GetDefaultAppsInstalled() && std::includes(installed_ids.begin(), installed_ids.end(), ids_.begin(), ids_.end())) { SetDefaultAppsInstalled(true); } } bool DefaultApps::ShouldShowPromo(const ExtensionIdSet& installed_ids) { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceAppsPromoVisible)) { return true; } if (GetDefaultAppsInstalled() && GetPromoCounter() < kAppsPromoCounterMax) { // If we have the exact set of default apps, show the promo. If we don't // have the exact set of default apps, this means that the user manually // installed one. The promo doesn't make sense if it shows apps the user // manually installed, so expire it immediately in that situation. if (installed_ids == ids_) return true; else SetPromoHidden(); } return false; } void DefaultApps::DidShowPromo() { if (!GetDefaultAppsInstalled()) { NOTREACHED() << "Should not show promo until default apps are installed."; return; } int promo_counter = GetPromoCounter(); if (promo_counter == kAppsPromoCounterMax) { NOTREACHED() << "Promo has already been shown the maximum number of times."; return; } if (promo_counter < kAppsPromoCounterMax) SetPromoCounter(++promo_counter); else SetPromoHidden(); } void DefaultApps::SetPromoHidden() { SetPromoCounter(kAppsPromoCounterMax); } int DefaultApps::GetPromoCounter() const { return prefs_->GetInteger(prefs::kAppsPromoCounter); } void DefaultApps::SetPromoCounter(int val) { prefs_->SetInteger(prefs::kAppsPromoCounter, val); prefs_->ScheduleSavePersistentPrefs(); } bool DefaultApps::GetDefaultAppsInstalled() const { return prefs_->GetBoolean(prefs::kDefaultAppsInstalled); } void DefaultApps::SetDefaultAppsInstalled(bool val) { prefs_->SetBoolean(prefs::kDefaultAppsInstalled, val); prefs_->ScheduleSavePersistentPrefs(); }
Remove component extensions Calendar and Docs
Remove component extensions Calendar and Docs BUG=http://code.google.com/p/chromium-os/issues/detail?id=8662 TEST=manual Review URL: http://codereview.chromium.org/4411001 git-svn-id: http://src.chromium.org/svn/trunk/src@65079 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 337c93d205a718ab611b63106790a5fa54c11dfd
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
4cdc8839345987817219acd53a5e6b902930821c
lib/IR/LLVMContext.cpp
lib/IR/LLVMContext.cpp
//===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements LLVMContext, as a wrapper around the opaque // class LLVMContextImpl. // //===----------------------------------------------------------------------===// #include "llvm/IR/LLVMContext.h" #include "LLVMContextImpl.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdlib> #include <string> #include <utility> using namespace llvm; LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) { // Create the fixed metadata kinds. This is done in the same order as the // MD_* enum values so that they correspond. std::pair<unsigned, StringRef> MDKinds[] = { {MD_dbg, "dbg"}, {MD_tbaa, "tbaa"}, {MD_prof, "prof"}, {MD_fpmath, "fpmath"}, {MD_range, "range"}, {MD_tbaa_struct, "tbaa.struct"}, {MD_invariant_load, "invariant.load"}, {MD_alias_scope, "alias.scope"}, {MD_noalias, "noalias"}, {MD_nontemporal, "nontemporal"}, {MD_mem_parallel_loop_access, "llvm.mem.parallel_loop_access"}, {MD_nonnull, "nonnull"}, {MD_dereferenceable, "dereferenceable"}, {MD_dereferenceable_or_null, "dereferenceable_or_null"}, {MD_make_implicit, "make.implicit"}, {MD_unpredictable, "unpredictable"}, {MD_invariant_group, "invariant.group"}, {MD_align, "align"}, {MD_loop, "llvm.loop"}, {MD_type, "type"}, {MD_section_prefix, "section_prefix"}, {MD_absolute_symbol, "absolute_symbol"}, {MD_associated, "associated"}, }; for (auto &MDKind : MDKinds) { unsigned ID = getMDKindID(MDKind.second); assert(ID == MDKind.first && "metadata kind id drifted"); (void)ID; } auto *DeoptEntry = pImpl->getOrInsertBundleTag("deopt"); assert(DeoptEntry->second == LLVMContext::OB_deopt && "deopt operand bundle id drifted!"); (void)DeoptEntry; auto *FuncletEntry = pImpl->getOrInsertBundleTag("funclet"); assert(FuncletEntry->second == LLVMContext::OB_funclet && "funclet operand bundle id drifted!"); (void)FuncletEntry; auto *GCTransitionEntry = pImpl->getOrInsertBundleTag("gc-transition"); assert(GCTransitionEntry->second == LLVMContext::OB_gc_transition && "gc-transition operand bundle id drifted!"); (void)GCTransitionEntry; SyncScope::ID SingleThreadSSID = pImpl->getOrInsertSyncScopeID("singlethread"); assert(SingleThreadSSID == SyncScope::SingleThread && "singlethread synchronization scope ID drifted!"); SyncScope::ID SystemSSID = pImpl->getOrInsertSyncScopeID(""); assert(SystemSSID == SyncScope::System && "system synchronization scope ID drifted!"); } LLVMContext::~LLVMContext() { delete pImpl; } void LLVMContext::addModule(Module *M) { pImpl->OwnedModules.insert(M); } void LLVMContext::removeModule(Module *M) { pImpl->OwnedModules.erase(M); } //===----------------------------------------------------------------------===// // Recoverable Backend Errors //===----------------------------------------------------------------------===// void LLVMContext:: setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler, void *DiagContext) { pImpl->InlineAsmDiagHandler = DiagHandler; pImpl->InlineAsmDiagContext = DiagContext; } /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by /// setInlineAsmDiagnosticHandler. LLVMContext::InlineAsmDiagHandlerTy LLVMContext::getInlineAsmDiagnosticHandler() const { return pImpl->InlineAsmDiagHandler; } /// getInlineAsmDiagnosticContext - Return the diagnostic context set by /// setInlineAsmDiagnosticHandler. void *LLVMContext::getInlineAsmDiagnosticContext() const { return pImpl->InlineAsmDiagContext; } void LLVMContext::setDiagnosticHandler(DiagnosticHandlerTy DiagnosticHandler, void *DiagnosticContext, bool RespectFilters) { pImpl->DiagnosticHandler = DiagnosticHandler; pImpl->DiagnosticContext = DiagnosticContext; pImpl->RespectDiagnosticFilters = RespectFilters; } void LLVMContext::setDiagnosticsHotnessRequested(bool Requested) { pImpl->DiagnosticsHotnessRequested = Requested; } bool LLVMContext::getDiagnosticsHotnessRequested() const { return pImpl->DiagnosticsHotnessRequested; } void LLVMContext::setDiagnosticsHotnessThreshold(uint64_t Threshold) { pImpl->DiagnosticsHotnessThreshold = Threshold; } uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const { return pImpl->DiagnosticsHotnessThreshold; } yaml::Output *LLVMContext::getDiagnosticsOutputFile() { return pImpl->DiagnosticsOutputFile.get(); } void LLVMContext::setDiagnosticsOutputFile(std::unique_ptr<yaml::Output> F) { pImpl->DiagnosticsOutputFile = std::move(F); } LLVMContext::DiagnosticHandlerTy LLVMContext::getDiagnosticHandler() const { return pImpl->DiagnosticHandler; } void *LLVMContext::getDiagnosticContext() const { return pImpl->DiagnosticContext; } void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle) { pImpl->YieldCallback = Callback; pImpl->YieldOpaqueHandle = OpaqueHandle; } void LLVMContext::yield() { if (pImpl->YieldCallback) pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle); } void LLVMContext::emitError(const Twine &ErrorStr) { diagnose(DiagnosticInfoInlineAsm(ErrorStr)); } void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) { assert (I && "Invalid instruction"); diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr)); } static bool isDiagnosticEnabled(const DiagnosticInfo &DI) { // Optimization remarks are selective. They need to check whether the regexp // pattern, passed via one of the -pass-remarks* flags, matches the name of // the pass that is emitting the diagnostic. If there is no match, ignore the // diagnostic and return. if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) return Remark->isEnabled(); return true; } const char * LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) { switch (Severity) { case DS_Error: return "error"; case DS_Warning: return "warning"; case DS_Remark: return "remark"; case DS_Note: return "note"; } llvm_unreachable("Unknown DiagnosticSeverity"); } void LLVMContext::diagnose(const DiagnosticInfo &DI) { // If there is a report handler, use it. if (pImpl->DiagnosticHandler) { if (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI)) pImpl->DiagnosticHandler(DI, pImpl->DiagnosticContext); return; } if (!isDiagnosticEnabled(DI)) return; // Otherwise, print the message with a prefix based on the severity. DiagnosticPrinterRawOStream DP(errs()); errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; DI.print(DP); errs() << "\n"; if (DI.getSeverity() == DS_Error) exit(1); } void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) { diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr)); } //===----------------------------------------------------------------------===// // Metadata Kind Uniquing //===----------------------------------------------------------------------===// /// Return a unique non-zero ID for the specified metadata kind. unsigned LLVMContext::getMDKindID(StringRef Name) const { // If this is new, assign it its ID. return pImpl->CustomMDKindNames.insert( std::make_pair( Name, pImpl->CustomMDKindNames.size())) .first->second; } /// getHandlerNames - Populate client-supplied smallvector using custom /// metadata name and ID. void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const { Names.resize(pImpl->CustomMDKindNames.size()); for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(), E = pImpl->CustomMDKindNames.end(); I != E; ++I) Names[I->second] = I->first(); } void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const { pImpl->getOperandBundleTags(Tags); } uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const { return pImpl->getOperandBundleTagID(Tag); } SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) { return pImpl->getOrInsertSyncScopeID(SSN); } void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const { pImpl->getSyncScopeNames(SSNs); } void LLVMContext::setGC(const Function &Fn, std::string GCName) { auto It = pImpl->GCNames.find(&Fn); if (It == pImpl->GCNames.end()) { pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName))); return; } It->second = std::move(GCName); } const std::string &LLVMContext::getGC(const Function &Fn) { return pImpl->GCNames[&Fn]; } void LLVMContext::deleteGC(const Function &Fn) { pImpl->GCNames.erase(&Fn); } bool LLVMContext::shouldDiscardValueNames() const { return pImpl->DiscardValueNames; } bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; } void LLVMContext::enableDebugTypeODRUniquing() { if (pImpl->DITypeMap) return; pImpl->DITypeMap.emplace(); } void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); } void LLVMContext::setDiscardValueNames(bool Discard) { pImpl->DiscardValueNames = Discard; } OptBisect &LLVMContext::getOptBisect() { return pImpl->getOptBisect(); }
//===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements LLVMContext, as a wrapper around the opaque // class LLVMContextImpl. // //===----------------------------------------------------------------------===// #include "llvm/IR/LLVMContext.h" #include "LLVMContextImpl.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdlib> #include <string> #include <utility> using namespace llvm; LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) { // Create the fixed metadata kinds. This is done in the same order as the // MD_* enum values so that they correspond. std::pair<unsigned, StringRef> MDKinds[] = { {MD_dbg, "dbg"}, {MD_tbaa, "tbaa"}, {MD_prof, "prof"}, {MD_fpmath, "fpmath"}, {MD_range, "range"}, {MD_tbaa_struct, "tbaa.struct"}, {MD_invariant_load, "invariant.load"}, {MD_alias_scope, "alias.scope"}, {MD_noalias, "noalias"}, {MD_nontemporal, "nontemporal"}, {MD_mem_parallel_loop_access, "llvm.mem.parallel_loop_access"}, {MD_nonnull, "nonnull"}, {MD_dereferenceable, "dereferenceable"}, {MD_dereferenceable_or_null, "dereferenceable_or_null"}, {MD_make_implicit, "make.implicit"}, {MD_unpredictable, "unpredictable"}, {MD_invariant_group, "invariant.group"}, {MD_align, "align"}, {MD_loop, "llvm.loop"}, {MD_type, "type"}, {MD_section_prefix, "section_prefix"}, {MD_absolute_symbol, "absolute_symbol"}, {MD_associated, "associated"}, }; for (auto &MDKind : MDKinds) { unsigned ID = getMDKindID(MDKind.second); assert(ID == MDKind.first && "metadata kind id drifted"); (void)ID; } auto *DeoptEntry = pImpl->getOrInsertBundleTag("deopt"); assert(DeoptEntry->second == LLVMContext::OB_deopt && "deopt operand bundle id drifted!"); (void)DeoptEntry; auto *FuncletEntry = pImpl->getOrInsertBundleTag("funclet"); assert(FuncletEntry->second == LLVMContext::OB_funclet && "funclet operand bundle id drifted!"); (void)FuncletEntry; auto *GCTransitionEntry = pImpl->getOrInsertBundleTag("gc-transition"); assert(GCTransitionEntry->second == LLVMContext::OB_gc_transition && "gc-transition operand bundle id drifted!"); (void)GCTransitionEntry; SyncScope::ID SingleThreadSSID = pImpl->getOrInsertSyncScopeID("singlethread"); assert(SingleThreadSSID == SyncScope::SingleThread && "singlethread synchronization scope ID drifted!"); (void)SingleThreadSSID; SyncScope::ID SystemSSID = pImpl->getOrInsertSyncScopeID(""); assert(SystemSSID == SyncScope::System && "system synchronization scope ID drifted!"); (void)SystemSSID; } LLVMContext::~LLVMContext() { delete pImpl; } void LLVMContext::addModule(Module *M) { pImpl->OwnedModules.insert(M); } void LLVMContext::removeModule(Module *M) { pImpl->OwnedModules.erase(M); } //===----------------------------------------------------------------------===// // Recoverable Backend Errors //===----------------------------------------------------------------------===// void LLVMContext:: setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler, void *DiagContext) { pImpl->InlineAsmDiagHandler = DiagHandler; pImpl->InlineAsmDiagContext = DiagContext; } /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by /// setInlineAsmDiagnosticHandler. LLVMContext::InlineAsmDiagHandlerTy LLVMContext::getInlineAsmDiagnosticHandler() const { return pImpl->InlineAsmDiagHandler; } /// getInlineAsmDiagnosticContext - Return the diagnostic context set by /// setInlineAsmDiagnosticHandler. void *LLVMContext::getInlineAsmDiagnosticContext() const { return pImpl->InlineAsmDiagContext; } void LLVMContext::setDiagnosticHandler(DiagnosticHandlerTy DiagnosticHandler, void *DiagnosticContext, bool RespectFilters) { pImpl->DiagnosticHandler = DiagnosticHandler; pImpl->DiagnosticContext = DiagnosticContext; pImpl->RespectDiagnosticFilters = RespectFilters; } void LLVMContext::setDiagnosticsHotnessRequested(bool Requested) { pImpl->DiagnosticsHotnessRequested = Requested; } bool LLVMContext::getDiagnosticsHotnessRequested() const { return pImpl->DiagnosticsHotnessRequested; } void LLVMContext::setDiagnosticsHotnessThreshold(uint64_t Threshold) { pImpl->DiagnosticsHotnessThreshold = Threshold; } uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const { return pImpl->DiagnosticsHotnessThreshold; } yaml::Output *LLVMContext::getDiagnosticsOutputFile() { return pImpl->DiagnosticsOutputFile.get(); } void LLVMContext::setDiagnosticsOutputFile(std::unique_ptr<yaml::Output> F) { pImpl->DiagnosticsOutputFile = std::move(F); } LLVMContext::DiagnosticHandlerTy LLVMContext::getDiagnosticHandler() const { return pImpl->DiagnosticHandler; } void *LLVMContext::getDiagnosticContext() const { return pImpl->DiagnosticContext; } void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle) { pImpl->YieldCallback = Callback; pImpl->YieldOpaqueHandle = OpaqueHandle; } void LLVMContext::yield() { if (pImpl->YieldCallback) pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle); } void LLVMContext::emitError(const Twine &ErrorStr) { diagnose(DiagnosticInfoInlineAsm(ErrorStr)); } void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) { assert (I && "Invalid instruction"); diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr)); } static bool isDiagnosticEnabled(const DiagnosticInfo &DI) { // Optimization remarks are selective. They need to check whether the regexp // pattern, passed via one of the -pass-remarks* flags, matches the name of // the pass that is emitting the diagnostic. If there is no match, ignore the // diagnostic and return. if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) return Remark->isEnabled(); return true; } const char * LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) { switch (Severity) { case DS_Error: return "error"; case DS_Warning: return "warning"; case DS_Remark: return "remark"; case DS_Note: return "note"; } llvm_unreachable("Unknown DiagnosticSeverity"); } void LLVMContext::diagnose(const DiagnosticInfo &DI) { // If there is a report handler, use it. if (pImpl->DiagnosticHandler) { if (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI)) pImpl->DiagnosticHandler(DI, pImpl->DiagnosticContext); return; } if (!isDiagnosticEnabled(DI)) return; // Otherwise, print the message with a prefix based on the severity. DiagnosticPrinterRawOStream DP(errs()); errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; DI.print(DP); errs() << "\n"; if (DI.getSeverity() == DS_Error) exit(1); } void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) { diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr)); } //===----------------------------------------------------------------------===// // Metadata Kind Uniquing //===----------------------------------------------------------------------===// /// Return a unique non-zero ID for the specified metadata kind. unsigned LLVMContext::getMDKindID(StringRef Name) const { // If this is new, assign it its ID. return pImpl->CustomMDKindNames.insert( std::make_pair( Name, pImpl->CustomMDKindNames.size())) .first->second; } /// getHandlerNames - Populate client-supplied smallvector using custom /// metadata name and ID. void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const { Names.resize(pImpl->CustomMDKindNames.size()); for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(), E = pImpl->CustomMDKindNames.end(); I != E; ++I) Names[I->second] = I->first(); } void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const { pImpl->getOperandBundleTags(Tags); } uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const { return pImpl->getOperandBundleTagID(Tag); } SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) { return pImpl->getOrInsertSyncScopeID(SSN); } void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const { pImpl->getSyncScopeNames(SSNs); } void LLVMContext::setGC(const Function &Fn, std::string GCName) { auto It = pImpl->GCNames.find(&Fn); if (It == pImpl->GCNames.end()) { pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName))); return; } It->second = std::move(GCName); } const std::string &LLVMContext::getGC(const Function &Fn) { return pImpl->GCNames[&Fn]; } void LLVMContext::deleteGC(const Function &Fn) { pImpl->GCNames.erase(&Fn); } bool LLVMContext::shouldDiscardValueNames() const { return pImpl->DiscardValueNames; } bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; } void LLVMContext::enableDebugTypeODRUniquing() { if (pImpl->DITypeMap) return; pImpl->DITypeMap.emplace(); } void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); } void LLVMContext::setDiscardValueNames(bool Discard) { pImpl->DiscardValueNames = Discard; } OptBisect &LLVMContext::getOptBisect() { return pImpl->getOptBisect(); }
Fix unused variable warnings
Fix unused variable warnings Differential Revision: https://reviews.llvm.org/D35280 git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@307740 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm
80d7a9babcb9ee413ef52258099b6c03e3ad6b55
main.cpp
main.cpp
// Copyright Vladimir Prus 2002-2004. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #include "SampleDaemon.h" #include <iostream> #include <boost/program_options.hpp> /* The simplest usage of the library. */ namespace po = boost::program_options; int main(int ac, char* av[]) { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("non-daemon", "Run blocking mode") ("remove-daemon", "Single Mode"); po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); if(vm.count("help")) { std::cout << desc << std::endl; exit(0); } SampleDaemon *s = new SampleDaemon(); s->set_daemon(vm.count("non-daemon") == 0); s->run(ac, av); return 0; }
// Copyright Vladimir Prus 2002-2004. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #include "SampleDaemon.h" #include <iostream> #include <boost/program_options.hpp> /* The simplest usage of the library. */ namespace po = boost::program_options; int main(int ac, char* av[]) { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("non-daemon", "Run blocking mode") ("terminate", "Terminate existing DropBot daemon(s)") ("daemon-status", "Show current daemon(s) and its status"); po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); if(vm.count("help")) { std::cout << desc << std::endl; exit(0); } SampleDaemon *s = new SampleDaemon(); s->set_daemon(vm.count("non-daemon") == 0); s->run(ac, av); return 0; }
Modify demo application
Modify demo application
C++
apache-2.0
Rayer/DropBot
0312feea028037641f02bddd025a48a689993c7e
main.cpp
main.cpp
#include <cstdio> #include <GL/glew.h> #include <GL/glut.h> #include <iostream> #include <fstream> #include <string> #include <cassert> static void redisplay_all(void); // viewing angle float phi = 0, theta = 0; // glut window identifiers int w_main, w_scene, w_performance, w_light, w_heightmap, w_conemap, w_texture; // shader program handlers int sl_shader, sl_mode_var; // last mouse position int m_last_x, m_last_y; std::string load_file(const char *filename) { std::ifstream ifs(filename); std::string res; char ch; while (ifs.get(ch)) res += ch; return res; } void print_program_infolog(int obj) { int len; glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &len); if (len > 1) { char buf[len + 1]; int chars; glGetProgramInfoLog(obj, len, &chars, buf); printf("%d: %s.\n", len, buf); } } void print_shader_infolog(int obj) { int len; glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &len); if (len > 1) { char buf[len + 1]; int chars; glGetShaderInfoLog(obj, len, &chars, buf); printf("%d: %s.\n", len, buf); } } void on_speckey(int key, int x, int y) { float k = glutGetModifiers() == GLUT_ACTIVE_SHIFT ? 10 : 1; switch (key) { case GLUT_KEY_UP: theta += k; break; case GLUT_KEY_DOWN: theta -= k; break; case GLUT_KEY_LEFT: phi += k; break; case GLUT_KEY_RIGHT: phi -= k; break; } redisplay_all(); } void on_key(unsigned char key, int x, int y) { switch (key) { case '\b': theta = phi = 0; break; } redisplay_all(); } void on_mouseclick(int button, int state, int x, int y) { m_last_x = x, m_last_y = y; } void on_mousemove(int x, int y) { phi += m_last_x - x; theta += m_last_y - y; m_last_x = x, m_last_y = y; redisplay_all(); } static int create_subwindow(void (*display_func)(void), void (*move_func)(int,int), void (*click_func)(int,int,int,int)) { // create a new subwindow int window = glutCreateSubWindow(w_main, 1, 1, 2, 2); // set opengl features glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); // setup callbacks if (display_func) glutDisplayFunc(display_func); if (move_func) glutMotionFunc(move_func); if (click_func) glutMouseFunc(click_func); glutSpecialFunc(on_speckey); glutKeyboardFunc(on_key); return window; } static void reshape_subwindow(int wnd, int w, int h, bool perspective, float rleft, float rtop, float rwidth, float rheight) { int w1 = static_cast<int>(w * rwidth), h1 = static_cast<int>(h * rheight); int l1 = static_cast<int>(w * rleft), t1 = static_cast<int>(h * rtop); glutSetWindow(wnd); // set window geometry glutPositionWindow(l1, t1); glutReshapeWindow(w1, h1); // set projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(l1, t1, w1, h1); if (perspective) gluPerspective(45, 1.0, 0.1, 1000); glMatrixMode(GL_MODELVIEW); } static void redisplay_all(void) { int wnds[] = {w_main, w_scene, w_performance, w_light, w_heightmap, w_conemap, w_texture}; for (int i = 0; i < sizeof(wnds)/sizeof(*wnds); ++i) { glutSetWindow(wnds[i]); glutPostRedisplay(); } } static void on_reshape(int w, int h) { reshape_subwindow(w_scene, w, h, true, 0.0, 0.0, 0.5, 2.0/3.0); reshape_subwindow(w_performance, w, h, true, 0.5, 0.0, 0.5, 2.0/3.0); reshape_subwindow(w_light, w, h, false, 0.00, 2.0/3.0, 0.25, 1.0/3.0); reshape_subwindow(w_heightmap, w, h, false, 0.25, 2.0/3.0, 0.25, 1.0/3.0); reshape_subwindow(w_texture, w, h, false, 0.50, 2.0/3.0, 0.25, 1.0/3.0); reshape_subwindow(w_conemap, w, h, false, 0.75, 2.0/3.0, 0.25, 1.0/3.0); redisplay_all(); } void draw_quad(void) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0,0,1, 0,0,0, 0,1,0); glScalef(0.4, 0.4, 0.4); glTranslatef(0, 0, -1); glRotatef(theta, 1, 0, 0); glRotatef(phi, 0, 0, 1); glBegin(GL_QUADS); glNormal3f(0, 0, 1); glVertex3f(-1, -1, 0); glVertex3f(+1, -1, 0); glVertex3f(+1, +1, 0); glVertex3f(-1, +1, 0); glEnd(); } void render_scene(void) { glutSetWindow(w_scene); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glColor3ub(0xff, 0x00, 0x00); glUseProgram(sl_shader); draw_quad(); glutSwapBuffers(); } void render_performance(void) { glutSetWindow(w_performance); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glColor3ub(0xff, 0xff, 0x00); //glUseProgram(sl_shader); draw_quad(); glutSwapBuffers(); } void render_main(void) { glutSetWindow(w_main); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glutSwapBuffers(); } void compile_shader(void) { GLint status; sl_shader = glCreateProgram(); printf("Vertex shader setup\n"); int vs = glCreateShader(GL_VERTEX_SHADER); std::string vs_source = load_file("light.vs"); const char *vs_src = vs_source.c_str(); glShaderSource(vs, 1, &vs_src, 0); glCompileShader(vs); glAttachShader(sl_shader, vs); print_shader_infolog(vs); glGetShaderiv(vs, GL_COMPILE_STATUS, &status); assert(status == GL_TRUE); printf("Fragment shader setup\n"); int ps = glCreateShader(GL_FRAGMENT_SHADER); std::string ps_source = load_file("shader.fs"); const char *ps_src = ps_source.c_str(); glShaderSource(ps, 1, &ps_src, 0); glCompileShader(ps); glAttachShader(sl_shader, ps); print_shader_infolog(ps); glGetShaderiv(ps, GL_COMPILE_STATUS, &status); assert(status == GL_TRUE); printf("Shader program setup\n"); glLinkProgram(sl_shader); print_program_infolog(sl_shader); glGetProgramiv(sl_shader, GL_LINK_STATUS, &status); assert(status == GL_TRUE); //glUseProgram(sl_shader); } int main(int argc, char **argv) { // initialize glut glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); //glutInitContextProfile(GLUT_CORE_PROFILE | GLUT_COMPATIBILITY_PROFILE); int w = 800 * 3 / 2, h = 600 * 3 / 2; // init main window glutInitWindowSize(w, h); w_main = glutCreateWindow("Local Raycasting Demo"); glutReshapeFunc(on_reshape); glutDisplayFunc(render_main); glutSpecialFunc(on_speckey); glutKeyboardFunc(on_key); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glewInit(); const char *glslver = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION); printf("GLSL ver: %s\n", glslver ? glslver : "[null]"); assert(glewIsSupported("GL_VERSION_2_0")); compile_shader(); // subwindows w_scene = create_subwindow(render_scene, on_mousemove, on_mouseclick); w_performance = create_subwindow(render_performance, on_mousemove, on_mouseclick); w_light = create_subwindow(0, 0, 0); w_heightmap = create_subwindow(0, 0, 0); w_conemap = create_subwindow(0, 0, 0); w_texture = create_subwindow(0, 0, 0); glutSetWindow(w_main); glutMainLoop(); }
#include <cstdio> #include <GL/glew.h> #include <GL/glut.h> #include <iostream> #include <fstream> #include <string> #include <cassert> #include <cmath> #include <png.h> void use_shader(bool draw_performance); static void redisplay_all(void); bool loadPngImage(char *name, int &outWidth, int &outHeight, int &outChannels, GLubyte **outData); void load_texture(int tex, const char *filename); enum Textures { T_DIFFUSE = GL_TEXTURE0, T_HEIGHTMAP, T_NORMALMAP, T_CONEMAP, T_RCONEMAP, T_END_, T_COUNT = T_END_ - GL_TEXTURE0 }; // viewing angle float phi = 0, theta = 0; // shader program handlers int sl_shader, sl_mode_var, sl_lightpos_var, sl_draw_performance_var, sl_root_var; // shader texture vars int slt_diffuse, slt_heightmap, slt_conemap; // last mouse position int m_last_x, m_last_y; // screen width, height int width, height; // mode // 0 - color only, 1 - normal map, 2 - parallax map, 3 - relief map, 4 - cone map, 5 - relaxed cone map int mode; // root-finding method: 0 - none, 1 - binary search int root_method; // light position float lt_x = 0.0, lt_y = 0.0, lt_z = 15; // texture memory GLubyte *textures[T_COUNT]; std::string load_file(const char *filename) { std::ifstream ifs(filename); std::string res; char ch; while (ifs.get(ch)) res += ch; return res; } void print_program_infolog(int obj) { int len; glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &len); if (len > 1) { char buf[len + 1]; int chars; glGetProgramInfoLog(obj, len, &chars, buf); printf("%d: %s.\n", len, buf); } } void print_shader_infolog(int obj) { int len; glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &len); if (len > 1) { char buf[len + 1]; int chars; glGetShaderInfoLog(obj, len, &chars, buf); printf("%d: %s.\n", len, buf); } } void on_speckey(int key, int x, int y) { float k = glutGetModifiers() == GLUT_ACTIVE_SHIFT ? 10 : 1; switch (key) { case GLUT_KEY_UP: theta += k; break; case GLUT_KEY_DOWN: theta -= k; break; case GLUT_KEY_LEFT: phi += k; break; case GLUT_KEY_RIGHT: phi -= k; break; } glutPostRedisplay(); } void on_key(unsigned char key, int x, int y) { const float k = 0.2; switch (tolower(key)) { case '\b': lt_y = lt_x = 0.0; theta = phi = 0; break; case 'w': lt_y += k; break; case 's': lt_y -= k; break; case 'd': lt_x += k; break; case 'a': lt_x -= k; break; case 'm': root_method++; root_method %= 2; break; } if (key >= '0' && key <= '9') mode = key - '0'; glutPostRedisplay(); } void on_mouseclick(int button, int state, int x, int y) { m_last_x = x, m_last_y = y; } void on_mousemove(int x, int y) { phi += m_last_x - x; theta += m_last_y - y; m_last_x = x, m_last_y = y; glutPostRedisplay(); } static void set_viewport(bool perspective, float rleft, float rtop, float rwidth, float rheight) { // calclulate absolute screen space coordinates int w1 = static_cast<int>(width * rwidth), h1 = static_cast<int>(height * rheight); int l1 = static_cast<int>(width * rleft), t1 = static_cast<int>(height * rtop); // set projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(l1, t1, w1, h1); if (perspective) gluPerspective(45, 1.0, 0.1, 1000); glMatrixMode(GL_MODELVIEW); } static void on_reshape(int w, int h) { width = w; height = h; glutPostRedisplay(); } void draw_quad(void) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -1); glRotatef(theta, 1, 0, 0); glRotatef(phi, 0, 0, 1); glScalef(0.3, 0.3, 0.3); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(-1, -1, 0); glTexCoord2f(1.0, 0.0); glVertex3f(+1, -1, 0); glTexCoord2f(1.0, 1.0); glVertex3f(+1, +1, 0); glTexCoord2f(0.0, 1.0); glVertex3f(-1, +1, 0); glEnd(); } void render_scene(void) { use_shader(false); set_viewport(true, 0.0, 0.0, 0.5, 1.0); draw_quad(); } void render_performance(void) { use_shader(true); set_viewport(true, 0.5, 0.0, 0.5, 1.0); draw_quad(); } void render_main(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); render_scene(); render_performance(); glutSwapBuffers(); } void use_shader(bool draw_performance) { // set uniform vars glUniform3f(sl_lightpos_var, lt_x, lt_y, lt_z); glUniform1i(sl_mode_var, mode); glUniform1i(sl_draw_performance_var, draw_performance); glUniform1i(sl_root_var, root_method); // texture variable locations static int difloc = glGetUniformLocation(sl_shader, "TDiffuse"); static int htloc = glGetUniformLocation(sl_shader, "THeightMap"); static int nloc = glGetUniformLocation(sl_shader, "TNormalMap"); static int cloc = glGetUniformLocation(sl_shader, "TConeMap"); static int rcloc = glGetUniformLocation(sl_shader, "TRConeMap"); // bind texture samplers glUniform1i(difloc, T_DIFFUSE - GL_TEXTURE0); glUniform1i(htloc, T_HEIGHTMAP - GL_TEXTURE0); glUniform1i(nloc, T_NORMALMAP - GL_TEXTURE0); glUniform1i(cloc, T_CONEMAP - GL_TEXTURE0); glUniform1i(rcloc, T_RCONEMAP - GL_TEXTURE0); } void compile_shader(void) { GLint status; sl_shader = glCreateProgram(); // vertex shader printf("Vertex shader setup\n"); int vs = glCreateShader(GL_VERTEX_SHADER); std::string vs_source = load_file("shader.v.glsl"); const char *vs_src = vs_source.c_str(); glShaderSource(vs, 1, &vs_src, 0); glCompileShader(vs); glAttachShader(sl_shader, vs); print_shader_infolog(vs); glGetShaderiv(vs, GL_COMPILE_STATUS, &status); assert(status == GL_TRUE); // fragment shader printf("Fragment shader setup\n"); int ps = glCreateShader(GL_FRAGMENT_SHADER); std::string ps_source = load_file("shader.f.glsl"); const char *ps_src = ps_source.c_str(); glShaderSource(ps, 1, &ps_src, 0); glCompileShader(ps); glAttachShader(sl_shader, ps); print_shader_infolog(ps); glGetShaderiv(ps, GL_COMPILE_STATUS, &status); assert(status == GL_TRUE); // link shader program printf("Shader program setup\n"); glLinkProgram(sl_shader); print_program_infolog(sl_shader); glGetProgramiv(sl_shader, GL_LINK_STATUS, &status); assert(status == GL_TRUE); // get variables location sl_lightpos_var = glGetUniformLocation(sl_shader, "LightPos"); sl_mode_var = glGetUniformLocation(sl_shader, "Mode"); sl_draw_performance_var = glGetUniformLocation(sl_shader, "DrawPerformance"); sl_root_var = glGetUniformLocation(sl_shader, "RootMethod"); // get texture variable locations slt_conemap = glGetUniformLocation(sl_shader, "TConeMap"); slt_diffuse = glGetUniformLocation(sl_shader, "TDiffuse"); slt_heightmap = glGetUniformLocation(sl_shader, "THeightMap"); // set shader as active glUseProgram(sl_shader); } int main(int argc, char **argv) { assert(argv[1]); // initialize glut glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); int w = 1800, h = 900; // init main window glutInitWindowSize(w, h); glutCreateWindow("Local Raycasting Demo"); glutReshapeFunc(on_reshape); glutDisplayFunc(render_main); glutSpecialFunc(on_speckey); glutKeyboardFunc(on_key); glutMotionFunc(on_mousemove); glutMouseFunc(on_mouseclick); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glClearColor(0.0,0.0,0.0,1.0); glewInit(); const char *glslver = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION); printf("GLSL ver: %s\n", glslver ? glslver : "[null]"); assert(glewIsSupported("GL_VERSION_2_0")); compile_shader(); load_texture(T_HEIGHTMAP, argv[1]); load_texture(T_DIFFUSE, "../img/hrube_512x512.png"); glutMainLoop(); } void load_texture(int tex, const char *filename) { int tidx = tex - GL_TEXTURE0; int wt, ht, channels; char fname[strlen(filename)+1]; GLuint tname; strcpy(fname, filename); bool ok = loadPngImage(fname, wt, ht, channels, &textures[tidx]); assert(ok); std::cout << "Image loaded " << wt << " " << ht << " channels " << channels << std::endl; int type = 0; switch (channels) { case 4: type = GL_RGBA; break; case 3: type = GL_RGB; break; case 1: type = GL_LUMINANCE; break; default: assert(false); break; } glActiveTexture(tex); glGenTextures(1, &tname); glBindTexture(GL_TEXTURE_2D, tname); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, channels, wt, ht, 0, type, GL_UNSIGNED_BYTE, textures[tidx]); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if (tex != T_HEIGHTMAP) return; // compute cone map //ht /= 2; wt /= 2; int cmid = T_CONEMAP - GL_TEXTURE0, rcmid = T_RCONEMAP - GL_TEXTURE0; int tsize = sizeof(GLubyte) * wt * ht; textures[cmid] = (GLubyte*) malloc(tsize); textures[rcmid] = (GLubyte*) malloc(tsize); std::cout << "Computing conemap: |" << std::string('.', wt) << "|\b" << std::string('\b', wt) << std::flush; for (int sx = 0; sx < wt; ++sx) for (int sy = 0; sy < ht; ++sy) { GLubyte sz = textures[tidx][ht*sx+sy]; float cone = 1.0; for (int tx = 0; tx < wt; ++tx) for (int ty = 0; ty < ht; ++ty) { GLubyte tz = textures[tidx][ht*tx+ty]; float dx = tx - sx, dy = ty - sy, dz = tz - sz; if (dz > 0.1) { cone = std::min(cone, sqrtf(dx*dx + dy*dy) / (dz * ht / 256.0f)); } } textures[cmid][ht*sx+sy] = static_cast<GLubyte>(cone * 255.99f); if (sy == ht-1) std::cout << '*' << std::flush; } std::cout << std::endl; glActiveTexture(T_CONEMAP); glGenTextures(1, &tname); glBindTexture(GL_TEXTURE_2D, tname); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, 1, wt, ht, 0, type, GL_UNSIGNED_BYTE, textures[cmid]); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } // taken from: http://blog.nobel-joergensen.com/2010/11/07/loading-a-png-as-texture-in-opengl-using-libpng/ bool loadPngImage(char *name, int &outWidth, int &outHeight, int &outChannels, GLubyte **outData) { png_structp png_ptr; png_infop info_ptr; unsigned int sig_read = 0; int color_type, interlace_type; FILE *fp; if ((fp = fopen(name, "rb")) == NULL) return false; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { fclose(fp); return false; } info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { fclose(fp); png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL); return false; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL); fclose(fp); return false; } png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, sig_read); png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, png_voidp_NULL); outWidth = info_ptr->width; outHeight = info_ptr->height; switch (info_ptr->color_type) { case PNG_COLOR_TYPE_RGBA: outChannels = 4; break; case PNG_COLOR_TYPE_RGB: outChannels = 3; break; case PNG_COLOR_TYPE_GRAY: outChannels = 1; break; default: std::cout << "Color type " << info_ptr->color_type << " not supported" << std::endl; png_destroy_read_struct(&png_ptr, &info_ptr, NULL); fclose(fp); return false; } unsigned int row_bytes = png_get_rowbytes(png_ptr, info_ptr); *outData = (unsigned char*) malloc(row_bytes * outHeight); png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr); for (int i = 0; i < outHeight; i++) { memcpy(*outData+(row_bytes * (outHeight-1-i)), row_pointers[i], row_bytes); } png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL); fclose(fp); return true; }
update main.cpp
update main.cpp
C++
mit
iljakuklic/gpu-raycast-experiment
6c370203ea88b4e8b00ed3d879554effb44241e8
main.cpp
main.cpp
#include <iostream> #include <cassert> #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include "vulkanwrapper/Instance.hpp" #include "vulkanwrapper/Device.hpp" using namespace std; void errorCallback(int error, const char *description) { cerr << error << ": " << description << endl; } void * getInstanceProcAddrWrapper(VkInstance instance, const char *pname) { return (void *) glfwGetInstanceProcAddress(instance, pname); } int main() { glfwSetErrorCallback(errorCallback); if(glfwInit() == GLFW_FALSE) { cerr << "Could not initialize GLFW.\n"; return 1; } if(glfwVulkanSupported() == GLFW_FALSE) { cerr << "Vulkan not supported.\n"; return 1; } PFN_vkCreateInstance vkCreateInstance = (PFN_vkCreateInstance) glfwGetInstanceProcAddress(nullptr, "vkCreateInstance"); std::uint32_t extensionCount; const char **glfwExtensions = glfwGetRequiredInstanceExtensions(&extensionCount); ++extensionCount; std::vector<const char*> extensions(extensionCount); for(unsigned int i = 0; i < extensionCount; ++i) { extensions[i] = glfwExtensions[i]; } extensions[extensionCount - 1] = "VK_EXT_debug_report"; VkInstanceCreateInfo instanceCreateInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, // sType nullptr, // pNext 0, // flags nullptr, // pApplicationInfo 0, // enabledLayerCount nullptr, // ppEnabledLayerNames extensionCount, // enabledExtensionCount extensions, // ppEnabledExtensionNames }; VkInstance instanceHandle; if(vkCreateInstance(&instanceCreateInfo, nullptr, &instanceHandle) != VK_SUCCESS) { cerr << "Could not create Vulkan instance.\n"; return 1; } vkw::Instance instance(instanceHandle, getInstanceProcAddrWrapper); auto physicalDevices = instance.enumeratePhysicalDevices(); cout << physicalDevices.size() << endl; auto deviceQueues = instance.getPhysicalDeviceQueueFamilyProperties(physicalDevices[0]); unsigned int universalQueueIndex = 0; for(unsigned int i = 0; i < deviceQueues.size(); ++i) { if(deviceQueues[i].queueFlags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_TRANSFER_BIT | VK_QUEUE_COMPUTE_BIT)) { universalQueueIndex = i; } } float queuePriority = 1.0; VkDeviceQueueCreateInfo queueCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, // sType nullptr, // pNext 0, // flags universalQueueIndex, // queueFamilyIndex 1, // queueCount &queuePriority // pQueuePriorities }; VkPhysicalDeviceFeatures features = instance.getPhysicalDeviceFeatures(physicalDevices[0]); VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, // sType nullptr, // pNext 0, // flags 1, // queueCreateInfoCount &queueCreateInfo, // pQueueCreateInfos 0, // enabledLayerCount nullptr, // ppEnabledLayerNames 0, // enabledExtensionsCount nullptr, // ppEnabledExtensionNames &features // pEnabledFeatures }; vkw::Device device = instance.createDevice(physicalDevices[0], deviceCreateInfo); }
#include <iostream> #include <cassert> #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include "vulkanwrapper/Instance.hpp" #include "vulkanwrapper/Device.hpp" using namespace std; void errorCallback(int error, const char *description) { cerr << error << ": " << description << endl; } VKAPI_ATTR VkBool32 VKAPI_CALL vulkanCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char *pLayerPrefix, const char *pMessage, void *pUserData) { cerr << pMessage << endl; return VK_FALSE; } void * getInstanceProcAddrWrapper(VkInstance instance, const char *pname) { return (void *) glfwGetInstanceProcAddress(instance, pname); } int main() { glfwSetErrorCallback(errorCallback); if(glfwInit() == GLFW_FALSE) { cerr << "Could not initialize GLFW.\n"; return 1; } if(glfwVulkanSupported() == GLFW_FALSE) { cerr << "Vulkan not supported.\n"; return 1; } PFN_vkCreateInstance vkCreateInstance = (PFN_vkCreateInstance) glfwGetInstanceProcAddress(nullptr, "vkCreateInstance"); std::uint32_t extensionCount; const char **glfwExtensions = glfwGetRequiredInstanceExtensions(&extensionCount); std::vector<const char*> extensions(extensionCount + 1); for(unsigned int i = 0; i < extensionCount; ++i) { extensions[i] = glfwExtensions[i]; } extensions[extensionCount] = "VK_EXT_debug_report"; const char *layers[] = { "VK_LAYER_LUNARG_standard_validation" }; VkInstanceCreateInfo instanceCreateInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, // sType nullptr, // pNext 0, // flags nullptr, // pApplicationInfo sizeof(layers) / sizeof (const char *), // enabledLayerCount layers, // ppEnabledLayerNames extensions.size(), // enabledExtensionCount extensions.data(), // ppEnabledExtensionNames }; VkInstance instanceHandle; if(vkCreateInstance(&instanceCreateInfo, nullptr, &instanceHandle) != VK_SUCCESS) { cerr << "Could not create Vulkan instance.\n"; return 1; } PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT) glfwGetInstanceProcAddress(instanceHandle, "vkCreateDebugReportCallbackEXT"); PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT) glfwGetInstanceProcAddress(instanceHandle, "vkDestroyDebugReportCallbackEXT"); assert(vkCreateDebugReportCallbackEXT != nullptr); assert(vkDestroyDebugReportCallbackEXT != nullptr); VkDebugReportCallbackCreateInfoEXT callbackCreateInfo; callbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; callbackCreateInfo.pNext = nullptr; callbackCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; callbackCreateInfo.pfnCallback = &vulkanCallback; callbackCreateInfo.pUserData = nullptr; VkDebugReportCallbackEXT callback; vkCreateDebugReportCallbackEXT(instanceHandle, &callbackCreateInfo, nullptr, &callback); vkw::Instance instance(instanceHandle, getInstanceProcAddrWrapper); auto physicalDevices = instance.enumeratePhysicalDevices(); cout << physicalDevices.size() << endl; auto deviceQueues = instance.getPhysicalDeviceQueueFamilyProperties(physicalDevices[0]); unsigned int universalQueueIndex = 0; for(unsigned int i = 0; i < deviceQueues.size(); ++i) { if(deviceQueues[i].queueFlags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_TRANSFER_BIT | VK_QUEUE_COMPUTE_BIT)) { universalQueueIndex = i; } } float queuePriority = 1.0; VkDeviceQueueCreateInfo queueCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, // sType nullptr, // pNext 0, // flags universalQueueIndex, // queueFamilyIndex 1, // queueCount &queuePriority // pQueuePriorities }; VkPhysicalDeviceFeatures features = instance.getPhysicalDeviceFeatures(physicalDevices[0]); VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, // sType nullptr, // pNext 0, // flags 1, // queueCreateInfoCount &queueCreateInfo, // pQueueCreateInfos 0, // enabledLayerCount nullptr, // ppEnabledLayerNames extensions.size(), // enabledExtensionsCount extensions.data(), // ppEnabledExtensionNames &features // pEnabledFeatures }; vkw::Device device = instance.createDevice(physicalDevices[0], deviceCreateInfo); vkDestroyDebugReportCallbackEXT(instanceHandle, callback, nullptr); }
Debug report
Debug report
C++
mit
chbaker0/vulkan-engine
9ad4b825cfff37f0de9acb11438a28f1c01178c8
structs/stn.cc
structs/stn.cc
#include "stn.hpp" #include <utility> #include <cassert> #include <cstdio> Stn::Stn(unsigned int num) { grow(num+1); nodes[0].tozero = nodes[0].fromzero = 0; } Stn::Stn(const Stn &o) : nodes(o.nodes.size()), undos(o.undos.size()) { for (unsigned int i = 0; i < o.nodes.size(); i++) { Node &n = nodes[i]; n.id = i; n.tozero = o.nodes[i].tozero; n.fromzero = o.nodes[i].fromzero; n.out.resize(o.nodes[i].out.size()); for (unsigned int j = 0; j < n.out.size(); j++) { n.out[j].first = &nodes[o.nodes[i].out[j].first->id]; n.out[j].second = o.nodes[i].out[j].second; } n.in.resize(o.nodes[i].in.size()); for (unsigned int j = 0; j < n.in.size(); j++) { n.in[j].first = &nodes[o.nodes[i].in[j].first->id]; n.in[j].second = o.nodes[i].in[j].second; } } for (unsigned int i = 0; i < o.undos.size(); i++) { Undo &u = undos[i]; u.popout.resize(o.undos[i].popout.size()); for (unsigned int j = 0; j < u.popout.size(); j++) u.popout[j] = &nodes[o.undos[i].popout[j]->id]; u.prevto.resize(o.undos[i].prevto.size()); for (unsigned int j = 0; j < u.prevto.size(); j++) { u.prevto[j].first = &nodes[o.undos[i].prevto[j].first->id]; u.prevto[j].second = o.undos[i].prevto[j].second; } u.prevfrom.resize(o.undos[i].prevfrom.size()); for (unsigned int j = 0; j < u.prevfrom.size(); j++) { u.prevfrom[j].first = &nodes[o.undos[i].prevfrom[j].first->id]; u.prevfrom[j].second = o.undos[i].prevfrom[j].second; } } } void Stn::grow(unsigned int num) { unsigned int oldsz = nodes.size(); nodes.resize(oldsz + num); for (unsigned int i = oldsz; i < nodes.size(); i++) nodes[i].id = i; } bool Stn::add(const Constraint &c) { undos.resize(undos.size()+1); Undo &u = undos.back(); addarcs(u, c); if (!propagate(u, c)) { undo(); return false; } return true; } void Stn::output(FILE *o) const { fprintf(o, "%u nodes\n", nnodes()); for (unsigned int i = 0; i < nnodes(); i++) nodes[i].output(o); for (unsigned int i = 0; i < undos.size(); i++) undos[i].output(o); } void Stn::Node::output(FILE *o) const { fprintf(o, " node: %u, tozero=%ld, fromzero=%ld\n", id, tozero, fromzero); fprintf(o, " out:\n"); for (unsigned int i = 0; i < out.size(); i++) fprintf(o, " %u, %ld\n", out[i].first->id, out[i].second); fprintf(o, " in:\n"); for (unsigned int i = 0; i < in.size(); i++) fprintf(o, " %u, %ld\n", in[i].first->id, in[i].second); } void Stn::Undo::output(FILE *o) const { fprintf(o, "popout:"); for (unsigned int i = 0; i < popout.size(); i++) fprintf(o, " %u", popout[i]->id); fputc('\n', o); fprintf(o, "prevto:\n"); for (unsigned int i = 0; i < prevto.size(); i++) fprintf(o, " %u %ld\n", prevto[i].first->id, prevto[i].second); fprintf(o, "prevfrom:\n"); for (unsigned int i = 0; i < prevfrom.size(); i++) fprintf(o, " %u %ld\n", prevfrom[i].first->id, prevfrom[i].second); } bool Stn::eq(const Stn &o) const { if (nnodes() != o.nnodes() || undos.size() != o.undos.size()) return false; for (unsigned int i = 0; i < nnodes(); i++) if (!nodes[i].eq(o.nodes[i])) return false; for (unsigned int i = 0; i < undos.size(); i++) if (!undos[i].eq(o.undos[i])) return false; return true; } bool Stn::Node::eq(const Stn::Node &o) const { if (id != o.id || tozero != o.tozero || fromzero != o.fromzero || out.size() != o.out.size() || in.size() != o.in.size()) return false; bool found = out.size() == 0; for (unsigned int i = 0; i < out.size() && !found; i++) { for (unsigned int j = 0; j < out.size() && !found; j++) { if (out[i].first->id == o.out[j].first->id && out[i].second == o.out[j].second) found = true; } } if (!found) return false; found = in.size() == 0; for (unsigned int i = 0; i < in.size() && !found; i++) { for (unsigned int j = 0; j < in.size() && !found; j++) { if (in[i].first->id == o.in[j].first->id && in[i].second == o.in[j].second) found = true; } } return found; } bool Stn::Undo::eq(const Undo &o) const { if (popout.size() != o.popout.size() || prevto.size() != o.prevto.size() || prevfrom.size() != o.prevfrom.size()) return false; for (unsigned int i = 0; i < popout.size(); i++) if (popout[i]->id != o.popout[i]->id) return false; for (unsigned int i = 0; i < prevto.size(); i++) { if (prevto[i].first->id != o.prevto[i].first->id || prevto[i].second != o.prevto[i].second) return false; } for (unsigned int i = 0; i < prevfrom.size(); i++) { if (prevfrom[i].first->id != o.prevfrom[i].first->id || prevfrom[i].second != o.prevfrom[i].second) return false; } return true; } void Stn::undo(void) { Undo &undo = undos.back(); for (unsigned int i = 0; i < undo.popout.size(); i++) { Node &u = *undo.popout[i]; assert (u.out.size() > 0); Node &v = *u.out.back().first; u.out.pop_back(); assert (v.in.size() > 0); assert (v.in.back().first->id == u.id); v.in.pop_back(); } for (unsigned int i = 0; i < undo.prevto.size(); i++) undo.prevto[i].first->tozero = undo.prevto[i].second; for (unsigned int i = 0; i < undo.prevfrom.size(); i++) undo.prevfrom[i].first->fromzero = undo.prevfrom[i].second; undos.pop_back(); } bool Stn::propagate(Undo &u, const Constraint &c) { bool seen[nnodes()]; bool toupdt[nnodes()]; bool fromupdt[nnodes()]; for (unsigned int i = 0; i < nnodes(); i++) toupdt[i] = fromupdt[i] = seen[i] = false; return proplower(u, toupdt, seen, nodes[c.i]) && propupper(u, fromupdt, seen, nodes[c.i]) && proplower(u, toupdt, seen, nodes[c.j]) && propupper(u, fromupdt, seen, nodes[c.j]); } void Stn::addarcs(Undo &undo, const Stn::Constraint &c) { if (c.b < inf()) { nodes[c.i].out.push_back(Arc(&nodes[c.j], c.b)); undo.popout.push_back(&nodes[c.i]); nodes[c.j].in.push_back(Arc(&nodes[c.i], c.b)); } if (c.a > neginf()) { nodes[c.j].out.push_back(Arc(&nodes[c.i], -c.a)); undo.popout.push_back(&nodes[c.j]); nodes[c.i].in.push_back(Arc(&nodes[c.j], -c.a)); } } bool Stn::proplower(Undo &undo, bool toupdt[], bool seen[], Node &u) { for (unsigned int i = 0; i < u.in.size(); i++) { Arc &a = u.in[i]; Node &v = *a.first; Time dist = subclamp(u.tozero, a.second); if (dist <= v.tozero) continue; if (v.fromzero < dist || seen[v.id]) return false; if (!toupdt[v.id]) { std::pair<Node*,Time> p(a.first, v.tozero); undo.prevto.push_back(p); toupdt[v.id] = true; } v.tozero = dist; seen[v.id] = true; if (!proplower(undo, toupdt, seen, v)) return false; seen[v.id] = false; } return true; } bool Stn::propupper(Undo &undo, bool fromupdt[], bool seen[], Node &u) { for (unsigned int i = 0; i < u.out.size(); i++) { Arc &a = u.out[i]; Node &v = *a.first; Time dist = addclamp(u.fromzero, a.second); if (dist >= v.fromzero) continue; if (v.tozero > dist || seen[v.id]) return false; if (!fromupdt[v.id]) { std::pair<Node*,Time> p(a.first, v.fromzero); undo.prevfrom.push_back(p); fromupdt[v.id] = true; } v.fromzero = dist; seen[v.id] = true; if (!propupper(undo, fromupdt, seen, v)) return false; seen[v.id] = false; } return true; }
#include "stn.hpp" #include <utility> #include <cassert> #include <cstdio> Stn::Stn(unsigned int num) { grow(num+1); nodes[0].tozero = nodes[0].fromzero = 0; } Stn::Stn(const Stn &o) : nodes(o.nodes.size()), undos(o.undos.size()) { for (unsigned int i = 0; i < o.nodes.size(); i++) { Node &n = nodes[i]; n.id = i; n.tozero = o.nodes[i].tozero; n.fromzero = o.nodes[i].fromzero; n.out.resize(o.nodes[i].out.size()); for (unsigned int j = 0; j < n.out.size(); j++) { n.out[j].first = &nodes[o.nodes[i].out[j].first->id]; n.out[j].second = o.nodes[i].out[j].second; } n.in.resize(o.nodes[i].in.size()); for (unsigned int j = 0; j < n.in.size(); j++) { n.in[j].first = &nodes[o.nodes[i].in[j].first->id]; n.in[j].second = o.nodes[i].in[j].second; } } for (unsigned int i = 0; i < o.undos.size(); i++) { Undo &u = undos[i]; u.popout.resize(o.undos[i].popout.size()); for (unsigned int j = 0; j < u.popout.size(); j++) u.popout[j] = &nodes[o.undos[i].popout[j]->id]; u.prevto.resize(o.undos[i].prevto.size()); for (unsigned int j = 0; j < u.prevto.size(); j++) { u.prevto[j].first = &nodes[o.undos[i].prevto[j].first->id]; u.prevto[j].second = o.undos[i].prevto[j].second; } u.prevfrom.resize(o.undos[i].prevfrom.size()); for (unsigned int j = 0; j < u.prevfrom.size(); j++) { u.prevfrom[j].first = &nodes[o.undos[i].prevfrom[j].first->id]; u.prevfrom[j].second = o.undos[i].prevfrom[j].second; } } } void Stn::grow(unsigned int num) { unsigned int oldsz = nodes.size(); nodes.resize(oldsz + num); for (unsigned int i = oldsz; i < nodes.size(); i++) nodes[i].id = i; } bool Stn::add(const Constraint &c) { undos.resize(undos.size()+1); Undo &u = undos.back(); addarcs(u, c); if (!propagate(u, c)) { undo(); return false; } return true; } void Stn::output(FILE *o) const { fprintf(o, "%u nodes\n", nnodes()); for (unsigned int i = 0; i < nnodes(); i++) nodes[i].output(o); for (unsigned int i = 0; i < undos.size(); i++) undos[i].output(o); } void Stn::Node::output(FILE *o) const { fprintf(o, " node: %u, tozero=%g, fromzero=%g\n", id, (double) tozero, (double) fromzero); fprintf(o, " out:\n"); for (unsigned int i = 0; i < out.size(); i++) fprintf(o, " %u, %g\n", out[i].first->id, (double) out[i].second); fprintf(o, " in:\n"); for (unsigned int i = 0; i < in.size(); i++) fprintf(o, " %u, %g\n", in[i].first->id, (double) in[i].second); } void Stn::Undo::output(FILE *o) const { fprintf(o, "popout:"); for (unsigned int i = 0; i < popout.size(); i++) fprintf(o, " %u", popout[i]->id); fputc('\n', o); fprintf(o, "prevto:\n"); for (unsigned int i = 0; i < prevto.size(); i++) fprintf(o, " %u %g\n", prevto[i].first->id, (double) prevto[i].second); fprintf(o, "prevfrom:\n"); for (unsigned int i = 0; i < prevfrom.size(); i++) fprintf(o, " %u %g\n", prevfrom[i].first->id, (double) prevfrom[i].second); } bool Stn::eq(const Stn &o) const { if (nnodes() != o.nnodes() || undos.size() != o.undos.size()) return false; for (unsigned int i = 0; i < nnodes(); i++) if (!nodes[i].eq(o.nodes[i])) return false; for (unsigned int i = 0; i < undos.size(); i++) if (!undos[i].eq(o.undos[i])) return false; return true; } bool Stn::Node::eq(const Stn::Node &o) const { if (id != o.id || tozero != o.tozero || fromzero != o.fromzero || out.size() != o.out.size() || in.size() != o.in.size()) return false; bool found = out.size() == 0; for (unsigned int i = 0; i < out.size() && !found; i++) { for (unsigned int j = 0; j < out.size() && !found; j++) { if (out[i].first->id == o.out[j].first->id && out[i].second == o.out[j].second) found = true; } } if (!found) return false; found = in.size() == 0; for (unsigned int i = 0; i < in.size() && !found; i++) { for (unsigned int j = 0; j < in.size() && !found; j++) { if (in[i].first->id == o.in[j].first->id && in[i].second == o.in[j].second) found = true; } } return found; } bool Stn::Undo::eq(const Undo &o) const { if (popout.size() != o.popout.size() || prevto.size() != o.prevto.size() || prevfrom.size() != o.prevfrom.size()) return false; for (unsigned int i = 0; i < popout.size(); i++) if (popout[i]->id != o.popout[i]->id) return false; for (unsigned int i = 0; i < prevto.size(); i++) { if (prevto[i].first->id != o.prevto[i].first->id || prevto[i].second != o.prevto[i].second) return false; } for (unsigned int i = 0; i < prevfrom.size(); i++) { if (prevfrom[i].first->id != o.prevfrom[i].first->id || prevfrom[i].second != o.prevfrom[i].second) return false; } return true; } void Stn::undo(void) { Undo &undo = undos.back(); for (unsigned int i = 0; i < undo.popout.size(); i++) { Node &u = *undo.popout[i]; assert (u.out.size() > 0); Node &v = *u.out.back().first; u.out.pop_back(); assert (v.in.size() > 0); assert (v.in.back().first->id == u.id); v.in.pop_back(); } for (unsigned int i = 0; i < undo.prevto.size(); i++) undo.prevto[i].first->tozero = undo.prevto[i].second; for (unsigned int i = 0; i < undo.prevfrom.size(); i++) undo.prevfrom[i].first->fromzero = undo.prevfrom[i].second; undos.pop_back(); } bool Stn::propagate(Undo &u, const Constraint &c) { bool seen[nnodes()]; bool toupdt[nnodes()]; bool fromupdt[nnodes()]; for (unsigned int i = 0; i < nnodes(); i++) toupdt[i] = fromupdt[i] = seen[i] = false; return proplower(u, toupdt, seen, nodes[c.i]) && propupper(u, fromupdt, seen, nodes[c.i]) && proplower(u, toupdt, seen, nodes[c.j]) && propupper(u, fromupdt, seen, nodes[c.j]); } void Stn::addarcs(Undo &undo, const Stn::Constraint &c) { if (c.b < inf()) { nodes[c.i].out.push_back(Arc(&nodes[c.j], c.b)); undo.popout.push_back(&nodes[c.i]); nodes[c.j].in.push_back(Arc(&nodes[c.i], c.b)); } if (c.a > neginf()) { nodes[c.j].out.push_back(Arc(&nodes[c.i], -c.a)); undo.popout.push_back(&nodes[c.j]); nodes[c.i].in.push_back(Arc(&nodes[c.j], -c.a)); } } bool Stn::proplower(Undo &undo, bool toupdt[], bool seen[], Node &u) { for (unsigned int i = 0; i < u.in.size(); i++) { Arc &a = u.in[i]; Node &v = *a.first; Time dist = subclamp(u.tozero, a.second); if (dist <= v.tozero) continue; if (v.fromzero < dist || seen[v.id]) return false; if (!toupdt[v.id]) { std::pair<Node*,Time> p(a.first, v.tozero); undo.prevto.push_back(p); toupdt[v.id] = true; } v.tozero = dist; seen[v.id] = true; if (!proplower(undo, toupdt, seen, v)) return false; seen[v.id] = false; } return true; } bool Stn::propupper(Undo &undo, bool fromupdt[], bool seen[], Node &u) { for (unsigned int i = 0; i < u.out.size(); i++) { Arc &a = u.out[i]; Node &v = *a.first; Time dist = addclamp(u.fromzero, a.second); if (dist >= v.fromzero) continue; if (v.tozero > dist || seen[v.id]) return false; if (!fromupdt[v.id]) { std::pair<Node*,Time> p(a.first, v.fromzero); undo.prevfrom.push_back(p); fromupdt[v.id] = true; } v.fromzero = dist; seen[v.id] = true; if (!propupper(undo, fromupdt, seen, v)) return false; seen[v.id] = false; } return true; }
Use the correct formats when printing the STN.
Use the correct formats when printing the STN.
C++
mit
eaburns/search,eaburns/search,eaburns/search,skiesel/search,skiesel/search,skiesel/search
ce20c5ff7ac85d2214f3f70d41733a967eae56eb
include/hexer/Mathpair.hpp
include/hexer/Mathpair.hpp
/***************************************************************************** (c) 2013 Hobu, Inc. [email protected] Author: Andrew Bell andrew.bell.ia at gmail.com This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #pragma once #include "export.hpp" namespace hexer { template <typename T> struct HEXER_DLL Mathpair { public: Mathpair() : m_x(0.0), m_y(0.0) {} Mathpair(T x, T y) : m_x(x), m_y(y) {} T m_x; T m_y; void operator -= (const Mathpair& p) { m_x -= p.m_x; m_y -= p.m_y; } Mathpair& operator += (const Mathpair& p) { m_x += p.m_x; m_y += p.m_y; return *this; } friend Mathpair operator - (Mathpair p1, const Mathpair& p2) { p1 -= p2; return p1; } friend Mathpair operator + (Mathpair p1, const Mathpair& p2) { p1 += p2; return p1; } }; typedef Mathpair<double> Point; typedef Mathpair<int> Coord; } // namespace hexer
/***************************************************************************** (c) 2013 Hobu, Inc. [email protected] Author: Andrew Bell andrew.bell.ia at gmail.com This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #pragma once #include "export.hpp" namespace hexer { template <typename T> struct HEXER_DLL Mathpair { public: Mathpair() : m_x(T(0)), m_y(T(0)) {} Mathpair(T x, T y) : m_x(x), m_y(y) {} T m_x; T m_y; void operator -= (const Mathpair& p) { m_x -= p.m_x; m_y -= p.m_y; } Mathpair& operator += (const Mathpair& p) { m_x += p.m_x; m_y += p.m_y; return *this; } friend Mathpair operator - (Mathpair p1, const Mathpair& p2) { p1 -= p2; return p1; } friend Mathpair operator + (Mathpair p1, const Mathpair& p2) { p1 += p2; return p1; } }; typedef Mathpair<double> Point; typedef Mathpair<int> Coord; } // namespace hexer
initialize a member with value 0 by using T's constructor, not a double
initialize a member with value 0 by using T's constructor, not a double
C++
lgpl-2.1
gadomski/hexer,gadomski/hexer,gadomski/hexer,gadomski/hexer
6a256afef1a954a46b82f9deb79376b19c53a8b9
include/jmsg/pqxxutils.hpp
include/jmsg/pqxxutils.hpp
#pragma once #include <pqxx/row> #include <pqxx/prepared_statement> #include "jmsg_types.hpp" /// pq key list for fs_param_cfg #define PQKL_fs_param_cfg "seqn,name,ver,fusion_mode,lfti,rfti,align_mode,x_focus,y_focus,ecf_redress,auto_mag,vangle_limit,hangle_limit,clr_mag,clr_time,clr_pos,position,gap,overlap,pre_mag,pre_time,arc1_mag,arc1_time,arc2_mag,arc2_time,arc2_on_time,arc2_off_time,arc_man_time,lft_push_speed,rt_push_speed,taper_splice,taper_wait_time,taper_length,taper_speed,tense_test,tense_speed,tense_length,loss_mode,loss_limit,loss_min,lft_mfd,rt_mfd,syn_bend_co,opp_bend_co,mfd_mis_co" /// pq occupy symbol list for fs_param_cfg #define PQOL_fs_param_cfg "$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45" /// pq member size of fs_param_cfg #define PQMS_fs_param_cfg "45" template<> pqxx::prepare::invocation & pqxx::prepare::invocation::operator()(const fs_param_cfg & src); pqxx::const_row_iterator pqxx2c(fs_param_cfg & dst, const pqxx::const_row_iterator & src); /// pq key list for heat_param_cfg #define PQKL_heat_param_cfg "seqn,name,material,length,auto_heat,heat_time,heat_temp,finish_temp,fast_heat,hold_temp" /// pq occupy symbol list for heat_param_cfg #define PQOL_heat_param_cfg "$1,$2,$3,$4,$5,$6,$7,$8,$9,$10" /// pq member size of heat_param_cfg #define PQMS_heat_param_cfg "10" template<> pqxx::prepare::invocation & pqxx::prepare::invocation::operator()(const heat_param_cfg & src); pqxx::const_row_iterator pqxx2c(heat_param_cfg & dst, const pqxx::const_row_iterator & src); /// pq key list for fusion_splice_result #define PQKL_fusion_splice_result "name,fsp_seqn,fsp_ver,time_consume,code,loss,recinfo_lft_ft,recinfo_lft_clad_dm,recinfo_lft_core_dm,recinfo_rt_ft,recinfo_rt_clad_dm,recinfo_rt_core_dm,defect_yzl_dbmp,defect_yzl_hangle,defect_yzl_vangle,defect_yzl_clad_dm,defect_yzl_core_dm,defect_yzr_dbmp,defect_yzr_hangle,defect_yzr_vangle,defect_yzr_clad_dm,defect_yzr_core_dm,defect_xzl_dbmp,defect_xzl_hangle,defect_xzl_vangle,defect_xzl_clad_dm,defect_xzl_core_dm,defect_xzr_dbmp,defect_xzr_hangle,defect_xzr_vangle,defect_xzr_clad_dm,defect_xzr_core_dm,defect_yz_hangle,defect_xz_hangle,defect_lft_vangle,defect_rt_vangle,defect_yz_img,defect_xz_img,defect_yz_defect_img,defect_xz_defect_img,prestate_core_offset,prestate_clad_offset,prestate_endface_gap,prestate_vertex_angle,tense_test_exed,tense_test_pass,manual_arc_count,xz_final_img,yz_final_img" /// pq occupy symbol list for fusion_splice_result #define PQOL_fusion_splice_result "$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49" /// pq member size of fusion_splice_result #define PQMS_fusion_splice_result "49" template<> pqxx::prepare::invocation & pqxx::prepare::invocation::operator()(const fusion_splice_result & src); pqxx::const_row_iterator pqxx2c(fusion_splice_result & dst, const pqxx::const_row_iterator & src);
#pragma once #include <pqxx/result> #include <pqxx/prepared_statement> #include "jmsg_types.hpp" /// pq key list for fs_param_cfg #define PQKL_fs_param_cfg "seqn,name,ver,fusion_mode,lfti,rfti,align_mode,x_focus,y_focus,ecf_redress,auto_mag,vangle_limit,hangle_limit,clr_mag,clr_time,clr_pos,position,gap,overlap,pre_mag,pre_time,arc1_mag,arc1_time,arc2_mag,arc2_time,arc2_on_time,arc2_off_time,arc_man_time,lft_push_speed,rt_push_speed,taper_splice,taper_wait_time,taper_length,taper_speed,tense_test,tense_speed,tense_length,loss_mode,loss_limit,loss_min,lft_mfd,rt_mfd,syn_bend_co,opp_bend_co,mfd_mis_co" /// pq occupy symbol list for fs_param_cfg #define PQOL_fs_param_cfg "$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45" /// pq member size of fs_param_cfg #define PQMS_fs_param_cfg "45" template<> pqxx::prepare::invocation & pqxx::prepare::invocation::operator()(const fs_param_cfg & src); pqxx::const_row_iterator pqxx2c(fs_param_cfg & dst, const pqxx::const_row_iterator & src); /// pq key list for heat_param_cfg #define PQKL_heat_param_cfg "seqn,name,material,length,auto_heat,heat_time,heat_temp,finish_temp,fast_heat,hold_temp" /// pq occupy symbol list for heat_param_cfg #define PQOL_heat_param_cfg "$1,$2,$3,$4,$5,$6,$7,$8,$9,$10" /// pq member size of heat_param_cfg #define PQMS_heat_param_cfg "10" template<> pqxx::prepare::invocation & pqxx::prepare::invocation::operator()(const heat_param_cfg & src); pqxx::const_row_iterator pqxx2c(heat_param_cfg & dst, const pqxx::const_row_iterator & src); /// pq key list for fusion_splice_result #define PQKL_fusion_splice_result "name,fsp_seqn,fsp_ver,time_consume,code,loss,recinfo_lft_ft,recinfo_lft_clad_dm,recinfo_lft_core_dm,recinfo_rt_ft,recinfo_rt_clad_dm,recinfo_rt_core_dm,defect_yzl_dbmp,defect_yzl_hangle,defect_yzl_vangle,defect_yzl_clad_dm,defect_yzl_core_dm,defect_yzr_dbmp,defect_yzr_hangle,defect_yzr_vangle,defect_yzr_clad_dm,defect_yzr_core_dm,defect_xzl_dbmp,defect_xzl_hangle,defect_xzl_vangle,defect_xzl_clad_dm,defect_xzl_core_dm,defect_xzr_dbmp,defect_xzr_hangle,defect_xzr_vangle,defect_xzr_clad_dm,defect_xzr_core_dm,defect_yz_hangle,defect_xz_hangle,defect_lft_vangle,defect_rt_vangle,defect_yz_img,defect_xz_img,defect_yz_defect_img,defect_xz_defect_img,prestate_core_offset,prestate_clad_offset,prestate_endface_gap,prestate_vertex_angle,tense_test_exed,tense_test_pass,manual_arc_count,xz_final_img,yz_final_img" /// pq occupy symbol list for fusion_splice_result #define PQOL_fusion_splice_result "$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49" /// pq member size of fusion_splice_result #define PQMS_fusion_splice_result "49" template<> pqxx::prepare::invocation & pqxx::prepare::invocation::operator()(const fusion_splice_result & src); pqxx::const_row_iterator pqxx2c(fusion_splice_result & dst, const pqxx::const_row_iterator & src);
use result agains row
pqxx: use result agains row Signed-off-by: Yi Qingliang <[email protected]>
C++
apache-2.0
walkthetalk/libem,walkthetalk/libem,walkthetalk/libem
f5270a32516bf44f31bb124052887cce4be057ff
include/sot/core/device.hh
include/sot/core/device.hh
/* * Copyright 2010, * Florent Lamiraux * * CNRS * * This file is part of sot-core. * sot-core 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. * sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SOT_DEVICE_HH #define SOT_DEVICE_HH /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* -- MaaL --- */ #include <jrl/mal/boost.hh> namespace ml= maal::boost; /* SOT */ #include <dynamic-graph/entity.h> #include <dynamic-graph/all-signals.h> #include <sot-core/vector-roll-pitch-yaw.h> #include "sot/core/api.hh" namespace dynamicgraph { namespace sot { /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ class SOT_CORE_EXPORT Device :public Entity { public: static const std::string CLASS_NAME; virtual const std::string& getClassName(void) const { return CLASS_NAME; } enum ForceSignalSource { FORCE_SIGNAL_RLEG, FORCE_SIGNAL_LLEG, FORCE_SIGNAL_RARM, FORCE_SIGNAL_LARM }; protected: ml::Vector state; bool withForceSignals[4]; public: /* --- CONSTRUCTION --- */ Device(const std::string& name); /* --- DESTRUCTION --- */ ~Device(); void setStateSize(const unsigned int& size); void setState(const ml::Vector& st); void increment(const double & dt = 5e-2); public: /* --- DISPLAY --- */ virtual void display(std::ostream& os) const; SOT_CORE_EXPORT friend std::ostream& operator<<(std::ostream& os,const Device& r) { r.display(os); return os; } public: /* --- SIGNALS --- */ dynamicgraph::SignalPtr<ml::Vector,int> controlSIN; dynamicgraph::SignalPtr<ml::Vector,int> attitudeSIN; dynamicgraph::SignalPtr<ml::Vector,int> zmpSIN; dynamicgraph::Signal<ml::Vector,int> stateSOUT; dynamicgraph::Signal<MatrixRotation,int> attitudeSOUT; dynamicgraph::Signal<ml::Vector,int>* forcesSOUT[4]; dynamicgraph::Signal<ml::Vector,int> pseudoTorqueSOUT; dynamicgraph::Signal<ml::Vector,int> previousControlSOUT; /*! \brief The current state of the robot from the command viewpoint. */ dynamicgraph::Signal<ml::Vector,int> motorcontrolSOUT; /*! \brief The ZMP reference send by the previous controller. */ dynamicgraph::Signal<ml::Vector,int> ZMPPreviousControllerSOUT; public: /* --- COMMANDS --- */ void commandLine(const std::string& cmdLine,std::istringstream& cmdArgs, std::ostream& os){} }; } // namespace sot } // namespace dynamicgraph #endif /* #ifndef SOT_DEVICE_HH */
/* * Copyright 2010, * Florent Lamiraux * * CNRS * * This file is part of sot-core. * sot-core 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. * sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SOT_DEVICE_HH #define SOT_DEVICE_HH /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* -- MaaL --- */ #include <jrl/mal/boost.hh> namespace ml= maal::boost; /* SOT */ #include <dynamic-graph/entity.h> #include <dynamic-graph/all-signals.h> #include <sot-core/vector-roll-pitch-yaw.h> #include "sot/core/api.hh" namespace dynamicgraph { namespace sot { /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ class SOT_CORE_EXPORT Device :public Entity { public: static const std::string CLASS_NAME; virtual const std::string& getClassName(void) const { return CLASS_NAME; } enum ForceSignalSource { FORCE_SIGNAL_RLEG, FORCE_SIGNAL_LLEG, FORCE_SIGNAL_RARM, FORCE_SIGNAL_LARM }; protected: ml::Vector state; bool withForceSignals[4]; public: /* --- CONSTRUCTION --- */ Device(const std::string& name); /* --- DESTRUCTION --- */ virtual ~Device(); void setStateSize(const unsigned int& size); void setState(const ml::Vector& st); void increment(const double & dt = 5e-2); public: /* --- DISPLAY --- */ virtual void display(std::ostream& os) const; SOT_CORE_EXPORT friend std::ostream& operator<<(std::ostream& os,const Device& r) { r.display(os); return os; } public: /* --- SIGNALS --- */ dynamicgraph::SignalPtr<ml::Vector,int> controlSIN; dynamicgraph::SignalPtr<ml::Vector,int> attitudeSIN; dynamicgraph::SignalPtr<ml::Vector,int> zmpSIN; dynamicgraph::Signal<ml::Vector,int> stateSOUT; dynamicgraph::Signal<MatrixRotation,int> attitudeSOUT; dynamicgraph::Signal<ml::Vector,int>* forcesSOUT[4]; dynamicgraph::Signal<ml::Vector,int> pseudoTorqueSOUT; dynamicgraph::Signal<ml::Vector,int> previousControlSOUT; /*! \brief The current state of the robot from the command viewpoint. */ dynamicgraph::Signal<ml::Vector,int> motorcontrolSOUT; /*! \brief The ZMP reference send by the previous controller. */ dynamicgraph::Signal<ml::Vector,int> ZMPPreviousControllerSOUT; public: /* --- COMMANDS --- */ void commandLine(const std::string& cmdLine,std::istringstream& cmdArgs, std::ostream& os){} }; } // namespace sot } // namespace dynamicgraph #endif /* #ifndef SOT_DEVICE_HH */
Make Device destructor virual.
Make Device destructor virual.
C++
bsd-2-clause
stack-of-tasks/sot-core,stack-of-tasks/sot-core,stack-of-tasks/sot-core
40a1e8e43a3936e154ecf6ee0e45b38a5d617e8a
include/wtl/filesystem.hpp
include/wtl/filesystem.hpp
#pragma once #ifndef WTL_FILESYSTEM_HPP_ #define WTL_FILESYSTEM_HPP_ #if defined(_WIN32) #include <direct.h> #else #include <sys/stat.h> #include <unistd.h> #endif #include <cerrno> #include <stdexcept> #include <string> namespace wtl { /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// namespace filesystem { inline bool create_directory(const std::string& path) { #if defined(_WIN32) const int status = ::_mkdir(path.c_str()); #else const int status = ::mkdir(path.c_str(), 0755); #endif if (status && errno != EEXIST) { throw std::runtime_error(path); } return status == 0; } inline void current_path(const std::string& path) { #if defined(_WIN32) if (::_chdir(path.c_str())) { #else if (::chdir(path.c_str())) { #endif throw std::runtime_error(path); } } inline std::string current_path() { char buffer[1024]; #if defined(_WIN32) if (!::_getcwd(buffer, sizeof(buffer))) { #else if (!::getcwd(buffer, sizeof(buffer))) { #endif throw std::runtime_error(buffer); } return std::string(buffer); } } // namespace filesystem /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // RAII class ChDir { public: ChDir(const std::string& dst, bool mkdir=false) { if (dst.empty() || dst == ".") return; if (mkdir) { filesystem::create_directory(dst); } filesystem::current_path(dst); } ~ChDir() { filesystem::current_path(origin_); } private: const std::string origin_ = filesystem::current_path(); }; } // namespace wtl #endif /* WTL_FILESYSTEM_HPP_ */
#pragma once #ifndef WTL_FILESYSTEM_HPP_ #define WTL_FILESYSTEM_HPP_ #if defined(_WIN32) #include <direct.h> #else #include <sys/stat.h> #include <unistd.h> #endif #include <cerrno> #include <stdexcept> #include <string> #include <regex> namespace wtl { /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// namespace filesystem { class path { public: path(const std::string& x): data_(x) {} path parent_path() const { std::regex patt("/[^/]*$"); std::string fmt = ""; return path(std::regex_replace(data_, patt, fmt)); } path filename() const { std::smatch mobj; std::regex patt("[^/]*$"); std::regex_search(data_, mobj, patt); return path(mobj.str(0)); } path stem() const { std::regex patt("\\.[^.]*$"); std::string fmt = ""; return path(std::regex_replace(data_, patt, fmt)).filename(); } path extension() const { std::smatch mobj; std::regex patt("\\.[^.]*$"); std::regex_search(data_, mobj, patt); return path(mobj.str(0)); } std::string string() const {return data_;} private: const std::string data_; }; inline bool create_directory(const std::string& path) { #if defined(_WIN32) const int status = ::_mkdir(path.c_str()); #else const int status = ::mkdir(path.c_str(), 0755); #endif if (status && errno != EEXIST) { throw std::runtime_error(path); } return status == 0; } inline void current_path(const std::string& path) { #if defined(_WIN32) if (::_chdir(path.c_str())) { #else if (::chdir(path.c_str())) { #endif throw std::runtime_error(path); } } inline std::string current_path() { char buffer[1024]; #if defined(_WIN32) if (!::_getcwd(buffer, sizeof(buffer))) { #else if (!::getcwd(buffer, sizeof(buffer))) { #endif throw std::runtime_error(buffer); } return std::string(buffer); } } // namespace filesystem /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // RAII class ChDir { public: ChDir(const std::string& dst, bool mkdir=false) { if (dst.empty() || dst == ".") return; if (mkdir) { filesystem::create_directory(dst); } filesystem::current_path(dst); } ~ChDir() { filesystem::current_path(origin_); } private: const std::string origin_ = filesystem::current_path(); }; } // namespace wtl #endif /* WTL_FILESYSTEM_HPP_ */
Add class fs::path
:sparkles: Add class fs::path
C++
mit
heavywatal/cxxwtils
4ee5c69e36d4de8afd9ff5dd88c31fb9c5a6cbb9
KTp/Models/contacts-list-model.cpp
KTp/Models/contacts-list-model.cpp
/* * Copyright (C) 2012 David Edmundson <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contacts-list-model.h" #include "contact.h" #include <TelepathyQt/Account> #include <TelepathyQt/Contact> #include <TelepathyQt/ContactCapabilities> #include <TelepathyQt/Connection> #include <TelepathyQt/ContactManager> #include <KTp/Models/contacts-model.h> #include <KTp/presence.h> class KTp::ContactsListModel::Private { public: QList<Tp::ContactPtr> contacts; KTp::GlobalContactManager *contactManager; }; KTp::ContactsListModel::ContactsListModel(QObject *parent) : QAbstractListModel(parent), d(new KTp::ContactsListModel::Private()) { d->contactManager = 0; } KTp::ContactsListModel::~ContactsListModel() { delete d; } void KTp::ContactsListModel::setAccountManager(const Tp::AccountManagerPtr &accountManager) { d->contactManager = new KTp::GlobalContactManager(accountManager, this); onContactsChanged(d->contactManager->allKnownContacts(), Tp::Contacts()); connect(d->contactManager, SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)), SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts))); } int KTp::ContactsListModel::rowCount(const QModelIndex &parent) const { Q_UNUSED (parent); return d->contacts.size(); } QVariant KTp::ContactsListModel::data(const QModelIndex &index, int role) const { int row = index.row(); if (row >=0 && row < d->contacts.size()) { const KTp::ContactPtr contact = KTp::ContactPtr::qObjectCast(d->contacts[row]); switch (role) { case ContactsModel::IdRole: return contact->id(); case ContactsModel::TypeRole: return ContactsModel::ContactRowType; case ContactsModel::ContactRole: return QVariant::fromValue(d->contacts[row]); //Tp::ContactPtr and NOT KTp::ContactPtr case ContactsModel::AccountRole: return QVariant::fromValue(d->contactManager->accountForContact(contact)); case Qt::DisplayRole: return contact->alias(); case ContactsModel::AliasRole: return contact->alias(); case ContactsModel::PresenceRole: return QVariant::fromValue(contact->presence()); case ContactsModel::PresenceIconRole: return QIcon(contact->presence().icon()); case ContactsModel::PresenceStatusRole: return contact->presence().status(); case ContactsModel::PresenceTypeRole: return contact->presence().type(); case ContactsModel::PresenceMessageRole: return contact->presence().statusMessage(); case ContactsModel::SubscriptionStateRole: return contact->subscriptionState(); case ContactsModel::PublishStateRole: return contact->publishState(); case ContactsModel::BlockedRole: return contact->isBlocked(); case ContactsModel::GroupsRole: return contact->groups(); case ContactsModel::AvatarRole: return contact->avatarData().fileName; case Qt::DecorationRole: return QImage(contact->avatarData().fileName); case ContactsModel::TextChatCapabilityRole: return contact->capabilities().textChats(); case ContactsModel::ClientTypesRole: return contact->clientTypes(); default: break; } } return QVariant(); } void KTp::ContactsListModel::onContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed) { //add contacts. Q_FOREACH(const Tp::ContactPtr &contact_uncasted, added) { KTp::ContactPtr contact = KTp::ContactPtr::qObjectCast(contact_uncasted); connect(contact.data(), SIGNAL(aliasChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarTokenChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SLOT(onChanged())); connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)), SLOT(onChanged())); connect(contact->manager()->connection()->selfContact().data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(locationUpdated(Tp::LocationInfo)), SLOT(onChanged())); connect(contact.data(), SIGNAL(infoFieldsChanged(Tp::Contact::InfoFields)), SLOT(onChanged())); connect(contact.data(), SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)), SLOT(onChanged())); connect(contact.data(), SIGNAL(publishStateChanged(Tp::Contact::PresenceState,QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(blockStatusChanged(bool)), SLOT(onChanged())); connect(contact.data(), SIGNAL(clientTypesChanged(QStringList)), SLOT(onChanged())); connect(contact.data(), SIGNAL(invalidated()), SLOT(onConnectionDropped())); } if (added.size() > 0) { beginInsertRows(QModelIndex(), d->contacts.size(), d->contacts.size() + added.size() -1); d->contacts.append(added.toList()); endInsertRows(); } //remove contacts Q_FOREACH(const Tp::ContactPtr &contact, removed) { int row = d->contacts.indexOf(contact); if (row >= 0) { //if contact found in list beginRemoveRows(QModelIndex(), row, row); d->contacts.removeOne(contact); endRemoveRows(); } } } void KTp::ContactsListModel::onChanged() { KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); int row = d->contacts.indexOf(contact); if (row > 0) { QModelIndex index = createIndex(row, 0); dataChanged(index, index); } } void KTp::ContactsListModel::onConnectionDropped() { KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); onContactsChanged(Tp::Contacts(), Tp::Contacts() << contact); }
/* * Copyright (C) 2012 David Edmundson <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contacts-list-model.h" #include "contact.h" #include <TelepathyQt/Account> #include <TelepathyQt/Contact> #include <TelepathyQt/ContactCapabilities> #include <TelepathyQt/Connection> #include <TelepathyQt/ContactManager> #include <KTp/Models/contacts-model.h> #include <KTp/presence.h> class KTp::ContactsListModel::Private { public: QList<Tp::ContactPtr> contacts; KTp::GlobalContactManager *contactManager; }; KTp::ContactsListModel::ContactsListModel(QObject *parent) : QAbstractListModel(parent), d(new KTp::ContactsListModel::Private()) { d->contactManager = 0; } KTp::ContactsListModel::~ContactsListModel() { delete d; } void KTp::ContactsListModel::setAccountManager(const Tp::AccountManagerPtr &accountManager) { d->contactManager = new KTp::GlobalContactManager(accountManager, this); onContactsChanged(d->contactManager->allKnownContacts(), Tp::Contacts()); connect(d->contactManager, SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)), SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts))); } int KTp::ContactsListModel::rowCount(const QModelIndex &parent) const { Q_UNUSED (parent); return d->contacts.size(); } QVariant KTp::ContactsListModel::data(const QModelIndex &index, int role) const { int row = index.row(); if (row >=0 && row < d->contacts.size()) { const KTp::ContactPtr contact = KTp::ContactPtr::qObjectCast(d->contacts[row]); switch (role) { case ContactsModel::IdRole: return contact->id(); case ContactsModel::TypeRole: return ContactsModel::ContactRowType; case ContactsModel::ContactRole: return QVariant::fromValue(d->contacts[row]); //Tp::ContactPtr and NOT KTp::ContactPtr case ContactsModel::AccountRole: return QVariant::fromValue(d->contactManager->accountForContact(contact)); case Qt::DisplayRole: return contact->alias(); case ContactsModel::AliasRole: return contact->alias(); case ContactsModel::PresenceRole: return QVariant::fromValue(contact->presence()); case ContactsModel::PresenceIconRole: return QIcon(contact->presence().icon()); case ContactsModel::PresenceStatusRole: return contact->presence().status(); case ContactsModel::PresenceTypeRole: return contact->presence().type(); case ContactsModel::PresenceMessageRole: return contact->presence().statusMessage(); case ContactsModel::SubscriptionStateRole: return contact->subscriptionState(); case ContactsModel::PublishStateRole: return contact->publishState(); case ContactsModel::BlockedRole: return contact->isBlocked(); case ContactsModel::GroupsRole: return contact->groups(); case ContactsModel::AvatarRole: return contact->avatarData().fileName; case Qt::DecorationRole: return QImage(contact->avatarData().fileName); case ContactsModel::TextChatCapabilityRole: return contact->capabilities().textChats(); case ContactsModel::ClientTypesRole: return contact->clientTypes(); default: break; } } return QVariant(); } void KTp::ContactsListModel::onContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed) { //add contacts. Q_FOREACH(const Tp::ContactPtr &contact_uncasted, added) { KTp::ContactPtr contact = KTp::ContactPtr::qObjectCast(contact_uncasted); connect(contact.data(), SIGNAL(aliasChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarTokenChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SLOT(onChanged())); connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)), SLOT(onChanged())); connect(contact->manager()->connection()->selfContact().data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(locationUpdated(Tp::LocationInfo)), SLOT(onChanged())); connect(contact.data(), SIGNAL(infoFieldsChanged(Tp::Contact::InfoFields)), SLOT(onChanged())); connect(contact.data(), SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)), SLOT(onChanged())); connect(contact.data(), SIGNAL(publishStateChanged(Tp::Contact::PresenceState,QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(blockStatusChanged(bool)), SLOT(onChanged())); connect(contact.data(), SIGNAL(clientTypesChanged(QStringList)), SLOT(onChanged())); connect(contact.data(), SIGNAL(addedToGroup(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(removedFromGroup(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(invalidated()), SLOT(onConnectionDropped())); } if (added.size() > 0) { beginInsertRows(QModelIndex(), d->contacts.size(), d->contacts.size() + added.size() -1); d->contacts.append(added.toList()); endInsertRows(); } //remove contacts Q_FOREACH(const Tp::ContactPtr &contact, removed) { int row = d->contacts.indexOf(contact); if (row >= 0) { //if contact found in list beginRemoveRows(QModelIndex(), row, row); d->contacts.removeOne(contact); endRemoveRows(); } } } void KTp::ContactsListModel::onChanged() { KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); int row = d->contacts.indexOf(contact); if (row > 0) { QModelIndex index = createIndex(row, 0); dataChanged(index, index); } } void KTp::ContactsListModel::onConnectionDropped() { KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); onContactsChanged(Tp::Contacts(), Tp::Contacts() << contact); }
Update model when contact is moved to a group
Update model when contact is moved to a group REVIEW: 108018
C++
lgpl-2.1
KDE/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals,leonhandreke/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals
bada14828f203a2a618401a269b883712e75744e
KTp/Widgets/add-contact-dialog.cpp
KTp/Widgets/add-contact-dialog.cpp
/* * Add contact dialog * * Copyright (C) 2011 David Edmundson <[email protected]> * Copyright (C) 2012 George Kiagiadakis <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "add-contact-dialog.h" #include "ui_add-contact-dialog.h" #include <KTp/Models/accounts-model.h> #include <KTp/Models/accounts-model-item.h> #include <QObject> #include <QSortFilterProxyModel> #include <QCloseEvent> #include <KMessageBox> #include <KPushButton> #include <KDebug> #include <TelepathyQt/Account> #include <TelepathyQt/Connection> #include <TelepathyQt/ContactManager> #include <TelepathyQt/PendingContacts> namespace KTp { /** A filter which only lists connections which accept adding contacts*/ class KTP_NO_EXPORT SubscribableAccountsModel : public QSortFilterProxyModel { public: SubscribableAccountsModel(QObject *parent); virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; }; SubscribableAccountsModel::SubscribableAccountsModel(QObject *parent) : QSortFilterProxyModel(parent) { } bool SubscribableAccountsModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { AccountsModelItem* item = sourceModel()->index(source_row, 0, source_parent).data(AccountsModel::ItemRole).value<AccountsModelItem*>(); if (item) { Tp::AccountPtr account = item->account(); //if there's no connection we can't add contacts as we have no contactmanager if (! account->connection()) { return false; } //only show items which can add a contact (i.e hide accounts like IRC which are online but there's no point listing) if (! account->connection()->contactManager()->canRequestPresenceSubscription()){ return false; } } return true; } struct KTP_NO_EXPORT AddContactDialog::Private { Private() : ui(new Ui::AddContactDialog), acceptInProgress(false) {} Ui::AddContactDialog *ui; bool acceptInProgress; }; AddContactDialog::AddContactDialog(AccountsModel *accountModel, QWidget *parent) : KDialog(parent), d(new Private) { QWidget *widget = new QWidget(this); d->ui->setupUi(widget); setMainWidget(widget); SubscribableAccountsModel *filteredModel = new SubscribableAccountsModel(this); filteredModel->setSourceModel(accountModel); d->ui->accountCombo->setModel(filteredModel); d->ui->screenNameLineEdit->setFocus(); } AddContactDialog::~AddContactDialog() { delete d->ui; delete d; } void AddContactDialog::accept() { Tp::AccountPtr account; QVariant itemData = d->ui->accountCombo->itemData(d->ui->accountCombo->currentIndex(), AccountsModel::ItemRole); AccountsModelItem* item = itemData.value<AccountsModelItem*>(); if (item) { account = item->account(); } if (account.isNull()) { KMessageBox::sorry(this, i18n("No account selected.")); } else if (account->connection().isNull()) { KMessageBox::sorry(this, i18n("The requested account has been disconnected " "and so the contact could not be added.")); } else if (d->ui->screenNameLineEdit->text().isEmpty()) { KMessageBox::sorry(this, i18n("You did not specify the name of the contact to add.")); } else { QStringList identifiers = QStringList() << d->ui->screenNameLineEdit->text(); kDebug() << "Requesting contacts for identifiers:" << identifiers; Tp::PendingContacts *pendingContacts = account->connection()->contactManager()->contactsForIdentifiers(identifiers); connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(_k_onContactsForIdentifiersFinished(Tp::PendingOperation*))); setInProgress(true); } } void AddContactDialog::closeEvent(QCloseEvent *e) { // ignore close event if we are in the middle of an operation if (!d->acceptInProgress) { KDialog::closeEvent(e); } } void AddContactDialog::_k_onContactsForIdentifiersFinished(Tp::PendingOperation *op) { if (op->isError()) { kWarning() << "Failed to retrieve a contact for the given identifier" << op->errorName() << op->errorMessage(); KMessageBox::sorry(this, i18n("Failed to create new contact.")); setInProgress(false); } else { kDebug() << "Requesting presence subscription"; Tp::PendingContacts *pc = qobject_cast<Tp::PendingContacts*>(op); connect(pc->manager()->requestPresenceSubscription(pc->contacts()), SIGNAL(finished(Tp::PendingOperation*)), SLOT(_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation*))); } } void AddContactDialog::_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation *op) { if (op->isError()) { kWarning() << "Failed to request presence subscription" << op->errorName() << op->errorMessage(); KMessageBox::sorry(this, i18n("Failed to request presence subscription " "from the requested contact.")); setInProgress(false); } else { QDialog::accept(); } } void AddContactDialog::setInProgress(bool inProgress) { d->acceptInProgress = inProgress; mainWidget()->setEnabled(!inProgress); button(KDialog::Ok)->setEnabled(!inProgress); button(KDialog::Cancel)->setEnabled(!inProgress); } } //namespace KTp #include "add-contact-dialog.moc"
/* * Add contact dialog * * Copyright (C) 2011 David Edmundson <[email protected]> * Copyright (C) 2012 George Kiagiadakis <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "add-contact-dialog.h" #include "ui_add-contact-dialog.h" #include <KTp/Models/accounts-model.h> #include <KTp/Models/accounts-model-item.h> #include <QObject> #include <QSortFilterProxyModel> #include <QCloseEvent> #include <KMessageBox> #include <KPushButton> #include <KDebug> #include <TelepathyQt/Account> #include <TelepathyQt/Connection> #include <TelepathyQt/ContactManager> #include <TelepathyQt/PendingContacts> namespace KTp { /** A filter which only lists connections which accept adding contacts*/ class KTP_NO_EXPORT SubscribableAccountsModel : public QSortFilterProxyModel { public: SubscribableAccountsModel(QObject *parent); virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; }; SubscribableAccountsModel::SubscribableAccountsModel(QObject *parent) : QSortFilterProxyModel(parent) { } bool SubscribableAccountsModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { AccountsModelItem* item = sourceModel()->index(source_row, 0, source_parent).data(AccountsModel::ItemRole).value<AccountsModelItem*>(); if (item) { Tp::AccountPtr account = item->account(); //if there's no connection we can't add contacts as we have no contactmanager if (! account->connection()) { return false; } //only show items which can add a contact (i.e hide accounts like IRC which are online but there's no point listing) if (! account->connection()->contactManager()->canRequestPresenceSubscription()){ return false; } } return true; } struct KTP_NO_EXPORT AddContactDialog::Private { Private() : ui(new Ui::AddContactDialog), acceptInProgress(false) {} Ui::AddContactDialog *ui; bool acceptInProgress; }; AddContactDialog::AddContactDialog(AccountsModel *accountModel, QWidget *parent) : KDialog(parent), d(new Private) { setWindowTitle(i18n("Add new contact")); setWindowIcon(QIcon::fromTheme(QLatin1String("list-add-user"))); QWidget *widget = new QWidget(this); d->ui->setupUi(widget); setMainWidget(widget); SubscribableAccountsModel *filteredModel = new SubscribableAccountsModel(this); filteredModel->setSourceModel(accountModel); d->ui->accountCombo->setModel(filteredModel); d->ui->screenNameLineEdit->setFocus(); } AddContactDialog::~AddContactDialog() { delete d->ui; delete d; } void AddContactDialog::accept() { Tp::AccountPtr account; QVariant itemData = d->ui->accountCombo->itemData(d->ui->accountCombo->currentIndex(), AccountsModel::ItemRole); AccountsModelItem* item = itemData.value<AccountsModelItem*>(); if (item) { account = item->account(); } if (account.isNull()) { KMessageBox::sorry(this, i18n("No account selected.")); } else if (account->connection().isNull()) { KMessageBox::sorry(this, i18n("The requested account has been disconnected " "and so the contact could not be added.")); } else if (d->ui->screenNameLineEdit->text().isEmpty()) { KMessageBox::sorry(this, i18n("You did not specify the name of the contact to add.")); } else { QStringList identifiers = QStringList() << d->ui->screenNameLineEdit->text(); kDebug() << "Requesting contacts for identifiers:" << identifiers; Tp::PendingContacts *pendingContacts = account->connection()->contactManager()->contactsForIdentifiers(identifiers); connect(pendingContacts, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(_k_onContactsForIdentifiersFinished(Tp::PendingOperation*))); setInProgress(true); } } void AddContactDialog::closeEvent(QCloseEvent *e) { // ignore close event if we are in the middle of an operation if (!d->acceptInProgress) { KDialog::closeEvent(e); } } void AddContactDialog::_k_onContactsForIdentifiersFinished(Tp::PendingOperation *op) { if (op->isError()) { kWarning() << "Failed to retrieve a contact for the given identifier" << op->errorName() << op->errorMessage(); KMessageBox::sorry(this, i18n("Failed to create new contact.")); setInProgress(false); } else { kDebug() << "Requesting presence subscription"; Tp::PendingContacts *pc = qobject_cast<Tp::PendingContacts*>(op); connect(pc->manager()->requestPresenceSubscription(pc->contacts()), SIGNAL(finished(Tp::PendingOperation*)), SLOT(_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation*))); } } void AddContactDialog::_k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation *op) { if (op->isError()) { kWarning() << "Failed to request presence subscription" << op->errorName() << op->errorMessage(); KMessageBox::sorry(this, i18n("Failed to request presence subscription " "from the requested contact.")); setInProgress(false); } else { QDialog::accept(); } } void AddContactDialog::setInProgress(bool inProgress) { d->acceptInProgress = inProgress; mainWidget()->setEnabled(!inProgress); button(KDialog::Ok)->setEnabled(!inProgress); button(KDialog::Cancel)->setEnabled(!inProgress); } } //namespace KTp #include "add-contact-dialog.moc"
Set window title & icon
AddContactDialog: Set window title & icon
C++
lgpl-2.1
leonhandreke/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals,KDE/ktp-common-internals
ba1bc60542a1a4c7ade1a563465328a3fdde1fc7
lib/Target/Mips/MipsMachineFunction.cpp
lib/Target/Mips/MipsMachineFunction.cpp
//===-- MipsMachineFunctionInfo.cpp - Private data used for Mips ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MipsMachineFunction.h" #include "MCTargetDesc/MipsBaseInfo.h" #include "MipsInstrInfo.h" #include "MipsSubtarget.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" using namespace llvm; static cl::opt<bool> FixGlobalBaseReg("mips-fix-global-base-reg", cl::Hidden, cl::init(true), cl::desc("Always use $gp as the global base register.")); // class MipsCallEntry. MipsCallEntry::MipsCallEntry(const StringRef &N) { #ifndef NDEBUG Name = N; Val = 0; #endif } MipsCallEntry::MipsCallEntry(const GlobalValue *V) { #ifndef NDEBUG Val = V; #endif } bool MipsCallEntry::isConstant(const MachineFrameInfo *) const { return false; } bool MipsCallEntry::isAliased(const MachineFrameInfo *) const { return false; } bool MipsCallEntry::mayAlias(const MachineFrameInfo *) const { return false; } void MipsCallEntry::printCustom(raw_ostream &O) const { O << "MipsCallEntry: "; #ifndef NDEBUG if (Val) O << Val->getName(); else O << Name; #endif } MipsFunctionInfo::~MipsFunctionInfo() { for (StringMap<const MipsCallEntry *>::iterator I = ExternalCallEntries.begin(), E = ExternalCallEntries.end(); I != E; ++I) delete I->getValue(); for (ValueMap<const GlobalValue *, const MipsCallEntry *>::iterator I = GlobalCallEntries.begin(), E = GlobalCallEntries.end(); I != E; ++I) delete I->second; } bool MipsFunctionInfo::globalBaseRegSet() const { return GlobalBaseReg; } unsigned MipsFunctionInfo::getGlobalBaseReg() { // Return if it has already been initialized. if (GlobalBaseReg) return GlobalBaseReg; const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>(); const TargetRegisterClass *RC; if (ST.inMips16Mode()) RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass; else RC = ST.isABI_N64() ? (const TargetRegisterClass*)&Mips::GPR64RegClass : (const TargetRegisterClass*)&Mips::GPR32RegClass; return GlobalBaseReg = MF.getRegInfo().createVirtualRegister(RC); } bool MipsFunctionInfo::mips16SPAliasRegSet() const { return Mips16SPAliasReg; } unsigned MipsFunctionInfo::getMips16SPAliasReg() { // Return if it has already been initialized. if (Mips16SPAliasReg) return Mips16SPAliasReg; const TargetRegisterClass *RC; RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass; return Mips16SPAliasReg = MF.getRegInfo().createVirtualRegister(RC); } void MipsFunctionInfo::createEhDataRegsFI() { for (int I = 0; I < 4; ++I) { const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>(); const TargetRegisterClass *RC = ST.isABI_N64() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass; EhDataRegFI[I] = MF.getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment(), false); } } bool MipsFunctionInfo::isEhDataRegFI(int FI) const { return CallsEhReturn && (FI == EhDataRegFI[0] || FI == EhDataRegFI[1] || FI == EhDataRegFI[2] || FI == EhDataRegFI[3]); } MachinePointerInfo MipsFunctionInfo::callPtrInfo(const StringRef &Name) { StringMap<const MipsCallEntry *>::const_iterator I; I = ExternalCallEntries.find(Name); if (I != ExternalCallEntries.end()) return MachinePointerInfo(I->getValue()); const MipsCallEntry *E = ExternalCallEntries[Name] = new MipsCallEntry(Name); return MachinePointerInfo(E); } MachinePointerInfo MipsFunctionInfo::callPtrInfo(const GlobalValue *Val) { ValueMap<const GlobalValue *, const MipsCallEntry *>::const_iterator I; I = GlobalCallEntries.find(Val); if (I != GlobalCallEntries.end()) return MachinePointerInfo(I->second); const MipsCallEntry *E = GlobalCallEntries[Val] = new MipsCallEntry(Val); return MachinePointerInfo(E); } void MipsFunctionInfo::anchor() { }
//===-- MipsMachineFunctionInfo.cpp - Private data used for Mips ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MipsMachineFunction.h" #include "MCTargetDesc/MipsBaseInfo.h" #include "MipsInstrInfo.h" #include "MipsSubtarget.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; static cl::opt<bool> FixGlobalBaseReg("mips-fix-global-base-reg", cl::Hidden, cl::init(true), cl::desc("Always use $gp as the global base register.")); // class MipsCallEntry. MipsCallEntry::MipsCallEntry(const StringRef &N) { #ifndef NDEBUG Name = N; Val = 0; #endif } MipsCallEntry::MipsCallEntry(const GlobalValue *V) { #ifndef NDEBUG Val = V; #endif } bool MipsCallEntry::isConstant(const MachineFrameInfo *) const { return false; } bool MipsCallEntry::isAliased(const MachineFrameInfo *) const { return false; } bool MipsCallEntry::mayAlias(const MachineFrameInfo *) const { return false; } void MipsCallEntry::printCustom(raw_ostream &O) const { O << "MipsCallEntry: "; #ifndef NDEBUG if (Val) O << Val->getName(); else O << Name; #endif } MipsFunctionInfo::~MipsFunctionInfo() { for (StringMap<const MipsCallEntry *>::iterator I = ExternalCallEntries.begin(), E = ExternalCallEntries.end(); I != E; ++I) delete I->getValue(); for (ValueMap<const GlobalValue *, const MipsCallEntry *>::iterator I = GlobalCallEntries.begin(), E = GlobalCallEntries.end(); I != E; ++I) delete I->second; } bool MipsFunctionInfo::globalBaseRegSet() const { return GlobalBaseReg; } unsigned MipsFunctionInfo::getGlobalBaseReg() { // Return if it has already been initialized. if (GlobalBaseReg) return GlobalBaseReg; const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>(); const TargetRegisterClass *RC; if (ST.inMips16Mode()) RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass; else RC = ST.isABI_N64() ? (const TargetRegisterClass*)&Mips::GPR64RegClass : (const TargetRegisterClass*)&Mips::GPR32RegClass; return GlobalBaseReg = MF.getRegInfo().createVirtualRegister(RC); } bool MipsFunctionInfo::mips16SPAliasRegSet() const { return Mips16SPAliasReg; } unsigned MipsFunctionInfo::getMips16SPAliasReg() { // Return if it has already been initialized. if (Mips16SPAliasReg) return Mips16SPAliasReg; const TargetRegisterClass *RC; RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass; return Mips16SPAliasReg = MF.getRegInfo().createVirtualRegister(RC); } void MipsFunctionInfo::createEhDataRegsFI() { for (int I = 0; I < 4; ++I) { const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>(); const TargetRegisterClass *RC = ST.isABI_N64() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass; EhDataRegFI[I] = MF.getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment(), false); } } bool MipsFunctionInfo::isEhDataRegFI(int FI) const { return CallsEhReturn && (FI == EhDataRegFI[0] || FI == EhDataRegFI[1] || FI == EhDataRegFI[2] || FI == EhDataRegFI[3]); } MachinePointerInfo MipsFunctionInfo::callPtrInfo(const StringRef &Name) { StringMap<const MipsCallEntry *>::const_iterator I; I = ExternalCallEntries.find(Name); if (I != ExternalCallEntries.end()) return MachinePointerInfo(I->getValue()); const MipsCallEntry *E = ExternalCallEntries[Name] = new MipsCallEntry(Name); return MachinePointerInfo(E); } MachinePointerInfo MipsFunctionInfo::callPtrInfo(const GlobalValue *Val) { ValueMap<const GlobalValue *, const MipsCallEntry *>::const_iterator I; I = GlobalCallEntries.find(Val); if (I != GlobalCallEntries.end()) return MachinePointerInfo(I->second); const MipsCallEntry *E = GlobalCallEntries[Val] = new MipsCallEntry(Val); return MachinePointerInfo(E); } void MipsFunctionInfo::anchor() { }
Add missing #include <raw_ostream.h>
MipsMachineFunction.cpp: Add missing #include <raw_ostream.h> git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@191597 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm
6f17aa70264006a37519db7dd10245dd54eb34bc
utils/src/Utils.cpp
utils/src/Utils.cpp
/* Copyright(C) * For free * All right reserved * */ /** * @file Utils.cpp * @brief 常用工具实现 * @author highway-9, [email protected] * @version 0.1.0 * @date 2015-11-28 */ #include "Utils.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/sysinfo.h> #include <uuid/uuid.h> #include <openssl/crypto.h> #include <openssl/md5.h> #include <openssl/sha.h> #ifndef PATH_MAX #define PATH_MAX 1024 // 默认最大路径长度 #endif /**********************************class String**********************************************/ std::string utils::String::int32ToString(int n) { return tToString(n); } std::string utils::String::uint32ToString(unsigned int n) { return tToString(n); } std::string utils::String::int64ToString(long long n) { return tToString(n); } std::string utils::String::uint64ToString(unsigned long long n) { return tToString(n); } std::string utils::String::floatToString(float n) { return tToString(n); } std::string utils::String::doubleToString(double n) { return tToString(n); } std::string utils::String::time_tToString(time_t n) { struct tm* p; p = localtime(&n); p->tm_year += 1900; p->tm_mon++; char time[50] = {'\0'}; sprintf(time, "%04d-%02d-%02d %02d:%02d:%02d", p->tm_year, p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); return time; } bool utils::String::stringToInt32(const std::string& str, int& n) { return stringToT(str, n); } bool utils::String::stringToUint32(const std::string& str, unsigned int& n) { return stringToT(str, n); } bool utils::String::stringToInt64(const std::string& str, long long& n) { return stringToT(str, n); } bool utils::String::stringToUint64(const std::string& str, unsigned long long& n) { return stringToT(str, n); } bool utils::String::stringToFloat(const std::string& str, float& n) { return stringToT(str, n); } bool utils::String::stringToDouble(const std::string& str, double& n) { return stringToT(str, n); } time_t utils::String::stringToTime_t(const std::string& time) { struct tm stTm; sscanf(time.c_str(), "%d-%d-%d %d:%d:%d", &(stTm.tm_year), &(stTm.tm_mon), &(stTm.tm_mday), &(stTm.tm_hour), &(stTm.tm_min), &(stTm.tm_sec)); stTm.tm_year -= 1900; stTm.tm_mon--; stTm.tm_isdst = -1; return mktime(&stTm); } /**********************************class FileSystem**********************************************/ std::string utils::FileSystem::currentWorkPath() { char buf[PATH_MAX] = {'\0'}; if (getcwd(buf, sizeof (buf) - 1) != NULL) { return buf; } return ""; } bool utils::FileSystem::setCurrentWorkPath(const std::string& path) { int ret = chdir(path.c_str()); return ret == -1 ? false : true; } std::string utils::FileSystem::currentExePath() { char buf[PATH_MAX] = {'\0'}; int ret = readlink("/proc/self/exe", buf, PATH_MAX); if (ret < 0 || ret >= PATH_MAX) { return ""; } std::string path(buf); int pos = -1; for (int i = path.size() - 1; i >= 0; --i) { if (path[i] == '/') { pos = i; break; } } if (pos == -1) { return ""; } path = path.substr(0, pos); return path; } std::string utils::FileSystem::currentExeName() { char buf[PATH_MAX] = {'\0'}; int ret = readlink("/proc/self/exe", buf, PATH_MAX); if (ret < 0 || ret >= PATH_MAX) { return ""; } std::string path(buf); int pos = -1; for (int i = path.size() - 1; i >= 0; --i) { if (path[i] == '/') { pos = i; break; } } if (pos == -1) { return std::string(); } path = path.substr(pos + 1, path.size() - 1); return path; } bool utils::FileSystem::isExists(const std::string& path) { // F_OK 用于判断文件是否存在 int ret = access(path.c_str(), F_OK); return ret == -1 ? false : true; } bool utils::FileSystem::mkdir(const std::string& path) { if (path.empty()) { return false; } if (utils::FileSystem::isExists(path)) { return true; } std::string dirPath = path; if (dirPath[dirPath.size() - 1] != '/') { dirPath += '/'; } for (unsigned int i = 0; i < dirPath.size(); ++i) { if (dirPath[i] == '/') { if (i == 0) { continue; } std::string tempPath = dirPath.substr(0, i); if (!utils::FileSystem::isExists(tempPath)) { if (::mkdir(tempPath.c_str(), 0755) == -1) { return false; } } } } return true; } bool utils::FileSystem::remove(const std::string& path) { if (path.empty()) { return false; } if (!utils::FileSystem::isExists(path)) { return false; } int ret = ::remove(path.c_str()); return ret == -1 ? false : true; } /**********************************class System**********************************************/ std::string utils::System::uuid() { uuid_t uuid; uuid_generate(uuid); char buf[37] = {'\0'}; uuid_unparse_upper(uuid, buf); return buf; } std::string utils::System::md5(const std::string& str) { MD5_CTX hashCtx; unsigned char hashRet[MD5_DIGEST_LENGTH]; int ret = MD5_Init(&hashCtx); if (ret == 0) { return ""; } ret = MD5_Update(&hashCtx, str.c_str(), str.size()); if (ret == 0) { return ""; } ret = MD5_Final(hashRet, &hashCtx); if (ret == 0) { return ""; } OPENSSL_cleanse(&hashCtx, sizeof (hashCtx)); std::string md5Text; char buf[2] = {'\0'}; for (int i = 0; i < MD5_DIGEST_LENGTH * 2; ++i) { memset(buf, '\0', sizeof (buf)); if (i & 0x1) { sprintf(buf, "%x", (hashRet[i / 2]) & 0xf); } else { sprintf(buf, "%x", (hashRet[i / 2] >> 4) & 0xf); } md5Text += buf; } return md5Text; } std::string utils::System::sha1(const std::string& str) { SHA_CTX hashCtx; unsigned char hashRet[SHA_DIGEST_LENGTH]; int ret = SHA1_Init(&hashCtx); if (ret == 0) { return ""; } ret = SHA1_Update(&hashCtx, str.c_str(), str.size()); if (ret == 0) { return ""; } ret = SHA1_Final(hashRet, &hashCtx); if (ret == 0) { return ""; } OPENSSL_cleanse(&hashCtx, sizeof (hashCtx)); std::string sha1Text; char buf[2] = {'\0'}; for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) { memset(buf, '\0', sizeof (buf)); sprintf(buf, "%02x", hashRet[i]); sha1Text += buf; } return sha1Text; } unsigned long utils::System::totalMemery() { struct sysinfo info; int ret = sysinfo(&info); return ret == -1 ? 0 : info.totalram; } unsigned long utils::System::freeMemery() { struct sysinfo info; int ret = sysinfo(&info); return ret == -1 ? 0 : info.freeram; }
/* Copyright(C) * For free * All right reserved * */ /** * @file Utils.cpp * @brief 常用工具实现 * @author highway-9, [email protected] * @version 0.1.0 * @date 2015-11-28 */ #include "Utils.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/sysinfo.h> #include <uuid/uuid.h> #include <openssl/crypto.h> #include <openssl/md5.h> #include <openssl/sha.h> #ifndef PATH_MAX #define PATH_MAX 1024 // 默认最大路径长度 #endif /**********************************class String**********************************************/ std::string utils::String::int32ToString(int n) { return tToString(n); } std::string utils::String::uint32ToString(unsigned int n) { return tToString(n); } std::string utils::String::int64ToString(long long n) { return tToString(n); } std::string utils::String::uint64ToString(unsigned long long n) { return tToString(n); } std::string utils::String::floatToString(float n) { return tToString(n); } std::string utils::String::doubleToString(double n) { return tToString(n); } std::string utils::String::time_tToString(time_t n) { struct tm* p; p = localtime(&n); p->tm_year += 1900; p->tm_mon++; char time[50] = {'\0'}; sprintf(time, "%04d-%02d-%02d %02d:%02d:%02d", p->tm_year, p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); return time; } bool utils::String::stringToInt32(const std::string& str, int& n) { return stringToT(str, n); } bool utils::String::stringToUint32(const std::string& str, unsigned int& n) { return stringToT(str, n); } bool utils::String::stringToInt64(const std::string& str, long long& n) { return stringToT(str, n); } bool utils::String::stringToUint64(const std::string& str, unsigned long long& n) { return stringToT(str, n); } bool utils::String::stringToFloat(const std::string& str, float& n) { return stringToT(str, n); } bool utils::String::stringToDouble(const std::string& str, double& n) { return stringToT(str, n); } time_t utils::String::stringToTime_t(const std::string& time) { struct tm stTm; sscanf(time.c_str(), "%d-%d-%d %d:%d:%d", &(stTm.tm_year), &(stTm.tm_mon), &(stTm.tm_mday), &(stTm.tm_hour), &(stTm.tm_min), &(stTm.tm_sec)); stTm.tm_year -= 1900; stTm.tm_mon--; stTm.tm_isdst = -1; return mktime(&stTm); } /**********************************class FileSystem**********************************************/ std::string utils::FileSystem::currentWorkPath() { char buf[PATH_MAX] = {'\0'}; if (getcwd(buf, sizeof (buf) - 1) != NULL) { return buf; } return ""; } bool utils::FileSystem::setCurrentWorkPath(const std::string& path) { int ret = chdir(path.c_str()); return ret == -1 ? false : true; } std::string utils::FileSystem::currentExePath() { char buf[PATH_MAX] = {'\0'}; int ret = readlink("/proc/self/exe", buf, PATH_MAX); if (ret < 0 || ret >= PATH_MAX) { return ""; } std::string path(buf); int pos = path.find_last_of("/"); if (pos == -1) { return ""; } path = path.substr(0, pos); return path; } std::string utils::FileSystem::currentExeName() { char buf[PATH_MAX] = {'\0'}; int ret = readlink("/proc/self/exe", buf, PATH_MAX); if (ret < 0 || ret >= PATH_MAX) { return ""; } std::string path(buf); int pos = path.find_last_of("/"); if (pos == -1) { return ""; } path = path.substr(pos + 1, path.size() - 1); return path; } bool utils::FileSystem::isExists(const std::string& path) { // F_OK 用于判断文件是否存在 int ret = access(path.c_str(), F_OK); return ret == -1 ? false : true; } bool utils::FileSystem::mkdir(const std::string& path) { if (path.empty()) { return false; } if (utils::FileSystem::isExists(path)) { return true; } std::string dirPath = path; if (dirPath[dirPath.size() - 1] != '/') { dirPath += '/'; } for (unsigned int i = 0; i < dirPath.size(); ++i) { if (dirPath[i] == '/') { if (i == 0) { continue; } std::string tempPath = dirPath.substr(0, i); if (!utils::FileSystem::isExists(tempPath)) { if (::mkdir(tempPath.c_str(), 0755) == -1) { return false; } } } } return true; } bool utils::FileSystem::remove(const std::string& path) { if (path.empty()) { return false; } if (!utils::FileSystem::isExists(path)) { return false; } int ret = ::remove(path.c_str()); return ret == -1 ? false : true; } /**********************************class System**********************************************/ std::string utils::System::uuid() { uuid_t uuid; uuid_generate(uuid); char buf[37] = {'\0'}; uuid_unparse_upper(uuid, buf); return buf; } std::string utils::System::md5(const std::string& str) { MD5_CTX hashCtx; unsigned char hashRet[MD5_DIGEST_LENGTH]; int ret = MD5_Init(&hashCtx); if (ret == 0) { return ""; } ret = MD5_Update(&hashCtx, str.c_str(), str.size()); if (ret == 0) { return ""; } ret = MD5_Final(hashRet, &hashCtx); if (ret == 0) { return ""; } OPENSSL_cleanse(&hashCtx, sizeof (hashCtx)); std::string md5Text; char buf[2] = {'\0'}; for (int i = 0; i < MD5_DIGEST_LENGTH * 2; ++i) { memset(buf, '\0', sizeof (buf)); if (i & 0x1) { sprintf(buf, "%x", (hashRet[i / 2]) & 0xf); } else { sprintf(buf, "%x", (hashRet[i / 2] >> 4) & 0xf); } md5Text += buf; } return md5Text; } std::string utils::System::sha1(const std::string& str) { SHA_CTX hashCtx; unsigned char hashRet[SHA_DIGEST_LENGTH]; int ret = SHA1_Init(&hashCtx); if (ret == 0) { return ""; } ret = SHA1_Update(&hashCtx, str.c_str(), str.size()); if (ret == 0) { return ""; } ret = SHA1_Final(hashRet, &hashCtx); if (ret == 0) { return ""; } OPENSSL_cleanse(&hashCtx, sizeof (hashCtx)); std::string sha1Text; char buf[2] = {'\0'}; for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) { memset(buf, '\0', sizeof (buf)); sprintf(buf, "%02x", hashRet[i]); sha1Text += buf; } return sha1Text; } unsigned long utils::System::totalMemery() { struct sysinfo info; int ret = sysinfo(&info); return ret == -1 ? 0 : info.totalram; } unsigned long utils::System::freeMemery() { struct sysinfo info; int ret = sysinfo(&info); return ret == -1 ? 0 : info.freeram; }
优化 Utils
优化 Utils
C++
mit
chxuan/easyrpc,chxuan/easyrpc,chxuan/easyrpc,chxuan/easyrpc
6b867fd7c9f11eac7e632677e75c0d58ff3db58a
lib/qtcamresolution.cpp
lib/qtcamresolution.cpp
/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "qtcamresolution.h" class QtCamResolutionPrivate : public QSharedData { public: QtCamResolutionPrivate() : fps(-1), nightFps(-1), zslFps(-1), megaPixels(-1) { } QString id; QString aspectRatio; QString commonName; QSize capture; QSize preview; QSize viewfinder; int fps; int nightFps; int zslFps; float megaPixels; QtCamResolution::Mode mode; QVariant device; }; QtCamResolution::QtCamResolution(const QString& id, const QString& aspectRatio, const QSize& capture, const QSize& preview, const QSize& viewfinder, int fps, int nightFps, int zslFps, float megaPixels, const QString& commonName, const Mode& mode, const QVariant device) : d_ptr(new QtCamResolutionPrivate) { d_ptr->id = id; d_ptr->aspectRatio = aspectRatio; d_ptr->commonName = commonName; d_ptr->capture = capture; d_ptr->preview = preview; d_ptr->viewfinder = viewfinder; d_ptr->fps = fps; d_ptr->nightFps = nightFps; d_ptr->zslFps = zslFps; d_ptr->megaPixels = megaPixels; d_ptr->mode = mode; d_ptr->device = device; } QtCamResolution::QtCamResolution(const QtCamResolution& other) : d_ptr(other.d_ptr) { } QtCamResolution& QtCamResolution::operator=(const QtCamResolution& other) { d_ptr = other.d_ptr; return *this; } QtCamResolution::QtCamResolution(const QtCamResolution::Mode& mode) : d_ptr(new QtCamResolutionPrivate) { d_ptr->mode = mode; } QtCamResolution::~QtCamResolution() { // QSharedData will take care of reference counting. } QString QtCamResolution::id() const { return d_ptr->id; } void QtCamResolution::setId(const QString& id) { d_ptr->id = id; } QString QtCamResolution::aspectRatio() const { return d_ptr->aspectRatio; } void QtCamResolution::setAspectRatio(const QString& aspectRatio) { d_ptr->aspectRatio = aspectRatio; } QString QtCamResolution::commonName() const { return d_ptr->commonName; } void QtCamResolution::setCommonName(const QString& commonName) { d_ptr->commonName = commonName; } QSize QtCamResolution::captureResolution() const { return d_ptr->capture; } void QtCamResolution::setCaptureResolution(const QSize& captureResolution) { d_ptr->capture = captureResolution; } QSize QtCamResolution::viewfinderResolution() const { return d_ptr->viewfinder; } void QtCamResolution::setViewfinderResolution(const QSize& viewfinderResolution) { d_ptr->viewfinder = viewfinderResolution; } QSize QtCamResolution::previewResolution() const { return d_ptr->preview; } void QtCamResolution::setPreviewResolution(const QSize& previewResolution) { d_ptr->preview = previewResolution; } int QtCamResolution::frameRate() const { return d_ptr->fps; } void QtCamResolution::setFrameRate(int frameRate) { d_ptr->fps = frameRate; } int QtCamResolution::nightFrameRate() const { return d_ptr->nightFps; } void QtCamResolution::setNightFrameRate(int nightFrameRate) { d_ptr->nightFps = nightFrameRate; } int QtCamResolution::zslFrameRate() const { return d_ptr->zslFps; } void QtCamResolution::setZslFrameRate(int zslFrameRate) { d_ptr->zslFps = zslFrameRate; } float QtCamResolution::megaPixels() const { return d_ptr->megaPixels; } void QtCamResolution::setMegaPixels(float megaPixels) { d_ptr->megaPixels = megaPixels; } QtCamResolution::Mode QtCamResolution::mode() const { return d_ptr->mode; } void QtCamResolution::setMode(const QtCamResolution::Mode& mode) { d_ptr->mode = mode; } QVariant QtCamResolution::device() const { return d_ptr->device; } void QtCamResolution::setDevice(const QVariant& device) { d_ptr->device = device; } bool QtCamResolution::isValid() const { return d_ptr->capture.isValid() && d_ptr->preview.isValid() && d_ptr->viewfinder.isValid() && d_ptr->fps > 0; } QTextStream& operator<<(QTextStream& s, const QtCamResolution& res) { #define DUMP_RES(rr) res.d_ptr->rr.width() << "x" << res.d_ptr->rr.height() s << "\n[" << res.d_ptr->id << "]" << "\n" << "aspect ratio: " << res.d_ptr->aspectRatio << "\n" << "common name: " << res.d_ptr->commonName << "\n" << "capture: " << DUMP_RES(capture) << "\n" << "preview: " << DUMP_RES(preview) << "\n" << "viewfinder: " << DUMP_RES(viewfinder) << "\n" << "fps: " << res.d_ptr->fps << "\n" << "night fp: " << res.d_ptr->nightFps << "\n" << "zsl fps: " << res.d_ptr->zslFps << "\n" << "megapixels: " << res.d_ptr->megaPixels << "\n" << "device: " << res.d_ptr->device.toString() << "\n" << "mode: " << res.d_ptr->mode << "\n"; return s; }
/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "qtcamresolution.h" class QtCamResolutionPrivate : public QSharedData { public: QtCamResolutionPrivate() : fps(-1), nightFps(-1), zslFps(-1), megaPixels(-1) { } QString id; QString aspectRatio; QString commonName; QSize capture; QSize preview; QSize viewfinder; int fps; int nightFps; int zslFps; float megaPixels; QtCamResolution::Mode mode; QVariant device; }; QtCamResolution::QtCamResolution(const QString& id, const QString& aspectRatio, const QSize& capture, const QSize& preview, const QSize& viewfinder, int fps, int nightFps, int zslFps, float megaPixels, const QString& commonName, const Mode& mode, const QVariant device) : d_ptr(new QtCamResolutionPrivate) { d_ptr->id = id; d_ptr->aspectRatio = aspectRatio; d_ptr->commonName = commonName; d_ptr->capture = capture; d_ptr->preview = preview; d_ptr->viewfinder = viewfinder; d_ptr->fps = fps; d_ptr->nightFps = nightFps; d_ptr->zslFps = zslFps; d_ptr->megaPixels = megaPixels; d_ptr->mode = mode; d_ptr->device = device; } QtCamResolution::QtCamResolution(const QtCamResolution& other) : d_ptr(other.d_ptr) { } QtCamResolution& QtCamResolution::operator=(const QtCamResolution& other) { d_ptr = other.d_ptr; return *this; } QtCamResolution::QtCamResolution(const QtCamResolution::Mode& mode) : d_ptr(new QtCamResolutionPrivate) { d_ptr->mode = mode; } QtCamResolution::~QtCamResolution() { // QSharedData will take care of reference counting. } QString QtCamResolution::id() const { return d_ptr->id; } void QtCamResolution::setId(const QString& id) { d_ptr->id = id; } QString QtCamResolution::aspectRatio() const { return d_ptr->aspectRatio; } void QtCamResolution::setAspectRatio(const QString& aspectRatio) { d_ptr->aspectRatio = aspectRatio; } QString QtCamResolution::commonName() const { return d_ptr->commonName; } void QtCamResolution::setCommonName(const QString& commonName) { d_ptr->commonName = commonName; } QSize QtCamResolution::captureResolution() const { return d_ptr->capture; } void QtCamResolution::setCaptureResolution(const QSize& captureResolution) { d_ptr->capture = captureResolution; } QSize QtCamResolution::viewfinderResolution() const { return d_ptr->viewfinder; } void QtCamResolution::setViewfinderResolution(const QSize& viewfinderResolution) { d_ptr->viewfinder = viewfinderResolution; } QSize QtCamResolution::previewResolution() const { return d_ptr->preview; } void QtCamResolution::setPreviewResolution(const QSize& previewResolution) { d_ptr->preview = previewResolution; } int QtCamResolution::frameRate() const { return d_ptr->fps; } void QtCamResolution::setFrameRate(int frameRate) { d_ptr->fps = frameRate; } int QtCamResolution::nightFrameRate() const { return d_ptr->nightFps; } void QtCamResolution::setNightFrameRate(int nightFrameRate) { d_ptr->nightFps = nightFrameRate; } int QtCamResolution::zslFrameRate() const { return d_ptr->zslFps; } void QtCamResolution::setZslFrameRate(int zslFrameRate) { d_ptr->zslFps = zslFrameRate; } float QtCamResolution::megaPixels() const { return d_ptr->megaPixels; } void QtCamResolution::setMegaPixels(float megaPixels) { d_ptr->megaPixels = megaPixels; } QtCamResolution::Mode QtCamResolution::mode() const { return d_ptr->mode; } void QtCamResolution::setMode(const QtCamResolution::Mode& mode) { d_ptr->mode = mode; } QVariant QtCamResolution::device() const { return d_ptr->device; } void QtCamResolution::setDevice(const QVariant& device) { d_ptr->device = device; } bool QtCamResolution::isValid() const { return d_ptr->capture.isValid() && d_ptr->preview.isValid() && d_ptr->viewfinder.isValid() && d_ptr->fps > -1; } QTextStream& operator<<(QTextStream& s, const QtCamResolution& res) { #define DUMP_RES(rr) res.d_ptr->rr.width() << "x" << res.d_ptr->rr.height() s << "\n[" << res.d_ptr->id << "]" << "\n" << "aspect ratio: " << res.d_ptr->aspectRatio << "\n" << "common name: " << res.d_ptr->commonName << "\n" << "capture: " << DUMP_RES(capture) << "\n" << "preview: " << DUMP_RES(preview) << "\n" << "viewfinder: " << DUMP_RES(viewfinder) << "\n" << "fps: " << res.d_ptr->fps << "\n" << "night fp: " << res.d_ptr->nightFps << "\n" << "zsl fps: " << res.d_ptr->zslFps << "\n" << "megapixels: " << res.d_ptr->megaPixels << "\n" << "device: " << res.d_ptr->device.toString() << "\n" << "mode: " << res.d_ptr->mode << "\n"; return s; }
fix logic in isValid()
qtcamresolution: fix logic in isValid() fps is invalid if it is -1 but 0 is allowed (even though it will not make GStreamer happy)
C++
lgpl-2.1
mlehtima/cameraplus,foolab/cameraplus,alinelena/cameraplus,mlehtima/cameraplus,alinelena/cameraplus,mer-hybris-kis3/cameraplus,mer-hybris-kis3/cameraplus,foolab/cameraplus,mer-hybris-kis3/cameraplus,foolab/cameraplus,alinelena/cameraplus,mer-hybris-kis3/cameraplus,mlehtima/cameraplus,alinelena/cameraplus,foolab/cameraplus,mlehtima/cameraplus
4fb1e9e498278362b8de76d30c45b68631949a7d
Logic/not.cpp
Logic/not.cpp
#include "not.h" Not::Not(QGraphicsItem *parent) : GraphicElement(1,1,1,1,parent) { setOutputsOnTop(true); setPixmap( ":/basic/not.png" ); updatePorts(); setPortName("NOT"); } Not::~Not() { } void Not::updateLogic() { char res = ! inputs().first()->value(); if(!isValid()) { res = -1; } outputs().first()->setValue(res); }
#include "not.h" Not::Not(QGraphicsItem *parent) : UnitOperation(1,1,1,1,parent) { setOutputsOnTop(true); setPixmap( ":/basic/not.png" ); updatePorts(); setPortName("NOT"); } Not::~Not() { } void Not::updateLogic() { char res = ! inputs().first()->value(); if(!isValid()) { res = -1; } outputs().first()->setValue(res); }
Update not.cpp
Update not.cpp
C++
bsd-2-clause
sanjivch/dyncm,sanjivch/dyncm,sanjivch/dyncm
cb1c5262710103d4c8702a463e7076410d035b30
src/ofApp.cpp
src/ofApp.cpp
#include "ofApp.h" void nebulaEye::setup() { sender.setup(OSC_IP, OSC_PORT); video.setup(); flow.setup(); bgSub.setup(); contour.setup(); zone.setup(); displayGuiGrp.setName("display"); displayGuiGrp.add(showGui.set("show this menu",true)); displayGuiGrp.add(showVideo.set("show video",true)); displayGuiGrp.add(showBgSub.set("show bgsub",true)); displayGuiGrp.add(bgSubIntensity.set("bg instensity",127,0,255)); displayGuiGrp.add(showContour.set("show contour",true)); displayGuiGrp.add(showFlow.set("show motion flow",true)); displayGuiGrp.add(showZone.set("show zone",true)); displayGuiGrp.add(showDebug.set("show flow mask",0,0,4)); gui.setup("nebula-eye","settings.xml",660,10); gui.add(displayGuiGrp); gui.add(video.guiGrp); gui.add(bgSub.guiGrp); gui.add(flow.guiGrp); gui.add(contour.guiGrp); gui.add(zone.guiGrp); recordPanel.setup("record", "recordSetting.xml",10, ofGetHeight()-50); recordPanel.add(record.set("recording",false)); ofAddListener(gui.savePressedE, &bgSub, &nebulaBackground::saveAlgoParam); showGui.addListener(&bgSub, &nebulaBackground::showGui); showZone.addListener(&zone, &nebula::Zone::attach); record.addListener(this, &nebulaEye::csvRecordCb); gui.loadFromFile("settings.xml"); ofSetCircleResolution(100); ofSetBackgroundColor(0,0,0,0); } void nebulaEye::update() { video.update(); if(video.isFrameNew()){ img = video.getPixels(); bgSub.update(img); flow.update(img); contour.update(bgSub.m_fgmask); // create zone mask // TODO redraw only on zone change zoneMask.resize(3); ofVec2f scaledCenter = zone.center.get(); scaledCenter.x = float(scaledCenter.x) * float(flow.m_flow.cols)/ofGetWidth(); scaledCenter.y = float(scaledCenter.y) * float(flow.m_flow.rows)/ofGetHeight(); cv::Point center = ofxCv::toCv(scaledCenter); for ( int i = 0; i < zoneMask.size() ; i++ ){ // clear everything zoneMask[i] = cv::Mat::zeros(flow.m_flow.rows, flow.m_flow.cols , CV_8UC1); // first draw a white filled circle int rad = zone.radius.get()[i] * zoneMask[i].cols / ofGetWidth(); cv::circle(zoneMask[i], center, rad, cv::Scalar(255,255,255),-1); } int rad = zone.radius.get()[0] * zoneMask[0].cols / ofGetWidth(); // then add a black one into the white to mask the other zone(s) cv::circle(zoneMask[1], center, rad, cv::Scalar(0),-1); rad = zone.radius.get()[1] * zoneMask[0].cols / ofGetWidth(); cv::circle(zoneMask[2], center, rad, 0,-1); // for the last zone, get a white image and draw a black circle zoneMask.push_back( cv::Mat::ones(flow.m_flow.rows, flow.m_flow.cols , CV_8UC1)*255 ); rad = zone.radius.get()[2] * zoneMask[2].cols / ofGetWidth(); cv::circle(zoneMask[zoneMask.size()-1], center, rad, 0, -1); sendOSC(); recordCSVData(); } } void nebulaEye::draw() { int w(ofGetWidth()), h(ofGetHeight()); if ( ( ofGetHeight() > 0 && img.getHeight() > 0 ) ) { if ( ofGetWidth()/ofGetHeight() > img.getWidth()/img.getHeight()){ h = ofGetHeight(); w = h * img.getWidth()/img.getHeight(); } else if (img.getWidth()>0){ w = ofGetWidth(); h = w * img.getHeight()/img.getWidth(); } } // ofLogVerbose("ofApp") << "drawing resolution : " << w << " x " << h; ofSetColor(255,255,255); if(showVideo) video.draw(0,0,w,h); if(showBgSub){ ofSetColor(255,255,255,bgSubIntensity); bgSub.draw(0,0,w,h); } if(showFlow){ ofSetColor(0,255,0,255); flow.draw(0,0,w, h); } if(showContour){ ofSetColor(255,255,255); contour.draw(0,0,w,h); } if(showZone){ ofSetColor(255,0,0,64); zone.draw(); } if (showDebug){ ofSetColor(255); int i = showDebug.get()-1; ofRectangle rect = ofRectangle(zoneMask[i].cols/2,zoneMask[i].rows/2, zoneMask[i].cols, zoneMask[i].rows); ofxCv::drawMat(zoneMask[i],rect.x, rect.y); cv::Mat m_flow; double zoneFlow = flow.getFlowInMask(zoneMask[i], &m_flow); ofVec2f offset(rect.x,rect.y); ofVec2f scale(rect.width/m_flow.cols, rect.height/m_flow.rows); int stepSize = 4; ofPopStyle(); ofSetColor(0,255,0); for(int y = 0; y < m_flow.rows; y += stepSize) { for(int x = 0; x < m_flow.cols; x += stepSize) { ofVec2f cur = ofVec2f(x, y) * scale + offset; const cv::Vec2f& vec = m_flow.at<cv::Vec2f>(y, x); ofDrawLine(cur, ofVec2f(x + vec[0], y + vec[1]) * scale + offset); } } ofPushStyle(); stringstream ss; ss << "zone flow : " << zoneFlow; ofDrawBitmapString(ss.str(), ofPoint(rect.x+10,rect.y-10)); } if (showGui){ gui.draw(); } recordPanel.draw(); } void nebulaEye::exit() { } void nebulaEye::mouseMoved(ofMouseEventArgs& mouse) { } void nebulaEye::mouseDragged(ofMouseEventArgs& mouse) { } void nebulaEye::mousePressed(ofMouseEventArgs& mouse) { } void nebulaEye::mouseReleased(ofMouseEventArgs& mouse) { } void nebulaEye::mouseScrolled(ofMouseEventArgs& mouse) { } void nebulaEye::mouseEntered(ofMouseEventArgs& mouse) { } void nebulaEye::mouseExited(ofMouseEventArgs& mouse) { } void nebulaEye::keyPressed(int key){ switch (key){ case 27: ofExit(); break; case 'h': showGui = !showGui; break; case 's': gui.saveToFile("settings.xml"); bgSub.saveAlgoParam(); break; default: break; } } void nebulaEye::sendOSC(){ ofxOscBundle bundle; //vector<ofPoint> centroids = contour.getCentroids(); for (int i = 0; i < contour.finder.size(); i++ ){ ofxOscMessage m; m.setAddress("/b"); m.addInt32Arg(contour.finder.getLabel(i)); ofVec2f centroid = ofxCv::toOf(contour.finder.getCentroid(i)); centroid -= zone.center; ofVec2f centroidPol = nebula::Utils::carToPol(centroid); centroidPol.y -= zone.angleOrigin; centroidPol.y = ofWrapDegrees(centroidPol.y); m.addFloatArg(centroidPol.x); m.addFloatArg(centroidPol.y); m.addFloatArg(contour.finder.getContourArea(i)); m.addInt32Arg(zone.inside(ofxCv::toOf(contour.finder.getCentroid(i)))); bundle.addMessage(m); } ofxOscMessage m; m.setAddress("/f"); flowZone.clear(); for ( int i = 0; i < zoneMask.size() ; i++ ){ double f = flow.getFlowInMask(zoneMask[i], NULL); flowZone.push_back(f); m.addFloatArg(f); } bundle.addMessage(m); sender.sendBundle(bundle); } void nebulaEye::csvRecordCb(bool & flag){ if ( flag ){ csvRecorder.clear(); stringstream ss; ss << ofGetYear(); ss << setfill('0') << setw(2) << ofGetMonth(); ss << setfill('0') << setw(2) << ofGetDay() << "-"; ss << setfill('0') << setw(2) << ofGetHours(); ss << setfill('0') << setw(2) << ofGetMinutes(); ss << setfill('0') << setw(2) << ofGetSeconds() << ".csv"; ofLog() << "try to create file : " << ss.str(); csvRecorder.filePath = ofToDataPath(ss.str()); ofLog() << "record CSV to : " << csvRecorder.filePath; int idx(0); csvRecorder.setString(0,idx++,"date"); csvRecorder.setString(0,idx++,"time"); csvRecorder.setString(0,idx++,"blob x"); csvRecorder.setString(0,idx++,"blob y"); csvRecorder.setString(0,idx++,"flow zone 0"); csvRecorder.setString(0,idx++,"flow zone 1"); csvRecorder.setString(0,idx++,"flow zone 2"); csvRecorder.setString(0,idx++,"flow zone 3"); } else { csvRecorder.saveFile(); // Save the recorded values in the csvRecorder ofxCsv object // csvRecorder.saveFile( ofToDataPath( csvFileName )); ofLog() << "Saved " << csvRecorder.numRows << " rows to " << csvRecorder.filePath; } } void nebulaEye::recordCSVData(){ if (!record) return; int row = csvRecorder.numRows; int idx = 0; csvRecorder.setString(row, 0, getDate()); csvRecorder.setString(row, 1, getHour()); int area(0), biggest(-1); for (int i = 0; i < contour.finder.size(); i++ ){ if ( contour.finder.getContourArea(i) > area ){ biggest = i; } } if ( biggest != -1 ){ ofVec2f centroid = ofxCv::toOf(contour.finder.getCentroid(biggest)); centroid -= zone.center; ofVec2f centroidPol = nebula::Utils::carToPol(centroid); centroidPol.y -= zone.angleOrigin; centroidPol.y = ofWrapDegrees(centroidPol.y); csvRecorder.setFloat(row,2,centroidPol.x); csvRecorder.setFloat(row,3,centroidPol.y); } else { csvRecorder.setString(row,2,"NA"); csvRecorder.setString(row,3,"NA"); } csvRecorder.setFloat(row,4,flowZone[0]); csvRecorder.setFloat(row,5,flowZone[1]); csvRecorder.setFloat(row,5,flowZone[2]); csvRecorder.setFloat(row,5,flowZone[3]); } string nebulaEye::getDate(){ stringstream ss; ss << setfill('0') << setw(2) << ofGetYear() << "/" << ofGetMonth() << "/" << ofGetDay(); return ss.str(); } string nebulaEye::getHour(){ stringstream ss; ss << setfill('0') << setw(2) << ofGetHours() << ":" << ofGetMinutes() << ":" << ofGetSeconds(); return ss.str(); }
#include "ofApp.h" void nebulaEye::setup() { sender.setup(OSC_IP, OSC_PORT); video.setup(); flow.setup(); bgSub.setup(); contour.setup(); zone.setup(); displayGuiGrp.setName("display"); displayGuiGrp.add(showGui.set("show this menu",true)); displayGuiGrp.add(showVideo.set("show video",true)); displayGuiGrp.add(showBgSub.set("show bgsub",true)); displayGuiGrp.add(bgSubIntensity.set("bg instensity",127,0,255)); displayGuiGrp.add(showContour.set("show contour",true)); displayGuiGrp.add(showFlow.set("show motion flow",true)); displayGuiGrp.add(showZone.set("show zone",true)); displayGuiGrp.add(showDebug.set("show flow mask",0,0,4)); gui.setup("nebula-eye","settings.xml",660,10); gui.add(displayGuiGrp); gui.add(video.guiGrp); gui.add(bgSub.guiGrp); gui.add(flow.guiGrp); gui.add(contour.guiGrp); gui.add(zone.guiGrp); recordPanel.setup("record", "recordSetting.xml",10, ofGetHeight()-50); recordPanel.add(record.set("recording",false)); ofAddListener(gui.savePressedE, &bgSub, &nebulaBackground::saveAlgoParam); showGui.addListener(&bgSub, &nebulaBackground::showGui); showZone.addListener(&zone, &nebula::Zone::attach); record.addListener(this, &nebulaEye::csvRecordCb); gui.loadFromFile("settings.xml"); ofSetCircleResolution(100); ofSetBackgroundColor(0,0,0,0); } void nebulaEye::update() { video.update(); if(video.isFrameNew()){ img = video.getPixels(); bgSub.update(img); flow.update(img); contour.update(bgSub.m_fgmask); // create zone mask // TODO redraw only on zone change zoneMask.resize(3); ofVec2f scaledCenter = zone.center.get(); scaledCenter.x = float(scaledCenter.x) * float(flow.m_flow.cols)/ofGetWidth(); scaledCenter.y = float(scaledCenter.y) * float(flow.m_flow.rows)/ofGetHeight(); cv::Point center = ofxCv::toCv(scaledCenter); for ( int i = 0; i < zoneMask.size() ; i++ ){ // clear everything zoneMask[i] = cv::Mat::zeros(flow.m_flow.rows, flow.m_flow.cols , CV_8UC1); // first draw a white filled circle int rad = zone.radius.get()[i] * zoneMask[i].cols / ofGetWidth(); cv::circle(zoneMask[i], center, rad, cv::Scalar(255,255,255),-1); } int rad = zone.radius.get()[0] * zoneMask[0].cols / ofGetWidth(); // then add a black one into the white to mask the other zone(s) cv::circle(zoneMask[1], center, rad, cv::Scalar(0),-1); rad = zone.radius.get()[1] * zoneMask[0].cols / ofGetWidth(); cv::circle(zoneMask[2], center, rad, 0,-1); // for the last zone, get a white image and draw a black circle zoneMask.push_back( cv::Mat::ones(flow.m_flow.rows, flow.m_flow.cols , CV_8UC1)*255 ); rad = zone.radius.get()[2] * zoneMask[2].cols / ofGetWidth(); cv::circle(zoneMask[zoneMask.size()-1], center, rad, 0, -1); sendOSC(); recordCSVData(); } } void nebulaEye::draw() { int w(ofGetWidth()), h(ofGetHeight()); if ( ( ofGetHeight() > 0 && img.getHeight() > 0 ) ) { if ( ofGetWidth()/ofGetHeight() > img.getWidth()/img.getHeight()){ h = ofGetHeight(); w = h * img.getWidth()/img.getHeight(); } else if (img.getWidth()>0){ w = ofGetWidth(); h = w * img.getHeight()/img.getWidth(); } } // ofLogVerbose("ofApp") << "drawing resolution : " << w << " x " << h; ofSetColor(255,255,255); if(showVideo) video.draw(0,0,w,h); if(showBgSub){ ofSetColor(255,255,255,bgSubIntensity); bgSub.draw(0,0,w,h); } if(showFlow){ ofSetColor(0,255,0,255); flow.draw(0,0,w, h); } if(showContour){ ofSetColor(255,255,255); contour.draw(0,0,w,h); } if(showZone){ ofSetColor(255,0,0,64); zone.draw(); } if (showDebug){ ofSetColor(255); int i = showDebug.get()-1; ofRectangle rect = ofRectangle(zoneMask[i].cols/2,zoneMask[i].rows/2, zoneMask[i].cols, zoneMask[i].rows); ofxCv::drawMat(zoneMask[i],rect.x, rect.y); cv::Mat m_flow; double zoneFlow = flow.getFlowInMask(zoneMask[i], &m_flow); ofVec2f offset(rect.x,rect.y); ofVec2f scale(rect.width/m_flow.cols, rect.height/m_flow.rows); int stepSize = 4; ofPopStyle(); ofSetColor(0,255,0); for(int y = 0; y < m_flow.rows; y += stepSize) { for(int x = 0; x < m_flow.cols; x += stepSize) { ofVec2f cur = ofVec2f(x, y) * scale + offset; const cv::Vec2f& vec = m_flow.at<cv::Vec2f>(y, x); ofDrawLine(cur, ofVec2f(x + vec[0], y + vec[1]) * scale + offset); } } ofPushStyle(); stringstream ss; ss << "zone flow : " << zoneFlow; ofDrawBitmapString(ss.str(), ofPoint(rect.x+10,rect.y-10)); } if (showGui){ gui.draw(); } recordPanel.draw(); } void nebulaEye::exit() { } void nebulaEye::mouseMoved(ofMouseEventArgs& mouse) { } void nebulaEye::mouseDragged(ofMouseEventArgs& mouse) { } void nebulaEye::mousePressed(ofMouseEventArgs& mouse) { } void nebulaEye::mouseReleased(ofMouseEventArgs& mouse) { } void nebulaEye::mouseScrolled(ofMouseEventArgs& mouse) { } void nebulaEye::mouseEntered(ofMouseEventArgs& mouse) { } void nebulaEye::mouseExited(ofMouseEventArgs& mouse) { } void nebulaEye::keyPressed(int key){ switch (key){ case 27: ofExit(); break; case 'h': showGui = !showGui; break; case 's': gui.saveToFile("settings.xml"); bgSub.saveAlgoParam(); break; default: break; } } void nebulaEye::sendOSC(){ ofxOscBundle bundle; //vector<ofPoint> centroids = contour.getCentroids(); for (int i = 0; i < contour.finder.size(); i++ ){ ofxOscMessage m; m.setAddress("/b"); m.addInt32Arg(contour.finder.getLabel(i)); ofVec2f centroid = ofxCv::toOf(contour.finder.getCentroid(i)); centroid -= zone.center; ofVec2f centroidPol = nebula::Utils::carToPol(centroid); centroidPol.y -= zone.angleOrigin; centroidPol.y = ofWrapDegrees(centroidPol.y); m.addFloatArg(centroidPol.x); m.addFloatArg(centroidPol.y); m.addFloatArg(contour.finder.getContourArea(i)); m.addInt32Arg(zone.inside(ofxCv::toOf(contour.finder.getCentroid(i)))); bundle.addMessage(m); } ofxOscMessage m; m.setAddress("/f"); flowZone.clear(); for ( int i = 0; i < zoneMask.size() ; i++ ){ double f = flow.getFlowInMask(zoneMask[i], NULL); flowZone.push_back(f); m.addFloatArg(f); } bundle.addMessage(m); sender.sendBundle(bundle); } void nebulaEye::csvRecordCb(bool & flag){ if ( flag ){ csvRecorder.clear(); stringstream ss; ss << ofGetYear(); ss << setfill('0') << setw(2) << ofGetMonth(); ss << setfill('0') << setw(2) << ofGetDay() << "-"; ss << setfill('0') << setw(2) << ofGetHours(); ss << setfill('0') << setw(2) << ofGetMinutes(); ss << setfill('0') << setw(2) << ofGetSeconds() << ".csv"; ofLog() << "try to create file : " << ss.str(); csvRecorder.filePath = ofToDataPath(ss.str()); ofLog() << "record CSV to : " << csvRecorder.filePath; int idx(0); csvRecorder.setString(0,idx++,"date"); csvRecorder.setString(0,idx++,"time"); csvRecorder.setString(0,idx++,"blob x"); csvRecorder.setString(0,idx++,"blob y"); csvRecorder.setString(0,idx++,"flow zone 0"); csvRecorder.setString(0,idx++,"flow zone 1"); csvRecorder.setString(0,idx++,"flow zone 2"); csvRecorder.setString(0,idx++,"flow zone 3"); } else { csvRecorder.saveFile(); // Save the recorded values in the csvRecorder ofxCsv object // csvRecorder.saveFile( ofToDataPath( csvFileName )); ofLog() << "Saved " << csvRecorder.numRows << " rows to " << csvRecorder.filePath; } } void nebulaEye::recordCSVData(){ if (!record) return; int row = csvRecorder.numRows; int idx = 0; csvRecorder.setString(row, 0, getDate()); csvRecorder.setString(row, 1, getHour()); int area(0), biggest(-1); for (int i = 0; i < contour.finder.size(); i++ ){ if ( contour.finder.getContourArea(i) > area ){ biggest = i; } } if ( biggest != -1 ){ ofVec2f centroid = ofxCv::toOf(contour.finder.getCentroid(biggest)); centroid -= zone.center; ofVec2f centroidPol = nebula::Utils::carToPol(centroid); centroidPol.y -= zone.angleOrigin; centroidPol.y = ofWrapDegrees(centroidPol.y); csvRecorder.setFloat(row,2,centroidPol.x); csvRecorder.setFloat(row,3,centroidPol.y); } else { csvRecorder.setString(row,2,"NA"); csvRecorder.setString(row,3,"NA"); } csvRecorder.setFloat(row,4,flowZone[0]); csvRecorder.setFloat(row,5,flowZone[1]); csvRecorder.setFloat(row,6,flowZone[2]); csvRecorder.setFloat(row,7,flowZone[3]); } string nebulaEye::getDate(){ stringstream ss; ss << setfill('0') << setw(2) << ofGetYear() << "/" << ofGetMonth() << "/" << ofGetDay(); return ss.str(); } string nebulaEye::getHour(){ stringstream ss; ss << setfill('0') << setw(2) << ofGetHours() << ":" << ofGetMinutes() << ":" << ofGetSeconds(); return ss.str(); }
fix flow writing in csv
fix flow writing in csv
C++
mit
avilleret/nebula-eye
c41b57e23bcb48f1edba1cce7491c9ecf0b9b4a0
Parallel/vtkPRandomGraphSource.cxx
Parallel/vtkPRandomGraphSource.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkPRandomGraphSource.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 "vtkPRandomGraphSource.h" #include "vtkCellData.h" #include "vtkExecutive.h" #include "vtkFloatArray.h" #include "vtkGraph.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkMath.h" #include "vtkMPI.h" #include "vtkMutableDirectedGraph.h" #include "vtkMutableUndirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkPBGLDistributedGraphHelper.h" #include "vtkPointData.h" #include "vtkSmartPointer.h" #include <vtksys/stl/set> #include <vtksys/stl/algorithm> #include <vtksys/stl/functional> #include <boost/mpi/communicator.hpp> #include <boost/mpi/collectives/scan.hpp> vtkCxxRevisionMacro(vtkPRandomGraphSource, "1.1"); vtkStandardNewMacro(vtkPRandomGraphSource); // ---------------------------------------------------------------------- vtkIdType vtkVertexBlockDistribution(const vtkVariant& pedigreeId, void* userData) { int numProcs = reinterpret_cast<int>(userData); return pedigreeId.ToInt(0); } // ---------------------------------------------------------------------- vtkPRandomGraphSource::vtkPRandomGraphSource() { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); this->NumberOfVertices = 10; this->NumberOfEdges = 10; this->EdgeProbability = 0.5; this->IncludeEdgeWeights = false; this->Directed = 0; this->UseEdgeProbability = 0; this->StartWithTree = 0; this->AllowSelfLoops = false; this->AllowBalancedEdgeDistribution = true; this->GeneratePedigreeIds = true; this->VertexPedigreeIdArrayName = 0; this->SetVertexPedigreeIdArrayName("vertex id"); this->EdgePedigreeIdArrayName = 0; this->SetEdgePedigreeIdArrayName("edge id"); this->EdgeWeightArrayName = 0; this->SetEdgeWeightArrayName("edge weight"); this->Seed = 1177 + 17 * rank; this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); } // ---------------------------------------------------------------------- vtkPRandomGraphSource::~vtkPRandomGraphSource() { this->SetVertexPedigreeIdArrayName(0); this->SetEdgePedigreeIdArrayName(0); this->SetEdgeWeightArrayName(0); } // ---------------------------------------------------------------------- void vtkPRandomGraphSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "NumberOfVertices: " << this->NumberOfVertices << endl; os << indent << "NumberOfEdges: " << this->NumberOfEdges << endl; os << indent << "EdgeProbability: " << this->EdgeProbability << endl; os << indent << "IncludeEdgeWeights: " << this->IncludeEdgeWeights << endl; os << indent << "Directed: " << this->Directed << endl; os << indent << "UseEdgeProbability: " << this->UseEdgeProbability << endl; os << indent << "StartWithTree: " << this->StartWithTree << endl; os << indent << "AllowSelfLoops: " << this->AllowSelfLoops << endl; os << indent << "AllowBalancedEdgeDistribution: " << this->AllowBalancedEdgeDistribution << endl; os << indent << "GeneratePedigreeIds: " << this->GeneratePedigreeIds << endl; os << indent << "VertexPedigreeIdArrayName: " << (this->VertexPedigreeIdArrayName ? this->VertexPedigreeIdArrayName : "(null)") << endl; os << indent << "EdgePedigreeIdArrayName: " << (this->EdgePedigreeIdArrayName ? this->EdgePedigreeIdArrayName : "(null)") << endl; os << indent << "EdgeWeightArrayName: " << (this->EdgeWeightArrayName ? this->EdgeWeightArrayName : "(null)") << endl; os << indent << "Seed: " << this->Seed << endl; } // ---------------------------------------------------------------------- int vtkPRandomGraphSource::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector *outputVector) { int myRank; int numProcs; MPI_Comm_rank(MPI_COMM_WORLD, &myRank); MPI_Comm_size(MPI_COMM_WORLD, &numProcs); // Seed the random number generator so we can produce repeatable results vtkMath::RandomSeed(this->Seed); // Create a mutable graph of the appropriate type. vtkSmartPointer<vtkMutableDirectedGraph> dirBuilder = vtkSmartPointer<vtkMutableDirectedGraph>::New(); vtkSmartPointer<vtkMutableUndirectedGraph> undirBuilder = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); // Create a Parallel BGL distributed graph helper vtkSmartPointer<vtkPBGLDistributedGraphHelper> helper = vtkSmartPointer<vtkPBGLDistributedGraphHelper>::New(); // Hook the distributed graph helper into the graph to make it a // distributed graph. if (this->Directed) { dirBuilder->SetDistributedGraphHelper(helper); } else { undirBuilder->SetDistributedGraphHelper(helper); } // Add NumberOfVertices new vertices, with a simple block // distribution. vtkIdType blockSize = this->NumberOfVertices / numProcs; vtkIdType myNumberOfVertices = blockSize; if (this->NumberOfVertices % numProcs != 0) { ++blockSize; if (myRank < this->NumberOfVertices % numProcs) { ++myNumberOfVertices; } } vtkIdType myStartVertex = blockSize * myRank; vtkIdType myEndVertex = myStartVertex + myNumberOfVertices; for (vtkIdType i = 0; i < myNumberOfVertices; ++i) { if (this->Directed) { dirBuilder->AddVertex(); } else { undirBuilder->AddVertex(); } } // Make sure everyone has added their own local vertices. helper->Synchronize(); if (this->StartWithTree) { vtkIdType myStart = myStartVertex; if (myStart == 0) { myStart = 1; } for (vtkIdType i = myStart; i < myEndVertex; i++) { // Pick a random vertex in [0, i-1]. int j = static_cast<vtkIdType>(vtkMath::Random(0, i)); vtkIdType iVertex = helper->MakeDistributedId(i / blockSize, i % blockSize); vtkIdType jVertex = helper->MakeDistributedId(j / blockSize, j % blockSize); if (this->Directed) { dirBuilder->AddEdge(jVertex, iVertex); } else { undirBuilder->AddEdge(jVertex, iVertex); } } // Make sure everyone has added the edges in the random tree. helper->Synchronize(); } if (this->UseEdgeProbability) { for (vtkIdType i = myStartVertex; i < myEndVertex; i++) { vtkIdType iVertex = helper->MakeDistributedId(i / blockSize, i % blockSize); vtkIdType begin = this->Directed ? 0 : i + 1; for (vtkIdType j = begin; j < this->NumberOfVertices; j++) { vtkIdType jVertex = helper->MakeDistributedId(j / blockSize, j % blockSize); double r = vtkMath::Random(); if (r < this->EdgeProbability) { if (this->Directed) { dirBuilder->AddEdge(iVertex, jVertex); } else { undirBuilder->AddEdge(iVertex, jVertex); } } } } } else { vtkIdType MaxEdges; if (this->AllowSelfLoops) { MaxEdges = this->NumberOfVertices * this->NumberOfVertices; } else { MaxEdges = (this->NumberOfVertices * (this->NumberOfVertices-1)) / 2; } if (this->NumberOfEdges > MaxEdges) { this->NumberOfEdges = MaxEdges; } vtkIdType avgNumberOfEdges = this->NumberOfEdges / numProcs; vtkIdType myNumberOfEdges = avgNumberOfEdges; if (myRank < this->NumberOfEdges % numProcs) { ++myNumberOfEdges; } for (vtkIdType i = 0; i < myNumberOfEdges; i++) { bool newEdgeFound = false; while (!newEdgeFound) { vtkIdType s; vtkIdType t; if (this->AllowBalancedEdgeDistribution) { s = static_cast<vtkIdType>(vtkMath::Random(myStartVertex, myEndVertex)); } else { s = static_cast<vtkIdType>(vtkMath::Random(0, this->NumberOfVertices)); } t = static_cast<vtkIdType>(vtkMath::Random(0, this->NumberOfVertices)); if (s == t && (!this->AllowSelfLoops)) { continue; } vtkIdType sVertex = helper->MakeDistributedId(s / blockSize, s % blockSize); vtkIdType tVertex = helper->MakeDistributedId(t / blockSize, t % blockSize); vtkDebugMacro(<<"Adding edge " << s << " to " << t); if (this->Directed) { dirBuilder->AddEdge(sVertex, tVertex); } else { undirBuilder->AddEdge(sVertex, tVertex); } newEdgeFound = true; } } } // Make sure everybody has added their edges and back-edges. helper->Synchronize(); // Copy the structure into the output. vtkGraph *output = vtkGraph::GetData(outputVector); if (this->Directed) { if (!output->CheckedShallowCopy(dirBuilder)) { vtkErrorMacro(<<"Invalid structure."); return 0; } } else { if (!output->CheckedShallowCopy(undirBuilder)) { vtkErrorMacro(<<"Invalid structure."); return 0; } } if (this->IncludeEdgeWeights) { if (!this->EdgeWeightArrayName) { vtkErrorMacro("When generating edge weights, " << "edge weights array name must be defined."); return 0; } vtkFloatArray *weights = vtkFloatArray::New(); weights->SetName(this->EdgeWeightArrayName); for (vtkIdType i = 0; i < output->GetNumberOfEdges(); ++i) { weights->InsertNextValue(vtkMath::Random()); } output->GetEdgeData()->AddArray(weights); weights->Delete(); } if (this->GeneratePedigreeIds) { if (!this->VertexPedigreeIdArrayName || !this->EdgePedigreeIdArrayName) { vtkErrorMacro("When generating pedigree ids, " << "vertex and edge pedigree id array names must be defined."); return 0; } vtkIdType numVert = output->GetNumberOfVertices(); vtkSmartPointer<vtkIdTypeArray> vertIds = vtkSmartPointer<vtkIdTypeArray>::New(); vertIds->SetName(this->VertexPedigreeIdArrayName); vertIds->SetNumberOfTuples(numVert); for (vtkIdType i = 0; i < numVert; ++i) { vertIds->SetValue(i, myStartVertex + i); } output->GetVertexData()->SetPedigreeIds(vertIds); // Attach a distribution function to the helper that maps these // global vertex numbers back to . TODO: Actually do it :) // Figure out how many edges come before us in the graph. boost::mpi::communicator world; vtkIdType myStartEdge = boost::mpi::scan(world, output->GetNumberOfEdges(), vtkstd::plus<vtkIdType>()); vtkIdType numEdge = output->GetNumberOfEdges(); vtkSmartPointer<vtkIdTypeArray> edgeIds = vtkSmartPointer<vtkIdTypeArray>::New(); edgeIds->SetName(this->EdgePedigreeIdArrayName); edgeIds->SetNumberOfTuples(numEdge); for (vtkIdType i = 0; i < numEdge; ++i) { edgeIds->SetValue(i, myStartEdge + i); } output->GetEdgeData()->SetPedigreeIds(edgeIds); } return 1; } //---------------------------------------------------------------------------- int vtkPRandomGraphSource::RequestDataObject( vtkInformation*, vtkInformationVector**, vtkInformationVector* ) { vtkDataObject *current = this->GetExecutive()->GetOutputData(0); if (!current || (this->Directed && !vtkDirectedGraph::SafeDownCast(current)) || (!this->Directed && vtkDirectedGraph::SafeDownCast(current))) { vtkGraph *output = 0; if (this->Directed) { output = vtkDirectedGraph::New(); } else { output = vtkUndirectedGraph::New(); } this->GetExecutive()->SetOutputData(0, output); output->Delete(); } return 1; }
/*========================================================================= Program: Visualization Toolkit Module: vtkPRandomGraphSource.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 "vtkPRandomGraphSource.h" #include "vtkCellData.h" #include "vtkExecutive.h" #include "vtkFloatArray.h" #include "vtkGraph.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkMath.h" #include "vtkMPI.h" #include "vtkMutableDirectedGraph.h" #include "vtkMutableUndirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkPBGLDistributedGraphHelper.h" #include "vtkPointData.h" #include "vtkSmartPointer.h" #include <vtksys/stl/set> #include <vtksys/stl/algorithm> #include <vtksys/stl/functional> #include <boost/mpi/communicator.hpp> #include <boost/mpi/collectives/scan.hpp> vtkCxxRevisionMacro(vtkPRandomGraphSource, "1.2"); vtkStandardNewMacro(vtkPRandomGraphSource); // ---------------------------------------------------------------------- vtkPRandomGraphSource::vtkPRandomGraphSource() { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); this->NumberOfVertices = 10; this->NumberOfEdges = 10; this->EdgeProbability = 0.5; this->IncludeEdgeWeights = false; this->Directed = 0; this->UseEdgeProbability = 0; this->StartWithTree = 0; this->AllowSelfLoops = false; this->AllowBalancedEdgeDistribution = true; this->GeneratePedigreeIds = true; this->VertexPedigreeIdArrayName = 0; this->SetVertexPedigreeIdArrayName("vertex id"); this->EdgePedigreeIdArrayName = 0; this->SetEdgePedigreeIdArrayName("edge id"); this->EdgeWeightArrayName = 0; this->SetEdgeWeightArrayName("edge weight"); this->Seed = 1177 + 17 * rank; this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); } // ---------------------------------------------------------------------- vtkPRandomGraphSource::~vtkPRandomGraphSource() { this->SetVertexPedigreeIdArrayName(0); this->SetEdgePedigreeIdArrayName(0); this->SetEdgeWeightArrayName(0); } // ---------------------------------------------------------------------- void vtkPRandomGraphSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "NumberOfVertices: " << this->NumberOfVertices << endl; os << indent << "NumberOfEdges: " << this->NumberOfEdges << endl; os << indent << "EdgeProbability: " << this->EdgeProbability << endl; os << indent << "IncludeEdgeWeights: " << this->IncludeEdgeWeights << endl; os << indent << "Directed: " << this->Directed << endl; os << indent << "UseEdgeProbability: " << this->UseEdgeProbability << endl; os << indent << "StartWithTree: " << this->StartWithTree << endl; os << indent << "AllowSelfLoops: " << this->AllowSelfLoops << endl; os << indent << "AllowBalancedEdgeDistribution: " << this->AllowBalancedEdgeDistribution << endl; os << indent << "GeneratePedigreeIds: " << this->GeneratePedigreeIds << endl; os << indent << "VertexPedigreeIdArrayName: " << (this->VertexPedigreeIdArrayName ? this->VertexPedigreeIdArrayName : "(null)") << endl; os << indent << "EdgePedigreeIdArrayName: " << (this->EdgePedigreeIdArrayName ? this->EdgePedigreeIdArrayName : "(null)") << endl; os << indent << "EdgeWeightArrayName: " << (this->EdgeWeightArrayName ? this->EdgeWeightArrayName : "(null)") << endl; os << indent << "Seed: " << this->Seed << endl; } // ---------------------------------------------------------------------- int vtkPRandomGraphSource::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector *outputVector) { int myRank; int numProcs; MPI_Comm_rank(MPI_COMM_WORLD, &myRank); MPI_Comm_size(MPI_COMM_WORLD, &numProcs); // Seed the random number generator so we can produce repeatable results vtkMath::RandomSeed(this->Seed); // Create a mutable graph of the appropriate type. vtkSmartPointer<vtkMutableDirectedGraph> dirBuilder = vtkSmartPointer<vtkMutableDirectedGraph>::New(); vtkSmartPointer<vtkMutableUndirectedGraph> undirBuilder = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); // Create a Parallel BGL distributed graph helper vtkSmartPointer<vtkPBGLDistributedGraphHelper> helper = vtkSmartPointer<vtkPBGLDistributedGraphHelper>::New(); // Hook the distributed graph helper into the graph to make it a // distributed graph. if (this->Directed) { dirBuilder->SetDistributedGraphHelper(helper); } else { undirBuilder->SetDistributedGraphHelper(helper); } // Add NumberOfVertices new vertices, with a simple block // distribution. vtkIdType blockSize = this->NumberOfVertices / numProcs; vtkIdType myNumberOfVertices = blockSize; if (this->NumberOfVertices % numProcs != 0) { ++blockSize; if (myRank < this->NumberOfVertices % numProcs) { ++myNumberOfVertices; } } vtkIdType myStartVertex = blockSize * myRank; vtkIdType myEndVertex = myStartVertex + myNumberOfVertices; for (vtkIdType i = 0; i < myNumberOfVertices; ++i) { if (this->Directed) { dirBuilder->AddVertex(); } else { undirBuilder->AddVertex(); } } // Make sure everyone has added their own local vertices. helper->Synchronize(); if (this->StartWithTree) { vtkIdType myStart = myStartVertex; if (myStart == 0) { myStart = 1; } for (vtkIdType i = myStart; i < myEndVertex; i++) { // Pick a random vertex in [0, i-1]. int j = static_cast<vtkIdType>(vtkMath::Random(0, i)); vtkIdType iVertex = helper->MakeDistributedId(i / blockSize, i % blockSize); vtkIdType jVertex = helper->MakeDistributedId(j / blockSize, j % blockSize); if (this->Directed) { dirBuilder->LazyAddEdge(jVertex, iVertex); } else { undirBuilder->LazyAddEdge(jVertex, iVertex); } } // Make sure everyone has added the edges in the random tree. helper->Synchronize(); } if (this->UseEdgeProbability) { for (vtkIdType i = myStartVertex; i < myEndVertex; i++) { vtkIdType iVertex = helper->MakeDistributedId(i / blockSize, i % blockSize); vtkIdType begin = this->Directed ? 0 : i + 1; for (vtkIdType j = begin; j < this->NumberOfVertices; j++) { vtkIdType jVertex = helper->MakeDistributedId(j / blockSize, j % blockSize); double r = vtkMath::Random(); if (r < this->EdgeProbability) { if (this->Directed) { dirBuilder->LazyAddEdge(iVertex, jVertex); } else { undirBuilder->LazyAddEdge(iVertex, jVertex); } } } } } else { vtkIdType MaxEdges; if (this->AllowSelfLoops) { MaxEdges = this->NumberOfVertices * this->NumberOfVertices; } else { MaxEdges = (this->NumberOfVertices * (this->NumberOfVertices-1)) / 2; } if (this->NumberOfEdges > MaxEdges) { this->NumberOfEdges = MaxEdges; } vtkIdType avgNumberOfEdges = this->NumberOfEdges / numProcs; vtkIdType myNumberOfEdges = avgNumberOfEdges; if (myRank < this->NumberOfEdges % numProcs) { ++myNumberOfEdges; } for (vtkIdType i = 0; i < myNumberOfEdges; i++) { bool newEdgeFound = false; while (!newEdgeFound) { vtkIdType s; vtkIdType t; if (this->AllowBalancedEdgeDistribution) { s = static_cast<vtkIdType>(vtkMath::Random(myStartVertex, myEndVertex)); } else { s = static_cast<vtkIdType>(vtkMath::Random(0, this->NumberOfVertices)); } t = static_cast<vtkIdType>(vtkMath::Random(0, this->NumberOfVertices)); if (s == t && (!this->AllowSelfLoops)) { continue; } vtkIdType sVertex = helper->MakeDistributedId(s / blockSize, s % blockSize); vtkIdType tVertex = helper->MakeDistributedId(t / blockSize, t % blockSize); vtkDebugMacro(<<"Adding edge " << s << " to " << t); if (this->Directed) { dirBuilder->LazyAddEdge(sVertex, tVertex); } else { undirBuilder->LazyAddEdge(sVertex, tVertex); } newEdgeFound = true; } } } // Make sure everybody has added their edges and back-edges. helper->Synchronize(); // Copy the structure into the output. vtkGraph *output = vtkGraph::GetData(outputVector); if (this->Directed) { if (!output->CheckedShallowCopy(dirBuilder)) { vtkErrorMacro(<<"Invalid structure."); return 0; } } else { if (!output->CheckedShallowCopy(undirBuilder)) { vtkErrorMacro(<<"Invalid structure."); return 0; } } if (this->IncludeEdgeWeights) { if (!this->EdgeWeightArrayName) { vtkErrorMacro("When generating edge weights, " << "edge weights array name must be defined."); return 0; } vtkFloatArray *weights = vtkFloatArray::New(); weights->SetName(this->EdgeWeightArrayName); for (vtkIdType i = 0; i < output->GetNumberOfEdges(); ++i) { weights->InsertNextValue(vtkMath::Random()); } output->GetEdgeData()->AddArray(weights); weights->Delete(); } if (this->GeneratePedigreeIds) { if (!this->VertexPedigreeIdArrayName || !this->EdgePedigreeIdArrayName) { vtkErrorMacro("When generating pedigree ids, " << "vertex and edge pedigree id array names must be defined."); return 0; } vtkIdType numVert = output->GetNumberOfVertices(); vtkSmartPointer<vtkIdTypeArray> vertIds = vtkSmartPointer<vtkIdTypeArray>::New(); vertIds->SetName(this->VertexPedigreeIdArrayName); vertIds->SetNumberOfTuples(numVert); for (vtkIdType i = 0; i < numVert; ++i) { vertIds->SetValue(i, myStartVertex + i); } output->GetVertexData()->SetPedigreeIds(vertIds); // Attach a distribution function to the helper that maps these // global vertex numbers back to . TODO: Actually do it :) // Figure out how many edges come before us in the graph. boost::mpi::communicator world; vtkIdType myStartEdge = boost::mpi::scan(world, output->GetNumberOfEdges(), vtkstd::plus<vtkIdType>()); vtkIdType numEdge = output->GetNumberOfEdges(); vtkSmartPointer<vtkIdTypeArray> edgeIds = vtkSmartPointer<vtkIdTypeArray>::New(); edgeIds->SetName(this->EdgePedigreeIdArrayName); edgeIds->SetNumberOfTuples(numEdge); for (vtkIdType i = 0; i < numEdge; ++i) { edgeIds->SetValue(i, myStartEdge + i); } output->GetEdgeData()->SetPedigreeIds(edgeIds); } return 1; } //---------------------------------------------------------------------------- int vtkPRandomGraphSource::RequestDataObject( vtkInformation*, vtkInformationVector**, vtkInformationVector* ) { vtkDataObject *current = this->GetExecutive()->GetOutputData(0); if (!current || (this->Directed && !vtkDirectedGraph::SafeDownCast(current)) || (!this->Directed && vtkDirectedGraph::SafeDownCast(current))) { vtkGraph *output = 0; if (this->Directed) { output = vtkDirectedGraph::New(); } else { output = vtkUndirectedGraph::New(); } this->GetExecutive()->SetOutputData(0, output); output->Delete(); } return 1; }
Use LazyAddEdge rather than AddEdge to add the random edges to the graph, which provides a huge performance Boost for large graphs.
PERF: Use LazyAddEdge rather than AddEdge to add the random edges to the graph, which provides a huge performance Boost for large graphs.
C++
bsd-3-clause
spthaolt/VTK,msmolens/VTK,hendradarwin/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,cjh1/VTK,spthaolt/VTK,aashish24/VTK-old,spthaolt/VTK,sumedhasingla/VTK,gram526/VTK,gram526/VTK,jmerkow/VTK,SimVascular/VTK,cjh1/VTK,daviddoria/PointGraphsPhase1,biddisco/VTK,sankhesh/VTK,jmerkow/VTK,demarle/VTK,naucoin/VTKSlicerWidgets,ashray/VTK-EVM,berendkleinhaneveld/VTK,hendradarwin/VTK,biddisco/VTK,berendkleinhaneveld/VTK,Wuteyan/VTK,johnkit/vtk-dev,jeffbaumes/jeffbaumes-vtk,spthaolt/VTK,SimVascular/VTK,biddisco/VTK,candy7393/VTK,keithroe/vtkoptix,sumedhasingla/VTK,Wuteyan/VTK,hendradarwin/VTK,mspark93/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,spthaolt/VTK,johnkit/vtk-dev,johnkit/vtk-dev,keithroe/vtkoptix,aashish24/VTK-old,candy7393/VTK,biddisco/VTK,msmolens/VTK,keithroe/vtkoptix,arnaudgelas/VTK,gram526/VTK,jmerkow/VTK,aashish24/VTK-old,naucoin/VTKSlicerWidgets,mspark93/VTK,demarle/VTK,sumedhasingla/VTK,hendradarwin/VTK,sumedhasingla/VTK,gram526/VTK,spthaolt/VTK,msmolens/VTK,msmolens/VTK,ashray/VTK-EVM,johnkit/vtk-dev,candy7393/VTK,arnaudgelas/VTK,collects/VTK,gram526/VTK,spthaolt/VTK,ashray/VTK-EVM,johnkit/vtk-dev,jeffbaumes/jeffbaumes-vtk,sankhesh/VTK,biddisco/VTK,arnaudgelas/VTK,aashish24/VTK-old,candy7393/VTK,hendradarwin/VTK,berendkleinhaneveld/VTK,SimVascular/VTK,hendradarwin/VTK,ashray/VTK-EVM,biddisco/VTK,johnkit/vtk-dev,keithroe/vtkoptix,demarle/VTK,mspark93/VTK,mspark93/VTK,mspark93/VTK,keithroe/vtkoptix,jmerkow/VTK,ashray/VTK-EVM,jeffbaumes/jeffbaumes-vtk,demarle/VTK,arnaudgelas/VTK,jeffbaumes/jeffbaumes-vtk,naucoin/VTKSlicerWidgets,mspark93/VTK,collects/VTK,Wuteyan/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,naucoin/VTKSlicerWidgets,keithroe/vtkoptix,collects/VTK,arnaudgelas/VTK,mspark93/VTK,jeffbaumes/jeffbaumes-vtk,Wuteyan/VTK,candy7393/VTK,sankhesh/VTK,ashray/VTK-EVM,sankhesh/VTK,candy7393/VTK,SimVascular/VTK,naucoin/VTKSlicerWidgets,sumedhasingla/VTK,sumedhasingla/VTK,arnaudgelas/VTK,candy7393/VTK,ashray/VTK-EVM,collects/VTK,msmolens/VTK,SimVascular/VTK,cjh1/VTK,daviddoria/PointGraphsPhase1,naucoin/VTKSlicerWidgets,gram526/VTK,gram526/VTK,cjh1/VTK,aashish24/VTK-old,sankhesh/VTK,aashish24/VTK-old,sankhesh/VTK,sankhesh/VTK,daviddoria/PointGraphsPhase1,ashray/VTK-EVM,jmerkow/VTK,jmerkow/VTK,cjh1/VTK,Wuteyan/VTK,candy7393/VTK,SimVascular/VTK,cjh1/VTK,msmolens/VTK,Wuteyan/VTK,berendkleinhaneveld/VTK,demarle/VTK,msmolens/VTK,hendradarwin/VTK,berendkleinhaneveld/VTK,collects/VTK,jmerkow/VTK,keithroe/vtkoptix,demarle/VTK,Wuteyan/VTK,sankhesh/VTK,mspark93/VTK,gram526/VTK,daviddoria/PointGraphsPhase1,daviddoria/PointGraphsPhase1,demarle/VTK,collects/VTK,jmerkow/VTK,biddisco/VTK,sumedhasingla/VTK,daviddoria/PointGraphsPhase1,johnkit/vtk-dev,keithroe/vtkoptix,demarle/VTK,sumedhasingla/VTK
c8c749784853f912e4bf50405af74a13c1862a5f
mix_lib/source/computer.cpp
mix_lib/source/computer.cpp
#include <mix/computer.h> #include <mix/command_processor.h> #include <mix/computer_listener.h> #include "internal/helpers.hpp" using namespace mix; Computer::Computer(IComputerListener* listener /*= nullptr*/) : ra_{} , rx_{} , rindexes_{} , rj_{} , rip_{} , comparison_state_{ComparisonIndicator::Less} , overflow_flag_{OverflowFlag::NoOverdlow} , memory_{} , listener_{listener} , devices_{listener} { } const Register& Computer::ra() const { return ra_; } const Register& Computer::rx() const { return rx_; } const AddressRegister& Computer::rj() const { return rj_; } void Computer::jump(int address) { const auto next = next_command(); set_next_command(address); rj_.set_value(next); internal::InvokeListener(listener_, &IComputerListener::on_jump, next); } void Computer::set_next_command(int address) { // #TODO: validate `address` (in range [0; 4000)) rip_.set_value(address); internal::InvokeListener(listener_, &IComputerListener::on_current_command_changed, address); } int Computer::current_command() const { return rip_.value(); } int Computer::next_command() const { return current_command() + 1; } void Computer::set_memory(int address, const Word& value) { if ((address < 0) || (static_cast<std::size_t>(address) >= memory_.size())) { throw std::out_of_range{"Invalid memory address"}; } memory_[static_cast<std::size_t>(address)] = value; internal::InvokeListener(listener_, &IComputerListener::on_memory_set, address); } const Word& Computer::memory(int address) const { if ((address < 0) || (address >= static_cast<int>(memory_.size()))) { throw std::out_of_range{"Invalid Memory address"}; } return memory_[static_cast<std::size_t>(address)]; } const IndexRegister& Computer::ri(std::size_t index) const { if ((index == 0) || (index > rindexes_.size())) { throw std::out_of_range{"Invalid IndexRegister"}; } return rindexes_[index - 1]; } void Computer::execute(const Command& command) { // #TODO: make exception-safe on_before_command/on_after_command() calls ? internal::InvokeListener(listener_, &IComputerListener::on_before_command, command); CommandProcessor processor{*this}; processor.process(command); internal::InvokeListener(listener_, &IComputerListener::on_after_command, command); } void Computer::set_ra(const Register& ra) { ra_ = ra; internal::InvokeListener(listener_, &IComputerListener::on_ra_set); } void Computer::set_rx(const Register& rx) { rx_ = rx; internal::InvokeListener(listener_, &IComputerListener::on_rx_set); } void Computer::set_ri(std::size_t index, const IndexRegister& ri) { if ((index == 0) || (index > rindexes_.size())) { throw std::out_of_range{"Invalid IndexRegister"}; } rindexes_[index - 1] = ri; internal::InvokeListener(listener_, &IComputerListener::on_ri_set, index); } OverflowFlag Computer::overflow_flag() const { return overflow_flag_; } bool Computer::has_overflow() const { return (overflow_flag_ == OverflowFlag::Overflow); } void Computer::set_overflow() { overflow_flag_ = OverflowFlag::Overflow; internal::InvokeListener(listener_, &IComputerListener::on_overflow_flag_set); } void Computer::clear_overflow() { overflow_flag_ = OverflowFlag::NoOverdlow; internal::InvokeListener(listener_, &IComputerListener::on_overflow_flag_set); } void Computer::set_listener(IComputerListener* listener) { listener_ = listener; devices_.set_listener(listener); } ComparisonIndicator Computer::comparison_state() const { return comparison_state_; } void Computer::set_comparison_state(ComparisonIndicator comparison) { comparison_state_ = comparison; internal::InvokeListener(listener_, &IComputerListener::on_comparison_state_set); } void Computer::halt() { }
#include <mix/computer.h> #include <mix/command_processor.h> #include <mix/computer_listener.h> #include "internal/helpers.hpp" using namespace mix; Computer::Computer(IComputerListener* listener /*= nullptr*/) : ra_{} , rx_{} , rindexes_{} , rj_{} , rip_{} , comparison_state_{ComparisonIndicator::Less} , overflow_flag_{OverflowFlag::NoOverdlow} , memory_{} , devices_{listener} , listener_{listener} { } const Register& Computer::ra() const { return ra_; } const Register& Computer::rx() const { return rx_; } const AddressRegister& Computer::rj() const { return rj_; } void Computer::jump(int address) { const auto next = next_command(); set_next_command(address); rj_.set_value(next); internal::InvokeListener(listener_, &IComputerListener::on_jump, next); } void Computer::set_next_command(int address) { // #TODO: validate `address` (in range [0; 4000)) rip_.set_value(address); internal::InvokeListener(listener_, &IComputerListener::on_current_command_changed, address); } int Computer::current_command() const { return rip_.value(); } int Computer::next_command() const { return current_command() + 1; } void Computer::set_memory(int address, const Word& value) { if ((address < 0) || (static_cast<std::size_t>(address) >= memory_.size())) { throw std::out_of_range{"Invalid memory address"}; } memory_[static_cast<std::size_t>(address)] = value; internal::InvokeListener(listener_, &IComputerListener::on_memory_set, address); } const Word& Computer::memory(int address) const { if ((address < 0) || (address >= static_cast<int>(memory_.size()))) { throw std::out_of_range{"Invalid Memory address"}; } return memory_[static_cast<std::size_t>(address)]; } const IndexRegister& Computer::ri(std::size_t index) const { if ((index == 0) || (index > rindexes_.size())) { throw std::out_of_range{"Invalid IndexRegister"}; } return rindexes_[index - 1]; } void Computer::execute(const Command& command) { // #TODO: make exception-safe on_before_command/on_after_command() calls ? internal::InvokeListener(listener_, &IComputerListener::on_before_command, command); CommandProcessor processor{*this}; processor.process(command); internal::InvokeListener(listener_, &IComputerListener::on_after_command, command); } void Computer::set_ra(const Register& ra) { ra_ = ra; internal::InvokeListener(listener_, &IComputerListener::on_ra_set); } void Computer::set_rx(const Register& rx) { rx_ = rx; internal::InvokeListener(listener_, &IComputerListener::on_rx_set); } void Computer::set_ri(std::size_t index, const IndexRegister& ri) { if ((index == 0) || (index > rindexes_.size())) { throw std::out_of_range{"Invalid IndexRegister"}; } rindexes_[index - 1] = ri; internal::InvokeListener(listener_, &IComputerListener::on_ri_set, index); } OverflowFlag Computer::overflow_flag() const { return overflow_flag_; } bool Computer::has_overflow() const { return (overflow_flag_ == OverflowFlag::Overflow); } void Computer::set_overflow() { overflow_flag_ = OverflowFlag::Overflow; internal::InvokeListener(listener_, &IComputerListener::on_overflow_flag_set); } void Computer::clear_overflow() { overflow_flag_ = OverflowFlag::NoOverdlow; internal::InvokeListener(listener_, &IComputerListener::on_overflow_flag_set); } void Computer::set_listener(IComputerListener* listener) { listener_ = listener; devices_.set_listener(listener); } ComparisonIndicator Computer::comparison_state() const { return comparison_state_; } void Computer::set_comparison_state(ComparisonIndicator comparison) { comparison_state_ = comparison; internal::InvokeListener(listener_, &IComputerListener::on_comparison_state_set); } void Computer::halt() { }
Fix order of member initialization in Computer
Fix order of member initialization in Computer
C++
mit
grishavanika/mix,grishavanika/mix,grishavanika/mix
b3b59529a94410502bb063978c1ecfdfed470844
src/queue.hpp
src/queue.hpp
#ifndef queue_hpp #define queue_hpp #include "util.hpp" /* FIFO */ template<class T> class Queue{ public: Queue(){ size = 0; start = nullptr; end = nullptr; } ~Queue(){ clear(); } void clear(){ while (!isEmpty()) { Node<T> * tempStart = start; start = start->next; delete tempStart; start->previous = nullptr; } size = 0; } bool isEmpty(){ return start == nullptr; } int getSize(){ return this->size; } void enQueue(T data){ if(isEmpty()){ start = new Node<T>(); start->data = data; end = start; } else{ end->next = new Node<T>(); Node<T> * tempEnd = end; end = end->next; end->data = data; end->previous = tempEnd; } size ++; } T deQueue(){ T temp = start->data; if(end != start){ Node<T> * tempStart = start->next; delete start; start = tempStart; start->previous = nullptr; } else{ end = nullptr; start = nullptr; } return temp; } T & operator [] (int index){ if(index >= size) fatal("Element index larger than queue length"); Node<T> * current; current = start; for (int count = 0; count < index ; count ++) { current = current->next; } return current->data; } private: Node<T> * start; Node<T> * end; int size; }; #endif
#ifndef queue_hpp #define queue_hpp #include "util.hpp" #include <deque> /* FIFO */ template<class T> class Queue{ public: Queue() { } ~Queue(){ clear(); } void clear(){ Q.clear(); } bool isEmpty(){ return Q.empty(); } int getSize(){ return Q.size(); } void enQueue(T data){ Q.push_back(data); } T deQueue(){ T obj = Q.front(); Q.pop_front(); return obj; } T & operator [] (int index){ if(index >= Q.size()) fatal("Element index larger than queue length"); return Q[index]; } private: std::deque<T> Q; }; #endif
Use deque<T> in standard library
Use deque<T> in standard library TODO: Use deque or queue everywhere and remove queue.hpp
C++
mit
Inndy/libabc
d699bfbf106bc5052fddc2c9e00fe776a1cb1ba7
src/ray/id.cc
src/ray/id.cc
#include "ray/id.h" #include <limits.h> #include <random> #include "ray/constants.h" #include "ray/status.h" namespace ray { UniqueID::UniqueID(const plasma::UniqueID &from) { std::memcpy(&id_, from.data(), kUniqueIDSize); } UniqueID UniqueID::from_random() { UniqueID id; uint8_t *data = id.mutable_data(); std::random_device engine; for (int i = 0; i < kUniqueIDSize; i++) { data[i] = static_cast<uint8_t>(engine()); } return id; } UniqueID UniqueID::from_binary(const std::string &binary) { UniqueID id; std::memcpy(&id, binary.data(), sizeof(id)); return id; } const UniqueID UniqueID::nil() { UniqueID result; uint8_t *data = result.mutable_data(); std::fill_n(data, kUniqueIDSize, 255); return result; } bool UniqueID::is_nil() const { const uint8_t *d = data(); for (int i = 0; i < kUniqueIDSize; ++i) { if (d[i] != 255) { return false; } } return true; } const uint8_t *UniqueID::data() const { return id_; } uint8_t *UniqueID::mutable_data() { return id_; } size_t UniqueID::size() const { return kUniqueIDSize; } std::string UniqueID::binary() const { return std::string(reinterpret_cast<const char *>(id_), kUniqueIDSize); } std::string UniqueID::hex() const { constexpr char hex[] = "0123456789abcdef"; std::string result; for (int i = 0; i < kUniqueIDSize; i++) { unsigned int val = id_[i]; result.push_back(hex[val >> 4]); result.push_back(hex[val & 0xf]); } return result; } plasma::UniqueID UniqueID::to_plasma_id() { plasma::UniqueID result; std::memcpy(result.mutable_data(), &id_, kUniqueIDSize); return result; } bool UniqueID::operator==(const UniqueID &rhs) const { return std::memcmp(data(), rhs.data(), kUniqueIDSize) == 0; } size_t UniqueID::hash() const { size_t result; // Skip the bytes for the object prefix. std::memcpy(&result, id_ + (kObjectIdIndexSize / CHAR_BIT), sizeof(size_t)); return result; } std::ostream &operator<<(std::ostream &os, const UniqueID &id) { os << id.hex(); return os; } const ObjectID ComputeObjectId(const TaskID &task_id, int64_t object_index) { RAY_CHECK(object_index <= kMaxTaskReturns && object_index >= -kMaxTaskPuts); ObjectID return_id = task_id; int64_t *first_bytes = reinterpret_cast<int64_t *>(&return_id); // Zero out the lowest kObjectIdIndexSize bits of the first byte of the // object ID. uint64_t bitmask = static_cast<uint64_t>(-1) << kObjectIdIndexSize; *first_bytes = *first_bytes & (bitmask); // OR the first byte of the object ID with the return index. *first_bytes = *first_bytes | (object_index & ~bitmask); return return_id; } const TaskID FinishTaskId(const TaskID &task_id) { return ComputeObjectId(task_id, 0); } const ObjectID ComputeReturnId(const TaskID &task_id, int64_t return_index) { RAY_CHECK(return_index >= 1 && return_index <= kMaxTaskReturns); return ComputeObjectId(task_id, return_index); } const ObjectID ComputePutId(const TaskID &task_id, int64_t put_index) { RAY_CHECK(put_index >= 1 && put_index <= kMaxTaskPuts); return ComputeObjectId(task_id, -1 * put_index); } const TaskID ComputeTaskId(const ObjectID &object_id) { TaskID task_id = object_id; int64_t *first_bytes = reinterpret_cast<int64_t *>(&task_id); // Zero out the lowest kObjectIdIndexSize bits of the first byte of the // object ID. uint64_t bitmask = static_cast<uint64_t>(-1) << kObjectIdIndexSize; *first_bytes = *first_bytes & (bitmask); return task_id; } int64_t ComputeObjectIndex(const ObjectID &object_id) { const int64_t *first_bytes = reinterpret_cast<const int64_t *>(&object_id); uint64_t bitmask = static_cast<uint64_t>(-1) << kObjectIdIndexSize; int64_t index = *first_bytes & (~bitmask); index <<= (8 * sizeof(int64_t) - kObjectIdIndexSize); index >>= (8 * sizeof(int64_t) - kObjectIdIndexSize); return index; } } // namespace ray
#include "ray/id.h" #include <limits.h> #include <random> #include "ray/constants.h" #include "ray/status.h" namespace ray { UniqueID::UniqueID(const plasma::UniqueID &from) { std::memcpy(&id_, from.data(), kUniqueIDSize); } UniqueID UniqueID::from_random() { UniqueID id; uint8_t *data = id.mutable_data(); std::random_device engine; for (int i = 0; i < kUniqueIDSize; i++) { data[i] = static_cast<uint8_t>(engine()); } return id; } UniqueID UniqueID::from_binary(const std::string &binary) { UniqueID id; std::memcpy(&id, binary.data(), sizeof(id)); return id; } const UniqueID UniqueID::nil() { UniqueID result; uint8_t *data = result.mutable_data(); std::fill_n(data, kUniqueIDSize, 255); return result; } bool UniqueID::is_nil() const { const uint8_t *d = data(); for (int i = 0; i < kUniqueIDSize; ++i) { if (d[i] != 255) { return false; } } return true; } const uint8_t *UniqueID::data() const { return id_; } uint8_t *UniqueID::mutable_data() { return id_; } size_t UniqueID::size() const { return kUniqueIDSize; } std::string UniqueID::binary() const { return std::string(reinterpret_cast<const char *>(id_), kUniqueIDSize); } std::string UniqueID::hex() const { constexpr char hex[] = "0123456789abcdef"; std::string result; for (int i = 0; i < kUniqueIDSize; i++) { unsigned int val = id_[i]; result.push_back(hex[val >> 4]); result.push_back(hex[val & 0xf]); } return result; } plasma::UniqueID UniqueID::to_plasma_id() { plasma::UniqueID result; std::memcpy(result.mutable_data(), &id_, kUniqueIDSize); return result; } bool UniqueID::operator==(const UniqueID &rhs) const { return std::memcmp(data(), rhs.data(), kUniqueIDSize) == 0; } // This code is from https://sites.google.com/site/murmurhash/ // and is public domain. uint64_t MurmurHash64A(const void *key, int len, unsigned int seed) { const uint64_t m = 0xc6a4a7935bd1e995; const int r = 47; uint64_t h = seed ^ (len * m); const uint64_t *data = reinterpret_cast<const uint64_t *>(key); const uint64_t *end = data + (len / 8); while (data != end) { uint64_t k = *data++; k *= m; k ^= k >> r; k *= m; h ^= k; h *= m; } const unsigned char *data2 = reinterpret_cast<const unsigned char *>(data); switch (len & 7) { case 7: h ^= uint64_t(data2[6]) << 48; case 6: h ^= uint64_t(data2[5]) << 40; case 5: h ^= uint64_t(data2[4]) << 32; case 4: h ^= uint64_t(data2[3]) << 24; case 3: h ^= uint64_t(data2[2]) << 16; case 2: h ^= uint64_t(data2[1]) << 8; case 1: h ^= uint64_t(data2[0]); h *= m; }; h ^= h >> r; h *= m; h ^= h >> r; return h; } size_t UniqueID::hash() const { return MurmurHash64A(&id_[0], kUniqueIDSize, 0); } std::ostream &operator<<(std::ostream &os, const UniqueID &id) { os << id.hex(); return os; } const ObjectID ComputeObjectId(const TaskID &task_id, int64_t object_index) { RAY_CHECK(object_index <= kMaxTaskReturns && object_index >= -kMaxTaskPuts); ObjectID return_id = task_id; int64_t *first_bytes = reinterpret_cast<int64_t *>(&return_id); // Zero out the lowest kObjectIdIndexSize bits of the first byte of the // object ID. uint64_t bitmask = static_cast<uint64_t>(-1) << kObjectIdIndexSize; *first_bytes = *first_bytes & (bitmask); // OR the first byte of the object ID with the return index. *first_bytes = *first_bytes | (object_index & ~bitmask); return return_id; } const TaskID FinishTaskId(const TaskID &task_id) { return ComputeObjectId(task_id, 0); } const ObjectID ComputeReturnId(const TaskID &task_id, int64_t return_index) { RAY_CHECK(return_index >= 1 && return_index <= kMaxTaskReturns); return ComputeObjectId(task_id, return_index); } const ObjectID ComputePutId(const TaskID &task_id, int64_t put_index) { RAY_CHECK(put_index >= 1 && put_index <= kMaxTaskPuts); return ComputeObjectId(task_id, -1 * put_index); } const TaskID ComputeTaskId(const ObjectID &object_id) { TaskID task_id = object_id; int64_t *first_bytes = reinterpret_cast<int64_t *>(&task_id); // Zero out the lowest kObjectIdIndexSize bits of the first byte of the // object ID. uint64_t bitmask = static_cast<uint64_t>(-1) << kObjectIdIndexSize; *first_bytes = *first_bytes & (bitmask); return task_id; } int64_t ComputeObjectIndex(const ObjectID &object_id) { const int64_t *first_bytes = reinterpret_cast<const int64_t *>(&object_id); uint64_t bitmask = static_cast<uint64_t>(-1) << kObjectIdIndexSize; int64_t index = *first_bytes & (~bitmask); index <<= (8 * sizeof(int64_t) - kObjectIdIndexSize); index >>= (8 * sizeof(int64_t) - kObjectIdIndexSize); return index; } } // namespace ray
Use hashing function that takes into account all UniqueID bytes (#2174)
Use hashing function that takes into account all UniqueID bytes (#2174)
C++
apache-2.0
atumanov/ray,robertnishihara/ray,pcmoritz/ray-1,stephanie-wang/ray,ujvl/ray-ng,pcmoritz/ray-1,richardliaw/ray,pcmoritz/ray-1,ray-project/ray,ray-project/ray,stephanie-wang/ray,richardliaw/ray,richardliaw/ray,richardliaw/ray,stephanie-wang/ray,pcmoritz/ray-1,ray-project/ray,ray-project/ray,atumanov/ray,stephanie-wang/ray,robertnishihara/ray,stephanie-wang/ray,atumanov/ray,robertnishihara/ray,atumanov/ray,atumanov/ray,ray-project/ray,robertnishihara/ray,robertnishihara/ray,ray-project/ray,pcmoritz/ray-1,richardliaw/ray,atumanov/ray,ujvl/ray-ng,robertnishihara/ray,stephanie-wang/ray,stephanie-wang/ray,stephanie-wang/ray,stephanie-wang/ray,robertnishihara/ray,ujvl/ray-ng,pcmoritz/ray-1,robertnishihara/ray,pcmoritz/ray-1,richardliaw/ray,atumanov/ray,atumanov/ray,ujvl/ray-ng,robertnishihara/ray,ray-project/ray,pcmoritz/ray-1,richardliaw/ray,ray-project/ray,richardliaw/ray
9eec0f2d185bff5c3cd0ffbd5b9c17a55c387a33
libDySySim/SimBlock.cpp
libDySySim/SimBlock.cpp
#include "SimBlock.h" #include <iostream> double dysysim::SimTime::delta_t = 1; double dysysim::SimTime::t = 0; std::map<int, dysysim::SimBlock *> dysysim::SimBlock::allSimBlocks_s; bool dysysim::SimBlock::idIsUnique(int id) { if (allSimBlocks_s.find(id) == end(allSimBlocks_s)) { return true; } std::cerr << "--- ErrorDYSYSIM id " << id << " already exists\n"; return false; }
#include "SimBlock.h" #include <iostream> double dysysim::SimTime::delta_t = 1; double dysysim::SimTime::t = 0; std::map<int, dysysim::SimBlock *> dysysim::SimBlock::allSimBlocks_s; bool dysysim::SimBlock::idIsUnique(int id) { if (allSimBlocks_s.find(id) == end(allSimBlocks_s)) { return true; } std::cerr << "--- Error DYSYSIM id " << id << " already exists\n"; return false; }
Solve typo
Solve typo
C++
mit
josokw/Fuzzy,josokw/Fuzzy,josokw/Fuzzy
2be7a31c3c4719da3d6e77849c7957399d78d556
libcaf_core/caf/all.hpp
libcaf_core/caf/all.hpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_ALL_HPP #define CAF_ALL_HPP #include "caf/config.hpp" #include "caf/sec.hpp" #include "caf/atom.hpp" #include "caf/send.hpp" #include "caf/skip.hpp" #include "caf/unit.hpp" #include "caf/term.hpp" #include "caf/actor.hpp" #include "caf/after.hpp" #include "caf/error.hpp" #include "caf/group.hpp" #include "caf/extend.hpp" #include "caf/logger.hpp" #include "caf/others.hpp" #include "caf/result.hpp" #include "caf/stream.hpp" #include "caf/message.hpp" #include "caf/node_id.hpp" #include "caf/behavior.hpp" #include "caf/duration.hpp" #include "caf/expected.hpp" #include "caf/exec_main.hpp" #include "caf/resumable.hpp" #include "caf/streambuf.hpp" #include "caf/to_string.hpp" #include "caf/actor_addr.hpp" #include "caf/actor_pool.hpp" #include "caf/attachable.hpp" #include "caf/message_id.hpp" #include "caf/replies_to.hpp" #include "caf/serializer.hpp" #include "caf/actor_clock.hpp" #include "caf/actor_proxy.hpp" #include "caf/exit_reason.hpp" #include "caf/local_actor.hpp" #include "caf/ref_counted.hpp" #include "caf/thread_hook.hpp" #include "caf/typed_actor.hpp" #include "caf/actor_system.hpp" #include "caf/deserializer.hpp" #include "caf/scoped_actor.hpp" #include "caf/actor_ostream.hpp" #include "caf/function_view.hpp" #include "caf/index_mapping.hpp" #include "caf/spawn_options.hpp" #include "caf/abstract_actor.hpp" #include "caf/abstract_group.hpp" #include "caf/blocking_actor.hpp" #include "caf/deep_to_string.hpp" #include "caf/execution_unit.hpp" #include "caf/memory_managed.hpp" #include "caf/stateful_actor.hpp" #include "caf/typed_behavior.hpp" #include "caf/proxy_registry.hpp" #include "caf/behavior_policy.hpp" #include "caf/message_builder.hpp" #include "caf/message_handler.hpp" #include "caf/response_handle.hpp" #include "caf/fused_scatterer.hpp" #include "caf/system_messages.hpp" #include "caf/abstract_channel.hpp" #include "caf/may_have_timeout.hpp" #include "caf/message_priority.hpp" #include "caf/typed_actor_view.hpp" #include "caf/binary_serializer.hpp" #include "caf/composed_behavior.hpp" #include "caf/event_based_actor.hpp" #include "caf/primitive_variant.hpp" #include "caf/timeout_definition.hpp" #include "caf/broadcast_scatterer.hpp" #include "caf/actor_system_config.hpp" #include "caf/binary_deserializer.hpp" #include "caf/composable_behavior.hpp" #include "caf/typed_actor_pointer.hpp" #include "caf/scoped_execution_unit.hpp" #include "caf/typed_response_promise.hpp" #include "caf/random_topic_scatterer.hpp" #include "caf/broadcast_topic_scatterer.hpp" #include "caf/typed_event_based_actor.hpp" #include "caf/abstract_composable_behavior.hpp" #include "caf/decorator/sequencer.hpp" #include "caf/meta/type_name.hpp" #include "caf/meta/annotation.hpp" #include "caf/meta/save_callback.hpp" #include "caf/meta/load_callback.hpp" #include "caf/meta/omittable_if_empty.hpp" #include "caf/scheduler/test_coordinator.hpp" #include "caf/scheduler/abstract_coordinator.hpp" /// /// @mainpage CAF /// /// @section Intro Introduction /// /// This library provides an implementation of the actor model for C++. /// It uses a network transparent messaging system to ease development /// of both concurrent and distributed software. /// /// `libcaf` uses a thread pool to schedule actors by default. /// A scheduled actor should not call blocking functions. /// Individual actors can be spawned (created) with a special flag to run in /// an own thread if one needs to make use of blocking APIs. /// /// Writing applications in `libcaf` requires a minimum of gluecode and /// each context <i>is</i> an actor. Scoped actors allow actor interaction /// from the context of threads such as main. /// /// @section GettingStarted Getting Started /// /// To build `libcaf,` you need `GCC >= 4.8 or <tt>Clang >= 3.2</tt>, /// and `CMake`. /// /// The usual build steps on Linux and macOS are: /// ///- `./configure ///- `make ///- `make install (as root, optionally) /// /// Please run the unit tests as well to verify that `libcaf` /// works properly. /// ///- `make test /// /// Please submit a bug report that includes (a) your compiler version, /// (b) your OS, and (c) the output of the unit tests if an error occurs: /// https://github.com/actor-framework/actor-framework/issues /// /// Please read the <b>Manual</b> for an introduction to `libcaf`. /// It is available online on Read The Docs at /// https://actor-framework.readthedocs.io or as PDF at /// http://www.actor-framework.org/pdf/manual.pdf /// /// @section IntroHelloWorld Hello World Example /// /// @include hello_world.cpp /// /// @section IntroMoreExamples More Examples /// /// The {@link math_actor.cpp Math Actor Example} shows the usage /// of {@link receive_loop} and {@link caf::arg_match arg_match}. /// The {@link dining_philosophers.cpp Dining Philosophers Example} /// introduces event-based actors covers various features of CAF. /// /// @namespace caf /// Root namespace of libcaf. /// /// @namespace caf::mixin /// Contains mixin classes implementing several actor traits. /// /// @namespace caf::exit_reason /// Contains all predefined exit reasons. /// /// @namespace caf::policy /// Contains policies encapsulating characteristics or algorithms. /// /// @namespace caf::io /// Contains all IO-related classes and functions. /// /// @namespace caf::io::network /// Contains classes and functions used for network abstraction. /// /// @namespace caf::io::basp /// Contains all classes and functions for the Binary Actor Sytem Protocol. /// /// @defgroup MessageHandling Message Handling /// /// This is the beating heart of CAF, since actor programming is /// a message oriented programming paradigm. /// /// A message in CAF is a n-tuple of values (with size >= 1). /// You can use almost every type in a messages as long as it is announced, /// i.e., known by the type system of CAF. /// /// @defgroup BlockingAPI Blocking API /// /// Blocking functions to receive messages. /// /// The blocking API of CAF is intended to be used for migrating /// previously threaded applications. When writing new code, you should /// consider the nonblocking API based on `become` and `unbecome` first. /// /// @section Send Sending Messages /// /// The function `send` can be used to send a message to an actor. /// The first argument is the receiver of the message followed by any number /// of values: /// /// ~~ /// // spawn some actors /// actor_system_config cfg; /// actor_system system{cfg}; /// auto a1 = system.spawn(...); /// auto a2 = system.spawn(...); /// auto a3 = system.spawn(...); /// /// // an actor executed in the current thread /// scoped_actor self{system}; /// /// // define an atom for message annotation /// using hello_atom = atom_constant<atom("hello")>; /// using compute_atom = atom_constant<atom("compute")>; /// using result_atom = atom_constant<atom("result")>; /// /// // send a message to a1 /// self->send(a1, hello_atom::value, "hello a1!"); /// /// // send a message to a1, a2, and a3 /// auto msg = make_message(compute_atom::value, 1, 2, 3); /// self->send(a1, msg); /// self->send(a2, msg); /// self->send(a3, msg); /// ~~ /// /// @section Receive Receive messages /// /// The function `receive` takes a `behavior` as argument. The behavior /// is a list of { callback } rules where the callback argument types /// define a pattern for matching messages. /// /// ~~ /// { /// [](hello_atom, const std::string& msg) { /// cout << "received hello message: " << msg << endl; /// }, /// [](compute_atom, int i0, int i1, int i2) { /// // send our result back to the sender of this messages /// return make_message(result_atom::value, i0 + i1 + i2); /// } /// } /// ~~ /// /// Blocking actors such as the scoped actor can call their receive member /// to handle incoming messages. /// /// ~~ /// self->receive( /// [](result_atom, int i) { /// cout << "result is: " << i << endl; /// } /// ); /// ~~ /// /// Please read the manual for further details about pattern matching. /// /// @section Atoms Atoms /// /// Atoms are a nice way to add semantic informations to a message. /// Assuming an actor wants to provide a "math sevice" for integers. It /// could provide operations such as addition, subtraction, etc. /// This operations all have two operands. Thus, the actor does not know /// what operation the sender of a message wanted by receiving just two integers. /// /// Example actor: /// ~~ /// using plus_atom = atom_constant<atom("plus")>; /// using minus_atom = atom_constant<atom("minus")>; /// behavior math_actor() { /// return { /// [](plus_atom, int a, int b) { /// return make_message(atom("result"), a + b); /// }, /// [](minus_atom, int a, int b) { /// return make_message(atom("result"), a - b); /// } /// }; /// } /// ~~ /// /// @section ReceiveLoops Receive Loops /// /// The previous examples used `receive` to create a behavior on-the-fly. /// This is inefficient in a loop since the argument passed to receive /// is created in each iteration again. It's possible to store the behavior /// in a variable and pass that variable to receive. This fixes the issue /// of re-creation each iteration but rips apart definition and usage. /// /// There are three convenience functions implementing receive loops to /// declare behavior where it belongs without unnecessary /// copies: `receive_while,` `receive_for` and `do_receive`. /// /// `receive_while` creates a functor evaluating a lambda expression. /// The loop continues until the given lambda returns `false`. A simple example: /// /// ~~ /// size_t received = 0; /// receive_while([&] { return received < 10; }) ( /// [&](int) { /// ++received; /// } /// ); /// // ... /// ~~ /// /// `receive_for` is a simple ranged-based loop: /// /// ~~ /// std::vector<int> results; /// size_t i = 0; /// receive_for(i, 10) ( /// [&](int value) { /// results.push_back(value); /// } /// ); /// ~~ /// /// `do_receive` returns a functor providing the function `until` that /// takes a lambda expression. The loop continues until the given lambda /// returns true. Example: /// /// ~~ /// size_t received = 0; /// do_receive ( /// [&](int) { /// ++received; /// } /// ).until([&] { return received >= 10; }); /// // ... /// ~~ /// /// @section FutureSend Sending Delayed Messages /// /// The function `delayed_send` provides a simple way to delay a message. /// This is particularly useful for recurring events, e.g., periodical polling. /// Usage example: /// /// ~~ /// scoped_actor self{...}; /// /// self->delayed_send(self, std::chrono::seconds(1), poll_atom::value); /// bool running = true; /// self->receive_while([&](){ return running; }) ( /// // ... /// [&](poll_atom) { /// // ... poll something ... /// // and do it again after 1sec /// self->delayed_send(self, std::chrono::seconds(1), poll_atom::value); /// } /// ); /// ~~ /// /// See also the {@link dancing_kirby.cpp dancing kirby example}. /// /// @defgroup ImplicitConversion Implicit Type Conversions /// /// The message passing of `libcaf` prohibits pointers in messages because /// it enforces network transparent messaging. /// Unfortunately, string literals in `C++` have the type `const char*, /// resp. `const char[]. Since `libcaf` is a user-friendly library, /// it silently converts string literals and C-strings to `std::string` objects. /// It also converts unicode literals to the corresponding STL container. /// /// A few examples: /// ~~ /// // sends an std::string containing "hello actor!" to itself /// send(self, "hello actor!"); /// /// const char* cstring = "cstring"; /// // sends an std::string containing "cstring" to itself /// send(self, cstring); /// /// // sends an std::u16string containing the UTF16 string "hello unicode world!" /// send(self, u"hello unicode world!"); /// /// // x has the type caf::tuple<std::string, std::string> /// auto x = make_message("hello", "tuple"); /// ~~ /// /// @defgroup ActorCreation Creating Actors // examples /// A trivial example program. /// @example hello_world.cpp /// A simple example for a delayed_send based application. /// @example dancing_kirby.cpp /// An event-based "Dining Philosophers" implementation. /// @example dining_philosophers.cpp #endif // CAF_ALL_HPP
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_ALL_HPP #define CAF_ALL_HPP #include "caf/config.hpp" #include "caf/sec.hpp" #include "caf/atom.hpp" #include "caf/send.hpp" #include "caf/skip.hpp" #include "caf/unit.hpp" #include "caf/term.hpp" #include "caf/actor.hpp" #include "caf/after.hpp" #include "caf/error.hpp" #include "caf/group.hpp" #include "caf/extend.hpp" #include "caf/logger.hpp" #include "caf/others.hpp" #include "caf/result.hpp" #include "caf/stream.hpp" #include "caf/message.hpp" #include "caf/node_id.hpp" #include "caf/behavior.hpp" #include "caf/duration.hpp" #include "caf/expected.hpp" #include "caf/exec_main.hpp" #include "caf/resumable.hpp" #include "caf/streambuf.hpp" #include "caf/to_string.hpp" #include "caf/actor_addr.hpp" #include "caf/actor_pool.hpp" #include "caf/attachable.hpp" #include "caf/message_id.hpp" #include "caf/replies_to.hpp" #include "caf/serializer.hpp" #include "caf/actor_clock.hpp" #include "caf/actor_proxy.hpp" #include "caf/exit_reason.hpp" #include "caf/local_actor.hpp" #include "caf/ref_counted.hpp" #include "caf/thread_hook.hpp" #include "caf/typed_actor.hpp" #include "caf/actor_system.hpp" #include "caf/deserializer.hpp" #include "caf/scoped_actor.hpp" #include "caf/upstream_msg.hpp" #include "caf/actor_ostream.hpp" #include "caf/function_view.hpp" #include "caf/index_mapping.hpp" #include "caf/spawn_options.hpp" #include "caf/abstract_actor.hpp" #include "caf/abstract_group.hpp" #include "caf/blocking_actor.hpp" #include "caf/deep_to_string.hpp" #include "caf/execution_unit.hpp" #include "caf/memory_managed.hpp" #include "caf/stateful_actor.hpp" #include "caf/typed_behavior.hpp" #include "caf/proxy_registry.hpp" #include "caf/downstream_msg.hpp" #include "caf/behavior_policy.hpp" #include "caf/message_builder.hpp" #include "caf/message_handler.hpp" #include "caf/response_handle.hpp" #include "caf/system_messages.hpp" #include "caf/abstract_channel.hpp" #include "caf/may_have_timeout.hpp" #include "caf/message_priority.hpp" #include "caf/typed_actor_view.hpp" #include "caf/binary_serializer.hpp" #include "caf/composed_behavior.hpp" #include "caf/event_based_actor.hpp" #include "caf/primitive_variant.hpp" #include "caf/timeout_definition.hpp" #include "caf/actor_system_config.hpp" #include "caf/binary_deserializer.hpp" #include "caf/composable_behavior.hpp" #include "caf/typed_actor_pointer.hpp" #include "caf/scoped_execution_unit.hpp" #include "caf/typed_response_promise.hpp" #include "caf/random_topic_scatterer.hpp" #include "caf/broadcast_topic_scatterer.hpp" #include "caf/typed_event_based_actor.hpp" #include "caf/abstract_composable_behavior.hpp" #include "caf/decorator/sequencer.hpp" #include "caf/meta/type_name.hpp" #include "caf/meta/annotation.hpp" #include "caf/meta/save_callback.hpp" #include "caf/meta/load_callback.hpp" #include "caf/meta/omittable_if_empty.hpp" #include "caf/scheduler/test_coordinator.hpp" #include "caf/scheduler/abstract_coordinator.hpp" /// /// @mainpage CAF /// /// @section Intro Introduction /// /// This library provides an implementation of the actor model for C++. /// It uses a network transparent messaging system to ease development /// of both concurrent and distributed software. /// /// `libcaf` uses a thread pool to schedule actors by default. /// A scheduled actor should not call blocking functions. /// Individual actors can be spawned (created) with a special flag to run in /// an own thread if one needs to make use of blocking APIs. /// /// Writing applications in `libcaf` requires a minimum of gluecode and /// each context <i>is</i> an actor. Scoped actors allow actor interaction /// from the context of threads such as main. /// /// @section GettingStarted Getting Started /// /// To build `libcaf,` you need `GCC >= 4.8 or <tt>Clang >= 3.2</tt>, /// and `CMake`. /// /// The usual build steps on Linux and macOS are: /// ///- `./configure ///- `make ///- `make install (as root, optionally) /// /// Please run the unit tests as well to verify that `libcaf` /// works properly. /// ///- `make test /// /// Please submit a bug report that includes (a) your compiler version, /// (b) your OS, and (c) the output of the unit tests if an error occurs: /// https://github.com/actor-framework/actor-framework/issues /// /// Please read the <b>Manual</b> for an introduction to `libcaf`. /// It is available online on Read The Docs at /// https://actor-framework.readthedocs.io or as PDF at /// http://www.actor-framework.org/pdf/manual.pdf /// /// @section IntroHelloWorld Hello World Example /// /// @include hello_world.cpp /// /// @section IntroMoreExamples More Examples /// /// The {@link math_actor.cpp Math Actor Example} shows the usage /// of {@link receive_loop} and {@link caf::arg_match arg_match}. /// The {@link dining_philosophers.cpp Dining Philosophers Example} /// introduces event-based actors covers various features of CAF. /// /// @namespace caf /// Root namespace of libcaf. /// /// @namespace caf::mixin /// Contains mixin classes implementing several actor traits. /// /// @namespace caf::exit_reason /// Contains all predefined exit reasons. /// /// @namespace caf::policy /// Contains policies encapsulating characteristics or algorithms. /// /// @namespace caf::io /// Contains all IO-related classes and functions. /// /// @namespace caf::io::network /// Contains classes and functions used for network abstraction. /// /// @namespace caf::io::basp /// Contains all classes and functions for the Binary Actor Sytem Protocol. /// /// @defgroup MessageHandling Message Handling /// /// This is the beating heart of CAF, since actor programming is /// a message oriented programming paradigm. /// /// A message in CAF is a n-tuple of values (with size >= 1). /// You can use almost every type in a messages as long as it is announced, /// i.e., known by the type system of CAF. /// /// @defgroup BlockingAPI Blocking API /// /// Blocking functions to receive messages. /// /// The blocking API of CAF is intended to be used for migrating /// previously threaded applications. When writing new code, you should /// consider the nonblocking API based on `become` and `unbecome` first. /// /// @section Send Sending Messages /// /// The function `send` can be used to send a message to an actor. /// The first argument is the receiver of the message followed by any number /// of values: /// /// ~~ /// // spawn some actors /// actor_system_config cfg; /// actor_system system{cfg}; /// auto a1 = system.spawn(...); /// auto a2 = system.spawn(...); /// auto a3 = system.spawn(...); /// /// // an actor executed in the current thread /// scoped_actor self{system}; /// /// // define an atom for message annotation /// using hello_atom = atom_constant<atom("hello")>; /// using compute_atom = atom_constant<atom("compute")>; /// using result_atom = atom_constant<atom("result")>; /// /// // send a message to a1 /// self->send(a1, hello_atom::value, "hello a1!"); /// /// // send a message to a1, a2, and a3 /// auto msg = make_message(compute_atom::value, 1, 2, 3); /// self->send(a1, msg); /// self->send(a2, msg); /// self->send(a3, msg); /// ~~ /// /// @section Receive Receive messages /// /// The function `receive` takes a `behavior` as argument. The behavior /// is a list of { callback } rules where the callback argument types /// define a pattern for matching messages. /// /// ~~ /// { /// [](hello_atom, const std::string& msg) { /// cout << "received hello message: " << msg << endl; /// }, /// [](compute_atom, int i0, int i1, int i2) { /// // send our result back to the sender of this messages /// return make_message(result_atom::value, i0 + i1 + i2); /// } /// } /// ~~ /// /// Blocking actors such as the scoped actor can call their receive member /// to handle incoming messages. /// /// ~~ /// self->receive( /// [](result_atom, int i) { /// cout << "result is: " << i << endl; /// } /// ); /// ~~ /// /// Please read the manual for further details about pattern matching. /// /// @section Atoms Atoms /// /// Atoms are a nice way to add semantic informations to a message. /// Assuming an actor wants to provide a "math sevice" for integers. It /// could provide operations such as addition, subtraction, etc. /// This operations all have two operands. Thus, the actor does not know /// what operation the sender of a message wanted by receiving just two integers. /// /// Example actor: /// ~~ /// using plus_atom = atom_constant<atom("plus")>; /// using minus_atom = atom_constant<atom("minus")>; /// behavior math_actor() { /// return { /// [](plus_atom, int a, int b) { /// return make_message(atom("result"), a + b); /// }, /// [](minus_atom, int a, int b) { /// return make_message(atom("result"), a - b); /// } /// }; /// } /// ~~ /// /// @section ReceiveLoops Receive Loops /// /// The previous examples used `receive` to create a behavior on-the-fly. /// This is inefficient in a loop since the argument passed to receive /// is created in each iteration again. It's possible to store the behavior /// in a variable and pass that variable to receive. This fixes the issue /// of re-creation each iteration but rips apart definition and usage. /// /// There are three convenience functions implementing receive loops to /// declare behavior where it belongs without unnecessary /// copies: `receive_while,` `receive_for` and `do_receive`. /// /// `receive_while` creates a functor evaluating a lambda expression. /// The loop continues until the given lambda returns `false`. A simple example: /// /// ~~ /// size_t received = 0; /// receive_while([&] { return received < 10; }) ( /// [&](int) { /// ++received; /// } /// ); /// // ... /// ~~ /// /// `receive_for` is a simple ranged-based loop: /// /// ~~ /// std::vector<int> results; /// size_t i = 0; /// receive_for(i, 10) ( /// [&](int value) { /// results.push_back(value); /// } /// ); /// ~~ /// /// `do_receive` returns a functor providing the function `until` that /// takes a lambda expression. The loop continues until the given lambda /// returns true. Example: /// /// ~~ /// size_t received = 0; /// do_receive ( /// [&](int) { /// ++received; /// } /// ).until([&] { return received >= 10; }); /// // ... /// ~~ /// /// @section FutureSend Sending Delayed Messages /// /// The function `delayed_send` provides a simple way to delay a message. /// This is particularly useful for recurring events, e.g., periodical polling. /// Usage example: /// /// ~~ /// scoped_actor self{...}; /// /// self->delayed_send(self, std::chrono::seconds(1), poll_atom::value); /// bool running = true; /// self->receive_while([&](){ return running; }) ( /// // ... /// [&](poll_atom) { /// // ... poll something ... /// // and do it again after 1sec /// self->delayed_send(self, std::chrono::seconds(1), poll_atom::value); /// } /// ); /// ~~ /// /// See also the {@link dancing_kirby.cpp dancing kirby example}. /// /// @defgroup ImplicitConversion Implicit Type Conversions /// /// The message passing of `libcaf` prohibits pointers in messages because /// it enforces network transparent messaging. /// Unfortunately, string literals in `C++` have the type `const char*, /// resp. `const char[]. Since `libcaf` is a user-friendly library, /// it silently converts string literals and C-strings to `std::string` objects. /// It also converts unicode literals to the corresponding STL container. /// /// A few examples: /// ~~ /// // sends an std::string containing "hello actor!" to itself /// send(self, "hello actor!"); /// /// const char* cstring = "cstring"; /// // sends an std::string containing "cstring" to itself /// send(self, cstring); /// /// // sends an std::u16string containing the UTF16 string "hello unicode world!" /// send(self, u"hello unicode world!"); /// /// // x has the type caf::tuple<std::string, std::string> /// auto x = make_message("hello", "tuple"); /// ~~ /// /// @defgroup ActorCreation Creating Actors // examples /// A trivial example program. /// @example hello_world.cpp /// A simple example for a delayed_send based application. /// @example dancing_kirby.cpp /// An event-based "Dining Philosophers" implementation. /// @example dining_philosophers.cpp #endif // CAF_ALL_HPP
Update includes in all.hpp
Update includes in all.hpp
C++
bsd-3-clause
actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework
a0aedac69b3c8e2c3bb065b7cb0ed38d6b1f50f5
libcaf_net/src/host.cpp
libcaf_net/src/host.cpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/net/host.hpp" #include "caf/config.hpp" #include "caf/detail/net_syscall.hpp" #include "caf/detail/socket_sys_includes.hpp" #include "caf/error.hpp" #include "caf/net/socket.hpp" #include "caf/none.hpp" namespace caf::net { #ifdef CAF_WINDOWS error this_host::startup() { WSADATA WinsockData; CAF_NET_SYSCALL("WSAStartup", result, !=, 0, WSAStartup(MAKEWORD(2, 2), &WinsockData)); return none; } void this_host::cleanup() { WSACleanup(); } #else // CAF_WINDOWS error this_host::startup() { return none; } void this_host::cleanup() { // nop } #endif // CAF_WINDOWS } // namespace caf::net
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2019 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/net/host.hpp" #include "caf/config.hpp" #include "caf/detail/net_syscall.hpp" #include "caf/detail/socket_sys_includes.hpp" #include "caf/error.hpp" #include "caf/make_message.hpp" #include "caf/message.hpp" #include "caf/net/socket.hpp" #include "caf/none.hpp" namespace caf::net { #ifdef CAF_WINDOWS error this_host::startup() { WSADATA WinsockData; CAF_NET_SYSCALL("WSAStartup", result, !=, 0, WSAStartup(MAKEWORD(2, 2), &WinsockData)); return none; } void this_host::cleanup() { WSACleanup(); } #else // CAF_WINDOWS error this_host::startup() { return none; } void this_host::cleanup() { // nop } #endif // CAF_WINDOWS } // namespace caf::net
Fix build on Windows
Fix build on Windows
C++
bsd-3-clause
actor-framework/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework
495213e040b7b34254c57971f8833a0069084604
python/fixfmt/functions.cc
python/fixfmt/functions.cc
#include <cassert> #include <cmath> #include <string> #include "fixfmt/text.hh" #include "py.hh" using namespace py; using std::string; //------------------------------------------------------------------------------ // FIXME: Add docstrings. namespace { template<typename TYPE> ref<Object> analyze_float(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"buf", "max_precision", nullptr}; PyObject* array_obj; int max_precision; Arg::ParseTupleAndKeywords( args, kw_args, "Oi", arg_names, &array_obj, &max_precision); BufferRef buffer(array_obj, PyBUF_ND); if (buffer->ndim != 1) throw TypeError("not a one-dimensional array"); if (buffer->itemsize != sizeof(TYPE)) throw TypeError("wrong itemsize"); TYPE const* const array = (TYPE const* const) buffer->buf; size_t const length = buffer->shape[0]; bool has_nan = false; bool has_pos_inf = false; bool has_neg_inf = false; size_t num = 0; TYPE min = std::numeric_limits<TYPE>::max(); TYPE max = std::numeric_limits<TYPE>::min(); // Estimate precision truncating 'precision' digits to the right of the // decimal point, and comparing the result to 'tolerance'. // FIXME: Might not be correct for long double. int precision = 0; TYPE precision_scale = 1; TYPE tolerance = fixfmt::pow10(-max_precision) / 2; // Note: Weird. LLVM 6.1.0 on OSX vectorizes this loop only if the precision // logic is _present_, with the result that it runs _faster_ than without. for (size_t i = 0; i < length; ++i) { TYPE const val = array[i]; // Flag NaN. if (std::isnan(val)) { has_nan = true; continue; } // Flag positive and negative infinity. if (std::isinf(val)) { if (val > 0) has_pos_inf = true; else has_neg_inf = true; continue; } // Keep count of non-NaN/infinity values. ++num; // Compute min and max, excluding NaN and infinity. if (val < min) min = val; if (val > max) max = val; // Expand precision if necessary to accommodate additional fractional // digits, up to the maximum specified precision. while (precision < max_precision) { TYPE const scaled = std::abs(val) * precision_scale; TYPE const remainder = scaled - (long) (scaled + tolerance); if (remainder < tolerance) break; else { ++precision; precision_scale *= 10; tolerance *= 10; } } } // FIXME: Wrap this better. PyObject* result = PyTuple_New(7); PyTuple_SET_ITEM(result, 0, Bool::from(has_nan).release()); PyTuple_SET_ITEM(result, 1, Bool::from(has_pos_inf).release()); PyTuple_SET_ITEM(result, 2, Bool::from(has_neg_inf).release()); PyTuple_SET_ITEM(result, 3, Long::FromLong(num).release()); PyTuple_SET_ITEM(result, 4, Float::FromDouble(min).release()); PyTuple_SET_ITEM(result, 5, Float::FromDouble(max).release()); PyTuple_SET_ITEM(result, 6, Long::FromLong(precision).release()); return ref<Tuple>::take(result); } ref<Object> center(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", "length", "pad", "position", nullptr}; char const* str; int length; char const* pad = " "; float position = 0.5; Arg::ParseTupleAndKeywords( args, kw_args, "sI|sd", arg_names, &str, &length, &pad, &position); // FIXME: Validate args. if (strlen(pad) == 0) throw ValueError("empty pad"); if (position < 0 or position > 1) throw ValueError("position out of range"); return Unicode::from(fixfmt::center(string(str), length, pad, position)); } ref<Object> pad(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", "length", "pad", "left", nullptr}; char const* str; int length; char const* pad = " "; int left = false; Arg::ParseTupleAndKeywords( args, kw_args, "sI|sp", arg_names, &str, &length, &pad, &left); // FIXME: Validate args. if (strlen(pad) == 0) throw ValueError("empty pad"); return Unicode::from(fixfmt::pad(string(str), length, pad, (bool) left)); } ref<Object> elide(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", "length", "ellipsis", "position", nullptr}; char const* str; int length; char const* ellipsis = fixfmt::ELLIPSIS; float position = 1.0; Arg::ParseTupleAndKeywords( args, kw_args, "sI|sf", arg_names, &str, &length, &ellipsis, &position); string r = fixfmt::elide(string(str), length, string(ellipsis), position); return Unicode::from(r); } ref<Object> palide(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", "length", "ellipsis", "pad", "position", "left", nullptr }; char const* str; int length; char const* ellipsis = fixfmt::ELLIPSIS; char const* pad = " "; float position = 1.0; int left = false; Arg::ParseTupleAndKeywords( args, kw_args, "sI|ssfp", arg_names, &str, &length, &ellipsis, &pad, &position, &left); // FIXME: Validate args. if (strlen(pad) == 0) throw ValueError("empty pad"); string r = fixfmt::palide( string(str), length, string(ellipsis), pad, position, (bool) left); return Unicode::from(r); } ref<Object> string_length(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", nullptr }; char const* str; Arg::ParseTupleAndKeywords(args, kw_args, "s", arg_names, &str); return Long::FromLong(fixfmt::string_length(str)); } } // anonymous namespace //------------------------------------------------------------------------------ Methods<Module>& add_functions(Methods<Module>& methods) { methods .add<analyze_float<double>> ("analyze_double") .add<analyze_float<float>> ("analyze_float") .add<center> ("center") .add<elide> ("elide") .add<pad> ("pad") .add<palide> ("palide") .add<string_length> ("string_length") ; return methods; }
#include <cassert> #include <cmath> #include <limits> #include <string> #include "fixfmt/text.hh" #include "py.hh" using namespace py; using std::string; //------------------------------------------------------------------------------ // FIXME: Add docstrings. namespace { template<typename TYPE> ref<Object> analyze_float(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = {"buf", "max_precision", nullptr}; PyObject* array_obj; int max_precision; Arg::ParseTupleAndKeywords( args, kw_args, "Oi", arg_names, &array_obj, &max_precision); BufferRef buffer(array_obj, PyBUF_ND); if (buffer->ndim != 1) throw TypeError("not a one-dimensional array"); if (buffer->itemsize != sizeof(TYPE)) throw TypeError("wrong itemsize"); TYPE const* const array = (TYPE const* const) buffer->buf; size_t const length = buffer->shape[0]; bool has_nan = false; bool has_pos_inf = false; bool has_neg_inf = false; size_t num = 0; TYPE min = std::numeric_limits<TYPE>::max(); TYPE max = std::numeric_limits<TYPE>::min(); // Estimate precision truncating 'precision' digits to the right of the // decimal point, and comparing the result to 'tolerance'. // FIXME: Might not be correct for long double. int precision = 0; TYPE precision_scale = 1; TYPE tolerance = fixfmt::pow10(-max_precision) / 2; // Note: Weird. LLVM 6.1.0 on OSX vectorizes this loop only if the precision // logic is _present_, with the result that it runs _faster_ than without. for (size_t i = 0; i < length; ++i) { TYPE const val = array[i]; // Flag NaN. if (std::isnan(val)) { has_nan = true; continue; } // Flag positive and negative infinity. if (std::isinf(val)) { if (val > 0) has_pos_inf = true; else has_neg_inf = true; continue; } // Keep count of non-NaN/infinity values. ++num; // Compute min and max, excluding NaN and infinity. if (val < min) min = val; if (val > max) max = val; // Expand precision if necessary to accommodate additional fractional // digits, up to the maximum specified precision. while (precision < max_precision) { TYPE const scaled = std::abs(val) * precision_scale; TYPE const remainder = scaled - (long) (scaled + tolerance); if (remainder < tolerance) break; else { ++precision; precision_scale *= 10; tolerance *= 10; } } } // FIXME: Wrap this better. PyObject* result = PyTuple_New(7); PyTuple_SET_ITEM(result, 0, Bool::from(has_nan).release()); PyTuple_SET_ITEM(result, 1, Bool::from(has_pos_inf).release()); PyTuple_SET_ITEM(result, 2, Bool::from(has_neg_inf).release()); PyTuple_SET_ITEM(result, 3, Long::FromLong(num).release()); PyTuple_SET_ITEM(result, 4, Float::FromDouble(min).release()); PyTuple_SET_ITEM(result, 5, Float::FromDouble(max).release()); PyTuple_SET_ITEM(result, 6, Long::FromLong(precision).release()); return ref<Tuple>::take(result); } ref<Object> center(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", "length", "pad", "position", nullptr}; char const* str; int length; char const* pad = " "; float position = 0.5; Arg::ParseTupleAndKeywords( args, kw_args, "sI|sd", arg_names, &str, &length, &pad, &position); // FIXME: Validate args. if (strlen(pad) == 0) throw ValueError("empty pad"); if (position < 0 or position > 1) throw ValueError("position out of range"); return Unicode::from(fixfmt::center(string(str), length, pad, position)); } ref<Object> pad(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", "length", "pad", "left", nullptr}; char const* str; int length; char const* pad = " "; int left = false; Arg::ParseTupleAndKeywords( args, kw_args, "sI|sp", arg_names, &str, &length, &pad, &left); // FIXME: Validate args. if (strlen(pad) == 0) throw ValueError("empty pad"); return Unicode::from(fixfmt::pad(string(str), length, pad, (bool) left)); } ref<Object> elide(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", "length", "ellipsis", "position", nullptr}; char const* str; int length; char const* ellipsis = fixfmt::ELLIPSIS; float position = 1.0; Arg::ParseTupleAndKeywords( args, kw_args, "sI|sf", arg_names, &str, &length, &ellipsis, &position); string r = fixfmt::elide(string(str), length, string(ellipsis), position); return Unicode::from(r); } ref<Object> palide(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", "length", "ellipsis", "pad", "position", "left", nullptr }; char const* str; int length; char const* ellipsis = fixfmt::ELLIPSIS; char const* pad = " "; float position = 1.0; int left = false; Arg::ParseTupleAndKeywords( args, kw_args, "sI|ssfp", arg_names, &str, &length, &ellipsis, &pad, &position, &left); // FIXME: Validate args. if (strlen(pad) == 0) throw ValueError("empty pad"); string r = fixfmt::palide( string(str), length, string(ellipsis), pad, position, (bool) left); return Unicode::from(r); } ref<Object> string_length(Module* module, Tuple* args, Dict* kw_args) { static char const* arg_names[] = { "string", nullptr }; char const* str; Arg::ParseTupleAndKeywords(args, kw_args, "s", arg_names, &str); return Long::FromLong(fixfmt::string_length(str)); } } // anonymous namespace //------------------------------------------------------------------------------ Methods<Module>& add_functions(Methods<Module>& methods) { methods .add<analyze_float<double>> ("analyze_double") .add<analyze_float<float>> ("analyze_float") .add<center> ("center") .add<elide> ("elide") .add<pad> ("pad") .add<palide> ("palide") .add<string_length> ("string_length") ; return methods; }
Add missing include.
Add missing include.
C++
apache-2.0
alexhsamuel/fixfmt,alexhsamuel/fixfmt
343165b1dc9188b0d591682b2a1ad23651b96cab
src/types.cpp
src/types.cpp
#include <iostream> #include <algorithm> #include "types.h" namespace bpftrace { std::ostream &operator<<(std::ostream &os, Type type) { os << typestr(type); return os; } std::ostream &operator<<(std::ostream &os, const SizedType &type) { if (type.type == Type::cast) { os << type.cast_type; } else if (type.type == Type::ctx) { os << "(ctx) " << type.cast_type; } else if (type.type == Type::integer) { os << (type.is_signed ? "" : "unsigned ") << "int" << 8*type.size; } else if (type.type == Type::array) { os << (type.is_signed ? "" : "unsigned ") << "int" << 8 * type.pointee_size; os << "[" << type.size << "]"; } else if (type.type == Type::string) { os << type.type << "[" << type.size << "]"; } else { os << type.type; } if (type.is_pointer) os << "*"; return os; } bool SizedType::IsEqual(const SizedType &t) const { return type == t.type && size == t.size && is_signed == t.is_signed; } bool SizedType::operator!=(const SizedType &t) const { return !IsEqual(t); } bool SizedType::operator==(const SizedType &t) const { return IsEqual(t); } bool SizedType::IsArray() const { return type == Type::array || type == Type::string || type == Type::usym || type == Type::inet || ((type == Type::cast || type == Type::ctx) && !is_pointer); } bool SizedType::IsStack() const { return type == Type::ustack || type == Type::kstack; } std::string typestr(Type t) { switch (t) { // clang-format off case Type::none: return "none"; break; case Type::integer: return "integer"; break; case Type::hist: return "hist"; break; case Type::lhist: return "lhist"; break; case Type::count: return "count"; break; case Type::sum: return "sum"; break; case Type::min: return "min"; break; case Type::max: return "max"; break; case Type::avg: return "avg"; break; case Type::stats: return "stats"; break; case Type::kstack: return "kstack"; break; case Type::ustack: return "ustack"; break; case Type::string: return "string"; break; case Type::ksym: return "ksym"; break; case Type::usym: return "usym"; break; case Type::cast: return "cast"; break; case Type::join: return "join"; break; case Type::probe: return "probe"; break; case Type::username: return "username"; break; case Type::inet: return "inet"; break; case Type::stack_mode:return "stack mode";break; case Type::array: return "array"; break; case Type::ctx: return "ctx"; break; // clang-format on default: std::cerr << "call or probe type not found" << std::endl; abort(); } } ProbeType probetype(const std::string &probeName) { ProbeType retType = ProbeType::invalid; auto v = std::find_if(PROBE_LIST.begin(), PROBE_LIST.end(), [&probeName] (const ProbeItem& p) { return (p.name == probeName || p.abbr == probeName); }); if (v != PROBE_LIST.end()) retType = v->type; return retType; } std::string probetypeName(const std::string &probeName) { std::string res = probeName; auto v = std::find_if(PROBE_LIST.begin(), PROBE_LIST.end(), [&probeName] (const ProbeItem& p) { return (p.name == probeName || p.abbr == probeName); }); if (v != PROBE_LIST.end()) res = v->name; return res; } std::string probetypeName(ProbeType t) { switch (t) { case ProbeType::invalid: return "invalid"; break; case ProbeType::kprobe: return "kprobe"; break; case ProbeType::kretprobe: return "kretprobe"; break; case ProbeType::uprobe: return "uprobe"; break; case ProbeType::uretprobe: return "uretprobe"; break; case ProbeType::usdt: return "usdt"; break; case ProbeType::tracepoint: return "tracepoint"; break; case ProbeType::profile: return "profile"; break; case ProbeType::interval: return "interval"; break; case ProbeType::software: return "software"; break; case ProbeType::hardware: return "hardware"; break; default: std::cerr << "probe type not found" << std::endl; abort(); } } uint64_t asyncactionint(AsyncAction a) { return (uint64_t)a; } } // namespace bpftrace
#include <iostream> #include <algorithm> #include "types.h" namespace bpftrace { std::ostream &operator<<(std::ostream &os, Type type) { os << typestr(type); return os; } std::ostream &operator<<(std::ostream &os, const SizedType &type) { if (type.type == Type::cast) { os << type.cast_type; } else if (type.type == Type::ctx) { os << "(ctx) " << type.cast_type; } else if (type.type == Type::integer) { os << (type.is_signed ? "" : "unsigned ") << "int" << 8*type.size; } else if (type.type == Type::array) { os << (type.is_signed ? "" : "unsigned ") << "int" << 8 * type.pointee_size; os << "[" << type.size << "]"; } else if (type.type == Type::string) { os << type.type << "[" << type.size << "]"; } else { os << type.type; } if (type.is_pointer) os << "*"; return os; } bool SizedType::IsEqual(const SizedType &t) const { return type == t.type && size == t.size && is_signed == t.is_signed; } bool SizedType::operator!=(const SizedType &t) const { return !IsEqual(t); } bool SizedType::operator==(const SizedType &t) const { return IsEqual(t); } bool SizedType::IsArray() const { return type == Type::array || type == Type::string || type == Type::usym || type == Type::inet || ((type == Type::cast || type == Type::ctx) && !is_pointer); } bool SizedType::IsStack() const { return type == Type::ustack || type == Type::kstack; } std::string typestr(Type t) { switch (t) { // clang-format off case Type::none: return "none"; break; case Type::integer: return "integer"; break; case Type::hist: return "hist"; break; case Type::lhist: return "lhist"; break; case Type::count: return "count"; break; case Type::sum: return "sum"; break; case Type::min: return "min"; break; case Type::max: return "max"; break; case Type::avg: return "avg"; break; case Type::stats: return "stats"; break; case Type::kstack: return "kstack"; break; case Type::ustack: return "ustack"; break; case Type::string: return "string"; break; case Type::ksym: return "ksym"; break; case Type::usym: return "usym"; break; case Type::cast: return "cast"; break; case Type::join: return "join"; break; case Type::probe: return "probe"; break; case Type::username: return "username"; break; case Type::inet: return "inet"; break; case Type::stack_mode:return "stack mode";break; case Type::array: return "array"; break; case Type::ctx: return "ctx"; break; // clang-format on default: std::cerr << "call or probe type not found" << std::endl; abort(); } } ProbeType probetype(const std::string &probeName) { ProbeType retType = ProbeType::invalid; auto v = std::find_if(PROBE_LIST.begin(), PROBE_LIST.end(), [&probeName] (const ProbeItem& p) { return (p.name == probeName || p.abbr == probeName); }); if (v != PROBE_LIST.end()) retType = v->type; return retType; } std::string probetypeName(const std::string &probeName) { std::string res = probeName; auto v = std::find_if(PROBE_LIST.begin(), PROBE_LIST.end(), [&probeName] (const ProbeItem& p) { return (p.name == probeName || p.abbr == probeName); }); if (v != PROBE_LIST.end()) res = v->name; return res; } std::string probetypeName(ProbeType t) { switch (t) { case ProbeType::invalid: return "invalid"; break; case ProbeType::kprobe: return "kprobe"; break; case ProbeType::kretprobe: return "kretprobe"; break; case ProbeType::uprobe: return "uprobe"; break; case ProbeType::uretprobe: return "uretprobe"; break; case ProbeType::usdt: return "usdt"; break; case ProbeType::tracepoint: return "tracepoint"; break; case ProbeType::profile: return "profile"; break; case ProbeType::interval: return "interval"; break; case ProbeType::software: return "software"; break; case ProbeType::hardware: return "hardware"; break; case ProbeType::watchpoint: return "watchpoint"; break; default: std::cerr << "probe type not found" << std::endl; abort(); } } uint64_t asyncactionint(AsyncAction a) { return (uint64_t)a; } } // namespace bpftrace
Add missing ProbeType::watchpoint to probetypeName function
Add missing ProbeType::watchpoint to probetypeName function I'll call it in next change and it would fail on watchpoint. Signed-off-by: Jiri Olsa <[email protected]>
C++
apache-2.0
iovisor/bpftrace,iovisor/bpftrace,iovisor/bpftrace,iovisor/bpftrace
ace2378e5eeb7af394a07f9bfca4acd14789d776
src/world.cpp
src/world.cpp
/****************************** ** Tsunagari Tile Engine ** ** world.cpp ** ** Copyright 2011 OmegaSDG ** ******************************/ #include <Gosu/Utility.hpp> #include <libxml/parser.h> #include <libxml/tree.h> #include "area.h" #include "entity.h" #include "log.h" #include "resourcer.h" #include "window.h" #include "world.h" static World* globalWorld = NULL; World* World::getWorld() { return globalWorld; } World::World(Resourcer* rc, GameWindow* wnd) : rc(rc), wnd(wnd), area(NULL), player(NULL) { globalWorld = this; } World::~World() { delete player; delete area; } bool World::init() { if (!processDescriptor()) // Try to load in descriptor. return false; // FIXME The player entity doesn't have a descriptor yet. player = new Entity(rc, NULL, "_NONE_", xml.playersprite); if (!player->init()) return false; wnd->setCaption(Gosu::widen(xml.name)); return loadArea(xml.entry.area, xml.entry.coords); } void World::buttonDown(const Gosu::Button btn) { area->buttonDown(btn); } void World::draw() { area->draw(); } bool World::needsRedraw() const { return area->needsRedraw(); } bool World::processDescriptor() { static const std::string descriptor = "world.conf"; xmlChar* str; XMLDocRef doc = rc->getXMLDoc(descriptor); if (!doc) return false; const xmlNode* root = xmlDocGetRootElement(doc.get()); if (!root) return false; xmlNode* node = root->xmlChildrenNode; // <world> node = node->xmlChildrenNode; // decend into children of <world> for (; node != NULL; node = node->next) { if (!xmlStrncmp(node->name, BAD_CAST("name"), 5)) { str = xmlNodeGetContent(node); xml.name = (char*)str; } if (!xmlStrncmp(node->name, BAD_CAST("author"), 7)) { str = xmlNodeGetContent(node); xml.author = (char*)str; } if (!xmlStrncmp(node->name, BAD_CAST("type"), 5)) { str = xmlGetProp(node, BAD_CAST("locality")); if (xmlStrncmp(str, BAD_CAST("local"), 6)) xml.locality = LOCAL; else if (xmlStrncmp(str, BAD_CAST("network"), 8)) xml.locality = NETWORK; else { Log::err(descriptor, "Invalid <type> value"); return false; } str = xmlGetProp(node, BAD_CAST("movement")); if (xmlStrncmp(str, BAD_CAST("turn"), 5)) xml.movement = TURN; else if (xmlStrncmp(str, BAD_CAST("tile"), 5)) xml.movement = TILE; else if (xmlStrncmp(str, BAD_CAST("notile"), 7)) xml.movement = NOTILE; else { xmlFreeDoc(doc); Log::err(descriptor, "Invalid <locality> value"); return false; } } if (!xmlStrncmp(node->name, BAD_CAST("player"), 7)) { str = xmlGetProp(node, BAD_CAST("sprite")); xml.playersprite = (char*)str; } if (!xmlStrncmp(node->name, BAD_CAST("entrypoint"), 11)) { str = xmlGetProp(node, BAD_CAST("area")); xml.entry.area = (char*)str; str = xmlGetProp(node, BAD_CAST("x")); xml.entry.coords.x = atol((char*)str); str = xmlGetProp(node, BAD_CAST("y")); xml.entry.coords.y = atol((char*)str); str = xmlGetProp(node, BAD_CAST("z")); xml.entry.coords.z = atol((char*)str); } if (!xmlStrncmp(node->name, BAD_CAST("eventscripts"), 13)) { node = node->xmlChildrenNode; // decend } if (!xmlStrncmp(node->name, BAD_CAST("script"), 7)) { str = xmlNodeGetContent(node); xml.scripts.push_back((char*)str); } } return true; } bool World::loadArea(const std::string& areaName, coord_t playerPos) { Area* newArea = new Area(rc, this, player, areaName); delete area; area = newArea; if (!area->init()) return false; player->setArea(area); player->setCoordsByTile(playerPos); return true; }
/****************************** ** Tsunagari Tile Engine ** ** world.cpp ** ** Copyright 2011 OmegaSDG ** ******************************/ #include <Gosu/Utility.hpp> #include <libxml/parser.h> #include <libxml/tree.h> #include "area.h" #include "entity.h" #include "log.h" #include "resourcer.h" #include "window.h" #include "world.h" static World* globalWorld = NULL; World* World::getWorld() { return globalWorld; } World::World(Resourcer* rc, GameWindow* wnd) : rc(rc), wnd(wnd), area(NULL), player(NULL) { globalWorld = this; } World::~World() { delete player; delete area; } bool World::init() { if (!processDescriptor()) // Try to load in descriptor. return false; // FIXME The player entity doesn't have a descriptor yet. player = new Entity(rc, NULL, "_NONE_", xml.playersprite); if (!player->init()) return false; wnd->setCaption(Gosu::widen(xml.name)); return loadArea(xml.entry.area, xml.entry.coords); } void World::buttonDown(const Gosu::Button btn) { area->buttonDown(btn); } void World::draw() { area->draw(); } bool World::needsRedraw() const { return area->needsRedraw(); } bool World::processDescriptor() { static const std::string descriptor = "world.conf"; xmlChar* str; XMLDocRef doc = rc->getXMLDoc(descriptor); if (!doc) return false; const xmlNode* root = xmlDocGetRootElement(doc.get()); if (!root) return false; xmlNode* node = root->xmlChildrenNode; // <world> node = node->xmlChildrenNode; // decend into children of <world> for (; node != NULL; node = node->next) { if (!xmlStrncmp(node->name, BAD_CAST("name"), 5)) { str = xmlNodeGetContent(node); xml.name = (char*)str; } if (!xmlStrncmp(node->name, BAD_CAST("author"), 7)) { str = xmlNodeGetContent(node); xml.author = (char*)str; } if (!xmlStrncmp(node->name, BAD_CAST("type"), 5)) { str = xmlGetProp(node, BAD_CAST("locality")); if (xmlStrncmp(str, BAD_CAST("local"), 6)) xml.locality = LOCAL; else if (xmlStrncmp(str, BAD_CAST("network"), 8)) xml.locality = NETWORK; else { Log::err(descriptor, "Invalid <type> value"); return false; } str = xmlGetProp(node, BAD_CAST("movement")); if (xmlStrncmp(str, BAD_CAST("turn"), 5)) xml.movement = TURN; else if (xmlStrncmp(str, BAD_CAST("tile"), 5)) xml.movement = TILE; else if (xmlStrncmp(str, BAD_CAST("notile"), 7)) xml.movement = NOTILE; else { Log::err(descriptor, "Invalid <locality> value"); return false; } } if (!xmlStrncmp(node->name, BAD_CAST("player"), 7)) { str = xmlGetProp(node, BAD_CAST("sprite")); xml.playersprite = (char*)str; } if (!xmlStrncmp(node->name, BAD_CAST("entrypoint"), 11)) { str = xmlGetProp(node, BAD_CAST("area")); xml.entry.area = (char*)str; str = xmlGetProp(node, BAD_CAST("x")); xml.entry.coords.x = atol((char*)str); str = xmlGetProp(node, BAD_CAST("y")); xml.entry.coords.y = atol((char*)str); str = xmlGetProp(node, BAD_CAST("z")); xml.entry.coords.z = atol((char*)str); } if (!xmlStrncmp(node->name, BAD_CAST("eventscripts"), 13)) { node = node->xmlChildrenNode; // decend } if (!xmlStrncmp(node->name, BAD_CAST("script"), 7)) { str = xmlNodeGetContent(node); xml.scripts.push_back((char*)str); } } return true; } bool World::loadArea(const std::string& areaName, coord_t playerPos) { Area* newArea = new Area(rc, this, player, areaName); delete area; area = newArea; if (!area->init()) return false; player->setArea(area); player->setCoordsByTile(playerPos); return true; }
remove free of shared_ptr
remove free of shared_ptr
C++
mit
pariahsoft/TsunagariC,pariahsoft/Tsunagari,pariahsoft/TsunagariC,pariahsoft/Tsunagari,pariahsoft/TsunagariC,pmer/TsunagariC,pmer/TsunagariC,pariahsoft/Tsunagari,pariahsoft/Tsunagari,pmer/TsunagariC
2a49d598998386086b0f542fae378fe91bd1904a
chrome/browser/ui/zoom/zoom_controller.cc
chrome/browser/ui/zoom/zoom_controller.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/zoom/zoom_controller.h" #include "chrome/browser/ui/sad_tab.h" #include "chrome/browser/ui/zoom/zoom_event_manager.h" #include "chrome/browser/ui/zoom/zoom_observer.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/page_type.h" #include "content/public/common/page_zoom.h" #include "extensions/common/extension.h" #include "grit/theme_resources.h" #include "net/base/net_util.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(ZoomController); ZoomController::ZoomController(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), can_show_bubble_(true), zoom_mode_(ZOOM_MODE_DEFAULT), zoom_level_(1.0), browser_context_(web_contents->GetBrowserContext()) { // TODO(wjmaclean) Make calls to HostZoomMap::GetDefaultForBrowserContext() // refer to the webcontents-specific HostZoomMap when that becomes available. content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetDefaultForBrowserContext(browser_context_); zoom_level_ = host_zoom_map->GetDefaultZoomLevel(); zoom_subscription_ = host_zoom_map->AddZoomLevelChangedCallback( base::Bind(&ZoomController::OnZoomLevelChanged, base::Unretained(this))); UpdateState(std::string()); } ZoomController::~ZoomController() {} bool ZoomController::IsAtDefaultZoom() const { return content::ZoomValuesEqual(GetZoomLevel(), GetDefaultZoomLevel()); } int ZoomController::GetResourceForZoomLevel() const { if (IsAtDefaultZoom()) return IDR_ZOOM_NORMAL; return GetZoomLevel() > GetDefaultZoomLevel() ? IDR_ZOOM_PLUS : IDR_ZOOM_MINUS; } void ZoomController::AddObserver(ZoomObserver* observer) { observers_.AddObserver(observer); } void ZoomController::RemoveObserver(ZoomObserver* observer) { observers_.RemoveObserver(observer); } double ZoomController::GetZoomLevel() const { return zoom_mode_ == ZOOM_MODE_MANUAL ? zoom_level_: content::HostZoomMap::GetZoomLevel(web_contents()); } int ZoomController::GetZoomPercent() const { double zoom_factor = content::ZoomLevelToZoomFactor(GetZoomLevel()); // Round double for return. return static_cast<int>(zoom_factor * 100 + 0.5); } bool ZoomController::SetZoomLevel(double zoom_level) { // An extension did not initiate this zoom change. return SetZoomLevelByExtension(zoom_level, NULL); } bool ZoomController::SetZoomLevelByExtension( double zoom_level, const scoped_refptr<const extensions::Extension>& extension) { bool is_normal_page = web_contents()->GetController().GetLastCommittedEntry()->GetPageType() == content::PAGE_TYPE_NORMAL; // Cannot zoom in disabled mode. Also, don't allow changing zoom level on // a crashed tab, an error page or an interstitial page. if (zoom_mode_ == ZOOM_MODE_DISABLED || !web_contents()->GetRenderViewHost()->IsRenderViewLive() || !is_normal_page) return false; // Store extension data so that |extension| can be attributed when the zoom // change completes. We expect that by the time this function returns that // any observers that require this information will have requested it. last_extension_ = extension; // Do not actually rescale the page in manual mode. if (zoom_mode_ == ZOOM_MODE_MANUAL) { double old_zoom_level = zoom_level_; zoom_level_ = zoom_level; // TODO(wjmaclean) Do we care about filling in host/scheme here? content::HostZoomMap::ZoomLevelChange change; change.mode = content::HostZoomMap::ZOOM_CHANGED_TEMPORARY_ZOOM; change.zoom_level = zoom_level; ZoomEventManager::GetForBrowserContext(browser_context_)-> OnZoomLevelChanged(change); ZoomChangedEventData zoom_change_data(web_contents(), old_zoom_level, zoom_level_, zoom_mode_, false /* can_show_bubble */); FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(zoom_change_data)); last_extension_ = NULL; return true; } content::HostZoomMap* zoom_map = content::HostZoomMap::GetDefaultForBrowserContext(browser_context_); DCHECK(zoom_map); DCHECK(!event_data_); event_data_.reset(new ZoomChangedEventData(web_contents(), GetZoomLevel(), zoom_level, zoom_mode_, false /* can_show_bubble */)); int render_process_id = web_contents()->GetRenderProcessHost()->GetID(); int render_view_id = web_contents()->GetRenderViewHost()->GetRoutingID(); if (zoom_mode_ == ZOOM_MODE_ISOLATED || zoom_map->UsesTemporaryZoomLevel(render_process_id, render_view_id)) { zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, zoom_level); } else { content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (!entry) { last_extension_ = NULL; return false; } std::string host = net::GetHostOrSpecFromURL(entry->GetURL()); zoom_map->SetZoomLevelForHost(host, zoom_level); } DCHECK(!event_data_); last_extension_ = NULL; return true; } void ZoomController::SetZoomMode(ZoomMode new_mode) { if (new_mode == zoom_mode_) return; content::HostZoomMap* zoom_map = content::HostZoomMap::GetDefaultForBrowserContext(browser_context_); DCHECK(zoom_map); int render_process_id = web_contents()->GetRenderProcessHost()->GetID(); int render_view_id = web_contents()->GetRenderViewHost()->GetRoutingID(); double original_zoom_level = GetZoomLevel(); DCHECK(!event_data_); event_data_.reset(new ZoomChangedEventData(web_contents(), original_zoom_level, original_zoom_level, new_mode, new_mode != ZOOM_MODE_DEFAULT)); switch (new_mode) { case ZOOM_MODE_DEFAULT: { content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (entry) { GURL url = entry->GetURL(); std::string host = net::GetHostOrSpecFromURL(url); if (zoom_map->HasZoomLevel(url.scheme(), host)) { // If there are other tabs with the same origin, then set this tab's // zoom level to match theirs. The temporary zoom level will be // cleared below, but this call will make sure this tab re-draws at // the correct zoom level. double origin_zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(), host); event_data_->new_zoom_level = origin_zoom_level; zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, origin_zoom_level); } else { // The host will need a level prior to removing the temporary level. // We don't want the zoom level to change just because we entered // default mode. zoom_map->SetZoomLevelForHost(host, original_zoom_level); } } // Remove per-tab zoom data for this tab. No event callback expected. zoom_map->ClearTemporaryZoomLevel(render_process_id, render_view_id); break; } case ZOOM_MODE_ISOLATED: { // Unless the zoom mode was |ZOOM_MODE_DISABLED| before this call, the // page needs an initial isolated zoom back to the same level it was at // in the other mode. if (zoom_mode_ != ZOOM_MODE_DISABLED) { zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, original_zoom_level); } else { // When we don't call any HostZoomMap set functions, we send the event // manually. FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(*event_data_)); event_data_.reset(); } break; } case ZOOM_MODE_MANUAL: { // Unless the zoom mode was |ZOOM_MODE_DISABLED| before this call, the // page needs to be resized to the default zoom. While in manual mode, // the zoom level is handled independently. if (zoom_mode_ != ZOOM_MODE_DISABLED) { zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, GetDefaultZoomLevel()); zoom_level_ = original_zoom_level; } else { // When we don't call any HostZoomMap set functions, we send the event // manually. FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(*event_data_)); event_data_.reset(); } break; } case ZOOM_MODE_DISABLED: { // The page needs to be zoomed back to default before disabling the zoom zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, GetDefaultZoomLevel()); break; } } // Any event data we've stored should have been consumed by this point. DCHECK(!event_data_); zoom_mode_ = new_mode; } void ZoomController::DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { // If the main frame's content has changed, the new page may have a different // zoom level from the old one. UpdateState(std::string()); } void ZoomController::WebContentsDestroyed() { // At this point we should no longer be sending any zoom events with this // WebContents. observers_.Clear(); } void ZoomController::OnZoomLevelChanged( const content::HostZoomMap::ZoomLevelChange& change) { UpdateState(change.host); } void ZoomController::UpdateState(const std::string& host) { // If |host| is empty, all observers should be updated. if (!host.empty()) { // Use the navigation entry's URL instead of the WebContents' so virtual // URLs work (e.g. chrome://settings). http://crbug.com/153950 content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (!entry || host != net::GetHostOrSpecFromURL(entry->GetURL())) { return; } } // The zoom bubble should not be shown for zoom changes where the host is // empty. bool can_show_bubble = can_show_bubble_ && !host.empty(); if (event_data_) { // For state changes initiated within the ZoomController, information about // the change should be sent. ZoomChangedEventData zoom_change_data = *event_data_; event_data_.reset(); zoom_change_data.can_show_bubble = can_show_bubble; FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(zoom_change_data)); } else { // TODO(wjmaclean) Should we consider having HostZoomMap send both old and // new zoom levels here? double zoom_level = GetZoomLevel(); ZoomChangedEventData zoom_change_data( web_contents(), zoom_level, zoom_level, zoom_mode_, can_show_bubble); FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(zoom_change_data)); } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/zoom/zoom_controller.h" #include "chrome/browser/ui/sad_tab.h" #include "chrome/browser/ui/zoom/zoom_event_manager.h" #include "chrome/browser/ui/zoom/zoom_observer.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/page_type.h" #include "content/public/common/page_zoom.h" #include "extensions/common/extension.h" #include "grit/theme_resources.h" #include "net/base/net_util.h" DEFINE_WEB_CONTENTS_USER_DATA_KEY(ZoomController); ZoomController::ZoomController(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), can_show_bubble_(true), zoom_mode_(ZOOM_MODE_DEFAULT), zoom_level_(1.0), browser_context_(web_contents->GetBrowserContext()) { // TODO(wjmaclean) Make calls to HostZoomMap::GetDefaultForBrowserContext() // refer to the webcontents-specific HostZoomMap when that becomes available. content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetDefaultForBrowserContext(browser_context_); zoom_level_ = host_zoom_map->GetDefaultZoomLevel(); zoom_subscription_ = host_zoom_map->AddZoomLevelChangedCallback( base::Bind(&ZoomController::OnZoomLevelChanged, base::Unretained(this))); UpdateState(std::string()); } ZoomController::~ZoomController() {} bool ZoomController::IsAtDefaultZoom() const { return content::ZoomValuesEqual(GetZoomLevel(), GetDefaultZoomLevel()); } int ZoomController::GetResourceForZoomLevel() const { if (IsAtDefaultZoom()) return IDR_ZOOM_NORMAL; return GetZoomLevel() > GetDefaultZoomLevel() ? IDR_ZOOM_PLUS : IDR_ZOOM_MINUS; } void ZoomController::AddObserver(ZoomObserver* observer) { observers_.AddObserver(observer); } void ZoomController::RemoveObserver(ZoomObserver* observer) { observers_.RemoveObserver(observer); } double ZoomController::GetZoomLevel() const { return zoom_mode_ == ZOOM_MODE_MANUAL ? zoom_level_: content::HostZoomMap::GetZoomLevel(web_contents()); } int ZoomController::GetZoomPercent() const { double zoom_factor = content::ZoomLevelToZoomFactor(GetZoomLevel()); // Round double for return. return static_cast<int>(zoom_factor * 100 + 0.5); } bool ZoomController::SetZoomLevel(double zoom_level) { // An extension did not initiate this zoom change. return SetZoomLevelByExtension(zoom_level, NULL); } bool ZoomController::SetZoomLevelByExtension( double zoom_level, const scoped_refptr<const extensions::Extension>& extension) { content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); bool is_normal_page = entry && entry->GetPageType() == content::PAGE_TYPE_NORMAL; // Cannot zoom in disabled mode. Also, don't allow changing zoom level on // a crashed tab, an error page or an interstitial page. if (zoom_mode_ == ZOOM_MODE_DISABLED || !web_contents()->GetRenderViewHost()->IsRenderViewLive() || !is_normal_page) return false; // Store extension data so that |extension| can be attributed when the zoom // change completes. We expect that by the time this function returns that // any observers that require this information will have requested it. last_extension_ = extension; // Do not actually rescale the page in manual mode. if (zoom_mode_ == ZOOM_MODE_MANUAL) { double old_zoom_level = zoom_level_; zoom_level_ = zoom_level; // TODO(wjmaclean) Do we care about filling in host/scheme here? content::HostZoomMap::ZoomLevelChange change; change.mode = content::HostZoomMap::ZOOM_CHANGED_TEMPORARY_ZOOM; change.zoom_level = zoom_level; ZoomEventManager::GetForBrowserContext(browser_context_)-> OnZoomLevelChanged(change); ZoomChangedEventData zoom_change_data(web_contents(), old_zoom_level, zoom_level_, zoom_mode_, false /* can_show_bubble */); FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(zoom_change_data)); last_extension_ = NULL; return true; } content::HostZoomMap* zoom_map = content::HostZoomMap::GetDefaultForBrowserContext(browser_context_); DCHECK(zoom_map); DCHECK(!event_data_); event_data_.reset(new ZoomChangedEventData(web_contents(), GetZoomLevel(), zoom_level, zoom_mode_, false /* can_show_bubble */)); int render_process_id = web_contents()->GetRenderProcessHost()->GetID(); int render_view_id = web_contents()->GetRenderViewHost()->GetRoutingID(); if (zoom_mode_ == ZOOM_MODE_ISOLATED || zoom_map->UsesTemporaryZoomLevel(render_process_id, render_view_id)) { zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, zoom_level); } else { if (!entry) { last_extension_ = NULL; return false; } std::string host = net::GetHostOrSpecFromURL(entry->GetURL()); zoom_map->SetZoomLevelForHost(host, zoom_level); } DCHECK(!event_data_); last_extension_ = NULL; return true; } void ZoomController::SetZoomMode(ZoomMode new_mode) { if (new_mode == zoom_mode_) return; content::HostZoomMap* zoom_map = content::HostZoomMap::GetDefaultForBrowserContext(browser_context_); DCHECK(zoom_map); int render_process_id = web_contents()->GetRenderProcessHost()->GetID(); int render_view_id = web_contents()->GetRenderViewHost()->GetRoutingID(); double original_zoom_level = GetZoomLevel(); DCHECK(!event_data_); event_data_.reset(new ZoomChangedEventData(web_contents(), original_zoom_level, original_zoom_level, new_mode, new_mode != ZOOM_MODE_DEFAULT)); switch (new_mode) { case ZOOM_MODE_DEFAULT: { content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (entry) { GURL url = entry->GetURL(); std::string host = net::GetHostOrSpecFromURL(url); if (zoom_map->HasZoomLevel(url.scheme(), host)) { // If there are other tabs with the same origin, then set this tab's // zoom level to match theirs. The temporary zoom level will be // cleared below, but this call will make sure this tab re-draws at // the correct zoom level. double origin_zoom_level = zoom_map->GetZoomLevelForHostAndScheme(url.scheme(), host); event_data_->new_zoom_level = origin_zoom_level; zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, origin_zoom_level); } else { // The host will need a level prior to removing the temporary level. // We don't want the zoom level to change just because we entered // default mode. zoom_map->SetZoomLevelForHost(host, original_zoom_level); } } // Remove per-tab zoom data for this tab. No event callback expected. zoom_map->ClearTemporaryZoomLevel(render_process_id, render_view_id); break; } case ZOOM_MODE_ISOLATED: { // Unless the zoom mode was |ZOOM_MODE_DISABLED| before this call, the // page needs an initial isolated zoom back to the same level it was at // in the other mode. if (zoom_mode_ != ZOOM_MODE_DISABLED) { zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, original_zoom_level); } else { // When we don't call any HostZoomMap set functions, we send the event // manually. FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(*event_data_)); event_data_.reset(); } break; } case ZOOM_MODE_MANUAL: { // Unless the zoom mode was |ZOOM_MODE_DISABLED| before this call, the // page needs to be resized to the default zoom. While in manual mode, // the zoom level is handled independently. if (zoom_mode_ != ZOOM_MODE_DISABLED) { zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, GetDefaultZoomLevel()); zoom_level_ = original_zoom_level; } else { // When we don't call any HostZoomMap set functions, we send the event // manually. FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(*event_data_)); event_data_.reset(); } break; } case ZOOM_MODE_DISABLED: { // The page needs to be zoomed back to default before disabling the zoom zoom_map->SetTemporaryZoomLevel( render_process_id, render_view_id, GetDefaultZoomLevel()); break; } } // Any event data we've stored should have been consumed by this point. DCHECK(!event_data_); zoom_mode_ = new_mode; } void ZoomController::DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { // If the main frame's content has changed, the new page may have a different // zoom level from the old one. UpdateState(std::string()); } void ZoomController::WebContentsDestroyed() { // At this point we should no longer be sending any zoom events with this // WebContents. observers_.Clear(); } void ZoomController::OnZoomLevelChanged( const content::HostZoomMap::ZoomLevelChange& change) { UpdateState(change.host); } void ZoomController::UpdateState(const std::string& host) { // If |host| is empty, all observers should be updated. if (!host.empty()) { // Use the navigation entry's URL instead of the WebContents' so virtual // URLs work (e.g. chrome://settings). http://crbug.com/153950 content::NavigationEntry* entry = web_contents()->GetController().GetLastCommittedEntry(); if (!entry || host != net::GetHostOrSpecFromURL(entry->GetURL())) { return; } } // The zoom bubble should not be shown for zoom changes where the host is // empty. bool can_show_bubble = can_show_bubble_ && !host.empty(); if (event_data_) { // For state changes initiated within the ZoomController, information about // the change should be sent. ZoomChangedEventData zoom_change_data = *event_data_; event_data_.reset(); zoom_change_data.can_show_bubble = can_show_bubble; FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(zoom_change_data)); } else { // TODO(wjmaclean) Should we consider having HostZoomMap send both old and // new zoom levels here? double zoom_level = GetZoomLevel(); ZoomChangedEventData zoom_change_data( web_contents(), zoom_level, zoom_level, zoom_mode_, can_show_bubble); FOR_EACH_OBSERVER( ZoomObserver, observers_, OnZoomChanged(zoom_change_data)); } }
Fix ZoomController crash on kiosk launching.
Fix ZoomController crash on kiosk launching. BUG=418214 Review URL: https://codereview.chromium.org/609983002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#297094}
C++
bsd-3-clause
Fireblend/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,dednal/chromium.src,dednal/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,jaruba/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,ltilve/chromium,jaruba/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,Jonekee/chromium.src,dushu1203/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,dednal/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,dushu1203/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src