text
stringlengths
54
60.6k
<commit_before>#include <iostream> using namespace std; #include "Vector_container.h" #include "List_container.h" #include "Child.h" void use(Container &c) { const int sz = c.size(); for (int i = 0; i != c.size(); ++i) cout << c[i] << endl; } void g() { Vector_container vc{ 1, 2, 3, 4, 5 }; use(vc); } void f(){ List_container l{ 1, 2, 3, 5, 8 }; use(l); } void readKey(){ int x; cin >> x; } typedef void(*Func)(void); Func getFuncAtPos(Base &b, int pos){ return (Func)*((int*)*(int*)(&b) + pos); } void virtualFuncCall(){ Child child; cout << "Instance Base Address:" << (&child) << endl; cout << "Virtual Functions Table Address:" << (int*)(&child) << endl; cout << "Virutal Functions Table's First Function Address:" << (int*)*(int*)(&child) << endl; Func pFunc = NULL; for (int i = 0; i < 3; ++i){ pFunc = getFuncAtPos(child, i); pFunc(); } Base *b = &child; b->w(); } int main() { virtualFuncCall(); readKey(); return 0; }<commit_msg>Mac OSX using long* to get vtbl.<commit_after>#include <iostream> using namespace std; #include "Vector_container.h" #include "List_container.h" #include "Child.h" void use(Container &c) { const int sz = c.size(); for (int i = 0; i != c.size(); ++i) cout << c[i] << endl; } void g() { Vector_container vc{ 1, 2, 3, 4, 5 }; use(vc); } void f(){ List_container l{ 1, 2, 3, 5, 8 }; use(l); } void readKey(){ int x; cin >> x; } typedef void(*Func)(void); Func getFuncAtPos(Base &b, int pos){ return (Func)*((long*)*(long*)(&b) + pos); } void virtualFuncCall(){ Child child; cout << "Instance Base Address:" << (&child) << endl; cout << "Virtual Functions Table Address:" << (long*)(&child) << endl; cout << "Virutal Functions Table's First Function Address:" << (long*)*(long*)(&child) << endl; Func pFunc = nullptr; for (int i = 0; i < 3; ++i){ pFunc = getFuncAtPos(child, i); pFunc(); } Base *b = &child; b->w(); } int main() { virtualFuncCall(); readKey(); return 0; }<|endoftext|>
<commit_before>b613b2f5-2e4f-11e5-8720-28cfe91dbc4b<commit_msg>b61b4bcf-2e4f-11e5-bd45-28cfe91dbc4b<commit_after>b61b4bcf-2e4f-11e5-bd45-28cfe91dbc4b<|endoftext|>
<commit_before>814299b5-2e4f-11e5-ba0b-28cfe91dbc4b<commit_msg>814a79e3-2e4f-11e5-9749-28cfe91dbc4b<commit_after>814a79e3-2e4f-11e5-9749-28cfe91dbc4b<|endoftext|>
<commit_before>8b33255e-2d14-11e5-af21-0401358ea401<commit_msg>8b33255f-2d14-11e5-af21-0401358ea401<commit_after>8b33255f-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>557a7f57-2e4f-11e5-b8d3-28cfe91dbc4b<commit_msg>55812702-2e4f-11e5-81a7-28cfe91dbc4b<commit_after>55812702-2e4f-11e5-81a7-28cfe91dbc4b<|endoftext|>
<commit_before>e567558a-327f-11e5-8dbd-9cf387a8033e<commit_msg>e56d5a97-327f-11e5-9994-9cf387a8033e<commit_after>e56d5a97-327f-11e5-9994-9cf387a8033e<|endoftext|>
<commit_before>66c20994-2fa5-11e5-96d4-00012e3d3f12<commit_msg>66c42c74-2fa5-11e5-a8ee-00012e3d3f12<commit_after>66c42c74-2fa5-11e5-a8ee-00012e3d3f12<|endoftext|>
<commit_before>24ede9c2-ad5d-11e7-bafe-ac87a332f658<commit_msg>update testing<commit_after>256300a6-ad5d-11e7-ba78-ac87a332f658<|endoftext|>
<commit_before>5f89492b-2d16-11e5-af21-0401358ea401<commit_msg>5f89492c-2d16-11e5-af21-0401358ea401<commit_after>5f89492c-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>d8a6937a-2e4e-11e5-85ee-28cfe91dbc4b<commit_msg>d8af4b80-2e4e-11e5-9242-28cfe91dbc4b<commit_after>d8af4b80-2e4e-11e5-9242-28cfe91dbc4b<|endoftext|>
<commit_before>1f735540-2e4f-11e5-a656-28cfe91dbc4b<commit_msg>1f7cc3a8-2e4f-11e5-90e4-28cfe91dbc4b<commit_after>1f7cc3a8-2e4f-11e5-90e4-28cfe91dbc4b<|endoftext|>
<commit_before>// Convert a .bmp file (from a high-compression jpg, as from a very cheap camera) // into another .bmp file with greatly attenuated 8x8-pixel-block jpg artifacts. extern "C" { #include "costella_unblock.h" } #include "EasyBMP.h" #include <png.h> #include <algorithm> #include <cstdlib> struct rgbpixel {unsigned char r,g,b; }; // Actually YCbCr, not YUV. // From www.equasys.de/colorconversion.html YCbCr - RGB. // (It might also work to use R,G,B directly, each pretending to be Y of YUV.) void YUVfromRGB(double& Y, double& U, double& V, const double R, const double G, const double B) { Y = 0.257 * R + 0.504 * G + 0.098 * B + 16; U = -0.148 * R - 0.291 * G + 0.439 * B + 128; V = 0.439 * R - 0.368 * G - 0.071 * B + 128; } void RGBfromYUV(double& R, double& G, double& B, double Y, double U, double V) { Y -= 16; U -= 128; V -= 128; R = 1.164 * Y + 1.596 * V; G = 1.164 * Y - 0.392 * U - 0.813 * V; B = 1.164 * Y + 2.017 * U; } std::string filenameExtension(const std::string& s) { const std::string::size_type i = s.find_last_of("."); if (i == std::string::npos) return ""; std::string ext(s.substr(i + 1)); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); return ext; } int main( int argc, char** argv) { if (argc != 3) { printf("usage: %s in.[bmp|png] out.[bmp|png]\n", argv[0]); return 1; } if (filenameExtension(argv[1]) != filenameExtension(argv[2])) printf("%s: warning: filenames %s and %s have different extensions.\n", argv[0], argv[1], argv[2]); const bool fPNG = filenameExtension(argv[1]) == "png"; int w, h; FILE *fp; struct rgbpixel **ppRowPNG = NULL; png_structp pPNG; png_infop pInfoPNG; BMP bmp; if (fPNG) { fp = fopen(argv[1], "rb"); pPNG = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); pInfoPNG = png_create_info_struct(pPNG); png_init_io(pPNG, fp); png_read_png(pPNG, pInfoPNG, PNG_TRANSFORM_STRIP_ALPHA|PNG_TRANSFORM_EXPAND|PNG_TRANSFORM_STRIP_16, NULL); ppRowPNG = (struct rgbpixel**)png_get_rows(pPNG, pInfoPNG); w = png_get_image_width(pPNG, pInfoPNG); h = png_get_image_height(pPNG, pInfoPNG); png_destroy_read_struct(&pPNG, NULL, NULL); fclose(fp); } else { bmp.ReadFromFile(argv[1]); w = bmp.TellWidth(); h = bmp.TellHeight(); } // Convert bmp.rgb_data or ppRowPNG to YUV color planes. const unsigned cb = w * h; unsigned char bufY[cb]; unsigned char bufU[cb]; unsigned char bufV[cb]; int y,x; int i=0; for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x,++i) { double R,G,B; if (fPNG) { const rgbpixel rgb = ppRowPNG[y][x]; R = rgb.r; G = rgb.g; B = rgb.b; } else { const RGBApixel* rgb = bmp(x,y); R = rgb->Red; G = rgb->Green; B = rgb->Blue; } double Y,U,V; YUVfromRGB(Y,U,V,R,G,B); #undef testing #ifdef testing double a,b,c; RGBfromYUV(a,b,c,Y,U,V); if (fabs(a-R) + fabs(b-G) + fabs(c-B) > 0.9 /* in the scale 0.0 to 255.0 */ ) printf("not inverses.\n"); // but that's two linear operators, before the necessary clamping. #endif // Clamp to 0..255. bufY[i] = COSTELLA_IMAGE_LIMIT_RANGE(Y); bufU[i] = COSTELLA_IMAGE_LIMIT_RANGE(U); bufV[i] = COSTELLA_IMAGE_LIMIT_RANGE(V); } } COSTELLA_IMAGE im; im.bAlpha = 0; im.bRgb = 0; im.udHeight = h; im.udWidth = w; // may fail if not a multiple of 16 im.sdRowStride = w; // maybe something about bufPitch, width bumped up to multiple of 16. im.sdAlphaRowStride = 0; #if 0 // Unblock only luma (bufY). im.bColor = im.bDownsampledChrominance = im.bNonreplicatedDownsampledChrominance = 0; im.ig = bufY /* COSTELLA_IMAGE_GRAY */; #else // Unblock luma, Cb, and Cr. im.bColor = im.bDownsampledChrominance = im.bNonreplicatedDownsampledChrominance = 1; im.ic.aubRY = bufY; im.ic.aubGCb = bufU; im.ic.aubBCr = bufV; #endif costella_unblock_initialize(stdout); const int fPhoto = 0; // API docs suggest 1, but that boosts ringing of high-contrast detail (timestamps, windows of buildings). // (Internal mucking about, in costella_unblock.c bConservativePhotographic tweaking udCumMeasuredConservative, // had either no effect or caused a segfault.) int ok = costella_unblock(&im, &im, fPhoto, 0, NULL, NULL, 0); if (!ok) printf("%s: problem during costella_unblock().\n", argv[0]); costella_unblock_finalize(stdout); // Convert bufY, bufU, bufV back into a bmp. // (Or, set im.bRgb=1 to avoid this conversion? That sets bOutYCbCr in CostellaUnblock(), // which causes calls to CostellaImageConvertRgbToYcbcr() and CostellaImageConvertYcbcrToRgb(). // Those call macros like COSTELLA_IMAGE_CONVERT_RGB_TO_YCBCR(), // which lookup tables like gasdCostellaImageConvertRCb[] for Red to Cb.) i=0; for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x,++i) { double R,G,B; RGBfromYUV(R,G,B, bufY[i], bufU[i], bufV[i]); if (fPNG) { ppRowPNG[y][x] = (rgbpixel){ COSTELLA_IMAGE_LIMIT_RANGE(R), COSTELLA_IMAGE_LIMIT_RANGE(G), COSTELLA_IMAGE_LIMIT_RANGE(B) }; } else { RGBApixel* rgb = bmp(x,y); rgb->Red = COSTELLA_IMAGE_LIMIT_RANGE(R); rgb->Green = COSTELLA_IMAGE_LIMIT_RANGE(G); rgb->Blue = COSTELLA_IMAGE_LIMIT_RANGE(B); } } } if (fPNG) { fp = fopen(argv[2], "wb"); pPNG = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_init_io(pPNG, fp); png_set_rows(pPNG, pInfoPNG, (png_bytepp)ppRowPNG); png_write_png(pPNG, pInfoPNG, PNG_TRANSFORM_IDENTITY, NULL); png_destroy_write_struct(&pPNG, &pInfoPNG); fclose(fp); } else { bmp.WriteToFile(argv[2]); } return 0; } <commit_msg>privately store PNG pixels so PNG saves without timestamp<commit_after>// Convert a .bmp file (from a high-compression jpg, as from a very cheap camera) // into another .bmp file with greatly attenuated 8x8-pixel-block jpg artifacts. extern "C" { #include "costella_unblock.h" } #include "EasyBMP.h" #include <png.h> #include <algorithm> #include <cstdlib> typedef unsigned char u8; // Actually YCbCr, not YUV. // From www.equasys.de/colorconversion.html YCbCr - RGB. void YUVfromRGB(u8& Y, u8& U, u8& V, const double R, const double G, const double B) { const double y = 0.257 * R + 0.504 * G + 0.098 * B + 16; const double u = -0.148 * R - 0.291 * G + 0.439 * B + 128; const double v = 0.439 * R - 0.368 * G - 0.071 * B + 128; // Clamp to [0, 255]. Y = COSTELLA_IMAGE_LIMIT_RANGE(y); U = COSTELLA_IMAGE_LIMIT_RANGE(u); V = COSTELLA_IMAGE_LIMIT_RANGE(v); } void RGBfromYUV(u8& R, u8& G, u8& B, double Y, double U, double V) { Y -= 16; U -= 128; V -= 128; const double r = 1.164 * Y + 1.596 * V; const double g = 1.164 * Y - 0.392 * U - 0.813 * V; const double b = 1.164 * Y + 2.017 * U; // Clamp to [0, 255]. R = COSTELLA_IMAGE_LIMIT_RANGE(r); G = COSTELLA_IMAGE_LIMIT_RANGE(g); B = COSTELLA_IMAGE_LIMIT_RANGE(b); } std::string filenameExtension(const std::string& s) { const auto i = s.find_last_of("."); if (i == std::string::npos) return ""; auto ext(s.substr(i + 1)); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); return ext; } int main(int argc, char** argv) { if (argc != 3) { printf("usage: %s in.[bmp|png] out.[bmp|png]\n", argv[0]); return 1; } if (filenameExtension(argv[1]) != filenameExtension(argv[2])) printf("%s: warning: filenames %s and %s have different extensions.\nFile %s will get the same format as %s.\n", argv[0], argv[1], argv[2], argv[2], argv[1]); const bool fBMP = filenameExtension(argv[1]) == "bmp"; FILE *fp; unsigned w, h; BMP bmp; png_bytep *pRows = NULL; if (fBMP) { bmp.ReadFromFile(argv[1]); w = bmp.TellWidth(); h = bmp.TellHeight(); } else { fp = fopen(argv[1], "rb"); auto pPNG = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); auto pInfoPNG = png_create_info_struct(pPNG); png_init_io(pPNG, fp); png_read_info(pPNG, pInfoPNG); if (png_get_color_type(pPNG, pInfoPNG) != PNG_COLOR_TYPE_RGB) { // Alpha, grayscale, and palette formats wouldn't have come from a JPG. printf("%s: png file %s isn't in RGB format.\n", argv[0], argv[1]); return 1; } // Transform 16 bit to 8 bit. if (png_get_bit_depth(pPNG, pInfoPNG) == 16) { png_set_strip_16(pPNG); png_read_update_info(pPNG, pInfoPNG); } w = png_get_image_width(pPNG, pInfoPNG); h = png_get_image_height(pPNG, pInfoPNG); pRows = new png_bytep[h]; const auto cb = png_get_rowbytes(pPNG, pInfoPNG); for (unsigned y = 0; y < h; ++y) pRows[y] = new png_byte[cb]; png_read_image(pPNG, pRows); fclose(fp); png_destroy_read_struct(&pPNG, &pInfoPNG, NULL); } // Convert bmp.rgb_data or pRows to YUV color planes. const auto cb = w * h; u8 bufY[cb]; u8 bufU[cb]; u8 bufV[cb]; unsigned y, x; auto i = 0; for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x,++i) { double R,G,B; if (fBMP) { const auto rgb = bmp(x,y); R = rgb->Red; G = rgb->Green; B = rgb->Blue; } else { const auto rgb = pRows[y] + 3*x; R = rgb[0]; G = rgb[1]; B = rgb[2]; } YUVfromRGB(bufY[i],bufU[i],bufV[i], R,G,B); } } COSTELLA_IMAGE im; im.bAlpha = 0; im.bRgb = 0; im.udHeight = h; im.udWidth = w; // may fail if not a multiple of 16 im.sdRowStride = w; // maybe something about bufPitch, width bumped up to multiple of 16. im.sdAlphaRowStride = 0; #if 0 // Unblock only luma (bufY). im.bColor = im.bDownsampledChrominance = im.bNonreplicatedDownsampledChrominance = 0; im.ig = bufY /* COSTELLA_IMAGE_GRAY */; #else // Unblock luma, Cb, and Cr. im.bColor = im.bDownsampledChrominance = im.bNonreplicatedDownsampledChrominance = 1; im.ic.aubRY = bufY; im.ic.aubGCb = bufU; im.ic.aubBCr = bufV; #endif costella_unblock_initialize(stdout); const auto fPhoto = 0; // API docs suggest 1, but that boosts ringing of high-contrast detail (timestamps, windows of buildings). // (Internal mucking about, in costella_unblock.c bConservativePhotographic tweaking udCumMeasuredConservative, // had either no effect or caused a segfault.) auto ok = costella_unblock(&im, &im, fPhoto, 0, NULL, NULL, 0); if (!ok) printf("%s: costella_unblock() failed.\n", argv[0]); costella_unblock_finalize(stdout); // Convert bufY, bufU, bufV back into a bmp. // (Or, set im.bRgb=1 to avoid this conversion? That sets bOutYCbCr in CostellaUnblock(), // which causes calls to CostellaImageConvertRgbToYcbcr() and CostellaImageConvertYcbcrToRgb(). // Those call macros like COSTELLA_IMAGE_CONVERT_RGB_TO_YCBCR(), // which lookup tables like gasdCostellaImageConvertRCb[] for Red to Cb.) i = 0; for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x,++i) { u8 R,G,B; RGBfromYUV(R,G,B, bufY[i],bufU[i],bufV[i]); if (fBMP) { auto rgb = bmp(x,y); rgb->Red = R; rgb->Green = G; rgb->Blue = B; } else { auto rgb = pRows[y] + 3*x; rgb[0] = R; rgb[1] = G; rgb[2] = B; } } } if (fBMP) { bmp.WriteToFile(argv[2]); } else { fp = fopen(argv[2], "wb"); auto pPNG = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); auto pInfoPNG = png_create_info_struct(pPNG); png_init_io(pPNG, fp); png_set_IHDR(pPNG, pInfoPNG, w, h, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); // Don't call png_set_tIME, so no tIME chunk is written, no %tEXtdate:create, %tEXtdate:modify, gAMA, cHRM, bKGD. // Then the output has no timestamp, so it can be diffed against a known-good test output. png_write_info(pPNG, pInfoPNG); png_write_image(pPNG, pRows); png_write_end(pPNG, NULL); fclose(fp); png_destroy_write_struct(&pPNG, &pInfoPNG); } return 0; } <|endoftext|>
<commit_before>b8b6ee8f-327f-11e5-bb16-9cf387a8033e<commit_msg>b8bd8aca-327f-11e5-847a-9cf387a8033e<commit_after>b8bd8aca-327f-11e5-847a-9cf387a8033e<|endoftext|>
<commit_before>#include "eval.hpp" #include <iostream> using klmr::lisp::value; using klmr::lisp::environment; auto read(std::string const& input) -> value { (void) input; using namespace klmr::lisp; return list{ symbol{"define"}, list{ symbol{"lambda"}, list{symbol{"n"}}, list{ symbol{"*"}, symbol{"n"}, symbol{"n"} } } }; // FIXME placeholder } auto get_global_environment() -> environment { using namespace klmr::lisp; auto env = environment{}; env.set(symbol{"lambda"}, macro{env, {"args", "expr"}, [] (environment& env) { auto&& fformals = as_list(env["formals"]); auto formals = std::vector<symbol>(length(fformals)); std::transform(begin(fformals), end(fformals), begin(formals), as_symbol); auto expr = env["expr"]; // FIXME Capture by value incurs expensive copy. Solved in C++14. return call{env, formals, [expr](environment& frame) { return eval(expr, frame); }}; }} ); env.set(symbol{"define"}, macro{env, {"name", "expr"}, [] (environment& env) { auto&& name = as_symbol(env["name"]); env.set(name, eval(env["expr"], env)); return nil; }} ); return env; } auto repl(std::string prompt) -> void { auto input = std::string{}; auto global_env = get_global_environment(); for (;;) { std::cout << prompt << std::flush; if (not getline(std::cin, input)) return; auto&& result = eval(read(input), global_env); std::cout << result << '\n'; } } auto main() -> int try { repl(">>> "); } catch (klmr::lisp::name_error const& msg) { std::cerr << msg.what() << '\n'; return 1; } <commit_msg>Fix mismatch between code and identifiers<commit_after>#include "eval.hpp" #include <iostream> using klmr::lisp::value; using klmr::lisp::environment; auto read(std::string const& input) -> value { (void) input; using namespace klmr::lisp; return list{ symbol{"define"}, symbol{"double"}, list{ symbol{"lambda"}, list{symbol{"n"}}, list{ symbol{"*"}, symbol{"n"}, symbol{"n"} } } }; // FIXME placeholder } auto get_global_environment() -> environment { using namespace klmr::lisp; auto env = environment{}; env.set(symbol{"lambda"}, macro{env, {"args", "expr"}, [] (environment& env) { auto&& args = as_list(env["args"]); auto formals = std::vector<symbol>(length(args)); std::transform(begin(args), end(args), begin(formals), as_symbol); auto expr = env["expr"]; // FIXME Capture by value incurs expensive copy. Solved in C++14. return call{env, formals, [expr](environment& frame) { return eval(expr, frame); }}; }} ); env.set(symbol{"define"}, macro{env, {"name", "expr"}, [] (environment& env) { auto&& name = as_symbol(env["name"]); env.set(name, eval(env["expr"], env)); return nil; }} ); return env; } auto repl(std::string prompt) -> void { auto input = std::string{}; auto global_env = get_global_environment(); for (;;) { std::cout << prompt << std::flush; if (not getline(std::cin, input)) return; auto&& result = eval(read(input), global_env); std::cout << result << '\n'; } } auto main() -> int try { repl(">>> "); } catch (klmr::lisp::name_error const& msg) { std::cerr << msg.what() << '\n'; return 1; } <|endoftext|>
<commit_before>5449bf50-5216-11e5-8124-6c40088e03e4<commit_msg>5453a2a2-5216-11e5-815e-6c40088e03e4<commit_after>5453a2a2-5216-11e5-815e-6c40088e03e4<|endoftext|>
<commit_before>d787f102-327f-11e5-9de8-9cf387a8033e<commit_msg>d78d9f75-327f-11e5-9a79-9cf387a8033e<commit_after>d78d9f75-327f-11e5-9a79-9cf387a8033e<|endoftext|>
<commit_before>cb66c47e-35ca-11e5-8e1a-6c40088e03e4<commit_msg>cb6d7f1a-35ca-11e5-a031-6c40088e03e4<commit_after>cb6d7f1a-35ca-11e5-a031-6c40088e03e4<|endoftext|>
<commit_before>c9fd7df5-327f-11e5-8e85-9cf387a8033e<commit_msg>ca05ab59-327f-11e5-bf5f-9cf387a8033e<commit_after>ca05ab59-327f-11e5-bf5f-9cf387a8033e<|endoftext|>
<commit_before>b49e317d-327f-11e5-b369-9cf387a8033e<commit_msg>b4a463a1-327f-11e5-8120-9cf387a8033e<commit_after>b4a463a1-327f-11e5-8120-9cf387a8033e<|endoftext|>
<commit_before>8d6dfcfe-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfcff-2d14-11e5-af21-0401358ea401<commit_after>8d6dfcff-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>b70dec42-327f-11e5-b8f2-9cf387a8033e<commit_msg>b714054f-327f-11e5-8e83-9cf387a8033e<commit_after>b714054f-327f-11e5-8e83-9cf387a8033e<|endoftext|>
<commit_before>f489c773-ad59-11e7-afac-ac87a332f658<commit_msg>Initial commit.2<commit_after>f4f1199c-ad59-11e7-9e4b-ac87a332f658<|endoftext|>
<commit_before>#include <SPI.h> #include <Ethernet.h> #include "sdcard.hpp" // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x44, 0x68 }; IPAddress ip(10, 0, 0, 24); // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); void setup() { Serial.begin(9600); sd::initialize(); Ethernet.begin(mac, ip); Serial.println("Beginning server..."); server.begin(); } #define HTTP_BUFFER_SIZE 255 /** * Read a line from the EthernetClient. */ String readHttpLine(EthernetClient & client) { char buffer[HTTP_BUFFER_SIZE + 1]; int index = 0; while (client.connected()) { if (client.available()) { int b = client.read(); if (b == -1) { // no data break; } char c = static_cast<char>(b); if (c == '\r') { // carriage-return client.read(); // line-feed break; } buffer[index] = c; ++index; if (index == HTTP_BUFFER_SIZE) { break; } } } buffer[index] = '\0'; return String(buffer); } enum HttpMethod { HTTP_UNKNOWN, HTTP_GET, HTTP_PUT, HTTP_POST, }; HttpMethod parseHttpMethod(const String & method_token) { if (method_token == "GET") return HTTP_GET; if (method_token == "PUT") return HTTP_PUT; if (method_token == "POST") return HTTP_POST; return HTTP_UNKNOWN; } void readHttpHeaders(EthernetClient & client, long & content_length, String & content_type) { while (true) { String header_line = readHttpLine(client); Serial.print("HEADER: "); Serial.println(header_line); if (header_line.startsWith("Content-Length:")) { content_length = header_line.substring(16).toInt(); Serial.print("Content length = "); Serial.println(content_length); } else if (header_line.startsWith("Content-Type:")) { content_type = header_line.substring(14); Serial.print("Content type = "); Serial.println(content_type); } if (header_line.length() == 0) { break; } } } int readMultipartFormDataHeaders(EthernetClient & client, String & boundary, String & disposition, String & content_type) { int header_length = 0; boundary = readHttpLine(client); header_length += boundary.length() + 2; Serial.print("BOUNDARY: "); Serial.println(boundary); while (true) { String header_line = readHttpLine(client); header_length += header_line.length() + 2; Serial.print("MULTIHEADER: "); Serial.println(header_line); if (header_line.startsWith("Content-Disposition:")) { disposition = header_line.substring(21); Serial.print("Disposition = "); Serial.println(disposition); } else if (header_line.startsWith("Content-Type:")) { content_type = header_line.substring(14); Serial.print("Content type = "); Serial.println(content_type); } if (header_line.length() == 0) { break; } } return header_length; } void skipHttpContent(EthernetClient& client, long content_length) { for (long i = 0; i < content_length; ++i) { int b = client.read(); if (b == -1) { break; } } } void readHttpContent(EthernetClient& client, long content_length, String& content) { for (long i = 0; i < content_length; ++i) { int b = client.read(); if (b == -1) { break; } char c = static_cast<char>(b); content += c; } Serial.print("CONTENT: "); Serial.println(content); } /** * Simple HTTP parser for GET and PUT requests. * * Args: * client: An EthernetClient * url: A String out parameter which will contain the URL * content_length: A int out parameter which will contain the content-length or -1 * * Returns: * GET or PUT */ HttpMethod readHttpRequest(EthernetClient & client, String & url, String & content_type, long& content_length) { String request = readHttpLine(client); int end_method = request.indexOf(' '); String method_token = request.substring(0, end_method); Serial.println(method_token); HttpMethod method = parseHttpMethod(method_token); int end_url = request.indexOf(' ', end_method + 1); url = request.substring(end_method + 1, end_url); Serial.println(url); content_length = -1; readHttpHeaders(client, content_length, content_type); // TODO: Add a check for the Host header - important for compliance with HTTP/1.1 //client.flush(); return method; } void httpBadRequest(EthernetClient& client, const String & content) { client.println("HTTP/1.1 400 Bad Request"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(content.length()); client.println(); client.print(content); } void httpMethodNotAllowed(EthernetClient& client, const String & content) { client.println("HTTP/1.1 405 Method Not Allowed"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(content.length()); client.println(); client.print(content); } void httpNotFound(EthernetClient& client, const String & content) { client.println("HTTP/1.1 404 Not Found"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(content.length()); client.println(); client.print(content); } void httpGone(EthernetClient& client) { client.println("HTTP/1.1 410 Gone"); client.print("Content-Length: 0"); client.println(); } void httpServiceUnavailable(EthernetClient& client, const String & content) { client.println("HTTP/1.1 503 Service Unavailable"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(content.length()); client.println(); client.print(content); } template <typename T> String makeString(T value) { return String(value); } #define DECIMAL_PLACES 2 template <> String makeString(float value) { char buffer[33]; char* s = dtostrf(value, DECIMAL_PLACES + 2, DECIMAL_PLACES, buffer); return String(s); } template <> String makeString(String value) { return value; } template <typename T> void httpOkScalar(EthernetClient& client, T scalar) { String response_content = makeString(scalar); client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(response_content.length()); client.println(); client.println(response_content); } void httpOk(EthernetClient& client, const String & content_type) { client.println("HTTP/1.1 200 OK"); client.print("Content-Type: "); client.println(content_type); client.println(); } void htmlHeader(EthernetClient& client, const String & title) { client.println("<!DOCTYPE html>"); client.println("<html lang=\"en\">"); client.println("<head>"); client.println("<meta charset=\"utf-8\">"); client.print("<title>"); client.print(title); client.println("</title>"); client.println("</head>"); } void handleUploadRequest(EthernetClient & client, long content_length) { skipHttpContent(client, content_length); httpOk(client, "text/html"); htmlHeader(client, "Upload - Mistral"); client.println("<body>"); client.println("<body>"); client.println("<form id=\"form1\" enctype=\"multipart/form-data\" method=\"post\" action=\"submit\">"); client.println("<label for=\"fileToUpload\">Select a File to Upload</label><br />"); client.println("<input type=\"file\" name=\"fileToUpload\" id=\"fileToUpload\" />"); client.println("<input type=\"submit\" />"); client.println("</form>"); client.println("</body>"); client.println("</html>"); } void handleFileUpload(EthernetClient & client, const String & content_type, long content_length) { //Serial.print("handleFileUpload(client, "); //Serial.print(content_type); //Serial.print(", "); //Serial.print(content_length); //Serial.println(")"); String boundary; String disposition; String part_content_type; int header_length = readMultipartFormDataHeaders(client, boundary, disposition, part_content_type); Serial.println(header_length); long expected_length = content_length - header_length - (boundary.length() + 4); Serial.print("expected length = "); Serial.println(expected_length); // TODO: Watchdog timer uint8_t buffer[HTTP_BUFFER_SIZE + 1]; long actual_length = 0; while (client.connected()) { Serial.println("Still connected"); while (int available = client.available()) { //Serial.print(length); //Serial.print(" - "); //Serial.println(available); int num_remaining = expected_length - actual_length; int num_to_read = min(min(available, HTTP_BUFFER_SIZE), num_remaining); int num_read = client.read(buffer, num_to_read); if (num_read < 0) { //Serial.println(num_read); break; } actual_length += num_read; buffer[num_read] = '\0'; Serial.print(reinterpret_cast<char*>(buffer)); Serial.print(actual_length); Serial.print(" : "); Serial.print(expected_length); if (actual_length >= expected_length) { goto stop; } } //Serial.print("length = "); //Serial.print(length); } stop: Serial.print("<<<"); String end_boundary = readHttpLine(client); Serial.println(boundary); Serial.println(end_boundary); if (end_boundary == boundary + "--") { Serial.println("Found boundary "); } else { Serial.println("Missing boundary"); } String message(actual_length); message += " bytes uploaded."; httpOkScalar(client, message); } void handleHomeRequest(EthernetClient & client, long content_length) { skipHttpContent(client, content_length); httpOk(client, "text/html"); htmlHeader(client, "Listing - Mistral"); client.println("<body>"); uint8_t flags = 0; dir_t p; sd::root().rewind(); while (sd::root().readDir(&p) > 0) { if (p.name[0] == DIR_NAME_FREE) break; if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue; if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue; for (uint8_t i = 0; i < 11; i++) { if (p.name[i] == ' ') continue; if (i == 8) { client.print('.'); } client.print(static_cast<char>(p.name[i])); } if (DIR_IS_SUBDIR(&p)) { client.print('/'); } // print modify date/time if requested if (flags & LS_DATE) { sd::root().printFatDate(p.lastWriteDate); client.print(' '); sd::root().printFatTime(p.lastWriteTime); } // print size if requested if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) { client.print(' '); client.print(p.fileSize); } client.println("<br>"); } client.println("</body>"); client.println("</html>"); } void handleRequest(EthernetClient & client, HttpMethod method, const String & url, const String & content_type, long content_length) { if (url == "/root") { handleHomeRequest(client, content_length); } else if (url == "/upload") { handleUploadRequest(client, content_length); } else if (url == "/submit") { handleFileUpload(client, content_type, content_length); } else if (url == "/favicon.ico") { httpGone(client); } else { httpNotFound(client, "No resource at this URL"); } } void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { String url; String content_type; long content_length; HttpMethod method = readHttpRequest(client, /*out*/ url, /*out*/ content_type, /*out*/ content_length); handleRequest(client, method, url, content_type, content_length); } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); } <commit_msg>Remove debugging statements. Improved return status<commit_after>#include <SPI.h> #include <Ethernet.h> #include "sdcard.hpp" // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x44, 0x68 }; IPAddress ip(10, 0, 0, 24); // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); void setup() { Serial.begin(9600); sd::initialize(); Ethernet.begin(mac, ip); Serial.println("Beginning server..."); server.begin(); } #define HTTP_BUFFER_SIZE 255 /** * Read a line from the EthernetClient. */ String readHttpLine(EthernetClient & client) { char buffer[HTTP_BUFFER_SIZE + 1]; int index = 0; while (client.connected()) { if (client.available()) { int b = client.read(); if (b == -1) { // no data break; } char c = static_cast<char>(b); if (c == '\r') { // carriage-return client.read(); // line-feed break; } buffer[index] = c; ++index; if (index == HTTP_BUFFER_SIZE) { break; } } } buffer[index] = '\0'; return String(buffer); } enum HttpMethod { HTTP_UNKNOWN, HTTP_GET, HTTP_PUT, HTTP_POST, }; HttpMethod parseHttpMethod(const String & method_token) { if (method_token == "GET") return HTTP_GET; if (method_token == "PUT") return HTTP_PUT; if (method_token == "POST") return HTTP_POST; return HTTP_UNKNOWN; } void readHttpHeaders(EthernetClient & client, long & content_length, String & content_type) { while (true) { String header_line = readHttpLine(client); Serial.print("HEADER: "); Serial.println(header_line); if (header_line.startsWith("Content-Length:")) { content_length = header_line.substring(16).toInt(); Serial.print("Content length = "); Serial.println(content_length); } else if (header_line.startsWith("Content-Type:")) { content_type = header_line.substring(14); Serial.print("Content type = "); Serial.println(content_type); } if (header_line.length() == 0) { break; } } } int readMultipartFormDataHeaders(EthernetClient & client, String & boundary, String & disposition, String & content_type) { int header_length = 0; boundary = readHttpLine(client); header_length += boundary.length() + 2; Serial.print("BOUNDARY: "); Serial.println(boundary); while (true) { String header_line = readHttpLine(client); header_length += header_line.length() + 2; Serial.print("MULTIHEADER: "); Serial.println(header_line); if (header_line.startsWith("Content-Disposition:")) { disposition = header_line.substring(21); Serial.print("Disposition = "); Serial.println(disposition); } else if (header_line.startsWith("Content-Type:")) { content_type = header_line.substring(14); Serial.print("Content type = "); Serial.println(content_type); } if (header_line.length() == 0) { break; } } return header_length; } void skipHttpContent(EthernetClient& client, long content_length) { for (long i = 0; i < content_length; ++i) { int b = client.read(); if (b == -1) { break; } } } void readHttpContent(EthernetClient& client, long content_length, String& content) { for (long i = 0; i < content_length; ++i) { int b = client.read(); if (b == -1) { break; } char c = static_cast<char>(b); content += c; } Serial.print("CONTENT: "); Serial.println(content); } /** * Simple HTTP parser for GET and PUT requests. * * Args: * client: An EthernetClient * url: A String out parameter which will contain the URL * content_length: A int out parameter which will contain the content-length or -1 * * Returns: * GET or PUT */ HttpMethod readHttpRequest(EthernetClient & client, String & url, String & content_type, long& content_length) { String request = readHttpLine(client); int end_method = request.indexOf(' '); String method_token = request.substring(0, end_method); Serial.println(method_token); HttpMethod method = parseHttpMethod(method_token); int end_url = request.indexOf(' ', end_method + 1); url = request.substring(end_method + 1, end_url); Serial.println(url); content_length = -1; readHttpHeaders(client, content_length, content_type); // TODO: Add a check for the Host header - important for compliance with HTTP/1.1 //client.flush(); return method; } void httpBadRequest(EthernetClient& client, const String & content) { client.println("HTTP/1.1 400 Bad Request"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(content.length()); client.println(); client.print(content); } void httpMethodNotAllowed(EthernetClient& client, const String & content) { client.println("HTTP/1.1 405 Method Not Allowed"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(content.length()); client.println(); client.print(content); } void httpNotFound(EthernetClient& client, const String & content) { client.println("HTTP/1.1 404 Not Found"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(content.length()); client.println(); client.print(content); } void httpGone(EthernetClient& client) { client.println("HTTP/1.1 410 Gone"); client.print("Content-Length: 0"); client.println(); } void httpServiceUnavailable(EthernetClient& client, const String & content) { client.println("HTTP/1.1 503 Service Unavailable"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(content.length()); client.println(); client.print(content); } template <typename T> String makeString(T value) { return String(value); } #define DECIMAL_PLACES 2 template <> String makeString(float value) { char buffer[33]; char* s = dtostrf(value, DECIMAL_PLACES + 2, DECIMAL_PLACES, buffer); return String(s); } template <> String makeString(String value) { return value; } template <typename T> void httpOkScalar(EthernetClient& client, T scalar) { String response_content = makeString(scalar); client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/plain"); client.print("Content-Length: "); client.println(response_content.length()); client.println(); client.println(response_content); } void httpOk(EthernetClient& client, const String & content_type) { client.println("HTTP/1.1 200 OK"); client.print("Content-Type: "); client.println(content_type); client.println(); } void htmlHeader(EthernetClient& client, const String & title) { client.println("<!DOCTYPE html>"); client.println("<html lang=\"en\">"); client.println("<head>"); client.println("<meta charset=\"utf-8\">"); client.print("<title>"); client.print(title); client.println("</title>"); client.println("</head>"); } void handleUploadRequest(EthernetClient & client, long content_length) { skipHttpContent(client, content_length); httpOk(client, "text/html"); htmlHeader(client, "Upload - Mistral"); client.println("<body>"); client.println("<body>"); client.println("<form id=\"form1\" enctype=\"multipart/form-data\" method=\"post\" action=\"submit\">"); client.println("<label for=\"fileToUpload\">Select a File to Upload</label><br />"); client.println("<input type=\"file\" name=\"fileToUpload\" id=\"fileToUpload\" />"); client.println("<input type=\"submit\" />"); client.println("</form>"); client.println("</body>"); client.println("</html>"); } void handleFileUpload(EthernetClient & client, const String & content_type, long content_length) { String boundary; String disposition; String part_content_type; int header_length = readMultipartFormDataHeaders(client, boundary, disposition, part_content_type); long expected_length = content_length - header_length - (boundary.length() + 4); // TODO: Watchdog timer uint8_t buffer[HTTP_BUFFER_SIZE + 1]; long actual_length = 0; while (client.connected()) { while (int available = client.available()) { int num_remaining = expected_length - actual_length; int num_to_read = min(min(available, HTTP_BUFFER_SIZE), num_remaining); int num_read = client.read(buffer, num_to_read); if (num_read < 0) { break; } actual_length += num_read; //buffer[num_read] = '\0'; //Serial.print(reinterpret_cast<char*>(buffer)); if (actual_length >= expected_length) { goto stop; } } } stop: String end_boundary = readHttpLine(client); if (end_boundary == boundary + "--") { Serial.println("Found boundary "); String message(actual_length); message += " bytes uploaded."; httpOkScalar(client, message); } else { Serial.println("Missing boundary"); httpBadRequest(client, "Missing boundary"); } } void handleHomeRequest(EthernetClient & client, long content_length) { skipHttpContent(client, content_length); httpOk(client, "text/html"); htmlHeader(client, "Listing - Mistral"); client.println("<body>"); uint8_t flags = 0; dir_t p; sd::root().rewind(); while (sd::root().readDir(&p) > 0) { if (p.name[0] == DIR_NAME_FREE) break; if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue; if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue; for (uint8_t i = 0; i < 11; i++) { if (p.name[i] == ' ') continue; if (i == 8) { client.print('.'); } client.print(static_cast<char>(p.name[i])); } if (DIR_IS_SUBDIR(&p)) { client.print('/'); } // print modify date/time if requested if (flags & LS_DATE) { sd::root().printFatDate(p.lastWriteDate); client.print(' '); sd::root().printFatTime(p.lastWriteTime); } // print size if requested if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) { client.print(' '); client.print(p.fileSize); } client.println("<br>"); } client.println("</body>"); client.println("</html>"); } void handleRequest(EthernetClient & client, HttpMethod method, const String & url, const String & content_type, long content_length) { if (url == "/root") { handleHomeRequest(client, content_length); } else if (url == "/upload") { handleUploadRequest(client, content_length); } else if (url == "/submit") { handleFileUpload(client, content_type, content_length); } else if (url == "/favicon.ico") { httpGone(client); } else { httpNotFound(client, "No resource at this URL"); } } void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { String url; String content_type; long content_length; HttpMethod method = readHttpRequest(client, /*out*/ url, /*out*/ content_type, /*out*/ content_length); handleRequest(client, method, url, content_type, content_length); } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); } <|endoftext|>
<commit_before>49744618-2e3a-11e5-b28a-c03896053bdd<commit_msg>4988e348-2e3a-11e5-9b97-c03896053bdd<commit_after>4988e348-2e3a-11e5-9b97-c03896053bdd<|endoftext|>
<commit_before>06869ab8-2e4f-11e5-a21a-28cfe91dbc4b<commit_msg>069b0c47-2e4f-11e5-9a18-28cfe91dbc4b<commit_after>069b0c47-2e4f-11e5-9a18-28cfe91dbc4b<|endoftext|>
<commit_before>6ee9f975-2e4f-11e5-a46e-28cfe91dbc4b<commit_msg>6ef2d821-2e4f-11e5-9aad-28cfe91dbc4b<commit_after>6ef2d821-2e4f-11e5-9aad-28cfe91dbc4b<|endoftext|>
<commit_before>4feb14a2-5216-11e5-b2e9-6c40088e03e4<commit_msg>4ff2e3be-5216-11e5-b936-6c40088e03e4<commit_after>4ff2e3be-5216-11e5-b936-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include "common.h" #include "time_utils.h" #include "cli_parser.h" #include "image_loader.h" #include "NeuralNetworkPixelClassifiers.h" #include "doublefann.h" #include <tulip/Graph.h> #include <tulip/TlpTools.h> #include <tulip/TulipPlugin.h> #include <boost/filesystem.hpp> #include <itkImageSeriesWriter.h> #include <itkNumericSeriesFileNames.h> #include <itkBinaryThresholdImageFilter.h> #include "LoggerPluginProgress.h" #include "log4cxx/logger.h" #include "log4cxx/consoleappender.h" #include "log4cxx/patternlayout.h" #include "log4cxx/basicconfigurator.h" #include "callgrind.h" using namespace tlp; using namespace std; int main(int argc, char **argv) { log4cxx::BasicConfigurator::configure( log4cxx::AppenderPtr(new log4cxx::ConsoleAppender( log4cxx::LayoutPtr(new log4cxx::PatternLayout("\%-5p - [%c] - \%m\%n")), log4cxx::ConsoleAppender::getSystemErr() ) ) ); log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main")); CliParser cli_parser; int parse_result = cli_parser.parse_argv(argc, argv); if(parse_result <= 0) { exit(parse_result); } boost::filesystem::path path_export_dir(cli_parser.get_export_dir()); if(boost::filesystem::exists(path_export_dir)) { if(boost::filesystem::is_directory(path_export_dir)) { if(!boost::filesystem::is_empty(path_export_dir)) { LOG4CXX_FATAL(logger, "Export directory " << path_export_dir << " exists but is not empty"); exit(-1); } } else { LOG4CXX_FATAL(logger, "Export directory " << path_export_dir << " already exists as a file"); exit(-1); } } else { if(!boost::filesystem::create_directories(path_export_dir)) { LOG4CXX_FATAL(logger, "Export directory " << path_export_dir << " cannot be created"); exit(-1); } } const unsigned int number_of_classes = cli_parser.get_class_images().size(); // Creation of the export folders for each class for(int i = 0; i < number_of_classes; ++i) { std::ostringstream export_dir; export_dir << cli_parser.get_export_dir() << "/" << std::setfill('0') << std::setw(6) << i; boost::filesystem::path path_class_export_dir(export_dir.str()); if(!boost::filesystem::create_directories(path_class_export_dir)) { LOG4CXX_FATAL(logger, "Output dir " << path_class_export_dir << " cannot be created"); exit(-1); } } timestamp_t last_timestamp = get_timestamp(); LOG4CXX_INFO(logger, "Loading features image"); typename itk::ImageFileReader< FeaturesImage >::Pointer featuresImageReader = itk::ImageFileReader< FeaturesImage >::New(); featuresImageReader->SetFileName(cli_parser.get_input_image()); try { featuresImageReader->Update(); } catch( itk::ExceptionObject &ex ) { LOG4CXX_FATAL(logger, "ITK is unable to load the image \"" << cli_parser.get_input_image() << "\" (" << ex.what() << ")"); exit(-1); } FeaturesImage::Pointer featuresImage = featuresImageReader->GetOutput(); LOG4CXX_INFO(logger, "Features image loaded in " << elapsed_time(last_timestamp, get_timestamp()) << "s"); NeuralNetworkPixelClassifiers pixelClassifiers; last_timestamp = get_timestamp(); LOG4CXX_INFO(logger, "Loading training classes"); try { pixelClassifiers.load_training_sets(cli_parser.get_class_images(), featuresImage); } catch (LearningClassException & ex) { LOG4CXX_FATAL(logger, "Unable to load the training classes: " << ex.what()); exit(-1); } LOG4CXX_INFO(logger, "Training classes loaded in " << elapsed_time(last_timestamp, get_timestamp()) << "s"); last_timestamp = get_timestamp(); LOG4CXX_INFO(logger, "Training neural networks"); std::vector< unsigned int > hidden_layers = cli_parser.get_ann_hidden_layers(); hidden_layers.insert(hidden_layers.begin(), featuresImage->GetNumberOfComponentsPerPixel()); // First layer: number of features hidden_layers.push_back(1); // Last layer: one output pixelClassifiers.create_and_train_neural_networks(hidden_layers, cli_parser.get_ann_learning_rate(), cli_parser.get_ann_max_epoch(), cli_parser.get_ann_mse_target()); LOG4CXX_INFO(logger, "Neural networks trained in " << elapsed_time(last_timestamp, get_timestamp()) << "s"); tlp::initTulipLib("/home/cyrille/Dev/Tulip/tulip-3.8-svn/debug/install/"); tlp::loadPlugins(0); last_timestamp = get_timestamp(); LOG4CXX_INFO(logger, "Generating graph structure"); tlp::DataSet data; data.set<int>("Width", featuresImage->GetLargestPossibleRegion().GetSize()[0]); data.set<int>("Height", featuresImage->GetLargestPossibleRegion().GetSize()[1]); data.set<int>("Depth", featuresImage->GetLargestPossibleRegion().GetSize()[2]); data.set<tlp::StringCollection>("Connectivity", tlp::StringCollection("4")); data.set<bool>("Positionning", true); data.set<double>("Spacing", 1.0); tlp::Graph *graph = tlp::importGraph("Grid 3D", data); tlp::BooleanProperty *everything = graph->getLocalProperty<tlp::BooleanProperty>("everything"); everything->setAllNodeValue(true); everything->setAllEdgeValue(true); tlp::BooleanProperty *roi = graph->getLocalProperty<tlp::BooleanProperty>("Roi"); roi->setAllNodeValue(true); tlp::DoubleProperty *weight = graph->getLocalProperty<tlp::DoubleProperty>("Weight"); weight->setAllEdgeValue(1); tlp::BooleanProperty *seed = graph->getLocalProperty<tlp::BooleanProperty>("Seed"); seed->setAllNodeValue(false); { tlp::Iterator<tlp::node> *itNodes = graph->getNodes(); tlp::node u; tlp::DoubleVectorProperty *features_property = graph->getLocalProperty<tlp::DoubleVectorProperty>("features"); const FeaturesImage::PixelType::ValueType *features_tmp; std::vector<double> features(featuresImage->GetNumberOfComponentsPerPixel()); while(itNodes->hasNext()) { u = itNodes->next(); FeaturesImage::PixelType texture = featuresImage->GetPixel(featuresImage->ComputeIndex(u.id)); features_tmp = texture.GetDataPointer(); features.assign(features_tmp, features_tmp + featuresImage->GetNumberOfComponentsPerPixel()); features_property->setNodeValue(u, features); } delete itNodes; } LOG4CXX_INFO(logger, "Graph structure generated in " << elapsed_time(last_timestamp, get_timestamp()) << "s"); LOG4CXX_INFO(logger, "Classifying pixels with neural networks"); std::vector< tlp::DoubleProperty* > regularized_segmentations(number_of_classes); for(unsigned int i = 0; i < number_of_classes; ++i) { std::ostringstream graph_name; graph_name << std::setfill('0') << std::setw(6) << i; tlp::Graph* subgraph = graph->addSubGraph(everything, 0, graph_name.str()); boost::shared_ptr< typename NeuralNetworkPixelClassifiers::NeuralNetwork > net = pixelClassifiers.get_neural_network(i); tlp::Iterator<tlp::node> *itNodes = subgraph->getNodes(); tlp::node u; tlp::DoubleVectorProperty *f0 = subgraph->getLocalProperty<tlp::DoubleVectorProperty>("f0"); tlp::DoubleVectorProperty *features_property = subgraph->getProperty<tlp::DoubleVectorProperty>("features"); std::vector<double> features(1); while(itNodes->hasNext()) { u = itNodes->next(); double* result = fann_run( net.get(), const_cast<fann_type *>( &(features_property->getNodeValue(u)[0]) ) ); // Conversion from vector<double> to double* features[0] = result[0]; f0->setNodeValue(u, features); } delete itNodes; LOG4CXX_INFO(logger, "Data classification done for image #" << i); { std::ostringstream output_graph; output_graph << cli_parser.get_export_dir() << "/graph_" << std::setfill('0') << std::setw(6) << i << ".tlp"; tlp::saveGraph(subgraph, output_graph.str()); } LOG4CXX_INFO(logger, "Applying CV_Ta algorithm on image #" << i); std::ostringstream export_dir; export_dir << cli_parser.get_export_dir() << "/" << std::setfill('0') << std::setw(6) << i; DataSet data4; data4.set<PropertyInterface*>("Data", f0); data4.set<PropertyInterface*>("Mask", seed); data4.set<unsigned int>("Number of iterations", cli_parser.get_num_iter()); data4.set<double>("Lambda1", cli_parser.get_lambda1()); data4.set<double>("Lambda2", cli_parser.get_lambda2()); data4.set<unsigned int>("Export interval", cli_parser.get_export_interval()); data4.set<string>("dir::Export directory", export_dir.str()); data4.set<PropertyInterface*>("Weight", weight); data4.set<PropertyInterface*>("Roi", roi); LoggerPluginProgress pp("main.cv_ta"); string error4; if(!subgraph->applyAlgorithm("Cv_Ta", error4, &data4, &pp)) { LOG4CXX_FATAL(logger, "Unable to apply the Cv_Ta algorithm: " << error4); return -1; } regularized_segmentations[i] = subgraph->getLocalProperty< DoubleProperty >("fn"); LOG4CXX_INFO(logger, "Regularization done for image #" << i); } tlp::saveGraph(graph, cli_parser.get_export_dir() + "/" + "graph.tlp"); ImageType::Pointer classification_image = ImageType::New(); classification_image->SetRegions(featuresImage->GetLargestPossibleRegion()); classification_image->Allocate(); ImageType::IndexType index; int width, height, depth; unsigned int id; graph->getAttribute<int>("width", width); graph->getAttribute<int>("height", height); graph->getAttribute<int>("depth", depth); tlp::Iterator<tlp::node> *itNodes = graph->getNodes(); tlp::node u; std::vector< double > values(number_of_classes); std::vector< double >::iterator max_it; unsigned int max_pos; while(itNodes->hasNext()) { u = itNodes->next(); id = u.id; index[0] = id % width; id /= width; index[1] = id % height; id /= height; index[2] = id; for(unsigned int i = 0; i < number_of_classes; ++i) { values[i] = regularized_segmentations[i]->getNodeValue(u); } max_it = std::max_element(values.begin(), values.end()); if(*max_it < 0.9) max_pos = 0; else max_pos = std::distance(values.begin(), max_it) + 1; classification_image->SetPixel(index, max_pos); //copy( &values[0], &values[networks->size()], std::ostream_iterator< double >(std::cout, ", ")); //std::cout << std::endl; } delete itNodes; std::string final_export_dir = cli_parser.get_export_dir() + "/final_export"; if(!boost::filesystem::create_directories(boost::filesystem::path(final_export_dir))) { std::cerr << final_export_dir << " cannot be created" << std::endl; return -1; } { std::string final_class_export_dir = final_export_dir + "/classmap"; if(!boost::filesystem::create_directories(boost::filesystem::path(final_class_export_dir))) { std::cerr << final_class_export_dir << " cannot be created" << std::endl; return -1; } itk::NumericSeriesFileNames::Pointer outputNames = itk::NumericSeriesFileNames::New(); final_class_export_dir = final_class_export_dir + "/%06d.bmp"; outputNames->SetSeriesFormat(final_class_export_dir.c_str()); outputNames->SetStartIndex(0); outputNames->SetEndIndex(depth - 1); typedef itk::ImageSeriesWriter< ImageType, itk::Image< unsigned char, 2 > > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput(classification_image); writer->SetFileNames(outputNames->GetFileNames()); writer->Update(); } for(int i = 0; i <= number_of_classes; ++i) { std::ostringstream class_name; if(i > 0) { class_name << std::setfill('0') << std::setw(6) << i; } else { class_name << "rejected"; } std::string final_class_export_dir = final_export_dir + "/" + class_name.str(); if(!boost::filesystem::create_directories(boost::filesystem::path(final_class_export_dir))) { std::cerr << final_class_export_dir << " cannot be created" << std::endl; return -1; } itk::NumericSeriesFileNames::Pointer outputNames = itk::NumericSeriesFileNames::New(); final_class_export_dir = final_class_export_dir + "/%06d.bmp"; outputNames->SetSeriesFormat(final_class_export_dir.c_str()); outputNames->SetStartIndex(0); outputNames->SetEndIndex(depth - 1); typedef itk::BinaryThresholdImageFilter< ImageType, ImageType > Thresholder; Thresholder::Pointer thresholder = Thresholder::New(); thresholder->SetLowerThreshold(i); thresholder->SetUpperThreshold(i); thresholder->SetInput(classification_image); typedef itk::ImageSeriesWriter< ImageType, itk::Image< unsigned char, 2 > > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput(thresholder->GetOutput()); //writer->SetSeriesFormat(final_export_dir.c_str()); writer->SetFileNames(outputNames->GetFileNames()); writer->Update(); } delete graph; return 0; } <commit_msg>Now regularizes the output of the neural networks instead of a zero function.<commit_after>#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include "common.h" #include "time_utils.h" #include "cli_parser.h" #include "image_loader.h" #include "NeuralNetworkPixelClassifiers.h" #include "doublefann.h" #include <tulip/Graph.h> #include <tulip/TlpTools.h> #include <tulip/TulipPlugin.h> #include <boost/filesystem.hpp> #include <itkImageSeriesWriter.h> #include <itkNumericSeriesFileNames.h> #include <itkBinaryThresholdImageFilter.h> #include "LoggerPluginProgress.h" #include "log4cxx/logger.h" #include "log4cxx/consoleappender.h" #include "log4cxx/patternlayout.h" #include "log4cxx/basicconfigurator.h" #include "callgrind.h" using namespace tlp; using namespace std; int main(int argc, char **argv) { log4cxx::BasicConfigurator::configure( log4cxx::AppenderPtr(new log4cxx::ConsoleAppender( log4cxx::LayoutPtr(new log4cxx::PatternLayout("\%-5p - [%c] - \%m\%n")), log4cxx::ConsoleAppender::getSystemErr() ) ) ); log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main")); CliParser cli_parser; int parse_result = cli_parser.parse_argv(argc, argv); if(parse_result <= 0) { exit(parse_result); } boost::filesystem::path path_export_dir(cli_parser.get_export_dir()); if(boost::filesystem::exists(path_export_dir)) { if(boost::filesystem::is_directory(path_export_dir)) { if(!boost::filesystem::is_empty(path_export_dir)) { LOG4CXX_FATAL(logger, "Export directory " << path_export_dir << " exists but is not empty"); exit(-1); } } else { LOG4CXX_FATAL(logger, "Export directory " << path_export_dir << " already exists as a file"); exit(-1); } } else { if(!boost::filesystem::create_directories(path_export_dir)) { LOG4CXX_FATAL(logger, "Export directory " << path_export_dir << " cannot be created"); exit(-1); } } const unsigned int number_of_classes = cli_parser.get_class_images().size(); // Creation of the export folders for each class for(int i = 0; i < number_of_classes; ++i) { std::ostringstream export_dir; export_dir << cli_parser.get_export_dir() << "/" << std::setfill('0') << std::setw(6) << i; boost::filesystem::path path_class_export_dir(export_dir.str()); if(!boost::filesystem::create_directories(path_class_export_dir)) { LOG4CXX_FATAL(logger, "Output dir " << path_class_export_dir << " cannot be created"); exit(-1); } } timestamp_t last_timestamp = get_timestamp(); LOG4CXX_INFO(logger, "Loading features image"); typename itk::ImageFileReader< FeaturesImage >::Pointer featuresImageReader = itk::ImageFileReader< FeaturesImage >::New(); featuresImageReader->SetFileName(cli_parser.get_input_image()); try { featuresImageReader->Update(); } catch( itk::ExceptionObject &ex ) { LOG4CXX_FATAL(logger, "ITK is unable to load the image \"" << cli_parser.get_input_image() << "\" (" << ex.what() << ")"); exit(-1); } FeaturesImage::Pointer featuresImage = featuresImageReader->GetOutput(); LOG4CXX_INFO(logger, "Features image loaded in " << elapsed_time(last_timestamp, get_timestamp()) << "s"); NeuralNetworkPixelClassifiers pixelClassifiers; last_timestamp = get_timestamp(); LOG4CXX_INFO(logger, "Loading training classes"); try { pixelClassifiers.load_training_sets(cli_parser.get_class_images(), featuresImage); } catch (LearningClassException & ex) { LOG4CXX_FATAL(logger, "Unable to load the training classes: " << ex.what()); exit(-1); } LOG4CXX_INFO(logger, "Training classes loaded in " << elapsed_time(last_timestamp, get_timestamp()) << "s"); last_timestamp = get_timestamp(); LOG4CXX_INFO(logger, "Training neural networks"); std::vector< unsigned int > hidden_layers = cli_parser.get_ann_hidden_layers(); hidden_layers.insert(hidden_layers.begin(), featuresImage->GetNumberOfComponentsPerPixel()); // First layer: number of features hidden_layers.push_back(1); // Last layer: one output pixelClassifiers.create_and_train_neural_networks(hidden_layers, cli_parser.get_ann_learning_rate(), cli_parser.get_ann_max_epoch(), cli_parser.get_ann_mse_target()); LOG4CXX_INFO(logger, "Neural networks trained in " << elapsed_time(last_timestamp, get_timestamp()) << "s"); tlp::initTulipLib("/home/cyrille/Dev/Tulip/tulip-3.8-svn/release/install/"); tlp::loadPlugins(0); last_timestamp = get_timestamp(); LOG4CXX_INFO(logger, "Generating graph structure"); tlp::DataSet data; data.set<int>("Width", featuresImage->GetLargestPossibleRegion().GetSize()[0]); data.set<int>("Height", featuresImage->GetLargestPossibleRegion().GetSize()[1]); data.set<int>("Depth", featuresImage->GetLargestPossibleRegion().GetSize()[2]); data.set<tlp::StringCollection>("Connectivity", tlp::StringCollection("4")); data.set<bool>("Positionning", true); data.set<double>("Spacing", 1.0); tlp::Graph *graph = tlp::importGraph("Grid 3D", data); tlp::BooleanProperty *everything = graph->getLocalProperty<tlp::BooleanProperty>("everything"); everything->setAllNodeValue(true); everything->setAllEdgeValue(true); tlp::BooleanProperty *roi = graph->getLocalProperty<tlp::BooleanProperty>("Roi"); roi->setAllNodeValue(true); tlp::DoubleProperty *weight = graph->getLocalProperty<tlp::DoubleProperty>("Weight"); weight->setAllEdgeValue(1); tlp::DoubleVectorProperty *features_property = graph->getLocalProperty<tlp::DoubleVectorProperty>("features"); { tlp::Iterator<tlp::node> *itNodes = graph->getNodes(); tlp::node u; const FeaturesImage::PixelType::ValueType *features_tmp; std::vector<double> features(featuresImage->GetNumberOfComponentsPerPixel()); while(itNodes->hasNext()) { u = itNodes->next(); FeaturesImage::PixelType texture = featuresImage->GetPixel(featuresImage->ComputeIndex(u.id)); features_tmp = texture.GetDataPointer(); features.assign(features_tmp, features_tmp + featuresImage->GetNumberOfComponentsPerPixel()); features_property->setNodeValue(u, features); } delete itNodes; } LOG4CXX_INFO(logger, "Graph structure generated in " << elapsed_time(last_timestamp, get_timestamp()) << "s"); LOG4CXX_INFO(logger, "Classifying pixels with neural networks"); std::vector< tlp::DoubleProperty* > regularized_segmentations(number_of_classes); for(unsigned int i = 0; i < number_of_classes; ++i) { std::ostringstream graph_name; graph_name << std::setfill('0') << std::setw(6) << i; tlp::Graph* subgraph = graph->addSubGraph(everything, 0, graph_name.str()); boost::shared_ptr< typename NeuralNetworkPixelClassifiers::NeuralNetwork > net = pixelClassifiers.get_neural_network(i); tlp::BooleanProperty *seed = subgraph->getLocalProperty<tlp::BooleanProperty>("Seed"); tlp::Iterator<tlp::node> *itNodes = subgraph->getNodes(); tlp::node u; tlp::DoubleVectorProperty *f0 = subgraph->getLocalProperty<tlp::DoubleVectorProperty>("f0"); std::vector<double> features(1); while(itNodes->hasNext()) { u = itNodes->next(); //double* result = fann_run( net.get(), const_cast<fann_type *>( &(features_property->getNodeValue(u)[0]) ) ); // Conversion from vector<double> to double* double* result = fann_run( net.get(), const_cast<fann_type *>( features_property->getNodeValue(u).data() ) ); // Conversion from vector<double> to double* features[0] = result[0]; f0->setNodeValue(u, features); seed->setNodeValue(u, result[0] > 0.5); } delete itNodes; LOG4CXX_INFO(logger, "Data classification done for image #" << i); { std::ostringstream output_graph; output_graph << cli_parser.get_export_dir() << "/graph_" << std::setfill('0') << std::setw(6) << i << ".tlp"; tlp::saveGraph(subgraph, output_graph.str()); } LOG4CXX_INFO(logger, "Applying CV_Ta algorithm on image #" << i); std::ostringstream export_dir; export_dir << cli_parser.get_export_dir() << "/" << std::setfill('0') << std::setw(6) << i; DataSet data4; data4.set<PropertyInterface*>("Data", f0); data4.set<PropertyInterface*>("Mask", seed); data4.set<unsigned int>("Number of iterations", cli_parser.get_num_iter()); data4.set<double>("Lambda1", cli_parser.get_lambda1()); data4.set<double>("Lambda2", cli_parser.get_lambda2()); data4.set<unsigned int>("Export interval", cli_parser.get_export_interval()); data4.set<string>("dir::Export directory", export_dir.str()); data4.set<PropertyInterface*>("Weight", weight); data4.set<PropertyInterface*>("Roi", roi); LoggerPluginProgress pp("main.cv_ta"); string error4; if(!subgraph->applyAlgorithm("Cv_Ta", error4, &data4, &pp)) { LOG4CXX_FATAL(logger, "Unable to apply the Cv_Ta algorithm: " << error4); return -1; } subgraph->delLocalProperty("Seed"); regularized_segmentations[i] = subgraph->getLocalProperty< DoubleProperty >("fn"); LOG4CXX_INFO(logger, "Regularization done for image #" << i); } tlp::saveGraph(graph, cli_parser.get_export_dir() + "/" + "graph.tlp"); ImageType::Pointer classification_image = ImageType::New(); classification_image->SetRegions(featuresImage->GetLargestPossibleRegion()); classification_image->Allocate(); ImageType::IndexType index; int width, height, depth; unsigned int id; graph->getAttribute<int>("width", width); graph->getAttribute<int>("height", height); graph->getAttribute<int>("depth", depth); tlp::Iterator<tlp::node> *itNodes = graph->getNodes(); tlp::node u; std::vector< double > values(number_of_classes); std::vector< double >::iterator max_it; unsigned int max_pos; while(itNodes->hasNext()) { u = itNodes->next(); id = u.id; index[0] = id % width; id /= width; index[1] = id % height; id /= height; index[2] = id; for(unsigned int i = 0; i < number_of_classes; ++i) { values[i] = regularized_segmentations[i]->getNodeValue(u); } max_it = std::max_element(values.begin(), values.end()); if(*max_it < 0.9) max_pos = 0; else max_pos = std::distance(values.begin(), max_it) + 1; classification_image->SetPixel(index, max_pos); //copy( &values[0], &values[networks->size()], std::ostream_iterator< double >(std::cout, ", ")); //std::cout << std::endl; } delete itNodes; std::string final_export_dir = cli_parser.get_export_dir() + "/final_export"; if(!boost::filesystem::create_directories(boost::filesystem::path(final_export_dir))) { std::cerr << final_export_dir << " cannot be created" << std::endl; return -1; } { std::string final_class_export_dir = final_export_dir + "/classmap"; if(!boost::filesystem::create_directories(boost::filesystem::path(final_class_export_dir))) { std::cerr << final_class_export_dir << " cannot be created" << std::endl; return -1; } itk::NumericSeriesFileNames::Pointer outputNames = itk::NumericSeriesFileNames::New(); final_class_export_dir = final_class_export_dir + "/%06d.bmp"; outputNames->SetSeriesFormat(final_class_export_dir.c_str()); outputNames->SetStartIndex(0); outputNames->SetEndIndex(depth - 1); typedef itk::ImageSeriesWriter< ImageType, itk::Image< unsigned char, 2 > > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput(classification_image); writer->SetFileNames(outputNames->GetFileNames()); writer->Update(); } for(int i = 0; i <= number_of_classes; ++i) { std::ostringstream class_name; if(i > 0) { class_name << std::setfill('0') << std::setw(6) << i; } else { class_name << "rejected"; } std::string final_class_export_dir = final_export_dir + "/" + class_name.str(); if(!boost::filesystem::create_directories(boost::filesystem::path(final_class_export_dir))) { std::cerr << final_class_export_dir << " cannot be created" << std::endl; return -1; } itk::NumericSeriesFileNames::Pointer outputNames = itk::NumericSeriesFileNames::New(); final_class_export_dir = final_class_export_dir + "/%06d.bmp"; outputNames->SetSeriesFormat(final_class_export_dir.c_str()); outputNames->SetStartIndex(0); outputNames->SetEndIndex(depth - 1); typedef itk::BinaryThresholdImageFilter< ImageType, ImageType > Thresholder; Thresholder::Pointer thresholder = Thresholder::New(); thresholder->SetLowerThreshold(i); thresholder->SetUpperThreshold(i); thresholder->SetInput(classification_image); typedef itk::ImageSeriesWriter< ImageType, itk::Image< unsigned char, 2 > > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput(thresholder->GetOutput()); //writer->SetSeriesFormat(final_export_dir.c_str()); writer->SetFileNames(outputNames->GetFileNames()); writer->Update(); } delete graph; return 0; } <|endoftext|>
<commit_before>5c5e0335-2e4f-11e5-a7a5-28cfe91dbc4b<commit_msg>5c65549e-2e4f-11e5-944a-28cfe91dbc4b<commit_after>5c65549e-2e4f-11e5-944a-28cfe91dbc4b<|endoftext|>
<commit_before>f57b19fe-585a-11e5-9101-6c40088e03e4<commit_msg>f582eb7a-585a-11e5-9380-6c40088e03e4<commit_after>f582eb7a-585a-11e5-9380-6c40088e03e4<|endoftext|>
<commit_before>#include "Kernel.h" #include "parser/Driver.h" #include "Codegen.h" #include <vector> #include <string> #include <iostream> #include <readline/readline.h> #include <readline/history.h> #include <sstream> namespace snow { using namespace std; struct CmdOptions { string cmd; vector<string> filenames; bool interactive; }; void parse_args(int argc, const char** argv, CmdOptions& opts) { opts.cmd = argv[0]; opts.interactive = false; for (int i = 1; i < argc; ++i) { std::string current(argv[i]); if (current == "--interactive" || current == "-i") { opts.interactive = true; } else { opts.filenames.push_back(argv[i]); } // TODO: Real option parsing. } } void interactive_prompt(); int main(int argc, const char** argv) { Kernel::init(); Kernel::require("prelude.sn"); CmdOptions opts; parse_args(argc, argv, opts); for each (iter, opts.filenames) { Kernel::require(*iter); } if (opts.interactive) { interactive_prompt(); } else if (opts.filenames.size() == 0) { warn("no input files :)"); return -1; } return 0; } bool is_expr_unfinished(const std::string& str) { // return true if the number of starting and ending brackets is not equal // count quotation marks int dquot_count = 0; const char* c = str.c_str(); bool escaped = false; int curly_count = 0; int bracket_count = 0; int parens_count = 0; bool in_string = false; while (*c) { if (*c == '\"' && !escaped) { dquot_count++; } if (!escaped && *c == '\\') escaped = true; else escaped = false; in_string = dquot_count & 1; if (!in_string) { switch (*c) { case '{': curly_count++; break; case '}': curly_count--; break; case '[': bracket_count++; break; case ']': bracket_count--; break; case '(': parens_count++; break; case ')': parens_count--; break; } } ++c; } return in_string || curly_count || bracket_count || parens_count; } void interactive_prompt() { const char* global_prompt = "snow> "; const char* unfinished_prompt = "snow*> "; bool unfinished_expr = false; std::stringstream buffer; char* line; while ((line = readline(unfinished_expr ? unfinished_prompt : global_prompt)) != NULL) { if (*line) // strlen(line) != 0 add_history(line); buffer << line; free(line); unfinished_expr = is_expr_unfinished(buffer.str()); if (!unfinished_expr) { VALUE result = Kernel::eval_in_global_scope(buffer.str()); std::cout << "=> " << value_to_string(snow::call_method(result, "inspect", 0)) << std::endl; buffer.str(""); } } } } int main (int argc, const char** argv) { return snow::main(argc, argv); } <commit_msg>put readline in a namespace<commit_after>#include "Kernel.h" #include "parser/Driver.h" #include "Codegen.h" #include <vector> #include <string> #include <iostream> namespace readline { #include <readline/readline.h> #include <readline/history.h> } #include <sstream> namespace snow { using namespace std; struct CmdOptions { string cmd; vector<string> filenames; bool interactive; }; void parse_args(int argc, const char** argv, CmdOptions& opts) { opts.cmd = argv[0]; opts.interactive = false; for (int i = 1; i < argc; ++i) { std::string current(argv[i]); if (current == "--interactive" || current == "-i") { opts.interactive = true; } else { opts.filenames.push_back(argv[i]); } // TODO: Real option parsing. } } void interactive_prompt(); int main(int argc, const char** argv) { Kernel::init(); Kernel::require("prelude.sn"); CmdOptions opts; parse_args(argc, argv, opts); for each (iter, opts.filenames) { Kernel::require(*iter); } if (opts.interactive) { interactive_prompt(); } else if (opts.filenames.size() == 0) { warn("no input files :)"); return -1; } return 0; } bool is_expr_unfinished(const std::string& str) { // return true if the number of starting and ending brackets is not equal // count quotation marks int dquot_count = 0; const char* c = str.c_str(); bool escaped = false; int curly_count = 0; int bracket_count = 0; int parens_count = 0; bool in_string = false; while (*c) { if (*c == '\"' && !escaped) { dquot_count++; } if (!escaped && *c == '\\') escaped = true; else escaped = false; in_string = dquot_count & 1; if (!in_string) { switch (*c) { case '{': curly_count++; break; case '}': curly_count--; break; case '[': bracket_count++; break; case ']': bracket_count--; break; case '(': parens_count++; break; case ')': parens_count--; break; } } ++c; } return in_string || curly_count || bracket_count || parens_count; } void interactive_prompt() { const char* global_prompt = "snow> "; const char* unfinished_prompt = "snow*> "; bool unfinished_expr = false; std::stringstream buffer; char* line; while ((line = readline::readline(unfinished_expr ? unfinished_prompt : global_prompt)) != NULL) { if (*line) // strlen(line) != 0 readline::add_history(line); buffer << line; free(line); unfinished_expr = is_expr_unfinished(buffer.str()); if (!unfinished_expr) { VALUE result = Kernel::eval_in_global_scope(buffer.str()); std::cout << "=> " << value_to_string(snow::call_method(result, "inspect", 0)) << std::endl; buffer.str(""); } } } } int main (int argc, const char** argv) { return snow::main(argc, argv); } <|endoftext|>
<commit_before>20f61114-2e4f-11e5-91f2-28cfe91dbc4b<commit_msg>20fe1466-2e4f-11e5-91ef-28cfe91dbc4b<commit_after>20fe1466-2e4f-11e5-91ef-28cfe91dbc4b<|endoftext|>
<commit_before>bbf87fa6-ad5c-11e7-af30-ac87a332f658<commit_msg>almost working<commit_after>bc814733-ad5c-11e7-a980-ac87a332f658<|endoftext|>
<commit_before> #include <iostream> #include <Groundfloor/Atoms/Defines.h> #include <Groundfloor/Atoms/Initialize.h> #include "Command/CommandQueueDefault.h" #include "Communication/CommunicationJumpropes.h" #include "Communication/SensorDataTransmitter.h" #include <Jumpropes/Initialize.h> #include <Jumpropes/Functions.h> #include "System/Modules.h" #include <OpenALRF/World/Map.h> #include <OpenALRF/World/AStarMapNode.h> OpenALRF::degrees_t CurrentAngle = 0; void RebootSystem() { auto Queue = AudacityRover::Modules::Instance()->CommandQueue.get(); Queue->Add({ OpenALRF::modSystem, OpenALRF::actSystemReboot }); Queue->Process(); } int GetAngleBetweenMapSearchNodes(const OpenALRF::MapSearchNode *ANodeCurrent, const OpenALRF::MapSearchNode *ANodeNext) { int dx = ANodeNext->GetX() - ANodeCurrent->GetX(); int dy = ANodeNext->GetY() - ANodeCurrent->GetY(); if ((dy == 0) && (dx < 0)) { return 270; } else if ((dy == 0) && (dx > 0)) { return 90; } else if ((dy < 0) && (dx == 0)) { return 0; } else if ((dy > 0) && (dx == 0)) { return 180; } else if ((dy != 0) && (dx != 0)) { return static_cast<int>(atan(dy/dx)); } return -1; } double GetDistanceBetweenMapSearchNodes(const OpenALRF::MapSearchNode *ANodeCurrent, const OpenALRF::MapSearchNode *ANodeNext) { double dx = fabs(ANodeCurrent->GetX() - ANodeNext->GetX()); double dy = fabs(ANodeCurrent->GetY() - ANodeNext->GetY()); return sqrt(dx*dx + dy*dy); } OpenALRF::degrees_t MakeCommandsFromMapSearchDifference(const OpenALRF::MapSearchNode *ANodeCurrent, const OpenALRF::MapSearchNode *ANodeNext, const OpenALRF::degrees_t ACurrentAngle) { auto Queue = AudacityRover::Modules::Instance()->CommandQueue.get(); int16_t distance = static_cast<int16_t>(GetDistanceBetweenMapSearchNodes(ANodeCurrent, ANodeNext) * 60); int angle = GetAngleBetweenMapSearchNodes(ANodeCurrent, ANodeNext); OpenALRF::degrees_t NewAngle = ACurrentAngle; if (angle == -1) { // do nothing } else if (angle == 180) { // best to just go backwards instead of turning Queue->Add({ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotBackward, distance }); NewAngle = 0; } else if (angle == 0) { Queue->Add({ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotForward, distance }); NewAngle = 0; } else { NewAngle -= ACurrentAngle; if (NewAngle > 180) { Queue->Add({ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotLeft, static_cast<int16_t>(180 - NewAngle) }); } else if (NewAngle > 0) { Queue->Add({ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotRight, NewAngle }); } Queue->Add({ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotForward, distance }); } return NewAngle; } void findSolutionForMap(const std::string AInMapFile, const std::string AOutMapFile) { OpenALRF::Map20x20m map(AInMapFile); OpenALRF::SetCurrentSearchMap(&map); AStarSearch<OpenALRF::MapSearchNode> astarsearch; OpenALRF::MapSearchNode StartNode(10, 20); OpenALRF::MapSearchNode EndNode(10, 0); astarsearch.SetStartAndGoalStates(StartNode, EndNode); int SearchState; do { SearchState = astarsearch.SearchStep(); } while (SearchState == STLAStar::SEARCH_STATE_SEARCHING); if (SearchState == STLAStar::SEARCH_STATE_SUCCEEDED) { OpenALRF::MapSearchNode *node = astarsearch.GetSolutionStart(); OpenALRF::MapSearchNode *previousnode = node; int steps = 0; for (;; ) { node = astarsearch.GetSolutionNext(); if (!node) break; map.SetMapValue(node->GetX(), node->GetY(), OpenALRF::MapValuePath); CurrentAngle = MakeCommandsFromMapSearchDifference(previousnode, node, CurrentAngle); previousnode = node; steps++; }; map.SaveToFile(AOutMapFile); // Once you're done with the solution you can free the nodes up astarsearch.FreeSolutionNodes(); } else if (SearchState == STLAStar::SEARCH_STATE_FAILED) { cout << "Search terminated. Did not find goal state\n"; } astarsearch.EnsureMemoryFreed(); } int main() { std::cout << "Hello" << std::endl; bool MapDone = false; if (Groundfloor::initGroundfloor()) { std::cout << "World!" << std::endl; if (Jumpropes::initJumpropes()) { std::cout << "And Universe!" << std::endl; try { auto Modules = AudacityRover::Modules::Instance(); Modules->System->ChangeStatus(OpenALRF::statRunning); while (!Modules->System->ShouldQuit()) { Modules->Comm->Process(); Modules->CommandQueue->Process(); if (Modules->System->CurrentStatus() == OpenALRF::statRunning) { Modules->SensorSweep(); Modules->Cat->Process(); if (!MapDone) { //findSolutionForMap("maptest.txt", "mapout.txt"); MapDone = true; } } GFMillisleep(5000); } if (Modules->System->ShouldQuit()) { std::cout << "Someone made me Quit" << std::endl; } } catch (std::exception &e) { std::cout << "An exception was thrown: " << e.what() << std::endl; } std::cout << "Goodbye!" << std::endl; /* OpenALRF::Command Hello{ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotForward, 2, 0 }; Queue.Add(Hello); OpenALRF::Command World{ OpenALRF::modCamera, OpenALRF::actCameraCapture, 0, 0 }; Queue.Add(World); */ Jumpropes::finiJumpropes(); } Groundfloor::initGroundfloor(); } return 1; } <commit_msg>code moved to openalrf<commit_after> #include <iostream> #include <Groundfloor/Atoms/Defines.h> #include <Groundfloor/Atoms/Initialize.h> #include "Command/CommandQueueDefault.h" #include "Communication/CommunicationJumpropes.h" #include "Communication/SensorDataTransmitter.h" #include <Jumpropes/Initialize.h> #include <Jumpropes/Functions.h> #include "System/Modules.h" #include <OpenALRF/World/Map.h> #include <OpenALRF/World/AStarMapNode.h> OpenALRF::degrees_t CurrentAngle = 0; void RebootSystem() { auto Queue = AudacityRover::Modules::Instance()->CommandQueue.get(); Queue->Add({ OpenALRF::modSystem, OpenALRF::actSystemReboot }); Queue->Process(); } int main() { std::cout << "Hello" << std::endl; bool MapDone = false; if (Groundfloor::initGroundfloor()) { std::cout << "World!" << std::endl; if (Jumpropes::initJumpropes()) { std::cout << "And Universe!" << std::endl; try { auto Modules = AudacityRover::Modules::Instance(); Modules->System->ChangeStatus(OpenALRF::statRunning); while (!Modules->System->ShouldQuit()) { Modules->Comm->Process(); Modules->CommandQueue->Process(); if (Modules->System->CurrentStatus() == OpenALRF::statRunning) { Modules->SensorSweep(); Modules->Cat->Process(); if (!MapDone) { //findSolutionForMap("maptest.txt", "mapout.txt"); MapDone = true; } } GFMillisleep(5000); } if (Modules->System->ShouldQuit()) { std::cout << "Someone made me Quit" << std::endl; } } catch (std::exception &e) { std::cout << "An exception was thrown: " << e.what() << std::endl; } std::cout << "Goodbye!" << std::endl; /* OpenALRF::Command Hello{ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotForward, 2, 0 }; Queue.Add(Hello); OpenALRF::Command World{ OpenALRF::modCamera, OpenALRF::actCameraCapture, 0, 0 }; Queue.Add(World); */ Jumpropes::finiJumpropes(); } Groundfloor::initGroundfloor(); } return 1; } <|endoftext|>
<commit_before>4a7bc766-2e4f-11e5-b51c-28cfe91dbc4b<commit_msg>4a82b06e-2e4f-11e5-ba03-28cfe91dbc4b<commit_after>4a82b06e-2e4f-11e5-ba03-28cfe91dbc4b<|endoftext|>
<commit_before>#include <dxgi1_5.h> #include <d3d11.h> #include "glcorearb.h" #include "wglext.h" #include <cassert> #include <cstdio> #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "opengl32.lib") #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 void APIENTRY DebugCallbackGL(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { OutputDebugStringA("DebugCallbackGL: "); OutputDebugStringA(message); OutputDebugStringA("\n"); } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CLOSE: ExitProcess(0); } return DefWindowProc(hWnd, msg, wParam, lParam); } int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { bool ok; HRESULT hr; // Register window class WNDCLASSEX wc = {}; wc.cbSize = sizeof(wc); wc.style = CS_OWNDC; wc.lpfnWndProc = WndProc; wc.hInstance = GetModuleHandleW(NULL); wc.hCursor = LoadCursorW(NULL, IDC_ARROW); wc.lpszClassName = TEXT("WindowClass"); ok = RegisterClassExW(&wc) != NULL; assert(ok); // Determine size of window based on window style DWORD dwStyle = WS_OVERLAPPEDWINDOW; DWORD dwExStyle = 0; RECT wr = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT }; ok = AdjustWindowRectEx(&wr, dwStyle, FALSE, dwExStyle) != FALSE; assert(ok); TCHAR* title = TEXT("OpenGL on DXGI"); // Create window HWND hWnd = CreateWindowEx( dwExStyle, TEXT("WindowClass"), title, dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top, NULL, NULL, hInstance, NULL); assert(hWnd); // Unhide the window ShowWindow(hWnd, SW_SHOWDEFAULT); // Create window that will be used to create a GL context HWND gl_hWnd = CreateWindowEx(0, TEXT("WindowClass"), 0, 0, 0, 0, 0, 0, 0, 0, hInstance, 0); assert(gl_hWnd); HDC gl_hDC = GetDC(gl_hWnd); assert(gl_hDC); // set pixelformat for window that supports OpenGL PIXELFORMATDESCRIPTOR gl_pfd = {}; gl_pfd.nSize = sizeof(gl_pfd); gl_pfd.nVersion = 1; gl_pfd.dwFlags = PFD_SUPPORT_OPENGL; int chosenPixelFormat = ChoosePixelFormat(gl_hDC, &gl_pfd); ok = SetPixelFormat(gl_hDC, chosenPixelFormat, &gl_pfd) != FALSE; assert(ok); // Create dummy GL context that will be used to create the real context HGLRC dummy_hGLRC = wglCreateContext(gl_hDC); assert(dummy_hGLRC); // Use the dummy context to get function to create a better context ok = wglMakeCurrent(gl_hDC, dummy_hGLRC) != FALSE; assert(ok); PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); int contextFlagsGL = 0; #ifdef _DEBUG contextFlagsGL |= WGL_CONTEXT_DEBUG_BIT_ARB; #endif int contextAttribsGL[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, contextFlagsGL, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; HGLRC hGLRC = wglCreateContextAttribsARB(gl_hDC, NULL, contextAttribsGL); assert(hGLRC); // Switch to the new context and ditch the old one ok = wglMakeCurrent(gl_hDC, hGLRC) != FALSE; assert(ok); ok = wglDeleteContext(dummy_hGLRC) != FALSE; assert(ok); // Grab WGL functions PFNWGLDXOPENDEVICENVPROC wglDXOpenDeviceNV = (PFNWGLDXOPENDEVICENVPROC)wglGetProcAddress("wglDXOpenDeviceNV"); PFNWGLDXREGISTEROBJECTNVPROC wglDXRegisterObjectNV = (PFNWGLDXREGISTEROBJECTNVPROC)wglGetProcAddress("wglDXRegisterObjectNV"); PFNWGLDXUNREGISTEROBJECTNVPROC wglDXUnregisterObjectNV = (PFNWGLDXUNREGISTEROBJECTNVPROC)wglGetProcAddress("wglDXUnregisterObjectNV"); PFNWGLDXLOCKOBJECTSNVPROC wglDXLockObjectsNV = (PFNWGLDXLOCKOBJECTSNVPROC)wglGetProcAddress("wglDXLockObjectsNV"); PFNWGLDXUNLOCKOBJECTSNVPROC wglDXUnlockObjectsNV = (PFNWGLDXUNLOCKOBJECTSNVPROC)wglGetProcAddress("wglDXUnlockObjectsNV"); // Fall back to GetProcAddress to get GL 1 functions. wglGetProcAddress returns NULL on those. HMODULE hOpenGL32 = LoadLibrary(TEXT("OpenGL32.dll")); // Grab OpenGL functions PFNGLENABLEPROC glEnable = (PFNGLENABLEPROC)GetProcAddress(hOpenGL32, "glEnable"); PFNGLDISABLEPROC glDisable = (PFNGLDISABLEPROC)GetProcAddress(hOpenGL32, "glDisable"); PFNGLCLEARPROC glClear = (PFNGLCLEARPROC)GetProcAddress(hOpenGL32, "glClear"); PFNGLCLEARCOLORPROC glClearColor = (PFNGLCLEARCOLORPROC)GetProcAddress(hOpenGL32, "glClearColor"); PFNGLSCISSORPROC glScissor = (PFNGLSCISSORPROC)GetProcAddress(hOpenGL32, "glScissor"); PFNGLGENTEXTURESPROC glGenTextures = (PFNGLGENTEXTURESPROC)GetProcAddress(hOpenGL32, "glGenTextures"); PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffers"); PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebuffer"); PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2D"); // Enable OpenGL debugging #ifdef _DEBUG glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); PFNGLDEBUGMESSAGECALLBACKPROC glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)wglGetProcAddress("glDebugMessageCallback"); glDebugMessageCallback(DebugCallbackGL, 0); #endif // create D3D11 device, context and swap chain. ID3D11Device *device; ID3D11DeviceContext *devCtx; IDXGISwapChain *swapChain; HANDLE hFrameLatencyWaitableObject; DXGI_SWAP_CHAIN_DESC scd = {}; scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; scd.SampleDesc.Count = 1; scd.BufferCount = 3; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scd.OutputWindow = hWnd; scd.Windowed = TRUE; scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; scd.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; UINT flags = 0; #if _DEBUG flags |= D3D11_CREATE_DEVICE_DEBUG; #endif hr = D3D11CreateDeviceAndSwapChain(NULL, // pAdapter D3D_DRIVER_TYPE_HARDWARE, // DriverType NULL, // Software flags, // Flags (Do not set D3D11_CREATE_DEVICE_SINGLETHREADED) NULL, // pFeatureLevels 0, // FeatureLevels D3D11_SDK_VERSION, // SDKVersion &scd, // pSwapChainDesc &swapChain, // ppSwapChain &device, // ppDevice NULL, // pFeatureLevel &devCtx); // ppImmediateContext assert(SUCCEEDED(hr)); // get frame latency waitable object IDXGISwapChain2* swapChain2; hr = swapChain->QueryInterface(&swapChain2); hFrameLatencyWaitableObject = swapChain2->GetFrameLatencyWaitableObject(); // Create depth stencil texture ID3D11Texture2D *dxDepthBuffer; hr = device->CreateTexture2D( &CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_R24G8_TYPELESS, SCREEN_WIDTH, SCREEN_HEIGHT, 1, 1, D3D11_BIND_DEPTH_STENCIL), NULL, &dxDepthBuffer); assert(SUCCEEDED(hr)); // Create depth stencil view ID3D11DepthStencilView *depthBufferView; hr = device->CreateDepthStencilView( dxDepthBuffer, &CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D, DXGI_FORMAT_D24_UNORM_S8_UINT), &depthBufferView); assert(SUCCEEDED(hr)); // Register D3D11 device with GL HANDLE gl_handleD3D; gl_handleD3D = wglDXOpenDeviceNV(device); // register the Direct3D depth/stencil buffer as texture2d in opengl GLuint dsvNameGL; glGenTextures(1, &dsvNameGL); HANDLE dsvHandleGL = wglDXRegisterObjectNV(gl_handleD3D, dxDepthBuffer, dsvNameGL, GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV); // Initialize GL FBO GLuint fbo; glGenFramebuffers(1, &fbo); // attach the Direct3D depth buffer to FBO glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dsvNameGL, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, dsvNameGL, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // GL RTV will be recreated every frame to use the FLIP swap chain GLuint rtvNameGL; glGenTextures(1, &rtvNameGL); // main loop while (true) { // Handle all events MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Wait until the previous frame is presented before drawing the next frame ok = WaitForSingleObject(hFrameLatencyWaitableObject, INFINITE) == WAIT_OBJECT_0; assert(ok); // Fetch the current swapchain backbuffer from the FLIP swap chain ID3D11Texture2D *dxColorBuffer; hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&dxColorBuffer); assert(SUCCEEDED(hr)); // Create RTV for swapchain backbuffer ID3D11RenderTargetView *colorBufferView; hr = device->CreateRenderTargetView( dxColorBuffer, &CD3D11_RENDER_TARGET_VIEW_DESC(D3D11_RTV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM), &colorBufferView); assert(SUCCEEDED(hr)); // register current backbuffer HANDLE rtvHandleGL = wglDXRegisterObjectNV(gl_handleD3D, dxColorBuffer, rtvNameGL, GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV); // Attach Direct3D color buffer to FBO glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rtvNameGL, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Attach back buffer and depth texture to redertarget for the device. devCtx->OMSetRenderTargets(1, &colorBufferView, depthBufferView); // Direct3d renders to the render targets float dxClearColor[] = { 0.5f, 0.0f, 0.0f, 1.0f }; devCtx->ClearRenderTargetView(colorBufferView, dxClearColor); // lock the dsv/rtv for GL access wglDXLockObjectsNV(gl_handleD3D, 1, &dsvHandleGL); wglDXLockObjectsNV(gl_handleD3D, 1, &rtvHandleGL); // OpenGL renders to the render targets glBindFramebuffer(GL_FRAMEBUFFER, fbo); // clear half the screen, so half the screen will be from DX and half from GL glEnable(GL_SCISSOR_TEST); glScissor(0, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT); glClearColor(0.0f, 0.5f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); glBindFramebuffer(GL_FRAMEBUFFER, 0); // unlock the dsv/rtv wglDXUnlockObjectsNV(gl_handleD3D, 1, &dsvHandleGL); wglDXUnlockObjectsNV(gl_handleD3D, 1, &rtvHandleGL); // DXGI presents the results on the screen hr = swapChain->Present(0, 0); assert(SUCCEEDED(hr)); // release current backbuffer back to the swap chain wglDXUnregisterObjectNV(gl_handleD3D, rtvHandleGL); colorBufferView->Release(); dxColorBuffer->Release(); } }<commit_msg>add more asserts<commit_after>#include <dxgi1_5.h> #include <d3d11.h> #include "glcorearb.h" #include "wglext.h" #include <cassert> #include <cstdio> #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "opengl32.lib") #define SCREEN_WIDTH 640 #define SCREEN_HEIGHT 480 void APIENTRY DebugCallbackGL(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { OutputDebugStringA("DebugCallbackGL: "); OutputDebugStringA(message); OutputDebugStringA("\n"); } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CLOSE: ExitProcess(0); } return DefWindowProc(hWnd, msg, wParam, lParam); } int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { bool ok; HRESULT hr; // Register window class WNDCLASSEX wc = {}; wc.cbSize = sizeof(wc); wc.style = CS_OWNDC; wc.lpfnWndProc = WndProc; wc.hInstance = GetModuleHandleW(NULL); wc.hCursor = LoadCursorW(NULL, IDC_ARROW); wc.lpszClassName = TEXT("WindowClass"); ok = RegisterClassExW(&wc) != NULL; assert(ok); // Determine size of window based on window style DWORD dwStyle = WS_OVERLAPPEDWINDOW; DWORD dwExStyle = 0; RECT wr = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT }; ok = AdjustWindowRectEx(&wr, dwStyle, FALSE, dwExStyle) != FALSE; assert(ok); TCHAR* title = TEXT("OpenGL on DXGI"); // Create window HWND hWnd = CreateWindowEx( dwExStyle, TEXT("WindowClass"), title, dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, wr.right - wr.left, wr.bottom - wr.top, NULL, NULL, hInstance, NULL); assert(hWnd); // Unhide the window ShowWindow(hWnd, SW_SHOWDEFAULT); // Create window that will be used to create a GL context HWND gl_hWnd = CreateWindowEx(0, TEXT("WindowClass"), 0, 0, 0, 0, 0, 0, 0, 0, hInstance, 0); assert(gl_hWnd); HDC gl_hDC = GetDC(gl_hWnd); assert(gl_hDC); // set pixelformat for window that supports OpenGL PIXELFORMATDESCRIPTOR gl_pfd = {}; gl_pfd.nSize = sizeof(gl_pfd); gl_pfd.nVersion = 1; gl_pfd.dwFlags = PFD_SUPPORT_OPENGL; int chosenPixelFormat = ChoosePixelFormat(gl_hDC, &gl_pfd); ok = SetPixelFormat(gl_hDC, chosenPixelFormat, &gl_pfd) != FALSE; assert(ok); // Create dummy GL context that will be used to create the real context HGLRC dummy_hGLRC = wglCreateContext(gl_hDC); assert(dummy_hGLRC); // Use the dummy context to get function to create a better context ok = wglMakeCurrent(gl_hDC, dummy_hGLRC) != FALSE; assert(ok); PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); int contextFlagsGL = 0; #ifdef _DEBUG contextFlagsGL |= WGL_CONTEXT_DEBUG_BIT_ARB; #endif int contextAttribsGL[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, contextFlagsGL, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; HGLRC hGLRC = wglCreateContextAttribsARB(gl_hDC, NULL, contextAttribsGL); assert(hGLRC); // Switch to the new context and ditch the old one ok = wglMakeCurrent(gl_hDC, hGLRC) != FALSE; assert(ok); ok = wglDeleteContext(dummy_hGLRC) != FALSE; assert(ok); // Grab WGL functions PFNWGLDXOPENDEVICENVPROC wglDXOpenDeviceNV = (PFNWGLDXOPENDEVICENVPROC)wglGetProcAddress("wglDXOpenDeviceNV"); PFNWGLDXREGISTEROBJECTNVPROC wglDXRegisterObjectNV = (PFNWGLDXREGISTEROBJECTNVPROC)wglGetProcAddress("wglDXRegisterObjectNV"); PFNWGLDXUNREGISTEROBJECTNVPROC wglDXUnregisterObjectNV = (PFNWGLDXUNREGISTEROBJECTNVPROC)wglGetProcAddress("wglDXUnregisterObjectNV"); PFNWGLDXLOCKOBJECTSNVPROC wglDXLockObjectsNV = (PFNWGLDXLOCKOBJECTSNVPROC)wglGetProcAddress("wglDXLockObjectsNV"); PFNWGLDXUNLOCKOBJECTSNVPROC wglDXUnlockObjectsNV = (PFNWGLDXUNLOCKOBJECTSNVPROC)wglGetProcAddress("wglDXUnlockObjectsNV"); // Fall back to GetProcAddress to get GL 1 functions. wglGetProcAddress returns NULL on those. HMODULE hOpenGL32 = LoadLibrary(TEXT("OpenGL32.dll")); // Grab OpenGL functions PFNGLENABLEPROC glEnable = (PFNGLENABLEPROC)GetProcAddress(hOpenGL32, "glEnable"); PFNGLDISABLEPROC glDisable = (PFNGLDISABLEPROC)GetProcAddress(hOpenGL32, "glDisable"); PFNGLCLEARPROC glClear = (PFNGLCLEARPROC)GetProcAddress(hOpenGL32, "glClear"); PFNGLCLEARCOLORPROC glClearColor = (PFNGLCLEARCOLORPROC)GetProcAddress(hOpenGL32, "glClearColor"); PFNGLSCISSORPROC glScissor = (PFNGLSCISSORPROC)GetProcAddress(hOpenGL32, "glScissor"); PFNGLGENTEXTURESPROC glGenTextures = (PFNGLGENTEXTURESPROC)GetProcAddress(hOpenGL32, "glGenTextures"); PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffers"); PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebuffer"); PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2D"); PFNGLCHECKFRAMEBUFFERSTATUSPROC glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wglGetProcAddress("glCheckFramebufferStatus"); // Enable OpenGL debugging #ifdef _DEBUG glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); PFNGLDEBUGMESSAGECALLBACKPROC glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)wglGetProcAddress("glDebugMessageCallback"); glDebugMessageCallback(DebugCallbackGL, 0); #endif // create D3D11 device, context and swap chain. ID3D11Device *device; ID3D11DeviceContext *devCtx; IDXGISwapChain *swapChain; HANDLE hFrameLatencyWaitableObject; DXGI_SWAP_CHAIN_DESC scd = {}; scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; scd.SampleDesc.Count = 1; scd.BufferCount = 3; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; scd.OutputWindow = hWnd; scd.Windowed = TRUE; scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; scd.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; UINT flags = 0; #if _DEBUG flags |= D3D11_CREATE_DEVICE_DEBUG; #endif hr = D3D11CreateDeviceAndSwapChain(NULL, // pAdapter D3D_DRIVER_TYPE_HARDWARE, // DriverType NULL, // Software flags, // Flags (Do not set D3D11_CREATE_DEVICE_SINGLETHREADED) NULL, // pFeatureLevels 0, // FeatureLevels D3D11_SDK_VERSION, // SDKVersion &scd, // pSwapChainDesc &swapChain, // ppSwapChain &device, // ppDevice NULL, // pFeatureLevel &devCtx); // ppImmediateContext assert(SUCCEEDED(hr)); // get frame latency waitable object IDXGISwapChain2* swapChain2; hr = swapChain->QueryInterface(&swapChain2); hFrameLatencyWaitableObject = swapChain2->GetFrameLatencyWaitableObject(); // Create depth stencil texture ID3D11Texture2D *dxDepthBuffer; hr = device->CreateTexture2D( &CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_R24G8_TYPELESS, SCREEN_WIDTH, SCREEN_HEIGHT, 1, 1, D3D11_BIND_DEPTH_STENCIL), NULL, &dxDepthBuffer); assert(SUCCEEDED(hr)); // Create depth stencil view ID3D11DepthStencilView *depthBufferView; hr = device->CreateDepthStencilView( dxDepthBuffer, &CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D, DXGI_FORMAT_D24_UNORM_S8_UINT, 0, 0, 1), &depthBufferView); assert(SUCCEEDED(hr)); // Register D3D11 device with GL HANDLE gl_handleD3D; gl_handleD3D = wglDXOpenDeviceNV(device); assert(gl_handleD3D); // check GetLastError() if this fails // register the Direct3D depth/stencil buffer as texture2d in opengl GLuint dsvNameGL; glGenTextures(1, &dsvNameGL); HANDLE dsvHandleGL = wglDXRegisterObjectNV(gl_handleD3D, dxDepthBuffer, dsvNameGL, GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV); assert(dsvHandleGL); // check GetLastError() if this fails // Initialize GL FBO GLuint fbo; glGenFramebuffers(1, &fbo); // attach the Direct3D depth buffer to FBO glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dsvNameGL, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, dsvNameGL, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); // GL RTV will be recreated every frame to use the FLIP swap chain GLuint rtvNameGL; glGenTextures(1, &rtvNameGL); // main loop while (true) { // Handle all events MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Wait until the previous frame is presented before drawing the next frame ok = WaitForSingleObject(hFrameLatencyWaitableObject, INFINITE) == WAIT_OBJECT_0; assert(ok); // Fetch the current swapchain backbuffer from the FLIP swap chain ID3D11Texture2D *dxColorBuffer; hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&dxColorBuffer); assert(SUCCEEDED(hr)); // Create RTV for swapchain backbuffer ID3D11RenderTargetView *colorBufferView; hr = device->CreateRenderTargetView( dxColorBuffer, &CD3D11_RENDER_TARGET_VIEW_DESC(D3D11_RTV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM), &colorBufferView); assert(SUCCEEDED(hr)); // register current backbuffer HANDLE rtvHandleGL = wglDXRegisterObjectNV(gl_handleD3D, dxColorBuffer, rtvNameGL, GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV); assert(rtvHandleGL); // check GetLastError() if this fails // Attach Direct3D color buffer to FBO glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rtvNameGL, 0); GLenum fbostatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); assert(fbostatus == GL_FRAMEBUFFER_COMPLETE); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Attach back buffer and depth texture to redertarget for the device. devCtx->OMSetRenderTargets(1, &colorBufferView, depthBufferView); // Direct3d renders to the render targets float dxClearColor[] = { 0.5f, 0.0f, 0.0f, 1.0f }; devCtx->ClearRenderTargetView(colorBufferView, dxClearColor); // lock the dsv/rtv for GL access wglDXLockObjectsNV(gl_handleD3D, 1, &dsvHandleGL); wglDXLockObjectsNV(gl_handleD3D, 1, &rtvHandleGL); // OpenGL renders to the render targets glBindFramebuffer(GL_FRAMEBUFFER, fbo); // clear half the screen, so half the screen will be from DX and half from GL glEnable(GL_SCISSOR_TEST); glScissor(0, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT); glClearColor(0.0f, 0.5f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); glBindFramebuffer(GL_FRAMEBUFFER, 0); // unlock the dsv/rtv wglDXUnlockObjectsNV(gl_handleD3D, 1, &dsvHandleGL); wglDXUnlockObjectsNV(gl_handleD3D, 1, &rtvHandleGL); // DXGI presents the results on the screen hr = swapChain->Present(0, 0); assert(SUCCEEDED(hr)); // release current backbuffer back to the swap chain wglDXUnregisterObjectNV(gl_handleD3D, rtvHandleGL); colorBufferView->Release(); dxColorBuffer->Release(); } }<|endoftext|>
<commit_before>8d6dfcc5-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfcc6-2d14-11e5-af21-0401358ea401<commit_after>8d6dfcc6-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>5720392e-2e4f-11e5-9d2e-28cfe91dbc4b<commit_msg>5727da23-2e4f-11e5-b700-28cfe91dbc4b<commit_after>5727da23-2e4f-11e5-b700-28cfe91dbc4b<|endoftext|>
<commit_before>ee3cb99c-ad5b-11e7-afe2-ac87a332f658<commit_msg>oh my, I hate roselyn<commit_after>eea5d7e3-ad5b-11e7-9dc2-ac87a332f658<|endoftext|>
<commit_before>d21c48f4-585a-11e5-ac36-6c40088e03e4<commit_msg>d223c264-585a-11e5-92d9-6c40088e03e4<commit_after>d223c264-585a-11e5-92d9-6c40088e03e4<|endoftext|>
<commit_before>c21334f8-4b02-11e5-bbbc-28cfe9171a43<commit_msg>Finished?<commit_after>c21f8528-4b02-11e5-9704-28cfe9171a43<|endoftext|>
<commit_before>2d4a0e08-2e3a-11e5-9090-c03896053bdd<commit_msg>2d5c39c0-2e3a-11e5-ac66-c03896053bdd<commit_after>2d5c39c0-2e3a-11e5-ac66-c03896053bdd<|endoftext|>
<commit_before>6a00b9d4-2fa5-11e5-b3f4-00012e3d3f12<commit_msg>6a028e92-2fa5-11e5-96d3-00012e3d3f12<commit_after>6a028e92-2fa5-11e5-96d3-00012e3d3f12<|endoftext|>
<commit_before>be651f2e-4b02-11e5-b7d9-28cfe9171a43<commit_msg>I'm done<commit_after>be731e11-4b02-11e5-bc94-28cfe9171a43<|endoftext|>
<commit_before>bef798ba-2e4f-11e5-8d11-28cfe91dbc4b<commit_msg>beff0ba3-2e4f-11e5-8b3f-28cfe91dbc4b<commit_after>beff0ba3-2e4f-11e5-8b3f-28cfe91dbc4b<|endoftext|>
<commit_before>790f822e-2d53-11e5-baeb-247703a38240<commit_msg>79100118-2d53-11e5-baeb-247703a38240<commit_after>79100118-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>ea02baf3-2747-11e6-8bce-e0f84713e7b8<commit_msg>master branch<commit_after>ea1899c7-2747-11e6-83d2-e0f84713e7b8<|endoftext|>
<commit_before>7bd0cf14-4b02-11e5-b1fb-28cfe9171a43<commit_msg>Test..<commit_after>7be4b9f3-4b02-11e5-acc0-28cfe9171a43<|endoftext|>
<commit_before>511d8782-ad5d-11e7-9bf3-ac87a332f658<commit_msg>Nope, didn't work, now it does<commit_after>51a53a30-ad5d-11e7-9283-ac87a332f658<|endoftext|>
<commit_before>5bf673f7-2d16-11e5-af21-0401358ea401<commit_msg>5bf673f8-2d16-11e5-af21-0401358ea401<commit_after>5bf673f8-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>36626880-2d3d-11e5-a082-c82a142b6f9b<commit_msg>36c81c3d-2d3d-11e5-be17-c82a142b6f9b<commit_after>36c81c3d-2d3d-11e5-be17-c82a142b6f9b<|endoftext|>
<commit_before>#include <iostream> #include <tuple> template<typename ... _T> struct _Switch { std::tuple<const _T& ...> mValues; _Switch(const _T& ... values) : mValues(values ...) { } }; template<typename ... _T> _Switch<_T...> _switch(const _T& ... values) { return _Switch<_T...>(values ...); } template<typename _Fnc, typename ... _T> struct _Case { _Fnc mFnc; std::tuple<const _T& ...> mValues; _Case(_Fnc&& fnc, std::tuple<const _T& ...>&& values) : mFnc(fnc), mValues(values) {} }; template<typename ... _T> struct _Case<void, _T...> { std::tuple<const _T& ...> mValues; _Case(const _T & ... values) : mValues(values ...) {} template<typename _Fnc> _Case<_Fnc, _T ...> operator()(_Fnc&& fnc) { return _Case<_Fnc, _T ...>(std::forward<_Fnc>(fnc), std::move(mValues)); } }; template<typename ... _T> _Case<void, _T...> _case(_T && ... values) { return _Case<void, _T...>(values ...); } template<typename _Fnc, typename ... _T> _Switch<_T ...> operator <= (_Switch<_T ...>&& s, _Case<_Fnc, _T ...>&& c) { return std::move(s); } int main() { std::cout << "Hello, World!" << std::endl; int x = 1, y = 3; _switch(x,y) <= _case(1,0)([](int, int){}) <= _case(1,1)([](int, int){}); return 0; }<commit_msg>implement expression templates<commit_after>#include <iostream> #include <tuple> #include <functional> template<typename _Cs, typename ... _T> struct _Switch { _Cs mCases; _Switch(_Cs && cases) : mCases(cases) { } void operator()(const _T& ... values) { } }; template<typename ... _T> struct _Switch<void, _T ...> { _Switch() { } }; template<typename ... _T> inline constexpr _Switch<void, _T...> _switch() { return _Switch<void, _T...>(); } template<typename _Fnc, typename ... _T> struct _Case { _Fnc mFnc; std::tuple<const _T& ...> mValues; _Case(_Fnc&& fnc, std::tuple<const _T& ...>&& values) : mFnc(fnc), mValues(values) {} bool operator()(_T&& ... values) { return true; } }; template<typename ... _T> struct _Case<void, _T...> { std::tuple<const _T& ...> mValues; _Case(const _T & ... values) : mValues(values ...) {} template<typename _Fnc> _Case<_Fnc, _T ...> operator()(_Fnc&& fnc) { return _Case<_Fnc, _T ...>(std::forward<_Fnc>(fnc), std::move(mValues)); } }; template<typename ... _T> inline constexpr _Case<void, _T...> _case(_T && ... values) { return _Case<void, _T...>(values ...); } template<typename _Cs, typename _Fnc, typename ... _T> inline constexpr auto operator <= (_Switch<_Cs, _T ...>&& s, _Case<_Fnc, _T ...>&& c) -> _Switch<decltype(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)))), _T ...> { using _Result = _Switch<decltype(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)))), _T ...>; return _Result(std::tuple_cat(std::move(s.mCases), std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c)))); } template<typename _Fnc, typename ... _T> inline constexpr _Switch<std::tuple<_Case<_Fnc, _T ...>>, _T ...> operator <= (_Switch<void, _T ...>&& s, _Case<_Fnc, _T ...>&& c) { return _Switch<std::tuple<_Case<_Fnc, _T ...>>, _T ...>(std::tuple<_Case<_Fnc, _T ...>>(std::forward<_Case<_Fnc, _T ...>>(c))); } int main() { int x = 1, y = 3; auto a = _switch<int, int>() <= _case(1,0)([](int, int){std::cout << "Hello, World 1-0!" << std::endl;}) <= _case(1,1)([](int, int){std::cout << "Hello, World 1-1" << std::endl;}); a(x,y); return 0; }<|endoftext|>
<commit_before>e976b334-585a-11e5-ba84-6c40088e03e4<commit_msg>e97d7110-585a-11e5-98b6-6c40088e03e4<commit_after>e97d7110-585a-11e5-98b6-6c40088e03e4<|endoftext|>
<commit_before>a555d368-35ca-11e5-86bd-6c40088e03e4<commit_msg>a55c99e6-35ca-11e5-bb01-6c40088e03e4<commit_after>a55c99e6-35ca-11e5-bb01-6c40088e03e4<|endoftext|>
<commit_before>bcf2bde3-2e4f-11e5-bf56-28cfe91dbc4b<commit_msg>bcf9f394-2e4f-11e5-8dd2-28cfe91dbc4b<commit_after>bcf9f394-2e4f-11e5-8dd2-28cfe91dbc4b<|endoftext|>
<commit_before>5f894a0a-2d16-11e5-af21-0401358ea401<commit_msg>5f894a0b-2d16-11e5-af21-0401358ea401<commit_after>5f894a0b-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>51d7210c-5216-11e5-aa0f-6c40088e03e4<commit_msg>51dd9dfe-5216-11e5-8f72-6c40088e03e4<commit_after>51dd9dfe-5216-11e5-8f72-6c40088e03e4<|endoftext|>
<commit_before>8b332588-2d14-11e5-af21-0401358ea401<commit_msg>8b332589-2d14-11e5-af21-0401358ea401<commit_after>8b332589-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>d27da0ca-585a-11e5-b90d-6c40088e03e4<commit_msg>d28498d0-585a-11e5-a69c-6c40088e03e4<commit_after>d28498d0-585a-11e5-a69c-6c40088e03e4<|endoftext|>
<commit_before>45a8f838-2e3a-11e5-b779-c03896053bdd<commit_msg>45b619f0-2e3a-11e5-8bec-c03896053bdd<commit_after>45b619f0-2e3a-11e5-8bec-c03896053bdd<|endoftext|>
<commit_before>60e40cc8-2e3a-11e5-be5f-c03896053bdd<commit_msg>60f6393e-2e3a-11e5-b31f-c03896053bdd<commit_after>60f6393e-2e3a-11e5-b31f-c03896053bdd<|endoftext|>
<commit_before>abe97499-2d3d-11e5-97c8-c82a142b6f9b<commit_msg>ac44f5ae-2d3d-11e5-b45c-c82a142b6f9b<commit_after>ac44f5ae-2d3d-11e5-b45c-c82a142b6f9b<|endoftext|>
<commit_before>10720d17-2e4f-11e5-8e6b-28cfe91dbc4b<commit_msg>1078ea94-2e4f-11e5-bb24-28cfe91dbc4b<commit_after>1078ea94-2e4f-11e5-bb24-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> #include <random> #include <sstream> #include <thread> #include <vector> #include "geometry.h" #include "help_text.h" #include "image.h" #include "scene.h" #include "vec2f.h" #include "vec3f.h" enum { EXIT_OK = 0, EXIT_FAIL_SAVE, EXIT_FAIL_LOAD, EXIT_BAD_ARGS, }; enum { INVALID_ARG = -1, HELP_ARG, SCENE_FILE_ARG, OUTPUT_FILE_ARG, THREAD_COUNT_ARG, }; struct user_inputs { user_inputs() : scene_file(0) , output_file(0) , thread_count(1) , requests_help(false) , requests_help_scene(false) { } const char* scene_file; const char* output_file; unsigned thread_count; bool requests_help; bool requests_help_scene; }; user_inputs parse_inputs(int argc, char** argv) { user_inputs in; int next_expected_arg = INVALID_ARG; for (int i = 1; i < argc; ++i) { if (next_expected_arg == SCENE_FILE_ARG) { in.scene_file = argv[i]; next_expected_arg = INVALID_ARG; } else if (next_expected_arg == OUTPUT_FILE_ARG) { in.output_file = argv[i]; next_expected_arg = INVALID_ARG; } else if (next_expected_arg == THREAD_COUNT_ARG) { std::istringstream input(argv[i]); input >> in.thread_count; if (!input) { std::cerr << "Invalid thread count: " << argv[i] << std::endl; std::exit(EXIT_BAD_ARGS); } next_expected_arg = INVALID_ARG; } else if (!strcmp(argv[i], "--scene")) { next_expected_arg = SCENE_FILE_ARG; } else if (!strcmp(argv[i], "--output")) { next_expected_arg = OUTPUT_FILE_ARG; } else if (!strcmp(argv[i], "--threads") || !strcmp(argv[i], "-j")) { next_expected_arg = THREAD_COUNT_ARG; } else if (!strcmp(argv[i], "--help")) { in.requests_help = true; next_expected_arg = HELP_ARG; } else if (next_expected_arg == HELP_ARG) { if (!strcmp(argv[i], "scene")) { in.requests_help_scene = true; in.requests_help = false; } next_expected_arg = INVALID_ARG; } else { std::cerr << "Unrecognized input: " << argv[i] << std::endl; std::exit(EXIT_BAD_ARGS); } } return in; } const char* get_with_default(const char* primary, const char* fallback) { return primary ? primary : fallback; } enum nearest_t { NOTHING_NEAREST, SPHERE_NEAREST, MESH_NEAREST, }; nearest_t nearest_intersect( const ray_sphere_intersect& rsi, const std::vector<sphere_t>& spheres, const ray_mesh_intersect& rmi, const std::vector<mesh_t>& meshes) { if (rsi.intersect_exists(spheres)) { if (rmi.intersect_exists(meshes)) { return rsi.t < rmi.t ? SPHERE_NEAREST : MESH_NEAREST; } else { return SPHERE_NEAREST; } } else { if (rmi.intersect_exists(meshes)) { return MESH_NEAREST; } else { return NOTHING_NEAREST; } } } enum cast_policy_t { CAST_TO_OBJECT, CAST_TO_LIGHT, }; const unsigned MAX_RECURSE = 10u; /* Casts a ray into the scene and returns a color. The default_color is the color returned if no object is hit. There are two possible cast_policy values, corresponding with two main types of casts: - cast-to-object: intersection with a solid object results in a search for visible lights - cast-to-light: intersection with a solid object results in the conclusion that the point is shadowed Note that these casts do not account for indirect lighting, i.e. global illumination */ vec3f cast_ray(const ray_t& ray, const scene_t& s, vec3f default_color, cast_policy_t cast_policy, float refractive_index, unsigned recursion_depth) { vec3f color = default_color; ray_sphere_intersect rsi = get_ray_sphere_intersect(ray, s.geometry.spheres); ray_mesh_intersect rmi = get_ray_mesh_intersect(ray, s.geometry.meshes); nearest_t nearest = nearest_intersect(rsi, s.geometry.spheres, rmi, s.geometry.meshes); if (nearest == SPHERE_NEAREST) { material_t material = s.sphere_materials[rsi.index_in(s.geometry.spheres)]; float solid_component = material.opacity - material.reflectivity; if (cast_policy == CAST_TO_OBJECT) { // todo: add a minimum threshold to collisions t parameters // since stopping the ray before the sphere may result in distortions vec3f pos = ray.position_at(0.9999f * rsi.t); if (solid_component > 0.f) { vec3f light_color(0,0,0); for (const light_t& light : s.lights) { ray_t light_ray = { pos, normalized(light.position - pos) }; light_color += cast_ray(light_ray, s, light.color, CAST_TO_LIGHT, refractive_index, recursion_depth + 1u); } color += solid_component * material.color * light_color; color += solid_component * material.color * s.ambient_light; } if (material.reflectivity > 0.f) { vec3f normal = rsi.near_geometry_it->normal_at(pos); ray_t reflected_ray = { pos, reflected(ray.direction, normal) }; if (recursion_depth < MAX_RECURSE) { color += material.reflectivity * material.color * cast_ray(reflected_ray, s, default_color, cast_policy, refractive_index, recursion_depth + 1u); } } float translucence = 1.f - material.opacity; if (translucence > 0.f) { vec3f inside_pos = ray.position_at(1.01f * rsi.t); vec3f normal = rsi.near_geometry_it->normal_at(inside_pos); if (dot(ray.direction, normal) > 0.f) { normal = -normal; } ray_t refracted_ray = { inside_pos, refracted(ray.direction, normal, refractive_index, material.refractive_index) }; if (recursion_depth < MAX_RECURSE) { color += translucence * material.color * cast_ray(refracted_ray, s, default_color, cast_policy, material.refractive_index, recursion_depth + 1u); } else { // todo: handle total internal reflection more nicely std::cout << "Max recurse depth!" << std::endl; } } } else { // cast_policy == CAST_TO_LIGHT // we hit an object while looking for our light // that means we're shadowed... // but it still has ambient light... color = s.ambient_light * solid_component * material.color; } } else if (nearest == MESH_NEAREST) { // todo: reduce duplication between sphere and mesh color calculations material_t material = s.mesh_materials[rmi.index_in(s.geometry.meshes)]; float solid_component = material.opacity - material.reflectivity; if (cast_policy == CAST_TO_OBJECT) { // todo: add a minimum threshold to collisions t parameters // since stopping the ray before the sphere may result in distortions vec3f pos = ray.position_at(0.9999f * rmi.t); if (solid_component > 0.f) { vec3f light_color(0,0,0); for (const light_t& light : s.lights) { ray_t light_ray = { pos, normalized(light.position - pos) }; light_color += cast_ray(light_ray, s, light.color, CAST_TO_LIGHT, refractive_index, recursion_depth + 1u); } color += solid_component * material.color * light_color; color += solid_component * material.color * s.ambient_light; } if (material.reflectivity > 0.f) { vec3f normal = rmi.face_normal(); ray_t reflected_ray = { pos, reflected(ray.direction, normal) }; if (recursion_depth < MAX_RECURSE) { color += material.reflectivity * material.color * cast_ray(reflected_ray, s, default_color, cast_policy, refractive_index, recursion_depth + 1u); } } float translucence = 1.f - material.opacity; if (translucence > 0.f) { vec3f inside_pos = ray.position_at(1.01f * rmi.t); vec3f normal = rmi.face_normal(); if (dot(ray.direction, normal) > 0.f) { normal = -normal; } ray_t refracted_ray = { inside_pos, refracted(ray.direction, normal, refractive_index, material.refractive_index) }; if (recursion_depth < MAX_RECURSE) { color += translucence * material.color * cast_ray(refracted_ray, s, default_color, cast_policy, material.refractive_index, recursion_depth + 1u); } else { // todo: handle total internal reflection more nicely std::cout << "Max recurse depth!" << std::endl; } } } else { // cast_policy == CAST_TO_LIGHT // shadowed... color = s.ambient_light * solid_component * material.color; } } return color; } image generate_image(const scene_t& s, unsigned thread_count) { const vec3f observer = s.observer; const resolution_t res = s.res; const unsigned sample_count = s.sample_count; const vec3f screen_top_left = s.screen_top_left; const vec3f screen_offset_per_px_x = s.screen_offset_per_px_x(); const vec3f screen_offset_per_px_y = s.screen_offset_per_px_y(); image img(res.x, res.y); std::vector<std::thread> threads(thread_count); for (unsigned thread_id = 0u; thread_id < threads.size(); ++thread_id) { threads[thread_id] = std::thread([&,thread_id]() { for (unsigned y = thread_id; y < res.y; y += thread_count) { std::mt19937 engine(y); std::uniform_real_distribution<float> distribution(0.f, 1.f); auto rng = std::bind(distribution, engine); for (unsigned x = 0u; x < res.x; ++x) { vec3f px_color = { 0, 0, 0 }; for (unsigned sample = 0u; sample < sample_count; ++sample) { vec3f background_color = { 0, 0, 0 }; vec3f pixel_pos = screen_top_left + (x + rng()) * screen_offset_per_px_x + (y + rng()) * screen_offset_per_px_y; ray_t eye_ray = { pixel_pos, normalized(pixel_pos - observer) }; px_color += cast_ray(eye_ray, s, background_color, CAST_TO_OBJECT, 1.f, 0u); } img.px(x, y) = px_color / sample_count; } } }); } for (auto& thread : threads) { thread.join(); } return img; } int main(int argc, char** argv) { user_inputs user = parse_inputs(argc, argv); if (user.requests_help) { std::cout << help_text << std::endl; std::exit(EXIT_OK); } else if (user.requests_help_scene) { std::cout << scene_file_help_text << std::endl; std::exit(EXIT_OK); } const scene_t scene = try_load_scene_from_file( get_with_default(user.scene_file, "world.yml"), EXIT_FAIL_LOAD); image img = generate_image(scene, user.thread_count); img.clamp_colors(); if (!img.save_as_png(get_with_default(user.output_file, "output.png"))) { return EXIT_FAIL_SAVE; } return EXIT_OK; } <commit_msg>Improve collision numerical imprecision hackery<commit_after>#include <iostream> #include <random> #include <sstream> #include <thread> #include <vector> #include "geometry.h" #include "help_text.h" #include "image.h" #include "scene.h" #include "vec2f.h" #include "vec3f.h" enum { EXIT_OK = 0, EXIT_FAIL_SAVE, EXIT_FAIL_LOAD, EXIT_BAD_ARGS, }; enum { INVALID_ARG = -1, HELP_ARG, SCENE_FILE_ARG, OUTPUT_FILE_ARG, THREAD_COUNT_ARG, }; struct user_inputs { user_inputs() : scene_file(0) , output_file(0) , thread_count(1) , requests_help(false) , requests_help_scene(false) { } const char* scene_file; const char* output_file; unsigned thread_count; bool requests_help; bool requests_help_scene; }; user_inputs parse_inputs(int argc, char** argv) { user_inputs in; int next_expected_arg = INVALID_ARG; for (int i = 1; i < argc; ++i) { if (next_expected_arg == SCENE_FILE_ARG) { in.scene_file = argv[i]; next_expected_arg = INVALID_ARG; } else if (next_expected_arg == OUTPUT_FILE_ARG) { in.output_file = argv[i]; next_expected_arg = INVALID_ARG; } else if (next_expected_arg == THREAD_COUNT_ARG) { std::istringstream input(argv[i]); input >> in.thread_count; if (!input) { std::cerr << "Invalid thread count: " << argv[i] << std::endl; std::exit(EXIT_BAD_ARGS); } next_expected_arg = INVALID_ARG; } else if (!strcmp(argv[i], "--scene")) { next_expected_arg = SCENE_FILE_ARG; } else if (!strcmp(argv[i], "--output")) { next_expected_arg = OUTPUT_FILE_ARG; } else if (!strcmp(argv[i], "--threads") || !strcmp(argv[i], "-j")) { next_expected_arg = THREAD_COUNT_ARG; } else if (!strcmp(argv[i], "--help")) { in.requests_help = true; next_expected_arg = HELP_ARG; } else if (next_expected_arg == HELP_ARG) { if (!strcmp(argv[i], "scene")) { in.requests_help_scene = true; in.requests_help = false; } next_expected_arg = INVALID_ARG; } else { std::cerr << "Unrecognized input: " << argv[i] << std::endl; std::exit(EXIT_BAD_ARGS); } } return in; } const char* get_with_default(const char* primary, const char* fallback) { return primary ? primary : fallback; } enum nearest_t { NOTHING_NEAREST, SPHERE_NEAREST, MESH_NEAREST, }; nearest_t nearest_intersect( const ray_sphere_intersect& rsi, const std::vector<sphere_t>& spheres, const ray_mesh_intersect& rmi, const std::vector<mesh_t>& meshes) { if (rsi.intersect_exists(spheres)) { if (rmi.intersect_exists(meshes)) { return rsi.t < rmi.t ? SPHERE_NEAREST : MESH_NEAREST; } else { return SPHERE_NEAREST; } } else { if (rmi.intersect_exists(meshes)) { return MESH_NEAREST; } else { return NOTHING_NEAREST; } } } enum cast_policy_t { CAST_TO_OBJECT, CAST_TO_LIGHT, }; // The maximum recursive depth const unsigned MAX_RECURSE = 10u; // The distance along the ray that the collision is offset by, // to ensure floating point inaccuracy doesn't result in recollision // with the same surface upon recasting from the collision point. // Overall, it's a bit of a hack. A backoff algorithm would be more // appropriate. const float BACKOFF = 1e-3f; /* Casts a ray into the scene and returns a color. The default_color is the color returned if no object is hit. There are two possible cast_policy values, corresponding with two main types of casts: - cast-to-object: intersection with a solid object results in a search for visible lights - cast-to-light: intersection with a solid object results in the conclusion that the point is shadowed Note that these casts do not account for indirect lighting, i.e. global illumination */ vec3f cast_ray(const ray_t& ray, const scene_t& s, vec3f default_color, cast_policy_t cast_policy, float refractive_index, unsigned recursion_depth) { vec3f color = default_color; ray_sphere_intersect rsi = get_ray_sphere_intersect(ray, s.geometry.spheres); ray_mesh_intersect rmi = get_ray_mesh_intersect(ray, s.geometry.meshes); nearest_t nearest = nearest_intersect(rsi, s.geometry.spheres, rmi, s.geometry.meshes); if (nearest == SPHERE_NEAREST) { material_t material = s.sphere_materials[rsi.index_in(s.geometry.spheres)]; float solid_component = material.opacity - material.reflectivity; if (cast_policy == CAST_TO_OBJECT) { vec3f pos = ray.position_at(rsi.t - BACKOFF); if (solid_component > 0.f) { vec3f light_color(0,0,0); for (const light_t& light : s.lights) { ray_t light_ray = { pos, normalized(light.position - pos) }; light_color += cast_ray(light_ray, s, light.color, CAST_TO_LIGHT, refractive_index, recursion_depth + 1u); } color += solid_component * material.color * light_color; color += solid_component * material.color * s.ambient_light; } if (material.reflectivity > 0.f) { vec3f normal = rsi.near_geometry_it->normal_at(pos); ray_t reflected_ray = { pos, reflected(ray.direction, normal) }; if (recursion_depth < MAX_RECURSE) { color += material.reflectivity * material.color * cast_ray(reflected_ray, s, default_color, cast_policy, refractive_index, recursion_depth + 1u); } } float translucence = 1.f - material.opacity; if (translucence > 0.f) { vec3f inside_pos = ray.position_at(rsi.t + BACKOFF); vec3f normal = rsi.near_geometry_it->normal_at(inside_pos); if (dot(ray.direction, normal) > 0.f) { normal = -normal; } ray_t refracted_ray = { inside_pos, refracted(ray.direction, normal, refractive_index, material.refractive_index) }; if (recursion_depth < MAX_RECURSE) { color += translucence * material.color * cast_ray(refracted_ray, s, default_color, cast_policy, material.refractive_index, recursion_depth + 1u); } else { // todo: handle total internal reflection more nicely std::cout << "Max recurse depth!" << std::endl; } } } else { // cast_policy == CAST_TO_LIGHT // we hit an object while looking for our light // that means we're shadowed... // but it still has ambient light... color = s.ambient_light * solid_component * material.color; } } else if (nearest == MESH_NEAREST) { // todo: reduce duplication between sphere and mesh color calculations material_t material = s.mesh_materials[rmi.index_in(s.geometry.meshes)]; float solid_component = material.opacity - material.reflectivity; if (cast_policy == CAST_TO_OBJECT) { vec3f pos = ray.position_at(rmi.t - BACKOFF); if (solid_component > 0.f) { vec3f light_color(0,0,0); for (const light_t& light : s.lights) { ray_t light_ray = { pos, normalized(light.position - pos) }; light_color += cast_ray(light_ray, s, light.color, CAST_TO_LIGHT, refractive_index, recursion_depth + 1u); } color += solid_component * material.color * light_color; color += solid_component * material.color * s.ambient_light; } if (material.reflectivity > 0.f) { vec3f normal = rmi.face_normal(); ray_t reflected_ray = { pos, reflected(ray.direction, normal) }; if (recursion_depth < MAX_RECURSE) { color += material.reflectivity * material.color * cast_ray(reflected_ray, s, default_color, cast_policy, refractive_index, recursion_depth + 1u); } } float translucence = 1.f - material.opacity; if (translucence > 0.f) { vec3f inside_pos = ray.position_at(rsi.t + BACKOFF); vec3f normal = rmi.face_normal(); if (dot(ray.direction, normal) > 0.f) { normal = -normal; } ray_t refracted_ray = { inside_pos, refracted(ray.direction, normal, refractive_index, material.refractive_index) }; if (recursion_depth < MAX_RECURSE) { color += translucence * material.color * cast_ray(refracted_ray, s, default_color, cast_policy, material.refractive_index, recursion_depth + 1u); } else { // todo: handle total internal reflection more nicely std::cout << "Max recurse depth!" << std::endl; } } } else { // cast_policy == CAST_TO_LIGHT // shadowed... color = s.ambient_light * solid_component * material.color; } } return color; } image generate_image(const scene_t& s, unsigned thread_count) { const vec3f observer = s.observer; const resolution_t res = s.res; const unsigned sample_count = s.sample_count; const vec3f screen_top_left = s.screen_top_left; const vec3f screen_offset_per_px_x = s.screen_offset_per_px_x(); const vec3f screen_offset_per_px_y = s.screen_offset_per_px_y(); image img(res.x, res.y); std::vector<std::thread> threads(thread_count); for (unsigned thread_id = 0u; thread_id < threads.size(); ++thread_id) { threads[thread_id] = std::thread([&,thread_id]() { for (unsigned y = thread_id; y < res.y; y += thread_count) { std::mt19937 engine(y); std::uniform_real_distribution<float> distribution(0.f, 1.f); auto rng = std::bind(distribution, engine); for (unsigned x = 0u; x < res.x; ++x) { vec3f px_color = { 0, 0, 0 }; for (unsigned sample = 0u; sample < sample_count; ++sample) { vec3f background_color = { 0, 0, 0 }; vec3f pixel_pos = screen_top_left + (x + rng()) * screen_offset_per_px_x + (y + rng()) * screen_offset_per_px_y; ray_t eye_ray = { pixel_pos, normalized(pixel_pos - observer) }; px_color += cast_ray(eye_ray, s, background_color, CAST_TO_OBJECT, 1.f, 0u); } img.px(x, y) = px_color / sample_count; } } }); } for (auto& thread : threads) { thread.join(); } return img; } int main(int argc, char** argv) { user_inputs user = parse_inputs(argc, argv); if (user.requests_help) { std::cout << help_text << std::endl; std::exit(EXIT_OK); } else if (user.requests_help_scene) { std::cout << scene_file_help_text << std::endl; std::exit(EXIT_OK); } const scene_t scene = try_load_scene_from_file( get_with_default(user.scene_file, "world.yml"), EXIT_FAIL_LOAD); image img = generate_image(scene, user.thread_count); img.clamp_colors(); if (!img.save_as_png(get_with_default(user.output_file, "output.png"))) { return EXIT_FAIL_SAVE; } return EXIT_OK; } <|endoftext|>
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "common/linux/http_upload.h" #include <assert.h> #include <dlfcn.h> #include <curl/curl.h> #include <curl/easy.h> namespace { // Callback to get the response data from server. static size_t WriteCallback(void *ptr, size_t size, size_t nmemb, void *userp) { if (!userp) return 0; std::string *response = reinterpret_cast<std::string *>(userp); size_t real_size = size * nmemb; response->append(reinterpret_cast<char *>(ptr), real_size); return real_size; } } // namespace namespace google_breakpad { static const char kUserAgent[] = "Breakpad/1.0 (Linux)"; // static bool HTTPUpload::SendRequest(const string &url, const map<string, string> &parameters, const string &upload_file, const string &file_part_name, const string &proxy, const string &proxy_user_pwd, const string &ca_certificate_file, string *response_body, string *error_description) { if (!CheckParameters(parameters)) return false; void *curl_lib = dlopen("libcurl.so", RTLD_NOW); if (!curl_lib) { if (error_description != NULL) *error_description = dlerror(); curl_lib = dlopen("libcurl.so.4", RTLD_NOW); } if (!curl_lib) { // Debian gives libcurl a different name when it is built against GnuTLS // instead of OpenSSL. curl_lib = dlopen("libcurl-gnutls.so.4", RTLD_NOW); } if (!curl_lib) { curl_lib = dlopen("libcurl.so.3", RTLD_NOW); } if (!curl_lib) { return false; } CURL* (*curl_easy_init)(void); *(void**) (&curl_easy_init) = dlsym(curl_lib, "curl_easy_init"); CURL *curl = (*curl_easy_init)(); if (error_description != NULL) *error_description = "No Error"; if (!curl) { dlclose(curl_lib); return false; } CURLcode err_code = CURLE_OK; CURLcode (*curl_easy_setopt)(CURL *, CURLoption, ...); *(void**) (&curl_easy_setopt) = dlsym(curl_lib, "curl_easy_setopt"); (*curl_easy_setopt)(curl, CURLOPT_URL, url.c_str()); (*curl_easy_setopt)(curl, CURLOPT_USERAGENT, kUserAgent); // Set proxy information if necessary. if (!proxy.empty()) (*curl_easy_setopt)(curl, CURLOPT_PROXY, proxy.c_str()); if (!proxy_user_pwd.empty()) (*curl_easy_setopt)(curl, CURLOPT_PROXYUSERPWD, proxy_user_pwd.c_str()); if (!ca_certificate_file.empty()) (*curl_easy_setopt)(curl, CURLOPT_CAINFO, ca_certificate_file.c_str()); struct curl_httppost *formpost = NULL; struct curl_httppost *lastptr = NULL; // Add form data. CURLFORMcode (*curl_formadd)(struct curl_httppost **, struct curl_httppost **, ...); *(void**) (&curl_formadd) = dlsym(curl_lib, "curl_formadd"); map<string, string>::const_iterator iter = parameters.begin(); for (; iter != parameters.end(); ++iter) (*curl_formadd)(&formpost, &lastptr, CURLFORM_COPYNAME, iter->first.c_str(), CURLFORM_COPYCONTENTS, iter->second.c_str(), CURLFORM_END); // Add form file. (*curl_formadd)(&formpost, &lastptr, CURLFORM_COPYNAME, file_part_name.c_str(), CURLFORM_FILE, upload_file.c_str(), CURLFORM_END); (*curl_easy_setopt)(curl, CURLOPT_HTTPPOST, formpost); // Disable 100-continue header. struct curl_slist *headerlist = NULL; char buf[] = "Expect:"; struct curl_slist* (*curl_slist_append)(struct curl_slist *, const char *); *(void**) (&curl_slist_append) = dlsym(curl_lib, "curl_slist_append"); headerlist = (*curl_slist_append)(headerlist, buf); (*curl_easy_setopt)(curl, CURLOPT_HTTPHEADER, headerlist); if (response_body != NULL) { (*curl_easy_setopt)(curl, CURLOPT_WRITEFUNCTION, WriteCallback); (*curl_easy_setopt)(curl, CURLOPT_WRITEDATA, reinterpret_cast<void *>(response_body)); } // Fail if 400+ is returned from the web server. (*curl_easy_setopt)(curl, CURLOPT_FAILONERROR, 1); CURLcode (*curl_easy_perform)(CURL *); *(void**) (&curl_easy_perform) = dlsym(curl_lib, "curl_easy_perform"); err_code = (*curl_easy_perform)(curl); const char* (*curl_easy_strerror)(CURLcode); *(void**) (&curl_easy_strerror) = dlsym(curl_lib, "curl_easy_strerror"); #ifndef NDEBUG if (err_code != CURLE_OK) fprintf(stderr, "Failed to send http request to %s, error: %s\n", url.c_str(), (*curl_easy_strerror)(err_code)); #endif if (error_description != NULL) *error_description = (*curl_easy_strerror)(err_code); void (*curl_easy_cleanup)(CURL *); *(void**) (&curl_easy_cleanup) = dlsym(curl_lib, "curl_easy_cleanup"); (*curl_easy_cleanup)(curl); if (formpost != NULL) { void (*curl_formfree)(struct curl_httppost *); *(void**) (&curl_formfree) = dlsym(curl_lib, "curl_formfree"); (*curl_formfree)(formpost); } if (headerlist != NULL) { void (*curl_slist_free_all)(struct curl_slist *); *(void**) (&curl_slist_free_all) = dlsym(curl_lib, "curl_slist_free_all"); (*curl_slist_free_all)(headerlist); } dlclose(curl_lib); return err_code == CURLE_OK; } // static bool HTTPUpload::CheckParameters(const map<string, string> &parameters) { for (map<string, string>::const_iterator pos = parameters.begin(); pos != parameters.end(); ++pos) { const string &str = pos->first; if (str.size() == 0) return false; // disallow empty parameter names for (unsigned int i = 0; i < str.size(); ++i) { int c = str[i]; if (c < 32 || c == '"' || c > 127) { return false; } } } return true; } } // namespace google_breakpad <commit_msg>Fix libcurl include in http_upload (trivial, no bug)<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "common/linux/http_upload.h" #include <assert.h> #include <dlfcn.h> #include "third_party/curl/curl.h" namespace { // Callback to get the response data from server. static size_t WriteCallback(void *ptr, size_t size, size_t nmemb, void *userp) { if (!userp) return 0; std::string *response = reinterpret_cast<std::string *>(userp); size_t real_size = size * nmemb; response->append(reinterpret_cast<char *>(ptr), real_size); return real_size; } } // namespace namespace google_breakpad { static const char kUserAgent[] = "Breakpad/1.0 (Linux)"; // static bool HTTPUpload::SendRequest(const string &url, const map<string, string> &parameters, const string &upload_file, const string &file_part_name, const string &proxy, const string &proxy_user_pwd, const string &ca_certificate_file, string *response_body, string *error_description) { if (!CheckParameters(parameters)) return false; void *curl_lib = dlopen("libcurl.so", RTLD_NOW); if (!curl_lib) { if (error_description != NULL) *error_description = dlerror(); curl_lib = dlopen("libcurl.so.4", RTLD_NOW); } if (!curl_lib) { // Debian gives libcurl a different name when it is built against GnuTLS // instead of OpenSSL. curl_lib = dlopen("libcurl-gnutls.so.4", RTLD_NOW); } if (!curl_lib) { curl_lib = dlopen("libcurl.so.3", RTLD_NOW); } if (!curl_lib) { return false; } CURL* (*curl_easy_init)(void); *(void**) (&curl_easy_init) = dlsym(curl_lib, "curl_easy_init"); CURL *curl = (*curl_easy_init)(); if (error_description != NULL) *error_description = "No Error"; if (!curl) { dlclose(curl_lib); return false; } CURLcode err_code = CURLE_OK; CURLcode (*curl_easy_setopt)(CURL *, CURLoption, ...); *(void**) (&curl_easy_setopt) = dlsym(curl_lib, "curl_easy_setopt"); (*curl_easy_setopt)(curl, CURLOPT_URL, url.c_str()); (*curl_easy_setopt)(curl, CURLOPT_USERAGENT, kUserAgent); // Set proxy information if necessary. if (!proxy.empty()) (*curl_easy_setopt)(curl, CURLOPT_PROXY, proxy.c_str()); if (!proxy_user_pwd.empty()) (*curl_easy_setopt)(curl, CURLOPT_PROXYUSERPWD, proxy_user_pwd.c_str()); if (!ca_certificate_file.empty()) (*curl_easy_setopt)(curl, CURLOPT_CAINFO, ca_certificate_file.c_str()); struct curl_httppost *formpost = NULL; struct curl_httppost *lastptr = NULL; // Add form data. CURLFORMcode (*curl_formadd)(struct curl_httppost **, struct curl_httppost **, ...); *(void**) (&curl_formadd) = dlsym(curl_lib, "curl_formadd"); map<string, string>::const_iterator iter = parameters.begin(); for (; iter != parameters.end(); ++iter) (*curl_formadd)(&formpost, &lastptr, CURLFORM_COPYNAME, iter->first.c_str(), CURLFORM_COPYCONTENTS, iter->second.c_str(), CURLFORM_END); // Add form file. (*curl_formadd)(&formpost, &lastptr, CURLFORM_COPYNAME, file_part_name.c_str(), CURLFORM_FILE, upload_file.c_str(), CURLFORM_END); (*curl_easy_setopt)(curl, CURLOPT_HTTPPOST, formpost); // Disable 100-continue header. struct curl_slist *headerlist = NULL; char buf[] = "Expect:"; struct curl_slist* (*curl_slist_append)(struct curl_slist *, const char *); *(void**) (&curl_slist_append) = dlsym(curl_lib, "curl_slist_append"); headerlist = (*curl_slist_append)(headerlist, buf); (*curl_easy_setopt)(curl, CURLOPT_HTTPHEADER, headerlist); if (response_body != NULL) { (*curl_easy_setopt)(curl, CURLOPT_WRITEFUNCTION, WriteCallback); (*curl_easy_setopt)(curl, CURLOPT_WRITEDATA, reinterpret_cast<void *>(response_body)); } // Fail if 400+ is returned from the web server. (*curl_easy_setopt)(curl, CURLOPT_FAILONERROR, 1); CURLcode (*curl_easy_perform)(CURL *); *(void**) (&curl_easy_perform) = dlsym(curl_lib, "curl_easy_perform"); err_code = (*curl_easy_perform)(curl); const char* (*curl_easy_strerror)(CURLcode); *(void**) (&curl_easy_strerror) = dlsym(curl_lib, "curl_easy_strerror"); #ifndef NDEBUG if (err_code != CURLE_OK) fprintf(stderr, "Failed to send http request to %s, error: %s\n", url.c_str(), (*curl_easy_strerror)(err_code)); #endif if (error_description != NULL) *error_description = (*curl_easy_strerror)(err_code); void (*curl_easy_cleanup)(CURL *); *(void**) (&curl_easy_cleanup) = dlsym(curl_lib, "curl_easy_cleanup"); (*curl_easy_cleanup)(curl); if (formpost != NULL) { void (*curl_formfree)(struct curl_httppost *); *(void**) (&curl_formfree) = dlsym(curl_lib, "curl_formfree"); (*curl_formfree)(formpost); } if (headerlist != NULL) { void (*curl_slist_free_all)(struct curl_slist *); *(void**) (&curl_slist_free_all) = dlsym(curl_lib, "curl_slist_free_all"); (*curl_slist_free_all)(headerlist); } dlclose(curl_lib); return err_code == CURLE_OK; } // static bool HTTPUpload::CheckParameters(const map<string, string> &parameters) { for (map<string, string>::const_iterator pos = parameters.begin(); pos != parameters.end(); ++pos) { const string &str = pos->first; if (str.size() == 0) return false; // disallow empty parameter names for (unsigned int i = 0; i < str.size(); ++i) { int c = str[i]; if (c < 32 || c == '"' || c > 127) { return false; } } } return true; } } // namespace google_breakpad <|endoftext|>
<commit_before>#ifndef _CITY_HASHER_HH #define _CITY_HASHER_HH #include <city.h> #include <string> /*! CityHasher is a std::hash-style wrapper around CityHash. We * encourage using CityHasher instead of the default std::hash if * possible. */ template <class Key> class CityHasher { public: size_t operator()(const Key& k) const { return CityHash64((const char*) &k, sizeof(k)); } }; /*! This is a template specialization of CityHasher for * std::string. */ template <> class CityHasher<std::string> { public: size_t operator()(const std::string& k) const { return CityHash64(k.c_str(), k.size()); } }; #endif // _CITY_HASHER_HH <commit_msg>fix include path in libcuckoo<commit_after>#ifndef _CITY_HASHER_HH #define _CITY_HASHER_HH #include "cityhash-1.1.1/city.h" #include <string> /*! CityHasher is a std::hash-style wrapper around CityHash. We * encourage using CityHasher instead of the default std::hash if * possible. */ template <class Key> class CityHasher { public: size_t operator()(const Key& k) const { return CityHash64((const char*) &k, sizeof(k)); } }; /*! This is a template specialization of CityHasher for * std::string. */ template <> class CityHasher<std::string> { public: size_t operator()(const std::string& k) const { return CityHash64(k.c_str(), k.size()); } }; #endif // _CITY_HASHER_HH <|endoftext|>
<commit_before>// Copyright 2016 Peter Georg // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef pMR_MISC_THREAD_H #define pMR_MISC_THREAD_H #include <algorithm> #include <stdexcept> namespace pMR { // ?!?! void splitThreadsIntoGangs(); template<typename T, typename W> void splitWorkToThreads(W const start, W const end, T const threadID, T const threadCount, W &threadStart, W &threadEnd, W const granularity = 1); } template<typename T, typename W> void pMR::splitWorkToThreads(W const start, W const end, T const threadID, T const threadCount, W &threadStart, W &threadEnd, W const granularity) { threadStart = start; threadEnd = end; if(end - start == 0) { return; } if(!(threadCount > 0)) { throw std::logic_error("Thread Count"); } if(threadID >= threadCount || threadID < 0) { throw std::out_of_range("Thread ID"); } W perThread = static_cast<W>( std::ceil( (static_cast<double>(end - start) / granularity) / threadCount) * granularity); threadStart += threadID * perThread; threadEnd = threadStart; W usedThreads = (end - start) / perThread; if(threadID < usedThreads) { threadEnd += perThread; } else { if(threadID == usedThreads) { threadEnd += (end - start) - usedThreads * perThread; } } } #endif // pMR_MISC_THREAD_H <commit_msg>Add missing include cmath<commit_after>// Copyright 2016 Peter Georg // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef pMR_MISC_THREAD_H #define pMR_MISC_THREAD_H #include <algorithm> #include <cmath> #include <stdexcept> namespace pMR { // ?!?! void splitThreadsIntoGangs(); template<typename T, typename W> void splitWorkToThreads(W const start, W const end, T const threadID, T const threadCount, W &threadStart, W &threadEnd, W const granularity = 1); } template<typename T, typename W> void pMR::splitWorkToThreads(W const start, W const end, T const threadID, T const threadCount, W &threadStart, W &threadEnd, W const granularity) { threadStart = start; threadEnd = end; if(end - start == 0) { return; } if(!(threadCount > 0)) { throw std::logic_error("Thread Count"); } if(threadID >= threadCount || threadID < 0) { throw std::out_of_range("Thread ID"); } W perThread = static_cast<W>( std::ceil( (static_cast<double>(end - start) / granularity) / threadCount) * granularity); threadStart += threadID * perThread; threadEnd = threadStart; W usedThreads = (end - start) / perThread; if(threadID < usedThreads) { threadEnd += perThread; } else { if(threadID == usedThreads) { threadEnd += (end - start) - usedThreads * perThread; } } } #endif // pMR_MISC_THREAD_H <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vclxtopwindow.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2007-11-02 12:14:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_toolkit.hxx" #ifndef _COM_SUN_STAR_LANG_SYSTEMDEPENDENT_HPP_ #include <com/sun/star/lang/SystemDependent.hpp> #endif #ifndef _COM_SUN_STAR_AWT_SYSTEMDEPENDENTXWINDOW_HPP_ #include <com/sun/star/awt/SystemDependentXWindow.hpp> #endif #if !defined(UNX) && !defined(OS2) #include <tools/prewin.h> #include <windows.h> #include <tools/postwin.h> #endif #include <vcl/syschild.hxx> #include <vcl/sysdata.hxx> #include <cppuhelper/typeprovider.hxx> #include <toolkit/awt/vclxtopwindow.hxx> #include <toolkit/awt/vclxmenu.hxx> #include <toolkit/helper/macros.hxx> #include <vcl/wrkwin.hxx> #include <vcl/syswin.hxx> #include <vcl/menu.hxx> #include <tools/debug.hxx> // ---------------------------------------------------- // class VCLXTopWindow // ---------------------------------------------------- VCLXTopWindow::VCLXTopWindow(bool bWHWND) : m_bWHWND(bWHWND) { } VCLXTopWindow::~VCLXTopWindow() { } // ::com::sun::star::uno::XInterface ::com::sun::star::uno::Any VCLXTopWindow::queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { ::com::sun::star::uno::Any aRet; if(! m_bWHWND) { aRet = ::cppu::queryInterface( rType, SAL_STATIC_CAST( ::com::sun::star::awt::XTopWindow*, this ) ); } else { aRet = ::cppu::queryInterface( rType, SAL_STATIC_CAST( ::com::sun::star::awt::XTopWindow*, this ), SAL_STATIC_CAST( ::com::sun::star::awt::XSystemDependentWindowPeer*, this ) ); } return (aRet.hasValue() ? aRet : VCLXContainer::queryInterface( rType )); } ::com::sun::star::uno::Sequence< sal_Int8 > VCLXTopWindow::getImplementationId() throw(::com::sun::star::uno::RuntimeException) { static ::cppu::OImplementationId* pId = NULL; static ::cppu::OImplementationId* pIdWithHandle = NULL; if ( m_bWHWND ) { if( !pIdWithHandle ) { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); if( !pIdWithHandle ) { static ::cppu::OImplementationId idWithHandle( sal_False ); pIdWithHandle = &idWithHandle; } } return (*pIdWithHandle).getImplementationId(); } else { if( !pId ) { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); if( !pId ) { static ::cppu::OImplementationId id( sal_False ); pId = &id; } } return (*pId).getImplementationId(); } } ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > VCLXTopWindow::getTypes() throw(::com::sun::star::uno::RuntimeException) { static ::cppu::OTypeCollection* pCollection = NULL; static ::cppu::OTypeCollection* pCollectionWithHandle = NULL; if ( m_bWHWND ) { if( !pCollectionWithHandle ) { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); if( !pCollectionWithHandle ) { static ::cppu::OTypeCollection collectionWithHandle( getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider>* ) NULL ), getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindow>* ) NULL ), getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XSystemDependentWindowPeer>* ) NULL ), VCLXContainer::getTypes() ); pCollectionWithHandle = &collectionWithHandle; } } return (*pCollectionWithHandle).getTypes(); } else { if( !pCollection ) { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); if( !pCollection ) { static ::cppu::OTypeCollection collection( getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider>* ) NULL ), getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindow>* ) NULL ), VCLXContainer::getTypes() ); pCollection = &collection; } } return (*pCollection).getTypes(); } } ::com::sun::star::uno::Any VCLXTopWindow::getWindowHandle( const ::com::sun::star::uno::Sequence< sal_Int8 >& /*ProcessId*/, sal_Int16 SystemType ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); // TODO, check the process id ::com::sun::star::uno::Any aRet; Window* pWindow = GetWindow(); if ( pWindow ) { const SystemEnvData* pSysData = ((SystemWindow *)pWindow)->GetSystemData(); if( pSysData ) { #if (defined WNT) if( SystemType == ::com::sun::star::lang::SystemDependent::SYSTEM_WIN32 ) { aRet <<= (sal_Int32)pSysData->hWnd; } #elif (defined OS2) if( SystemType == ::com::sun::star::lang::SystemDependent::SYSTEM_OS2 ) { aRet <<= (sal_Int32)pSysData->hWnd; } #elif (defined QUARTZ) if( SystemType == ::com::sun::star::lang::SystemDependent::SYSTEM_MAC ) { aRet <<= (sal_IntPtr)pSysData->rWindow; } #elif (defined UNX) if( SystemType == ::com::sun::star::lang::SystemDependent::SYSTEM_XWINDOW ) { ::com::sun::star::awt::SystemDependentXWindow aSD; aSD.DisplayPointer = sal::static_int_cast< sal_Int64 >(reinterpret_cast< sal_IntPtr >(pSysData->pDisplay)); aSD.WindowHandle = pSysData->aWindow; aRet <<= aSD; } #endif } } return aRet; } void VCLXTopWindow::addTopWindowListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindowListener >& rxListener ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); GetTopWindowListeners().addInterface( rxListener ); } void VCLXTopWindow::removeTopWindowListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindowListener >& rxListener ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); GetTopWindowListeners().removeInterface( rxListener ); } void VCLXTopWindow::toFront( ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); Window* pWindow = GetWindow(); if ( pWindow ) ((WorkWindow*)pWindow)->ToTop( TOTOP_RESTOREWHENMIN ); } void VCLXTopWindow::toBack( ) throw(::com::sun::star::uno::RuntimeException) { /* Not possible in VCL... ::vos::OGuard aGuard( GetMutex() ); Window* pWindow = GetWindow(); if ( pWindow ) { ((WorkWindow*)pWindow)->ToBack(); } */ } void VCLXTopWindow::setMenuBar( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XMenuBar >& rxMenu ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); SystemWindow* pWindow = (SystemWindow*) GetWindow(); if ( pWindow ) { pWindow->SetMenuBar( NULL ); if ( rxMenu.is() ) { VCLXMenu* pMenu = VCLXMenu::GetImplementation( rxMenu ); if ( pMenu && !pMenu->IsPopupMenu() ) pWindow->SetMenuBar( (MenuBar*) pMenu->GetMenu() ); } } mxMenuBar = rxMenu; } <commit_msg>INTEGRATION: CWS macosxquicktime01 (1.9.42); FILE MERGED 2007/10/26 08:29:45 pl 1.9.42.1: #i82621# changed SystemEnvData and SystemParentData for QUARTZ<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vclxtopwindow.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2007-12-07 11:40:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_toolkit.hxx" #ifndef _COM_SUN_STAR_LANG_SYSTEMDEPENDENT_HPP_ #include <com/sun/star/lang/SystemDependent.hpp> #endif #ifndef _COM_SUN_STAR_AWT_SYSTEMDEPENDENTXWINDOW_HPP_ #include <com/sun/star/awt/SystemDependentXWindow.hpp> #endif #if !defined(UNX) && !defined(OS2) #include <tools/prewin.h> #include <windows.h> #include <tools/postwin.h> #endif #ifdef QUARTZ #include "premac.h" #include <Cocoa/Cocoa.h> #include "postmac.h" #endif #include <vcl/syschild.hxx> #include <vcl/sysdata.hxx> #include <cppuhelper/typeprovider.hxx> #include <toolkit/awt/vclxtopwindow.hxx> #include <toolkit/awt/vclxmenu.hxx> #include <toolkit/helper/macros.hxx> #include <vcl/wrkwin.hxx> #include <vcl/syswin.hxx> #include <vcl/menu.hxx> #include <tools/debug.hxx> // ---------------------------------------------------- // class VCLXTopWindow // ---------------------------------------------------- VCLXTopWindow::VCLXTopWindow(bool bWHWND) : m_bWHWND(bWHWND) { } VCLXTopWindow::~VCLXTopWindow() { } // ::com::sun::star::uno::XInterface ::com::sun::star::uno::Any VCLXTopWindow::queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { ::com::sun::star::uno::Any aRet; if(! m_bWHWND) { aRet = ::cppu::queryInterface( rType, SAL_STATIC_CAST( ::com::sun::star::awt::XTopWindow*, this ) ); } else { aRet = ::cppu::queryInterface( rType, SAL_STATIC_CAST( ::com::sun::star::awt::XTopWindow*, this ), SAL_STATIC_CAST( ::com::sun::star::awt::XSystemDependentWindowPeer*, this ) ); } return (aRet.hasValue() ? aRet : VCLXContainer::queryInterface( rType )); } ::com::sun::star::uno::Sequence< sal_Int8 > VCLXTopWindow::getImplementationId() throw(::com::sun::star::uno::RuntimeException) { static ::cppu::OImplementationId* pId = NULL; static ::cppu::OImplementationId* pIdWithHandle = NULL; if ( m_bWHWND ) { if( !pIdWithHandle ) { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); if( !pIdWithHandle ) { static ::cppu::OImplementationId idWithHandle( sal_False ); pIdWithHandle = &idWithHandle; } } return (*pIdWithHandle).getImplementationId(); } else { if( !pId ) { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); if( !pId ) { static ::cppu::OImplementationId id( sal_False ); pId = &id; } } return (*pId).getImplementationId(); } } ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > VCLXTopWindow::getTypes() throw(::com::sun::star::uno::RuntimeException) { static ::cppu::OTypeCollection* pCollection = NULL; static ::cppu::OTypeCollection* pCollectionWithHandle = NULL; if ( m_bWHWND ) { if( !pCollectionWithHandle ) { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); if( !pCollectionWithHandle ) { static ::cppu::OTypeCollection collectionWithHandle( getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider>* ) NULL ), getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindow>* ) NULL ), getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XSystemDependentWindowPeer>* ) NULL ), VCLXContainer::getTypes() ); pCollectionWithHandle = &collectionWithHandle; } } return (*pCollectionWithHandle).getTypes(); } else { if( !pCollection ) { ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); if( !pCollection ) { static ::cppu::OTypeCollection collection( getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider>* ) NULL ), getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindow>* ) NULL ), VCLXContainer::getTypes() ); pCollection = &collection; } } return (*pCollection).getTypes(); } } ::com::sun::star::uno::Any VCLXTopWindow::getWindowHandle( const ::com::sun::star::uno::Sequence< sal_Int8 >& /*ProcessId*/, sal_Int16 SystemType ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); // TODO, check the process id ::com::sun::star::uno::Any aRet; Window* pWindow = GetWindow(); if ( pWindow ) { const SystemEnvData* pSysData = ((SystemWindow *)pWindow)->GetSystemData(); if( pSysData ) { #if (defined WNT) if( SystemType == ::com::sun::star::lang::SystemDependent::SYSTEM_WIN32 ) { aRet <<= (sal_Int32)pSysData->hWnd; } #elif (defined OS2) if( SystemType == ::com::sun::star::lang::SystemDependent::SYSTEM_OS2 ) { aRet <<= (sal_Int32)pSysData->hWnd; } #elif (defined QUARTZ) if( SystemType == ::com::sun::star::lang::SystemDependent::SYSTEM_MAC ) { aRet <<= (sal_IntPtr)pSysData->pView; } #elif (defined UNX) if( SystemType == ::com::sun::star::lang::SystemDependent::SYSTEM_XWINDOW ) { ::com::sun::star::awt::SystemDependentXWindow aSD; aSD.DisplayPointer = sal::static_int_cast< sal_Int64 >(reinterpret_cast< sal_IntPtr >(pSysData->pDisplay)); aSD.WindowHandle = pSysData->aWindow; aRet <<= aSD; } #endif } } return aRet; } void VCLXTopWindow::addTopWindowListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindowListener >& rxListener ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); GetTopWindowListeners().addInterface( rxListener ); } void VCLXTopWindow::removeTopWindowListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindowListener >& rxListener ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); GetTopWindowListeners().removeInterface( rxListener ); } void VCLXTopWindow::toFront( ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); Window* pWindow = GetWindow(); if ( pWindow ) ((WorkWindow*)pWindow)->ToTop( TOTOP_RESTOREWHENMIN ); } void VCLXTopWindow::toBack( ) throw(::com::sun::star::uno::RuntimeException) { /* Not possible in VCL... ::vos::OGuard aGuard( GetMutex() ); Window* pWindow = GetWindow(); if ( pWindow ) { ((WorkWindow*)pWindow)->ToBack(); } */ } void VCLXTopWindow::setMenuBar( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XMenuBar >& rxMenu ) throw(::com::sun::star::uno::RuntimeException) { ::vos::OGuard aGuard( GetMutex() ); SystemWindow* pWindow = (SystemWindow*) GetWindow(); if ( pWindow ) { pWindow->SetMenuBar( NULL ); if ( rxMenu.is() ) { VCLXMenu* pMenu = VCLXMenu::GetImplementation( rxMenu ); if ( pMenu && !pMenu->IsPopupMenu() ) pWindow->SetMenuBar( (MenuBar*) pMenu->GetMenu() ); } } mxMenuBar = rxMenu; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2017 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "cql3/statements/index_target.hh" #include <boost/algorithm/string/predicate.hpp> #include <regex> namespace secondary_index { struct target_parser { static std::pair<const column_definition*, cql3::statements::index_target::target_type> parse(schema_ptr schema, const index_metadata& im) { sstring target = im.options().at(cql3::statements::index_target::target_option_name); auto result = parse(schema, target); if (!result) { throw exceptions::configuration_exception(sprint("Unable to parse targets for index %s (%s)", im.name(), target)); } return *result; } static stdx::optional<std::pair<const column_definition*, cql3::statements::index_target::target_type>> parse(schema_ptr schema, const sstring& target) { using namespace cql3::statements; // if the regex matches then the target is in the form "keys(foo)", "entries(bar)" etc // if not, then it must be a simple column name and implictly its type is VALUES sstring column_name; index_target::target_type target_type; static const std::regex target_regex("^(keys|entries|values|full)\\((.+)\\)$"); std::cmatch match; if (std::regex_match(target.data(), match, target_regex)) { target_type = index_target::from_sstring(match[1].str()); column_name = match[2].str(); } else { column_name = target; target_type = index_target::target_type::values; } // in the case of a quoted column name the name in the target string // will be enclosed in quotes, which we need to unwrap. It may also // include quote characters internally, escaped like so: // abc"def -> abc""def. // Because the target string is stored in a CQL compatible form, we // need to un-escape any such quotes to get the actual column name static const sstring quote{"\""}; if (boost::starts_with(target, quote)) { column_name = column_name.substr(1, column_name.length()-2); static const std::regex two_quotes("\"\""); column_name = std::regex_replace(std::string{column_name}, two_quotes, std::string{quote}); } auto column = schema->get_column_definition(utf8_type->decompose(column_name)); if (!column) { return stdx::nullopt; } return std::make_pair(column, target_type); } }; } <commit_msg>secondary index: clean up dead unquoting code<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2017 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "cql3/statements/index_target.hh" #include <boost/algorithm/string/predicate.hpp> #include <regex> namespace secondary_index { struct target_parser { static std::pair<const column_definition*, cql3::statements::index_target::target_type> parse(schema_ptr schema, const index_metadata& im) { sstring target = im.options().at(cql3::statements::index_target::target_option_name); auto result = parse(schema, target); if (!result) { throw exceptions::configuration_exception(sprint("Unable to parse targets for index %s (%s)", im.name(), target)); } return *result; } static stdx::optional<std::pair<const column_definition*, cql3::statements::index_target::target_type>> parse(schema_ptr schema, const sstring& target) { using namespace cql3::statements; // if the regex matches then the target is in the form "keys(foo)", "entries(bar)" etc // if not, then it must be a simple column name and implictly its type is VALUES sstring column_name; index_target::target_type target_type; static const std::regex target_regex("^(keys|entries|values|full)\\((.+)\\)$"); std::cmatch match; if (std::regex_match(target.data(), match, target_regex)) { target_type = index_target::from_sstring(match[1].str()); column_name = match[2].str(); } else { column_name = target; target_type = index_target::target_type::values; } auto column = schema->get_column_definition(utf8_type->decompose(column_name)); if (!column) { return stdx::nullopt; } return std::make_pair(column, target_type); } }; } <|endoftext|>
<commit_before>/** * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "Curl.h" #include "CurlVersionInfo.h" #include "Easy.h" #include "Http2PushFrameHeaders.h" #include "Multi.h" #include "Share.h" #include <curl/curl.h> #include <nan.h> #include <node.h> #include <iostream> namespace NodeLibcurl { static void AtExitCallback(void* arg) { (void)arg; curl_global_cleanup(); } NAN_MODULE_INIT(Init) { // Some background story on this commented code and other usages of setlocale // elsewhere on the addon: Libcurl, when built with libidn2, calls function // `idn2_lookup_ul` to retrieve a punycode representation // of a domain. This function internally uses libunistring // `u8_strconv_from_encoding`, which expects an existing locale being set: // https://github.com/libidn/libidn2/blob/02a3127d21f8a99042a8ae82f1513b3ffc0170f2/lib/lookup.c#L536 // Node.js (correctly) does not set any locale by default, and so when this // function gets called // an error is returned, and libcurl bails out with MALFORMED URL error. // We could just call setlocale here, like the commented code, and it would // work, however this would // impact addon users that, in some way, use locale. // (I've opened this issue to make sure // https://github.com/nodejs/help/issues/1878) Instead of doing that, we are // instead calling setlocale on some specific parts of the code, to be // more specific, on Easy#SetPerform, Multi#AddHandle and Multi#OnSocket // That code is behind a DEFINE guard, which the user can disable by passing // `node_libcurl_no_setlocale` option when building, this will define // NODE_LIBCURL_NO_SETLOCALE. // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setlocale-wsetlocale?view=vs-2019 // setlocale(AC_ALL, "") Initialize(target); Easy::Initialize(target); Multi::Initialize(target); Share::Initialize(target); CurlVersionInfo::Initialize(target); Http2PushFrameHeaders::Initialize(target); // this will stay until Node.js v10 support is dropped // after this happens we will be able to get the environment by running // node::GetCurrentEnvironment #pragma GCC diagnostic ignored "-Wdeprecated-declarations" node::AtExit(AtExitCallback, NULL); #pragma GCC diagnostic pop } NODE_MODULE(node_libcurl, Init); } // namespace NodeLibcurl <commit_msg>fix: support Node.js v16<commit_after>/** * Copyright (c) Jonathan Cardoso Machado. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "Curl.h" #include "CurlVersionInfo.h" #include "Easy.h" #include "Http2PushFrameHeaders.h" #include "Multi.h" #include "Share.h" #include <curl/curl.h> #include <nan.h> #include <node.h> #include <iostream> namespace NodeLibcurl { static void AtExitCallback(void* arg) { (void)arg; curl_global_cleanup(); } NAN_MODULE_INIT(Init) { // Some background story on this commented code and other usages of setlocale // elsewhere on the addon: Libcurl, when built with libidn2, calls function // `idn2_lookup_ul` to retrieve a punycode representation // of a domain. This function internally uses libunistring // `u8_strconv_from_encoding`, which expects an existing locale being set: // https://github.com/libidn/libidn2/blob/02a3127d21f8a99042a8ae82f1513b3ffc0170f2/lib/lookup.c#L536 // Node.js (correctly) does not set any locale by default, and so when this // function gets called // an error is returned, and libcurl bails out with MALFORMED URL error. // We could just call setlocale here, like the commented code, and it would // work, however this would // impact addon users that, in some way, use locale. // (I've opened this issue to make sure // https://github.com/nodejs/help/issues/1878) Instead of doing that, we are // instead calling setlocale on some specific parts of the code, to be // more specific, on Easy#SetPerform, Multi#AddHandle and Multi#OnSocket // That code is behind a DEFINE guard, which the user can disable by passing // `node_libcurl_no_setlocale` option when building, this will define // NODE_LIBCURL_NO_SETLOCALE. // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setlocale-wsetlocale?view=vs-2019 // setlocale(AC_ALL, "") Initialize(target); Easy::Initialize(target); Multi::Initialize(target); Share::Initialize(target); CurlVersionInfo::Initialize(target); Http2PushFrameHeaders::Initialize(target); #if NODE_VERSION_AT_LEAST(11, 0, 0) auto context = Nan::GetCurrentContext(); node::AtExit(node::GetCurrentEnvironment(context), AtExitCallback, NULL); #else // this will stay until Node.js v10 support is dropped #pragma GCC diagnostic ignored "-Wdeprecated-declarations" node::AtExit(AtExitCallback, NULL); #pragma GCC diagnostic pop #endif } NODE_MODULE(node_libcurl, Init); } // namespace NodeLibcurl <|endoftext|>
<commit_before>#ifndef INTERPOLATOR_HPP #define INTERPOLATOR_HPP #include <cmath> #include <list> #include <time.h> #include <sys/time.h> #include "InterpolatorInfo.hpp" #include "MovementQuadruple.hpp" #include "Position6DOF.hpp" #include "ros/ros.h" #include "../matlab/profiling.hpp" x #define MAX_NUMBER_QUADCOPTER_HIGH 10 // TODO equals MAX_NUMBER_QUADCOPTER #define MIN_TIME_TO_WAIT 500000000 // in ns, only for rpy-values #define PREDICT_FUTURE_POSITION_TIME 200000000 // in ns #define PREDICT_FUTURE_POSITION_STEPS 1 // Interpolate with ? number of latest positions (unused) #define ROTATIONAL_CORRECTION 0 // 0-no correction; 1-always take new value; linear in between wouldn't work #define POSITIONED_NORTH_AT_START 0 // 0 or 1, used as bool, North means pitch+ -> y+ #define REACHING_TARGET_DIFF 0.6 // Factor 0 <= x <= 1 #define REACHING_HEIGHT_DIFF 0.6 // Factor 0 <= x <= 1 #define SPEED_MIN_INCLINING 150 // in mm/s #define SPEED_MAX_INCLINING 500 // in mm/s #define SPEED_MIN_DECLINING -150 // in mm/s #define SPEED_MAX_DECLINING -500 // in mm/s #define SPEED_MIN_PLANE 80 // in mm/s #define SPEED_MAX_PLANE 300 // in mm/s #define DISTANCE_CLOSE_TO_TARGET 50 // in mm /* * TODO hold * TODO test of speed, either optimize or save data-to-sent in advance * * TODO list future movement - fix * TODO use of timestamps * */ class Interpolator { public: Interpolator(); MovementQuadruple calibrate(int id, std::list<MovementQuadruple> sentQuadruples); MovementQuadruple calculateNextMQ(std::list<MovementQuadruple> sentQuadruples, std::list<Position6DOF> positions, Position6DOF target, int id); protected: void checkState( int id ); private: InterpolatorInfo status[MAX_NUMBER_QUADCOPTER_HIGH]; double stepSizeOfChange; // depends on the distance of position to target long int timeDiff1; long int timeDiff2; long int timeDiff3; }; #endif // INTERPOLATOR_HPP <commit_msg>Interpolator - TODOs<commit_after>#ifndef INTERPOLATOR_HPP #define INTERPOLATOR_HPP #include <cmath> #include <list> #include <time.h> #include <sys/time.h> #include "InterpolatorInfo.hpp" #include "MovementQuadruple.hpp" #include "Position6DOF.hpp" #include "ros/ros.h" #include "../matlab/profiling.hpp" x #define MAX_NUMBER_QUADCOPTER_HIGH 10 // TODO equals MAX_NUMBER_QUADCOPTER #define MIN_TIME_TO_WAIT 500000000 // in ns, only for rpy-values #define PREDICT_FUTURE_POSITION_TIME 200000000 // in ns #define PREDICT_FUTURE_POSITION_STEPS 1 // Interpolate with ? number of latest positions (unused) #define ROTATIONAL_CORRECTION 0 // 0-no correction; 1-always take new value; linear in between wouldn't work #define POSITIONED_NORTH_AT_START 0 // 0 or 1, used as bool, North means pitch+ -> y+ #define REACHING_TARGET_DIFF 0.6 // Factor 0 <= x <= 1 #define REACHING_HEIGHT_DIFF 0.6 // Factor 0 <= x <= 1 #define SPEED_MIN_INCLINING 150 // in mm/s #define SPEED_MAX_INCLINING 500 // in mm/s #define SPEED_MIN_DECLINING -150 // in mm/s #define SPEED_MAX_DECLINING -500 // in mm/s #define SPEED_MIN_PLANE 80 // in mm/s #define SPEED_MAX_PLANE 300 // in mm/s #define DISTANCE_CLOSE_TO_TARGET 50 // in mm /* * TODO test of speed, either optimize or save data-to-sent in advance * * TODO list future movement - fix * TODO use of timestamps * TODO ROS_INFO, ROS_WARN, ROS_ERROR, ROS_DEBUG - correct use * TODO flight of circles, rotation, ... * * TODO hold * */ class Interpolator { public: Interpolator(); MovementQuadruple calibrate(int id, std::list<MovementQuadruple> sentQuadruples); MovementQuadruple calculateNextMQ(std::list<MovementQuadruple> sentQuadruples, std::list<Position6DOF> positions, Position6DOF target, int id); protected: void checkState( int id ); private: InterpolatorInfo status[MAX_NUMBER_QUADCOPTER_HIGH]; double stepSizeOfChange; // depends on the distance of position to target long int timeDiff1; long int timeDiff2; long int timeDiff3; }; #endif // INTERPOLATOR_HPP <|endoftext|>
<commit_before>#include "oddlib/path.hpp" #include "oddlib/stream.hpp" #include "logger.hpp" #include <array> namespace Oddlib { Path::Path( IStream& pathChunkStream, Uint32 collisionDataOffset, Uint32 objectIndexTableOffset, Uint32 objectDataOffset, Uint32 mapXSize, Uint32 mapYSize, bool isAo) : mXSize(mapXSize), mYSize(mapYSize), mIsAo(isAo) { TRACE_ENTRYEXIT; ReadCameraMap(pathChunkStream); if (collisionDataOffset != 0) { const auto numCollisionDataBytes = objectDataOffset - collisionDataOffset; const auto numCollisionItems = numCollisionDataBytes / sizeof(CollisionItem); ReadCollisionItems(pathChunkStream, numCollisionItems); ReadMapObjects(pathChunkStream, objectIndexTableOffset); } } Uint32 Path::XSize() const { return mXSize; } Uint32 Path::YSize() const { return mYSize; } const Path::Camera& Path::CameraByPosition(Uint32 x, Uint32 y) const { if (x >= XSize() || y >= YSize()) { LOG_ERROR("Out of bounds x:y" << std::to_string(x) << " " << std::to_string(y) <<" vs " << std::to_string(XSize()) << " " << std::to_string(YSize())); } return mCameras[(y * XSize()) + x]; } void Path::ReadCameraMap(IStream& stream) { const Uint32 numberOfCameras = XSize() * YSize(); mCameras.reserve(numberOfCameras); std::array<Uint8, 8> nameBuffer; for (Uint32 i = 0; i < numberOfCameras; i++) { stream.ReadBytes(nameBuffer.data(), nameBuffer.size()); std::string tmpStr(reinterpret_cast<const char*>(nameBuffer.data()), nameBuffer.size()); if (tmpStr[0] != 0) { tmpStr += ".CAM"; } mCameras.emplace_back(Camera(std::move(tmpStr))); } } void Path::ReadCollisionItems(IStream& stream, Uint32 numberOfCollisionItems) { for (Uint32 i = 0; i < numberOfCollisionItems; i++) { CollisionItem tmp = {}; stream.ReadUInt16(tmp.mP1.mX); stream.ReadUInt16(tmp.mP1.mY); stream.ReadUInt16(tmp.mP2.mX); stream.ReadUInt16(tmp.mP2.mY); stream.ReadUInt16(tmp.mType); for (int j = 0; j < 4; j++) { stream.ReadUInt16(tmp.mUnknown[j]); } stream.ReadUInt16(tmp.mLineLength); mCollisionItems.emplace_back(tmp); } } void Path::ReadMapObjects(IStream& stream, Uint32 objectIndexTableOffset) { const size_t collisionEnd = stream.Pos(); // TODO -16 is for the chunk header, probably shouldn't have this already included in the // pathdb, may also apply to collision info stream.Seek(objectIndexTableOffset-16); // Read the pointers to the object list for each camera const Uint32 numberOfCameras = XSize() * YSize(); std::vector<Uint32> cameraObjectOffsets; cameraObjectOffsets.reserve(numberOfCameras); for (Uint32 i = 0; i < numberOfCameras; i++) { Uint32 offset = 0; stream.ReadUInt32(offset); cameraObjectOffsets.push_back(offset); } // Now load the objects for each camera for (auto i = 0u; i < cameraObjectOffsets.size(); i++) { // If max Uint32/-1 then it means there are no objects for this camera const auto objectsOffset = cameraObjectOffsets[i]; if (objectsOffset != 0xFFFFFFFF) { stream.Seek(collisionEnd + objectsOffset); for (;;) { MapObject mapObject; stream.ReadUInt16(mapObject.mFlags); stream.ReadUInt16(mapObject.mLength); stream.ReadUInt32(mapObject.mType); LOG_INFO("Object TLV: " << mapObject.mType << " " << mapObject.mLength << " " << mapObject.mLength); if (mIsAo) { // Don't know what this is for Uint32 unknownData = 0; stream.ReadUInt32(unknownData); } stream.ReadUInt16(mapObject.mRectTopLeft.mX); stream.ReadUInt16(mapObject.mRectTopLeft.mY); // Ao duplicated the first two parts of data for some reason if (mIsAo) { Uint32 duplicatedXY = 0; stream.ReadUInt32(duplicatedXY); } stream.ReadUInt16(mapObject.mRectBottomRight.mX); stream.ReadUInt16(mapObject.mRectBottomRight.mY); if (mapObject.mLength > 0) { const Uint32 len = mapObject.mLength - (sizeof(Uint16) * (mIsAo ? 12 : 8)); if (len > 512) { LOG_ERROR("Map object data length " << mapObject.mLength << " is larger than fixed size"); abort(); } stream.ReadBytes(mapObject.mData.data(), len); } mCameras[i].mObjects.emplace_back(mapObject); if (mapObject.mFlags & 0x4) { break; } } } } } }<commit_msg>build fix<commit_after>#include "oddlib/path.hpp" #include "oddlib/stream.hpp" #include "logger.hpp" #include <array> namespace Oddlib { Path::Path( IStream& pathChunkStream, Uint32 collisionDataOffset, Uint32 objectIndexTableOffset, Uint32 objectDataOffset, Uint32 mapXSize, Uint32 mapYSize, bool isAo) : mXSize(mapXSize), mYSize(mapYSize), mIsAo(isAo) { TRACE_ENTRYEXIT; ReadCameraMap(pathChunkStream); if (collisionDataOffset != 0) { const Uint32 numCollisionDataBytes = objectDataOffset - collisionDataOffset; const Uint32 numCollisionItems = numCollisionDataBytes / sizeof(CollisionItem); ReadCollisionItems(pathChunkStream, numCollisionItems); ReadMapObjects(pathChunkStream, objectIndexTableOffset); } } Uint32 Path::XSize() const { return mXSize; } Uint32 Path::YSize() const { return mYSize; } const Path::Camera& Path::CameraByPosition(Uint32 x, Uint32 y) const { if (x >= XSize() || y >= YSize()) { LOG_ERROR("Out of bounds x:y" << std::to_string(x) << " " << std::to_string(y) <<" vs " << std::to_string(XSize()) << " " << std::to_string(YSize())); } return mCameras[(y * XSize()) + x]; } void Path::ReadCameraMap(IStream& stream) { const Uint32 numberOfCameras = XSize() * YSize(); mCameras.reserve(numberOfCameras); std::array<Uint8, 8> nameBuffer; for (Uint32 i = 0; i < numberOfCameras; i++) { stream.ReadBytes(nameBuffer.data(), nameBuffer.size()); std::string tmpStr(reinterpret_cast<const char*>(nameBuffer.data()), nameBuffer.size()); if (tmpStr[0] != 0) { tmpStr += ".CAM"; } mCameras.emplace_back(Camera(std::move(tmpStr))); } } void Path::ReadCollisionItems(IStream& stream, Uint32 numberOfCollisionItems) { for (Uint32 i = 0; i < numberOfCollisionItems; i++) { CollisionItem tmp = {}; stream.ReadUInt16(tmp.mP1.mX); stream.ReadUInt16(tmp.mP1.mY); stream.ReadUInt16(tmp.mP2.mX); stream.ReadUInt16(tmp.mP2.mY); stream.ReadUInt16(tmp.mType); for (int j = 0; j < 4; j++) { stream.ReadUInt16(tmp.mUnknown[j]); } stream.ReadUInt16(tmp.mLineLength); mCollisionItems.emplace_back(tmp); } } void Path::ReadMapObjects(IStream& stream, Uint32 objectIndexTableOffset) { const size_t collisionEnd = stream.Pos(); // TODO -16 is for the chunk header, probably shouldn't have this already included in the // pathdb, may also apply to collision info stream.Seek(objectIndexTableOffset-16); // Read the pointers to the object list for each camera const Uint32 numberOfCameras = XSize() * YSize(); std::vector<Uint32> cameraObjectOffsets; cameraObjectOffsets.reserve(numberOfCameras); for (Uint32 i = 0; i < numberOfCameras; i++) { Uint32 offset = 0; stream.ReadUInt32(offset); cameraObjectOffsets.push_back(offset); } // Now load the objects for each camera for (auto i = 0u; i < cameraObjectOffsets.size(); i++) { // If max Uint32/-1 then it means there are no objects for this camera const auto objectsOffset = cameraObjectOffsets[i]; if (objectsOffset != 0xFFFFFFFF) { stream.Seek(collisionEnd + objectsOffset); for (;;) { MapObject mapObject; stream.ReadUInt16(mapObject.mFlags); stream.ReadUInt16(mapObject.mLength); stream.ReadUInt32(mapObject.mType); LOG_INFO("Object TLV: " << mapObject.mType << " " << mapObject.mLength << " " << mapObject.mLength); if (mIsAo) { // Don't know what this is for Uint32 unknownData = 0; stream.ReadUInt32(unknownData); } stream.ReadUInt16(mapObject.mRectTopLeft.mX); stream.ReadUInt16(mapObject.mRectTopLeft.mY); // Ao duplicated the first two parts of data for some reason if (mIsAo) { Uint32 duplicatedXY = 0; stream.ReadUInt32(duplicatedXY); } stream.ReadUInt16(mapObject.mRectBottomRight.mX); stream.ReadUInt16(mapObject.mRectBottomRight.mY); if (mapObject.mLength > 0) { const Uint32 len = mapObject.mLength - (sizeof(Uint16) * (mIsAo ? 12 : 8)); if (len > 512) { LOG_ERROR("Map object data length " << mapObject.mLength << " is larger than fixed size"); abort(); } stream.ReadBytes(mapObject.mData.data(), len); } mCameras[i].mObjects.emplace_back(mapObject); if (mapObject.mFlags & 0x4) { break; } } } } } }<|endoftext|>
<commit_before>#include <cassert> #include <algorithm> #include "pointer.hpp" #include "surface-map-state.hpp" #include "wayfire/signal-definitions.hpp" #include "../core-impl.hpp" #include "../../output/output-impl.hpp" #include "touch.hpp" #include "keyboard.hpp" #include "cursor.hpp" #include "input-manager.hpp" #include "wayfire/output-layout.hpp" #include "wayfire/workspace-manager.hpp" #include <wayfire/util/log.hpp> #include <wayfire/debug.hpp> #include "switch.hpp" #include "tablet.hpp" #include "pointing-device.hpp" static std::unique_ptr<wf::input_device_impl_t> create_wf_device_for_device( wlr_input_device *device) { switch (device->type) { case WLR_INPUT_DEVICE_SWITCH: return std::make_unique<wf::switch_device_t>(device); case WLR_INPUT_DEVICE_POINTER: return std::make_unique<wf::pointing_device_t>(device); case WLR_INPUT_DEVICE_TABLET_TOOL: return std::make_unique<wf::tablet_t>( wf::get_core_impl().seat->cursor->cursor, device); case WLR_INPUT_DEVICE_TABLET_PAD: return std::make_unique<wf::tablet_pad_t>(device); default: return std::make_unique<wf::input_device_impl_t>(device); } } void wf::input_manager_t::handle_new_input(wlr_input_device *dev) { LOGI("handle new input: ", dev->name, ", default mapping: ", dev->output_name); input_devices.push_back(create_wf_device_for_device(dev)); wf::input_device_signal data; data.device = nonstd::make_observer(input_devices.back().get()); wf::get_core().emit_signal("input-device-added", &data); refresh_device_mappings(); } void wf::input_manager_t::refresh_device_mappings() { // Might trigger motion events which we want to avoid at other stages auto state = wf::get_core().get_current_state(); if (state != wf::compositor_state_t::RUNNING) { return; } auto cursor = wf::get_core().get_wlr_cursor(); for (auto& device : this->input_devices) { wlr_input_device *dev = device->get_wlr_handle(); auto section = wf::get_core().config_backend->get_input_device_section(dev); auto mapped_output = section->get_option("output")->get_value_str(); if (mapped_output.empty()) { mapped_output = nonull(dev->output_name); } auto wo = wf::get_core().output_layout->find_output(mapped_output); if (wo) { LOGD("Mapping input ", dev->name, " to output ", wo->to_string(), "."); wlr_cursor_map_input_to_output(cursor, dev, wo->handle); } } } void wf::input_manager_t::handle_input_destroyed(wlr_input_device *dev) { LOGI("remove input: ", dev->name); for (auto& device : input_devices) { if (device->get_wlr_handle() == dev) { wf::input_device_signal data; data.device = {device}; wf::get_core().emit_signal("input-device-removed", &data); } } auto it = std::remove_if(input_devices.begin(), input_devices.end(), [=] (const std::unique_ptr<wf::input_device_impl_t>& idev) { return idev->get_wlr_handle() == dev; }); input_devices.erase(it, input_devices.end()); } void load_locked_mods_from_config(xkb_mod_mask_t& locked_mods) { wf::option_wrapper_t<bool> numlock_state, capslock_state; numlock_state.load_option("input/kb_numlock_default_state"); capslock_state.load_option("input/kb_capslock_default_state"); if (numlock_state) { locked_mods |= wf::KB_MOD_NUM_LOCK; } if (capslock_state) { locked_mods |= wf::KB_MOD_CAPS_LOCK; } } wf::input_manager_t::input_manager_t() { wf::pointing_device_t::config.load(); load_locked_mods_from_config(locked_mods); input_device_created.set_callback([&] (void *data) { auto dev = static_cast<wlr_input_device*>(data); assert(dev); handle_new_input(dev); }); input_device_created.connect(&wf::get_core().backend->events.new_input); config_updated = [=] (wf::signal_data_t*) { for (auto& dev : input_devices) { dev->update_options(); } }; wf::get_core().connect_signal("reload-config", &config_updated); output_added = [=] (wf::signal_data_t *data) { auto wo = (wf::output_impl_t*)get_signaled_output(data); if (exclusive_client != nullptr) { wo->inhibit_plugins(); } refresh_device_mappings(); }; wf::get_core().output_layout->connect_signal("output-added", &output_added); } wf::input_manager_t::~input_manager_t() { wf::get_core().disconnect_signal("reload-config", &config_updated); wf::get_core().output_layout->disconnect_signal( "output-added", &output_added); } bool wf::input_manager_t::grab_input(wf::plugin_grab_interface_t *iface) { if (!iface || !iface->is_grabbed()) { return false; } assert(!active_grab); // cannot have two active input grabs! auto& seat = wf::get_core_impl().seat; seat->touch->set_grab(iface); active_grab = iface; // TODO: move this to the seat via a signal? auto kbd = wlr_seat_get_keyboard(seat->seat); auto mods = kbd ? kbd->modifiers : wlr_keyboard_modifiers{0, 0, 0, 0}; mods.depressed = 0; wlr_seat_keyboard_send_modifiers(seat->seat, &mods); seat->set_keyboard_focus(nullptr); seat->lpointer->set_enable_focus(false); wf::get_core().set_cursor("default"); return true; } void wf::input_manager_t::ungrab_input() { active_grab = nullptr; if (wf::get_core().get_active_output()) { wf::get_core().set_active_view( wf::get_core().get_active_output()->get_active_view()); } /* We must update cursor focus, however, if we update "too soon", the current * pointer event (button press/release, maybe something else) will be sent to * the client, which shouldn't happen (at the time of the event, there was * still an active input grab) */ idle_update_cursor.run_once([&] () { auto& seat = wf::get_core_impl().seat; seat->touch->set_grab(nullptr); seat->lpointer->set_enable_focus(true); }); } bool wf::input_manager_t::input_grabbed() { return active_grab; } bool wf::input_manager_t::can_focus_surface(wf::surface_interface_t *surface) { if (exclusive_client && (surface->get_client() != exclusive_client)) { /* We have exclusive focus surface, for ex. a lockscreen. * The only kind of things we can focus are OSKs and similar */ auto view = (wf::view_interface_t*)surface->get_main_surface(); if (view && view->get_output()) { auto layer = view->get_output()->workspace->get_view_layer(view->self()); return layer == wf::LAYER_DESKTOP_WIDGET; } return false; } return true; } wf::surface_interface_t*wf::input_manager_t::input_surface_at( wf::pointf_t global, wf::pointf_t& local) { auto output = wf::get_core().output_layout->get_output_coords_at(global, global); /* If the output at these coordinates was just destroyed or some other edge case * */ if (!output) { return nullptr; } auto og = output->get_layout_geometry(); global.x -= og.x; global.y -= og.y; for (auto& v : output->workspace->get_views_in_layer(wf::VISIBLE_LAYERS)) { for (auto& view : v->enumerate_views()) { if (!view->minimized && view->is_visible() && can_focus_surface(view.get())) { auto surface = view->map_input_coordinates(global, local); if (surface) { return surface; } } } } return nullptr; } void wf::input_manager_t::set_exclusive_focus(wl_client *client) { exclusive_client = client; for (auto& wo : wf::get_core().output_layout->get_outputs()) { auto impl = (wf::output_impl_t*)wo; if (client) { impl->inhibit_plugins(); } else { impl->uninhibit_plugins(); } } /* We no longer have an exclusively focused client, so we should restore * focus to the topmost view */ if (!client) { wf::get_core().get_active_output()->refocus(nullptr); } } wf::bindings_repository_t& wf::input_manager_t::get_active_bindings() { auto wo = wf::get_core().get_active_output(); auto impl = dynamic_cast<wf::output_impl_t*>(wo); if (!impl) { static wf::bindings_repository_t dummy_repo{nullptr}; return dummy_repo; } return impl->get_bindings(); } wf::SurfaceMapStateListener::SurfaceMapStateListener() { on_surface_map_state_change = [=] (void *data) { if (this->callback) { auto ev = static_cast<surface_map_state_changed_signal*>(data); this->callback(ev ? ev->surface : nullptr); } }; wf::get_core().connect_signal("surface-mapped", &on_surface_map_state_change); wf::get_core().connect_signal("surface-unmapped", &on_surface_map_state_change); } wf::SurfaceMapStateListener::~SurfaceMapStateListener() { wf::get_core().disconnect_signal("surface-mapped", &on_surface_map_state_change); wf::get_core().disconnect_signal("surface-unmapped", &on_surface_map_state_change); } void wf::SurfaceMapStateListener::set_callback(Callback call) { this->callback = call; } <commit_msg>input-manager: map devices to no output if no entry in config file<commit_after>#include <cassert> #include <algorithm> #include "pointer.hpp" #include "surface-map-state.hpp" #include "wayfire/signal-definitions.hpp" #include "../core-impl.hpp" #include "../../output/output-impl.hpp" #include "touch.hpp" #include "keyboard.hpp" #include "cursor.hpp" #include "input-manager.hpp" #include "wayfire/output-layout.hpp" #include "wayfire/workspace-manager.hpp" #include <wayfire/util/log.hpp> #include <wayfire/debug.hpp> #include "switch.hpp" #include "tablet.hpp" #include "pointing-device.hpp" static std::unique_ptr<wf::input_device_impl_t> create_wf_device_for_device( wlr_input_device *device) { switch (device->type) { case WLR_INPUT_DEVICE_SWITCH: return std::make_unique<wf::switch_device_t>(device); case WLR_INPUT_DEVICE_POINTER: return std::make_unique<wf::pointing_device_t>(device); case WLR_INPUT_DEVICE_TABLET_TOOL: return std::make_unique<wf::tablet_t>( wf::get_core_impl().seat->cursor->cursor, device); case WLR_INPUT_DEVICE_TABLET_PAD: return std::make_unique<wf::tablet_pad_t>(device); default: return std::make_unique<wf::input_device_impl_t>(device); } } void wf::input_manager_t::handle_new_input(wlr_input_device *dev) { LOGI("handle new input: ", dev->name, ", default mapping: ", dev->output_name); input_devices.push_back(create_wf_device_for_device(dev)); wf::input_device_signal data; data.device = nonstd::make_observer(input_devices.back().get()); wf::get_core().emit_signal("input-device-added", &data); refresh_device_mappings(); } void wf::input_manager_t::refresh_device_mappings() { // Might trigger motion events which we want to avoid at other stages auto state = wf::get_core().get_current_state(); if (state != wf::compositor_state_t::RUNNING) { return; } auto cursor = wf::get_core().get_wlr_cursor(); for (auto& device : this->input_devices) { wlr_input_device *dev = device->get_wlr_handle(); auto section = wf::get_core().config_backend->get_input_device_section(dev); auto mapped_output = section->get_option("output")->get_value_str(); if (mapped_output.empty()) { mapped_output = nonull(dev->output_name); } auto wo = wf::get_core().output_layout->find_output(mapped_output); if (wo) { LOGD("Mapping input ", dev->name, " to output ", wo->to_string(), "."); wlr_cursor_map_input_to_output(cursor, dev, wo->handle); } else { LOGD("Mapping input ", dev->name, " to output null."); wlr_cursor_map_input_to_output(cursor, dev, nullptr); } } } void wf::input_manager_t::handle_input_destroyed(wlr_input_device *dev) { LOGI("remove input: ", dev->name); for (auto& device : input_devices) { if (device->get_wlr_handle() == dev) { wf::input_device_signal data; data.device = {device}; wf::get_core().emit_signal("input-device-removed", &data); } } auto it = std::remove_if(input_devices.begin(), input_devices.end(), [=] (const std::unique_ptr<wf::input_device_impl_t>& idev) { return idev->get_wlr_handle() == dev; }); input_devices.erase(it, input_devices.end()); } void load_locked_mods_from_config(xkb_mod_mask_t& locked_mods) { wf::option_wrapper_t<bool> numlock_state, capslock_state; numlock_state.load_option("input/kb_numlock_default_state"); capslock_state.load_option("input/kb_capslock_default_state"); if (numlock_state) { locked_mods |= wf::KB_MOD_NUM_LOCK; } if (capslock_state) { locked_mods |= wf::KB_MOD_CAPS_LOCK; } } wf::input_manager_t::input_manager_t() { wf::pointing_device_t::config.load(); load_locked_mods_from_config(locked_mods); input_device_created.set_callback([&] (void *data) { auto dev = static_cast<wlr_input_device*>(data); assert(dev); handle_new_input(dev); }); input_device_created.connect(&wf::get_core().backend->events.new_input); config_updated = [=] (wf::signal_data_t*) { for (auto& dev : input_devices) { dev->update_options(); } }; wf::get_core().connect_signal("reload-config", &config_updated); output_added = [=] (wf::signal_data_t *data) { auto wo = (wf::output_impl_t*)get_signaled_output(data); if (exclusive_client != nullptr) { wo->inhibit_plugins(); } refresh_device_mappings(); }; wf::get_core().output_layout->connect_signal("output-added", &output_added); } wf::input_manager_t::~input_manager_t() { wf::get_core().disconnect_signal("reload-config", &config_updated); wf::get_core().output_layout->disconnect_signal( "output-added", &output_added); } bool wf::input_manager_t::grab_input(wf::plugin_grab_interface_t *iface) { if (!iface || !iface->is_grabbed()) { return false; } assert(!active_grab); // cannot have two active input grabs! auto& seat = wf::get_core_impl().seat; seat->touch->set_grab(iface); active_grab = iface; // TODO: move this to the seat via a signal? auto kbd = wlr_seat_get_keyboard(seat->seat); auto mods = kbd ? kbd->modifiers : wlr_keyboard_modifiers{0, 0, 0, 0}; mods.depressed = 0; wlr_seat_keyboard_send_modifiers(seat->seat, &mods); seat->set_keyboard_focus(nullptr); seat->lpointer->set_enable_focus(false); wf::get_core().set_cursor("default"); return true; } void wf::input_manager_t::ungrab_input() { active_grab = nullptr; if (wf::get_core().get_active_output()) { wf::get_core().set_active_view( wf::get_core().get_active_output()->get_active_view()); } /* We must update cursor focus, however, if we update "too soon", the current * pointer event (button press/release, maybe something else) will be sent to * the client, which shouldn't happen (at the time of the event, there was * still an active input grab) */ idle_update_cursor.run_once([&] () { auto& seat = wf::get_core_impl().seat; seat->touch->set_grab(nullptr); seat->lpointer->set_enable_focus(true); }); } bool wf::input_manager_t::input_grabbed() { return active_grab; } bool wf::input_manager_t::can_focus_surface(wf::surface_interface_t *surface) { if (exclusive_client && (surface->get_client() != exclusive_client)) { /* We have exclusive focus surface, for ex. a lockscreen. * The only kind of things we can focus are OSKs and similar */ auto view = (wf::view_interface_t*)surface->get_main_surface(); if (view && view->get_output()) { auto layer = view->get_output()->workspace->get_view_layer(view->self()); return layer == wf::LAYER_DESKTOP_WIDGET; } return false; } return true; } wf::surface_interface_t*wf::input_manager_t::input_surface_at( wf::pointf_t global, wf::pointf_t& local) { auto output = wf::get_core().output_layout->get_output_coords_at(global, global); /* If the output at these coordinates was just destroyed or some other edge case * */ if (!output) { return nullptr; } auto og = output->get_layout_geometry(); global.x -= og.x; global.y -= og.y; for (auto& v : output->workspace->get_views_in_layer(wf::VISIBLE_LAYERS)) { for (auto& view : v->enumerate_views()) { if (!view->minimized && view->is_visible() && can_focus_surface(view.get())) { auto surface = view->map_input_coordinates(global, local); if (surface) { return surface; } } } } return nullptr; } void wf::input_manager_t::set_exclusive_focus(wl_client *client) { exclusive_client = client; for (auto& wo : wf::get_core().output_layout->get_outputs()) { auto impl = (wf::output_impl_t*)wo; if (client) { impl->inhibit_plugins(); } else { impl->uninhibit_plugins(); } } /* We no longer have an exclusively focused client, so we should restore * focus to the topmost view */ if (!client) { wf::get_core().get_active_output()->refocus(nullptr); } } wf::bindings_repository_t& wf::input_manager_t::get_active_bindings() { auto wo = wf::get_core().get_active_output(); auto impl = dynamic_cast<wf::output_impl_t*>(wo); if (!impl) { static wf::bindings_repository_t dummy_repo{nullptr}; return dummy_repo; } return impl->get_bindings(); } wf::SurfaceMapStateListener::SurfaceMapStateListener() { on_surface_map_state_change = [=] (void *data) { if (this->callback) { auto ev = static_cast<surface_map_state_changed_signal*>(data); this->callback(ev ? ev->surface : nullptr); } }; wf::get_core().connect_signal("surface-mapped", &on_surface_map_state_change); wf::get_core().connect_signal("surface-unmapped", &on_surface_map_state_change); } wf::SurfaceMapStateListener::~SurfaceMapStateListener() { wf::get_core().disconnect_signal("surface-mapped", &on_surface_map_state_change); wf::get_core().disconnect_signal("surface-unmapped", &on_surface_map_state_change); } void wf::SurfaceMapStateListener::set_callback(Callback call) { this->callback = call; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright 2008, mC2 team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "pch.hpp" #include "core/tracklist/Standard.h" using namespace musik::core::tracklist; Standard::Standard(void) : currentPosition(0),hintedRows(10){ this->trackQuery.OnTracksEvent.connect(this,&Standard::OnTracksMetaFromQuery); } Standard::~Standard(void){ } musik::core::TrackPtr Standard::CurrentTrack(){ return this->Track(this->currentPosition); } musik::core::TrackPtr Standard::NextTrack(){ this->SetCurrentPosition(this->currentPosition+1); return this->CurrentTrack(); } musik::core::TrackPtr Standard::PreviousTrack(){ this->SetCurrentPosition(this->currentPosition-1); return this->CurrentTrack(); } musik::core::TrackPtr Standard::operator [](int position){ if(position>=0 && position<this->tracks.size()) this->LoadTrack(position); return this->tracks[position]; if(position==-1) this->LoadTrack(0); return this->tracks.front(); return musik::core::TrackPtr(); } musik::core::TrackPtr Standard::Track(int position){ if(position>=0 && position<this->tracks.size()) return this->tracks[position]; if(position==-1) return this->tracks.front(); return musik::core::TrackPtr(); } int Standard::Size(){ return this->tracks.size(); } void Standard::SetCurrentPosition(int position){ if(position<-1){ this->currentPosition = -1; }else{ if(position >= (int)this->tracks.size()){ this->currentPosition = this->tracks.size()-1; }else{ this->currentPosition = position; } } } int Standard::CurrentPosition(){ if(this->currentPosition<0) return -1; if(this->currentPosition >= (int)this->tracks.size()) return this->tracks.size()-1; return this->currentPosition; } void Standard::ConnectToQuery(musik::core::Query::ListBase &listQuery){ listQuery.OnTrackEvent().connect(this,&Standard::OnTracksFromQuery); } void Standard::SetLibrary(musik::core::LibraryPtr setLibrary){ this->library = setLibrary; } musik::core::LibraryPtr Standard::Library(){ return this->library; } void Standard::OnTracksFromQuery(musik::core::TrackVector *newTracks,bool clear){ if(clear){ this->trackCache.clear(); this->SetCurrentPosition(-1); // undefined this->tracks = *newTracks; this->OnTracks(true); }else{ this->tracks.insert(this->tracks.end(),newTracks->begin(),newTracks->end()); this->OnTracks(false); } } void Standard::LoadTrack(int position){ if(!this->InCache(position)){ // Not in cache // Lets load the hinted number of tracks forward int trackCount(0); for(int i(position);i<position+this->hintedRows;++i){ if(!this->InCache(i)){ // Not in cache, load the track and add to Cache musik::core::TrackPtr track = this->Track(i); if(track){ this->trackCache.insert(CacheTrack(track,i)); ++trackCount; this->trackQuery.RequestTrack(track); } } } if(trackCount && this->library){ this->library->AddQuery(this->trackQuery,musik::core::Query::Prioritize); this->trackQuery.Clear(); } } } void Standard::HintNumberOfRows(int rows){ this->hintedRows = rows; } bool Standard::InCache(int position){ CacheIndexPosition& indexPosition = boost::multi_index::get<tagPosition>(this->trackCache); if( indexPosition.find(position) == indexPosition.end() ) return false; return true; } bool Standard::InCache(musik::core::TrackPtr track){ CacheIndexTrack& indexTrack = boost::multi_index::get<tagTrack>(this->trackCache); if( indexTrack.find(track) == indexTrack.end() ) return false; return true; } void Standard::OnTracksMetaFromQuery(musik::core::TrackVector *metaTracks){ std::vector<int> updateTrackPositions; CacheIndexTrack& indexTrack = boost::multi_index::get<tagTrack>(this->trackCache); for(musik::core::TrackVector::iterator track=metaTracks->begin();track!=metaTracks->end();++track){ CacheIndexTrack::iterator cacheTrackIterator = indexTrack.find(*track); if(cacheTrackIterator!=indexTrack.end()){ updateTrackPositions.push_back(cacheTrackIterator->position); } } this->OnTrackMeta(updateTrackPositions); } void Standard::AddRequestedMetakey(const char* metakey){ this->requestedMetaKeys.insert(metakey); this->trackQuery.RequestMetakeys(this->requestedMetaKeys); } void Standard::RemoveRequestedMetakey(const char* metakey){ this->requestedMetaKeys.erase(metakey); this->trackQuery.RequestMetakeys(this->requestedMetaKeys); } void Standard::CopyTracks(musik::core::tracklist::IRandomAccess &tracklist){ if(this!=&tracklist){ // Do not copy to itself this->SetLibrary(tracklist.Library()); this->tracks.clear(); this->tracks.reserve(tracklist.Size()); for(int i(0);i<tracklist.Size();++i){ this->tracks.push_back(tracklist.Track(i)->Copy()); } this->SetCurrentPosition(tracklist.CurrentPosition()); this->OnTracks(true); } } void Standard::AppendTracks(musik::core::tracklist::IRandomAccess &tracklist){ if(!this->library){ this->SetLibrary(tracklist.Library()); } this->tracks.reserve(this->tracks.size()+tracklist.Size()); for(int i(0);i<tracklist.Size();++i){ this->tracks.push_back(tracklist.Track(i)->Copy()); } this->OnTracks(false); } <commit_msg>- fixed tracklist::Standard from repeating the last song.<commit_after>////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright 2008, mC2 team // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #include "pch.hpp" #include "core/tracklist/Standard.h" using namespace musik::core::tracklist; Standard::Standard(void) : currentPosition(0),hintedRows(10){ this->trackQuery.OnTracksEvent.connect(this,&Standard::OnTracksMetaFromQuery); } Standard::~Standard(void){ } musik::core::TrackPtr Standard::CurrentTrack(){ return this->Track(this->currentPosition); } musik::core::TrackPtr Standard::NextTrack(){ this->SetCurrentPosition(this->currentPosition+1); return this->CurrentTrack(); } musik::core::TrackPtr Standard::PreviousTrack(){ this->SetCurrentPosition(this->currentPosition-1); return this->CurrentTrack(); } musik::core::TrackPtr Standard::operator [](int position){ if(position>=0 && position<this->tracks.size()) this->LoadTrack(position); return this->tracks[position]; if(position==-1) this->LoadTrack(0); return this->tracks.front(); return musik::core::TrackPtr(); } musik::core::TrackPtr Standard::Track(int position){ if(position>=0 && position<this->tracks.size()) return this->tracks[position]; if(position==-1) return this->tracks.front(); return musik::core::TrackPtr(); } int Standard::Size(){ return this->tracks.size(); } void Standard::SetCurrentPosition(int position){ if(position<-1){ this->currentPosition = -1; }else{ if(position >= (int)this->tracks.size()){ this->currentPosition = this->tracks.size(); }else{ this->currentPosition = position; } } } int Standard::CurrentPosition(){ if(this->currentPosition<0) return -1; if(this->currentPosition >= (int)this->tracks.size()) return this->tracks.size()-1; return this->currentPosition; } void Standard::ConnectToQuery(musik::core::Query::ListBase &listQuery){ listQuery.OnTrackEvent().connect(this,&Standard::OnTracksFromQuery); } void Standard::SetLibrary(musik::core::LibraryPtr setLibrary){ this->library = setLibrary; } musik::core::LibraryPtr Standard::Library(){ return this->library; } void Standard::OnTracksFromQuery(musik::core::TrackVector *newTracks,bool clear){ if(clear){ this->trackCache.clear(); this->SetCurrentPosition(-1); // undefined this->tracks = *newTracks; this->OnTracks(true); }else{ this->tracks.insert(this->tracks.end(),newTracks->begin(),newTracks->end()); this->OnTracks(false); } } void Standard::LoadTrack(int position){ if(!this->InCache(position)){ // Not in cache // Lets load the hinted number of tracks forward int trackCount(0); for(int i(position);i<position+this->hintedRows;++i){ if(!this->InCache(i)){ // Not in cache, load the track and add to Cache musik::core::TrackPtr track = this->Track(i); if(track){ this->trackCache.insert(CacheTrack(track,i)); ++trackCount; this->trackQuery.RequestTrack(track); } } } if(trackCount && this->library){ this->library->AddQuery(this->trackQuery,musik::core::Query::Prioritize); this->trackQuery.Clear(); } } } void Standard::HintNumberOfRows(int rows){ this->hintedRows = rows; } bool Standard::InCache(int position){ CacheIndexPosition& indexPosition = boost::multi_index::get<tagPosition>(this->trackCache); if( indexPosition.find(position) == indexPosition.end() ) return false; return true; } bool Standard::InCache(musik::core::TrackPtr track){ CacheIndexTrack& indexTrack = boost::multi_index::get<tagTrack>(this->trackCache); if( indexTrack.find(track) == indexTrack.end() ) return false; return true; } void Standard::OnTracksMetaFromQuery(musik::core::TrackVector *metaTracks){ std::vector<int> updateTrackPositions; CacheIndexTrack& indexTrack = boost::multi_index::get<tagTrack>(this->trackCache); for(musik::core::TrackVector::iterator track=metaTracks->begin();track!=metaTracks->end();++track){ CacheIndexTrack::iterator cacheTrackIterator = indexTrack.find(*track); if(cacheTrackIterator!=indexTrack.end()){ updateTrackPositions.push_back(cacheTrackIterator->position); } } this->OnTrackMeta(updateTrackPositions); } void Standard::AddRequestedMetakey(const char* metakey){ this->requestedMetaKeys.insert(metakey); this->trackQuery.RequestMetakeys(this->requestedMetaKeys); } void Standard::RemoveRequestedMetakey(const char* metakey){ this->requestedMetaKeys.erase(metakey); this->trackQuery.RequestMetakeys(this->requestedMetaKeys); } void Standard::CopyTracks(musik::core::tracklist::IRandomAccess &tracklist){ if(this!=&tracklist){ // Do not copy to itself this->SetLibrary(tracklist.Library()); this->tracks.clear(); this->tracks.reserve(tracklist.Size()); for(int i(0);i<tracklist.Size();++i){ this->tracks.push_back(tracklist.Track(i)->Copy()); } this->SetCurrentPosition(tracklist.CurrentPosition()); this->OnTracks(true); } } void Standard::AppendTracks(musik::core::tracklist::IRandomAccess &tracklist){ if(!this->library){ this->SetLibrary(tracklist.Library()); } this->tracks.reserve(this->tracks.size()+tracklist.Size()); for(int i(0);i<tracklist.Size();++i){ this->tracks.push_back(tracklist.Track(i)->Copy()); } this->OnTracks(false); } <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android Open Source Project * * 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 "tools/trace_to_text/trace_to_json.h" #include <stdio.h> #include "perfetto/base/logging.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/temp_file.h" #include "perfetto/trace_processor/trace_processor.h" #include "tools/trace_to_text/utils.h" namespace perfetto { namespace trace_to_text { namespace { const char kTraceHeader[] = R"({ "traceEvents": [], )"; const char kTraceFooter[] = R"(, "controllerTraceDataKey": "systraceController" })"; bool ExportUserspaceEvents(trace_processor::TraceProcessor* tp, TraceWriter* writer) { // First check if there are any non-Chrome events. If so then bail out. // TODO(eseckler): support merged Android/Chrome traces. static const char kSystemEventsQuery[] = "select count(1) from raw " "where name not like 'chrome.%' " "and name not like 'track_event.%'"; auto raw_it = tp->ExecuteQuery(kSystemEventsQuery); if (!raw_it.Next()) { auto status = raw_it.Status(); PERFETTO_ELOG("Failed when counting non-Chrome raw events %s.", status.c_message()); return false; } auto count_val = raw_it.Get(0); PERFETTO_CHECK(count_val.type == trace_processor::SqlValue::kLong); PERFETTO_DCHECK(!raw_it.Next()); if (count_val.long_value > 0) return false; fprintf(stderr, "Converting userspace events%c", kProgressChar); fflush(stderr); // Write userspace trace to a temporary file. // TODO(eseckler): Support streaming the result out of TP directly instead. auto file = base::TempFile::Create(); char query[100]; sprintf(query, "select export_json(\"%s\")", file.path().c_str()); auto it = tp->ExecuteQuery(query); if (!it.Next()) { auto status = it.Status(); PERFETTO_CHECK(!status.ok()); PERFETTO_ELOG("Could not convert userspace events: %s", status.c_message()); return false; } base::ScopedFstream source(fopen(file.path().c_str(), "r")); if (!source) { PERFETTO_ELOG("Could not convert userspace events: Couldn't read file %s", file.path().c_str()); return false; } char buf[BUFSIZ]; size_t size; while ((size = fread(buf, sizeof(char), BUFSIZ, *source)) > 0) { // Skip writing the closing brace since we'll append system trace data. if (feof(*source)) size--; writer->Write(buf, size); } return true; } } // namespace int TraceToJson(std::istream* input, std::ostream* output, bool compress, Keep truncate_keep) { std::unique_ptr<TraceWriter> trace_writer( compress ? new DeflateTraceWriter(output) : new TraceWriter(output)); trace_processor::Config config; std::unique_ptr<trace_processor::TraceProcessor> tp = trace_processor::TraceProcessor::CreateInstance(config); if (!ReadTrace(tp.get(), input)) return 1; tp->NotifyEndOfFile(); // TODO(eseckler): Support truncation of userspace event data. if (ExportUserspaceEvents(tp.get(), trace_writer.get())) { trace_writer->Write(",\n"); } else { trace_writer->Write(kTraceHeader); } int ret = ExtractSystrace(tp.get(), trace_writer.get(), /*wrapped_in_json=*/true, truncate_keep); if (ret) return ret; trace_writer->Write(kTraceFooter); return 0; } } // namespace trace_to_text } // namespace perfetto <commit_msg>Revert "traceconv: ignore userspace events for traces with Android data"<commit_after>/* * Copyright (C) 2019 The Android Open Source Project * * 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 "tools/trace_to_text/trace_to_json.h" #include <stdio.h> #include "perfetto/base/logging.h" #include "perfetto/ext/base/scoped_file.h" #include "perfetto/ext/base/temp_file.h" #include "perfetto/trace_processor/trace_processor.h" #include "tools/trace_to_text/utils.h" namespace perfetto { namespace trace_to_text { namespace { const char kTraceHeader[] = R"({ "traceEvents": [], )"; const char kTraceFooter[] = R"(, "controllerTraceDataKey": "systraceController" })"; bool ExportUserspaceEvents(trace_processor::TraceProcessor* tp, TraceWriter* writer) { fprintf(stderr, "Converting userspace events%c", kProgressChar); fflush(stderr); // Write userspace trace to a temporary file. // TODO(eseckler): Support streaming the result out of TP directly instead. auto file = base::TempFile::Create(); char query[100]; sprintf(query, "select export_json(\"%s\")", file.path().c_str()); auto it = tp->ExecuteQuery(query); if (!it.Next()) { auto status = it.Status(); PERFETTO_CHECK(!status.ok()); PERFETTO_ELOG("Could not convert userspace events: %s", status.c_message()); return false; } base::ScopedFstream source(fopen(file.path().c_str(), "r")); if (!source) { PERFETTO_ELOG("Could not convert userspace events: Couldn't read file %s", file.path().c_str()); return false; } char buf[BUFSIZ]; size_t size; while ((size = fread(buf, sizeof(char), BUFSIZ, *source)) > 0) { // Skip writing the closing brace since we'll append system trace data. if (feof(*source)) size--; writer->Write(buf, size); } return true; } } // namespace int TraceToJson(std::istream* input, std::ostream* output, bool compress, Keep truncate_keep) { std::unique_ptr<TraceWriter> trace_writer( compress ? new DeflateTraceWriter(output) : new TraceWriter(output)); trace_processor::Config config; std::unique_ptr<trace_processor::TraceProcessor> tp = trace_processor::TraceProcessor::CreateInstance(config); if (!ReadTrace(tp.get(), input)) return 1; tp->NotifyEndOfFile(); // TODO(eseckler): Support truncation of userspace event data. if (ExportUserspaceEvents(tp.get(), trace_writer.get())) { trace_writer->Write(",\n"); } else { trace_writer->Write(kTraceHeader); } int ret = ExtractSystrace(tp.get(), trace_writer.get(), /*wrapped_in_json=*/true, truncate_keep); if (ret) return ret; trace_writer->Write(kTraceFooter); return 0; } } // namespace trace_to_text } // namespace perfetto <|endoftext|>
<commit_before>/// HEADER #include <csapex/command_meta.h> /// SYSTEM #include <boost/foreach.hpp> using namespace csapex::command; Meta::Meta() : locked(false) { } void Meta::add(Command::Ptr cmd) { assert(!locked); nested.push_back(cmd); } bool Meta::execute() { locked = true; bool change = false; BOOST_FOREACH(Command::Ptr cmd, nested) { change |= cmd->execute(); } return change; } bool Meta::undo() { BOOST_REVERSE_FOREACH(Command::Ptr cmd, nested) { if(!cmd->undo()) { // undo_later.push_back(cmd); } } return true; } bool Meta::redo() { bool change = false; BOOST_FOREACH(Command::Ptr cmd, nested) { change |= cmd->redo(); } return change; } <commit_msg>bugfix<commit_after>/// HEADER #include <csapex/command_meta.h> /// SYSTEM #include <boost/foreach.hpp> using namespace csapex::command; Meta::Meta() : locked(false) { } void Meta::add(Command::Ptr cmd) { assert(!locked); nested.push_back(cmd); } bool Meta::execute() { locked = true; bool change = true; BOOST_FOREACH(Command::Ptr cmd, nested) { change &= cmd->execute(); } return change; } bool Meta::undo() { BOOST_REVERSE_FOREACH(Command::Ptr cmd, nested) { if(!cmd->undo()) { // undo_later.push_back(cmd); } } return true; } bool Meta::redo() { bool change = true; BOOST_FOREACH(Command::Ptr cmd, nested) { change &= cmd->redo(); } return change; } <|endoftext|>
<commit_before>#ifndef CONNECTOR #define CONNECTOR #include <gecode/search/message.pb.hh> #include <gecode/search/zmq.hpp> namespace message { class Node; } namespace Profiling { class Node; enum NodeStatus { SOLVED = 0, FAILED = 1, BRANCH = 2, SKIPPED = 6, MERGING = 7 }; class Connector { private: const unsigned int port; unsigned int _thread_id; zmq::context_t context; zmq::socket_t socket; void sendOverSocket(const message::Node& msg); public: Connector(unsigned int port, unsigned int tid = 0); /// connect to a socket via port specified in the construction (6565 by default) void connect(); // sends START_SENDING message to the Profiler with a model name void restart(const std::string& file_path = "", int restart_id = -1); void done(); /// disconnect from a socket void disconnect(); void sendNode(int sid, int pid, int alt, int kids, NodeStatus status, const char* label, unsigned int thread = -1, int restart = -1, float domain = -1, const std::string& nogood = "", const std::string& info = ""); void sendNode(const Profiling::Node& node); Node createNode(int sid, int pid, int alt, int kids, NodeStatus status); }; class Node { private: message::Node _node; Connector& _c; const message::Node& get_node() const { return _node; } Node(const Node& node); /// no copying allowed public: friend class Connector; Node(int sid, int pid, int alt, int kids, NodeStatus status, Connector& c); ~Node(); void send(); inline Node& set_label(const std::string& label) { _node.set_label(label); return *this; } inline Node& set_thread_id(unsigned int thread_id) { _node.set_thread_id(thread_id); return *this; } inline Node& set_restart_id(int restart_id) { _node.set_thread_id(restart_id); return *this; } inline Node& set_domain_size(float domain_size) { _node.set_domain_size(domain_size); return *this; } inline Node& set_nogood(const std::string& nogood) { _node.set_nogood(nogood); return *this; } inline Node& set_info(const std::string& nogood) { _node.set_nogood(nogood); return *this; } inline Node& set_solution(const std::string& solution) { _node.set_solution(solution); return *this; } }; } #endif<commit_msg>fixed restart_id not properly set<commit_after>#ifndef CONNECTOR #define CONNECTOR #include <gecode/search/message.pb.hh> #include <gecode/search/zmq.hpp> namespace message { class Node; } namespace Profiling { class Node; enum NodeStatus { SOLVED = 0, FAILED = 1, BRANCH = 2, SKIPPED = 6, MERGING = 7 }; class Connector { private: const unsigned int port; unsigned int _thread_id; zmq::context_t context; zmq::socket_t socket; void sendOverSocket(const message::Node& msg); public: Connector(unsigned int port, unsigned int tid = 0); /// connect to a socket via port specified in the construction (6565 by default) void connect(); // sends START_SENDING message to the Profiler with a model name void restart(const std::string& file_path = "", int restart_id = -1); void done(); /// disconnect from a socket void disconnect(); void sendNode(int sid, int pid, int alt, int kids, NodeStatus status, const char* label, unsigned int thread = -1, int restart = -1, float domain = -1, const std::string& nogood = "", const std::string& info = ""); void sendNode(const Profiling::Node& node); Node createNode(int sid, int pid, int alt, int kids, NodeStatus status); }; class Node { private: message::Node _node; Connector& _c; const message::Node& get_node() const { return _node; } Node(const Node& node); /// no copying allowed public: friend class Connector; Node(int sid, int pid, int alt, int kids, NodeStatus status, Connector& c); ~Node(); void send(); inline Node& set_label(const std::string& label) { _node.set_label(label); return *this; } inline Node& set_thread_id(unsigned int thread_id) { _node.set_thread_id(thread_id); return *this; } inline Node& set_restart_id(int restart_id) { _node.set_restart_id(restart_id); return *this; } inline Node& set_domain_size(float domain_size) { _node.set_domain_size(domain_size); return *this; } inline Node& set_nogood(const std::string& nogood) { _node.set_nogood(nogood); return *this; } inline Node& set_info(const std::string& nogood) { _node.set_nogood(nogood); return *this; } inline Node& set_solution(const std::string& solution) { _node.set_solution(solution); return *this; } }; } #endif<|endoftext|>
<commit_before>/* Copyright 2017 QReal Research Group * * 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 "structuralControlFlowGenerator.h" using namespace qReal; using namespace generatorBase; using namespace semantics; StructuralControlFlowGenerator::StructuralControlFlowGenerator(const qrRepo::RepoApi &repo , ErrorReporterInterface &errorReporter , GeneratorCustomizer &customizer , PrimaryControlFlowValidator &validator , const Id &diagramId , QObject *parent , bool isThisDiagramMain) : ControlFlowGeneratorBase(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain) , mNumberOfVerteces(0) { } ControlFlowGeneratorBase *StructuralControlFlowGenerator::cloneFor(const Id &diagramId, bool cloneForNewDiagram) { // to do return nullptr; } void StructuralControlFlowGenerator::beforeSearch() { // to do } void StructuralControlFlowGenerator::visitFinal(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitFork(const Id &id, QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitJoin(const Id &id, QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitRegular(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitConditional(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitLoop(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitSwitch(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitUnknown(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::afterSearch() { // to do } void StructuralControlFlowGenerator::performGeneration() { ControlFlowGeneratorBase::performGeneration(); // to check whether diagram was right findDominators(); performAnalysis(); } void StructuralControlFlowGenerator::buildGraph(const Id &id, const QList<LinkInfo> &links) { int numberOfCurrentVertex = -1; if (mInitialVerteces.contains(id)) { numberOfCurrentVertex = mInitialVerteces[id]; } else { numberOfCurrentVertex = mNumberOfVerteces; mNumberOfVerteces++; mInitialVerteces[id] = numberOfCurrentVertex; mVerteces.push_back(numberOfCurrentVertex); } for (const LinkInfo link : links) { int targetNumber = -1; if (mInitialVerteces.contains(link.target)) { targetNumber = mInitialVerteces[link.target]; } else { targetNumber = mNumberOfVerteces; mNumberOfVerteces++; mInitialVerteces[link.target] = targetNumber; mVerteces.push_back(targetNumber); } mFollowers[numberOfCurrentVertex].push_back(targetNumber); mPredecessors[targetNumber].push_back(numberOfCurrentVertex); } } // to do // to save invariant that mGraph only has valid nodes and edges, // so it would be possible not to pass setOfNodes void StructuralControlFlowGenerator::performAnalysis() { for (VertexIterator it = mInitialVerteces.values().begin(); it != mInitialVerteces.values().end(); ++it) { mUsed[*it] = false; mPostOrder[*it] = -1; } int time = 0; const VertexLabel root = 0; dfs(root, time); int currentTime = 0; int maxTime = time; // it is supposed that mFollowers.size() == mPredecessors.size() == actual number of // verteces in current flowgraph while (mFollowers.keys().size() > 1 && currentTime < maxTime) { int currentNode = -1; // dummy cycle for finding node number that // has postOrder equal to currentTime for (VertexIterator it = mPostOrder.keys().begin(); it != mPostOrder.keys().end(); ++it) { VertexLabel number = *(it); if (mPostOrder[number] == currentTime) { currentNode = number; break; } } } } void StructuralControlFlowGenerator::findDominators() { for (int i = 1; i < mVerteces.size(); i++) { mDominators[i] = mVerteces.toSet(); } const VertexLabel root = 0; mDominators[root] = { root }; bool somethingChanged = true; while (somethingChanged) { somethingChanged = false; // excluding root for (VertexIterator it = mVerteces.begin(); it != mVerteces.end(); it++) { VertexLabel vertex = *it; if (vertex) { QSet<VertexLabel> newDominators = mVerteces.toSet(); for (int t = 0; t < mPredecessors[vertex].size(); t++) { VertexLabel predecessor = mPredecessors[vertex].at(t); newDominators.intersect(mDominators[predecessor]); } // adding the current number, because reflexivity of dominance relation newDominators.insert(vertex); if (newDominators != mDominators[vertex]) { somethingChanged = true; mDominators[vertex] = newDominators; } } } } } void StructuralControlFlowGenerator::dfs(VertexLabel u, int &postOrderLabel) { mUsed[u] = true; for (int t = 0; t < mFollowers[u].size(); t++) { int v = mFollowers[u].at(t); if (!mUsed[v]) { dfs(v, postOrderLabel); } } mPostOrder[u] = postOrderLabel; postOrderLabel++; } StructuralControlFlowGenerator::RegionType StructuralControlFlowGenerator::acyclicRegionType(int &nodeNumber, QSet<int> &nodesThatComposeRegion) { nodesThatComposeRegion.clear(); int currentNodeNumber = nodeNumber; bool hasOnlyOneIncomingEdge = true; bool hasOnlyOneOutcomingEdge = mFollowers[currentNodeNumber].size() == 1; while (hasOnlyOneIncomingEdge && hasOnlyOneOutcomingEdge) { nodesThatComposeRegion.insert(currentNodeNumber); currentNodeNumber = mFollowers[currentNodeNumber].at(0); hasOnlyOneIncomingEdge = mPredecessors[currentNodeNumber].size() == 1; hasOnlyOneOutcomingEdge = mFollowers[currentNodeNumber].size() == 1; } if (hasOnlyOneIncomingEdge) { nodesThatComposeRegion.insert(currentNodeNumber); } currentNodeNumber = nodeNumber; hasOnlyOneIncomingEdge = mPredecessors[currentNodeNumber].size() == 1; hasOnlyOneOutcomingEdge = true; while (hasOnlyOneIncomingEdge && hasOnlyOneOutcomingEdge) { nodesThatComposeRegion.insert(currentNodeNumber); currentNodeNumber = mPredecessors[currentNodeNumber].at(0); hasOnlyOneIncomingEdge = mPredecessors[currentNodeNumber].size() == 1; hasOnlyOneOutcomingEdge = mFollowers[currentNodeNumber].size() == 1; } if (hasOnlyOneOutcomingEdge) { nodesThatComposeRegion.insert(currentNodeNumber); } nodeNumber = currentNodeNumber; if (nodesThatComposeRegion.size() == 2) { return Block; } // checking for IfThenElse if (mFollowers[nodeNumber].size() == 2) { int m = mFollowers[nodeNumber].at(0); int n = mFollowers[nodeNumber].at(1); if (mFollowers[m].size() == 1 && mFollowers[n].size() == 1 && mFollowers[m].at(0) == mFollowers[n].at(0) && mPredecessors[m].size() == 1 && mPredecessors[n].size() == 1) { nodesThatComposeRegion.clear(); nodesThatComposeRegion.insert(nodeNumber); nodesThatComposeRegion.insert(m); nodesThatComposeRegion.insert(n); return IfThenElse; } } } StructuralControlFlowGenerator::Node::Node(StructuralControlFlowGenerator::RegionType type, int number) : mRegionType(type) , mNumber(number) , mParent(nullptr) { } void StructuralControlFlowGenerator::Node::appendChild(StructuralControlFlowGenerator::Node *child) { mChildren.append(child); } void StructuralControlFlowGenerator::Node::appendChildren(const QVector<StructuralControlFlowGenerator::Node *> &children) { for (StructuralControlFlowGenerator::Node *child : children) { mChildren.append(child); } } StructuralControlFlowGenerator::Node *StructuralControlFlowGenerator::Node::structOf() const { return mParent; } void StructuralControlFlowGenerator::Node::setParent(StructuralControlFlowGenerator::Node *parent) { mParent = parent; } StructuralControlFlowGenerator::RegionType StructuralControlFlowGenerator::Node::structType() const { return mRegionType; } QVector<StructuralControlFlowGenerator::Node *> StructuralControlFlowGenerator::Node::structNodes() const { return mChildren; } <commit_msg>Handling IfThen pattern<commit_after>/* Copyright 2017 QReal Research Group * * 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 "structuralControlFlowGenerator.h" using namespace qReal; using namespace generatorBase; using namespace semantics; StructuralControlFlowGenerator::StructuralControlFlowGenerator(const qrRepo::RepoApi &repo , ErrorReporterInterface &errorReporter , GeneratorCustomizer &customizer , PrimaryControlFlowValidator &validator , const Id &diagramId , QObject *parent , bool isThisDiagramMain) : ControlFlowGeneratorBase(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain) , mNumberOfVerteces(0) { } ControlFlowGeneratorBase *StructuralControlFlowGenerator::cloneFor(const Id &diagramId, bool cloneForNewDiagram) { // to do return nullptr; } void StructuralControlFlowGenerator::beforeSearch() { // to do } void StructuralControlFlowGenerator::visitFinal(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitFork(const Id &id, QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitJoin(const Id &id, QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitRegular(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitConditional(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitLoop(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitSwitch(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::visitUnknown(const Id &id, const QList<LinkInfo> &links) { buildGraph(id, links); } void StructuralControlFlowGenerator::afterSearch() { // to do } void StructuralControlFlowGenerator::performGeneration() { ControlFlowGeneratorBase::performGeneration(); // to check whether diagram was right findDominators(); performAnalysis(); } void StructuralControlFlowGenerator::buildGraph(const Id &id, const QList<LinkInfo> &links) { int numberOfCurrentVertex = -1; if (mInitialVerteces.contains(id)) { numberOfCurrentVertex = mInitialVerteces[id]; } else { numberOfCurrentVertex = mNumberOfVerteces; mNumberOfVerteces++; mInitialVerteces[id] = numberOfCurrentVertex; mVerteces.push_back(numberOfCurrentVertex); } for (const LinkInfo link : links) { int targetNumber = -1; if (mInitialVerteces.contains(link.target)) { targetNumber = mInitialVerteces[link.target]; } else { targetNumber = mNumberOfVerteces; mNumberOfVerteces++; mInitialVerteces[link.target] = targetNumber; mVerteces.push_back(targetNumber); } mFollowers[numberOfCurrentVertex].push_back(targetNumber); mPredecessors[targetNumber].push_back(numberOfCurrentVertex); } } // to do // to save invariant that mGraph only has valid nodes and edges, // so it would be possible not to pass setOfNodes void StructuralControlFlowGenerator::performAnalysis() { for (VertexIterator it = mInitialVerteces.values().begin(); it != mInitialVerteces.values().end(); ++it) { mUsed[*it] = false; mPostOrder[*it] = -1; } int time = 0; const VertexLabel root = 0; dfs(root, time); int currentTime = 0; int maxTime = time; // it is supposed that mFollowers.size() == mPredecessors.size() == actual number of // verteces in current flowgraph while (mFollowers.keys().size() > 1 && currentTime < maxTime) { int currentNode = -1; // dummy cycle for finding node number that // has postOrder equal to currentTime for (VertexIterator it = mPostOrder.keys().begin(); it != mPostOrder.keys().end(); ++it) { VertexLabel number = *(it); if (mPostOrder[number] == currentTime) { currentNode = number; break; } } } } void StructuralControlFlowGenerator::findDominators() { for (int i = 1; i < mVerteces.size(); i++) { mDominators[i] = mVerteces.toSet(); } const VertexLabel root = 0; mDominators[root] = { root }; bool somethingChanged = true; while (somethingChanged) { somethingChanged = false; // excluding root for (VertexIterator it = mVerteces.begin(); it != mVerteces.end(); it++) { VertexLabel vertex = *it; if (vertex) { QSet<VertexLabel> newDominators = mVerteces.toSet(); for (int t = 0; t < mPredecessors[vertex].size(); t++) { VertexLabel predecessor = mPredecessors[vertex].at(t); newDominators.intersect(mDominators[predecessor]); } // adding the current number, because reflexivity of dominance relation newDominators.insert(vertex); if (newDominators != mDominators[vertex]) { somethingChanged = true; mDominators[vertex] = newDominators; } } } } } void StructuralControlFlowGenerator::dfs(VertexLabel u, int &postOrderLabel) { mUsed[u] = true; for (int t = 0; t < mFollowers[u].size(); t++) { int v = mFollowers[u].at(t); if (!mUsed[v]) { dfs(v, postOrderLabel); } } mPostOrder[u] = postOrderLabel; postOrderLabel++; } StructuralControlFlowGenerator::RegionType StructuralControlFlowGenerator::acyclicRegionType(int &nodeNumber, QSet<int> &nodesThatComposeRegion) { nodesThatComposeRegion.clear(); int currentNodeNumber = nodeNumber; bool hasOnlyOneIncomingEdge = true; bool hasOnlyOneOutcomingEdge = mFollowers[currentNodeNumber].size() == 1; while (hasOnlyOneIncomingEdge && hasOnlyOneOutcomingEdge) { nodesThatComposeRegion.insert(currentNodeNumber); currentNodeNumber = mFollowers[currentNodeNumber].at(0); hasOnlyOneIncomingEdge = mPredecessors[currentNodeNumber].size() == 1; hasOnlyOneOutcomingEdge = mFollowers[currentNodeNumber].size() == 1; } if (hasOnlyOneIncomingEdge) { nodesThatComposeRegion.insert(currentNodeNumber); } currentNodeNumber = nodeNumber; hasOnlyOneIncomingEdge = mPredecessors[currentNodeNumber].size() == 1; hasOnlyOneOutcomingEdge = true; while (hasOnlyOneIncomingEdge && hasOnlyOneOutcomingEdge) { nodesThatComposeRegion.insert(currentNodeNumber); currentNodeNumber = mPredecessors[currentNodeNumber].at(0); hasOnlyOneIncomingEdge = mPredecessors[currentNodeNumber].size() == 1; hasOnlyOneOutcomingEdge = mFollowers[currentNodeNumber].size() == 1; } if (hasOnlyOneOutcomingEdge) { nodesThatComposeRegion.insert(currentNodeNumber); } nodeNumber = currentNodeNumber; if (nodesThatComposeRegion.size() == 2) { return Block; } nodesThatComposeRegion.clear(); // checking for IfThenElse if (mFollowers[nodeNumber].size() == 2) { int m = mFollowers[nodeNumber].at(0); int n = mFollowers[nodeNumber].at(1); if (mFollowers[m].size() == 1 && mFollowers[n].size() == 1 && mFollowers[m].at(0) == mFollowers[n].at(0) && mPredecessors[m].size() == 1 && mPredecessors[n].size() == 1) { nodesThatComposeRegion.insert(nodeNumber); nodesThatComposeRegion.insert(m); nodesThatComposeRegion.insert(n); return IfThenElse; } } // checking IfThen if (mFollowers[nodeNumber].size() == 2) { int m = mFollowers[nodeNumber].at(0); int n = mFollowers[nodeNumber].at(1); int thenNodeNumber = -1; if (mFollowers[m].size() == 1 && mFollowers[m].at(0) == n && mPredecessors[m].size() == 1) { thenNodeNumber = m; } else if (mFollowers[n].size() == 1 && mFollowers[n].at(0) == m && mPredecessors[n].size() == 1) { thenNodeNumber = n; } if (thenNodeNumber != -1) { nodesThatComposeRegion.insert(nodeNumber); nodesThatComposeRegion.insert(m); nodesThatComposeRegion.insert(n); return IfThen; } } } StructuralControlFlowGenerator::Node::Node(StructuralControlFlowGenerator::RegionType type, int number) : mRegionType(type) , mNumber(number) , mParent(nullptr) { } void StructuralControlFlowGenerator::Node::appendChild(StructuralControlFlowGenerator::Node *child) { mChildren.append(child); } void StructuralControlFlowGenerator::Node::appendChildren(const QVector<StructuralControlFlowGenerator::Node *> &children) { for (StructuralControlFlowGenerator::Node *child : children) { mChildren.append(child); } } StructuralControlFlowGenerator::Node *StructuralControlFlowGenerator::Node::structOf() const { return mParent; } void StructuralControlFlowGenerator::Node::setParent(StructuralControlFlowGenerator::Node *parent) { mParent = parent; } StructuralControlFlowGenerator::RegionType StructuralControlFlowGenerator::Node::structType() const { return mRegionType; } QVector<StructuralControlFlowGenerator::Node *> StructuralControlFlowGenerator::Node::structNodes() const { return mChildren; } <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include "backendnode.h" #include "audiooutput.h" #include "effect.h" #include "mediaobject.h" #include "videowidget.h" #include "volumeeffect.h" //windows specific (DirectX Media Object) #include <dmo.h> #include <QtCore/QSettings> #include <QtCore/QSet> #include <QtCore/QVariant> #include <QtCore/QtPlugin> QT_BEGIN_NAMESPACE Q_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend); namespace Phonon { namespace DS9 { bool Backend::AudioMoniker::operator==(const AudioMoniker &other) { return other->IsEqual(*this) == S_OK; } Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) { ::CoInitialize(0); //registering meta types qRegisterMetaType<HRESULT>("HRESULT"); qRegisterMetaType<Graph>("Graph"); } Backend::~Backend() { m_audioOutputs.clear(); m_audioEffects.clear(); ::CoUninitialize(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(this, parent); #ifndef QT_NO_PHONON_EFFECT case EffectClass: return new Effect(m_audioEffects[ args[0].toInt() ], parent); #endif //QT_NO_PHONON_EFFECT #ifndef QT_NO_PHONON_VIDEO case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); #endif //QT_NO_PHONON_VIDEO #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT case VolumeFaderEffectClass: return new VolumeEffect(parent); #endif //QT_NO_PHONON_VOLUMEFADEREFFECT default: return 0; } } bool Backend::supportsVideo() const { #ifndef QT_NO_PHONON_VIDEO return true; #else return false; #endif //QT_NO_PHONON_VIDEO } QStringList Backend::availableMimeTypes() const { QStringList ret; { QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types"), QSettings::NativeFormat); ret += settings.childGroups(); } { QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types"), QSettings::NativeFormat); ret += settings.childGroups(); } ret.removeDuplicates(); ret.replaceInStrings("\\", "/"); qSort(ret); return ret; } Filter Backend::getAudioOutputFilter(int index) const { Filter ret; if (index >= 0 && index < m_audioOutputs.count()) { m_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(&ret)); } else { //just return the default audio renderer (not directsound) ret = Filter(CLSID_AudioRender, IID_IBaseFilter); } return ret; } QList<int> Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const { QList<int> ret; switch(type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret << 0; // only one audio device with index 0 #else ComPointer<ICreateDevEnum> devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum); if (!devEnum) { return ret; //it is impossible to enumerate the devices } ComPointer<IEnumMoniker> enumMon; HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0); if (FAILED(hr)) { break; } AudioMoniker mon; //let's reorder the devices so that directshound appears first int nbds = 0; //number of directsound devices while (S_OK == enumMon->Next(1, mon.pparam(), 0)) { LPOLESTR str = 0; mon->GetDisplayName(0,0,&str); const QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); int insert_pos = 0; if (!m_audioOutputs.contains(mon)) { insert_pos = m_audioOutputs.count(); m_audioOutputs.append(mon); } else { insert_pos = m_audioOutputs.indexOf(mon); } if (name.contains(QLatin1String("DirectSound"))) { ret.insert(nbds++, insert_pos); } else { ret.append(insert_pos); } } #endif break; } #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { m_audioEffects.clear(); ComPointer<IEnumDMO> enumDMO; HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam()); if (SUCCEEDED(hr)) { CLSID clsid; while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) { ret += m_audioEffects.count(); m_audioEffects.append(clsid); } } break; } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret["name"] = QLatin1String("default audio device"); #else const AudioMoniker &mon = m_audioOutputs[index]; LPOLESTR str = 0; HRESULT hr = mon->GetDisplayName(0,0, &str); if (SUCCEEDED(hr)) { QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); ret["name"] = name.mid(name.indexOf('\\') + 1); } #endif } break; #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { WCHAR name[80]; // 80 is clearly stated in the MSDN doc HRESULT hr = ::DMOGetName(m_audioEffects[index], name); if (SUCCEEDED(hr)) { ret["name"] = QString::fromUtf16((unsigned short*)name); } } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } bool Backend::endConnectionChange(QSet<QObject *> objects) { if (objects.isEmpty()) return true; //end of a transaction for(QSet<QObject *>::const_iterator it = objects.begin(); it != objects.end(); ++it) { if (BackendNode *node = qobject_cast<BackendNode*>(*it)) { MediaObject *mo = node->mediaObject(); if (mo) { switch(mo->transactionState) { case Phonon::ErrorState: case Phonon::StoppedState: case Phonon::LoadingState: //nothing to do break; case Phonon::PausedState: mo->pause(); break; default: mo->play(); break; } return mo->state() != Phonon::ErrorState; } } } return false; } bool Backend::startConnectionChange(QSet<QObject *> objects) { if (objects.isEmpty()) return true; //let's save the state of the graph (before we stop it) for(QSet<QObject *>::const_iterator it = objects.begin(); it != objects.end(); ++it) { if (BackendNode *node = qobject_cast<BackendNode*>(*it)) { if (MediaObject *mo = node->mediaObject()) { if (mo->state() != Phonon::StoppedState) { mo->transactionState = mo->state(); mo->ensureStopped(); //we have to stop the graph.. } return true; } } } return false; } bool Backend::connectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } //setting the graph if needed if (source->mediaObject() == 0 && sink->mediaObject() == 0) { //error: no graph selected return false; } else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) { //this' graph becomes the common one source->mediaObject()->grabNode(sink); } else if (source->mediaObject() == 0) { //sink's graph becomes the common one sink->mediaObject()->grabNode(source); } return source->mediaObject()->connectNodes(source, sink); } bool Backend::disconnectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } return source->mediaObject() == 0 || source->mediaObject()->disconnectNodes(source, sink); } } } QT_END_NAMESPACE #include "moc_backend.cpp" <commit_msg>qt4.4 compile++<commit_after>/* This file is part of the KDE project. Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "backend.h" #include "backendnode.h" #include "audiooutput.h" #include "effect.h" #include "mediaobject.h" #include "videowidget.h" #include "volumeeffect.h" //windows specific (DirectX Media Object) #include <dmo.h> #include <QtCore/QSettings> #include <QtCore/QSet> #include <QtCore/QVariant> #include <QtCore/QtPlugin> QT_BEGIN_NAMESPACE Q_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend); namespace Phonon { namespace DS9 { bool Backend::AudioMoniker::operator==(const AudioMoniker &other) { return other->IsEqual(*this) == S_OK; } Backend::Backend(QObject *parent, const QVariantList &) : QObject(parent) { ::CoInitialize(0); //registering meta types qRegisterMetaType<HRESULT>("HRESULT"); qRegisterMetaType<Graph>("Graph"); } Backend::~Backend() { m_audioOutputs.clear(); m_audioEffects.clear(); ::CoUninitialize(); } QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args) { switch (c) { case MediaObjectClass: return new MediaObject(parent); case AudioOutputClass: return new AudioOutput(this, parent); #ifndef QT_NO_PHONON_EFFECT case EffectClass: return new Effect(m_audioEffects[ args[0].toInt() ], parent); #endif //QT_NO_PHONON_EFFECT #ifndef QT_NO_PHONON_VIDEO case VideoWidgetClass: return new VideoWidget(qobject_cast<QWidget *>(parent)); #endif //QT_NO_PHONON_VIDEO #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT case VolumeFaderEffectClass: return new VolumeEffect(parent); #endif //QT_NO_PHONON_VOLUMEFADEREFFECT default: return 0; } } bool Backend::supportsVideo() const { #ifndef QT_NO_PHONON_VIDEO return true; #else return false; #endif //QT_NO_PHONON_VIDEO } QStringList Backend::availableMimeTypes() const { #if 0 // needs Qt4.5 QStringList ret; { QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types"), QSettings::NativeFormat); ret += settings.childGroups(); } { QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types"), QSettings::NativeFormat); ret += settings.childGroups(); } ret.removeDuplicates(); #else QStringList ret; { QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types"), QSettings::NativeFormat); Q_FOREACH(const QString &s, settings.childGroups()) if(!ret.contains(s)) ret += s; } { QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types"), QSettings::NativeFormat); Q_FOREACH(const QString &s, settings.childGroups()) if(!ret.contains(s)) ret += s; } #endif ret.replaceInStrings("\\", "/"); qSort(ret); return ret; } Filter Backend::getAudioOutputFilter(int index) const { Filter ret; if (index >= 0 && index < m_audioOutputs.count()) { m_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(&ret)); } else { //just return the default audio renderer (not directsound) ret = Filter(CLSID_AudioRender, IID_IBaseFilter); } return ret; } QList<int> Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const { QList<int> ret; switch(type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret << 0; // only one audio device with index 0 #else ComPointer<ICreateDevEnum> devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum); if (!devEnum) { return ret; //it is impossible to enumerate the devices } ComPointer<IEnumMoniker> enumMon; HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0); if (FAILED(hr)) { break; } AudioMoniker mon; //let's reorder the devices so that directshound appears first int nbds = 0; //number of directsound devices while (S_OK == enumMon->Next(1, mon.pparam(), 0)) { LPOLESTR str = 0; mon->GetDisplayName(0,0,&str); const QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); int insert_pos = 0; if (!m_audioOutputs.contains(mon)) { insert_pos = m_audioOutputs.count(); m_audioOutputs.append(mon); } else { insert_pos = m_audioOutputs.indexOf(mon); } if (name.contains(QLatin1String("DirectSound"))) { ret.insert(nbds++, insert_pos); } else { ret.append(insert_pos); } } #endif break; } #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { m_audioEffects.clear(); ComPointer<IEnumDMO> enumDMO; HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam()); if (SUCCEEDED(hr)) { CLSID clsid; while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) { ret += m_audioEffects.count(); m_audioEffects.append(clsid); } } break; } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const { QHash<QByteArray, QVariant> ret; switch (type) { case Phonon::AudioOutputDeviceType: { #ifdef Q_OS_WINCE ret["name"] = QLatin1String("default audio device"); #else const AudioMoniker &mon = m_audioOutputs[index]; LPOLESTR str = 0; HRESULT hr = mon->GetDisplayName(0,0, &str); if (SUCCEEDED(hr)) { QString name = QString::fromUtf16((unsigned short*)str); ComPointer<IMalloc> alloc; ::CoGetMalloc(1, alloc.pparam()); alloc->Free(str); ret["name"] = name.mid(name.indexOf('\\') + 1); } #endif } break; #ifndef QT_NO_PHONON_EFFECT case Phonon::EffectType: { WCHAR name[80]; // 80 is clearly stated in the MSDN doc HRESULT hr = ::DMOGetName(m_audioEffects[index], name); if (SUCCEEDED(hr)) { ret["name"] = QString::fromUtf16((unsigned short*)name); } } break; #endif //QT_NO_PHONON_EFFECT default: break; } return ret; } bool Backend::endConnectionChange(QSet<QObject *> objects) { if (objects.isEmpty()) return true; //end of a transaction for(QSet<QObject *>::const_iterator it = objects.begin(); it != objects.end(); ++it) { if (BackendNode *node = qobject_cast<BackendNode*>(*it)) { MediaObject *mo = node->mediaObject(); if (mo) { switch(mo->transactionState) { case Phonon::ErrorState: case Phonon::StoppedState: case Phonon::LoadingState: //nothing to do break; case Phonon::PausedState: mo->pause(); break; default: mo->play(); break; } return mo->state() != Phonon::ErrorState; } } } return false; } bool Backend::startConnectionChange(QSet<QObject *> objects) { if (objects.isEmpty()) return true; //let's save the state of the graph (before we stop it) for(QSet<QObject *>::const_iterator it = objects.begin(); it != objects.end(); ++it) { if (BackendNode *node = qobject_cast<BackendNode*>(*it)) { if (MediaObject *mo = node->mediaObject()) { if (mo->state() != Phonon::StoppedState) { mo->transactionState = mo->state(); mo->ensureStopped(); //we have to stop the graph.. } return true; } } } return false; } bool Backend::connectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } //setting the graph if needed if (source->mediaObject() == 0 && sink->mediaObject() == 0) { //error: no graph selected return false; } else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) { //this' graph becomes the common one source->mediaObject()->grabNode(sink); } else if (source->mediaObject() == 0) { //sink's graph becomes the common one sink->mediaObject()->grabNode(source); } return source->mediaObject()->connectNodes(source, sink); } bool Backend::disconnectNodes(QObject *_source, QObject *_sink) { BackendNode *source = qobject_cast<BackendNode*>(_source); if (!source) { return false; } BackendNode *sink = qobject_cast<BackendNode*>(_sink); if (!sink) { return false; } return source->mediaObject() == 0 || source->mediaObject()->disconnectNodes(source, sink); } } } QT_END_NAMESPACE #include "moc_backend.cpp" <|endoftext|>
<commit_before>// implementation for chart.h #include <cassert> #include <sstream> namespace MathTL { template <unsigned int DIM_d, unsigned int DIM_m> std::ostream& operator << (std::ostream& s, const Chart<DIM_d,DIM_m>& c) { s << c.to_string(); return s; } template <unsigned int DIM> AffineLinearMapping<DIM>::AffineLinearMapping() : A_(DIM, DIM), A_inv(DIM, DIM), det_A(1.0), b_() { A_.diagonal(DIM, 1.0); A_inv.diagonal(DIM, 1.0); } template <unsigned int DIM> AffineLinearMapping<DIM>::AffineLinearMapping(const Matrix<double>& A, const Point<DIM>& b) : A_(A), A_inv(DIM, DIM), b_(b) { assert(A.row_dimension() == DIM && A.column_dimension() == DIM); assert(DIM == 1 || DIM == 2); switch (DIM) { case 1: det_A = A_(0,0); A_inv(0,0) = 1./det_A; break; case 2: det_A = A_(0,0)*A_(1,1)-A_(1,0)*A_(0,1); A_inv(0,0) = A_(1,1)/det_A; A_inv(0,1) = -A_(0,1)/det_A; A_inv(1,0) = -A_(1,0)/det_A; A_inv(1,1) = A_(0,0)/det_A; break; } } template <unsigned int DIM> inline void AffineLinearMapping<DIM>::map_point(const Point<DIM>& x, Point<DIM>& y) const { A_.apply(x, y); y += b_; } template <unsigned int DIM> inline void AffineLinearMapping<DIM>::map_point_inv(const Point<DIM>& x, Point<DIM>& y) const { A_inv.apply(Point<DIM>(x-b_), y); } template <unsigned int DIM> inline const double AffineLinearMapping<DIM>::Gram_factor(const Point<DIM>& x) const { return fabs(det_A); } template <unsigned int DIM> inline const double AffineLinearMapping<DIM>::Gram_D_factor(const unsigned int i, const Point<DIM>& x) const { return 0.0; } template <unsigned int DIM> inline const double AffineLinearMapping<DIM>::Dkappa_inv(const unsigned int i, const unsigned int j, const Point<DIM>& x) const { return A_inv(i, j); } template <unsigned int DIM> const bool AffineLinearMapping<DIM>::in_patch(const Point<DIM>& x) const { Point<DIM> y; map_point_inv(x, y); for (unsigned int i = 0; i < DIM; i++) if (y[i] < 0 || y[i] > 1) return false; return true; } template <unsigned int DIM> const string AffineLinearMapping<DIM>::to_string() const { std::stringstream strs; strs << "A =" << endl << A() << "b = " << b() << endl; return strs.str(); } } <commit_msg>gcc 4.0 problem fixed<commit_after>// implementation for chart.h #include <iostream> #include <cassert> #include <sstream> using std::cout; using std::endl; namespace MathTL { template <unsigned int DIM_d, unsigned int DIM_m> std::ostream& operator << (std::ostream& s, const Chart<DIM_d,DIM_m>& c) { s << c.to_string(); return s; } template <unsigned int DIM> AffineLinearMapping<DIM>::AffineLinearMapping() : A_(DIM, DIM), A_inv(DIM, DIM), det_A(1.0), b_() { A_.diagonal(DIM, 1.0); A_inv.diagonal(DIM, 1.0); } template <unsigned int DIM> AffineLinearMapping<DIM>::AffineLinearMapping(const Matrix<double>& A, const Point<DIM>& b) : A_(A), A_inv(DIM, DIM), b_(b) { assert(A.row_dimension() == DIM && A.column_dimension() == DIM); assert(DIM == 1 || DIM == 2); switch (DIM) { case 1: det_A = A_(0,0); A_inv(0,0) = 1./det_A; break; case 2: det_A = A_(0,0)*A_(1,1)-A_(1,0)*A_(0,1); A_inv(0,0) = A_(1,1)/det_A; A_inv(0,1) = -A_(0,1)/det_A; A_inv(1,0) = -A_(1,0)/det_A; A_inv(1,1) = A_(0,0)/det_A; break; } } template <unsigned int DIM> inline void AffineLinearMapping<DIM>::map_point(const Point<DIM>& x, Point<DIM>& y) const { A_.apply(x, y); y += b_; } template <unsigned int DIM> inline void AffineLinearMapping<DIM>::map_point_inv(const Point<DIM>& x, Point<DIM>& y) const { A_inv.apply(Point<DIM>(x-b_), y); } template <unsigned int DIM> inline const double AffineLinearMapping<DIM>::Gram_factor(const Point<DIM>& x) const { return fabs(det_A); } template <unsigned int DIM> inline const double AffineLinearMapping<DIM>::Gram_D_factor(const unsigned int i, const Point<DIM>& x) const { return 0.0; } template <unsigned int DIM> inline const double AffineLinearMapping<DIM>::Dkappa_inv(const unsigned int i, const unsigned int j, const Point<DIM>& x) const { return A_inv(i, j); } template <unsigned int DIM> const bool AffineLinearMapping<DIM>::in_patch(const Point<DIM>& x) const { Point<DIM> y; map_point_inv(x, y); for (unsigned int i = 0; i < DIM; i++) if (y[i] < 0 || y[i] > 1) return false; return true; } template <unsigned int DIM> const string AffineLinearMapping<DIM>::to_string() const { std::stringstream strs; strs << "A =" << endl << A() << "b = " << b() << endl; return strs.str(); } } <|endoftext|>
<commit_before>//===- LazyLiveness.cpp - Lazy, CFG-invariant liveness information --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass implements a lazy liveness analysis as per "Fast Liveness Checking // for SSA-form Programs," by Boissinot, et al. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "lazyliveness" #include "llvm/CodeGen/LazyLiveness.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/PostOrderIterator.h" using namespace llvm; char LazyLiveness::ID = 0; void LazyLiveness::computeBackedgeChain(MachineFunction& mf, MachineBasicBlock* MBB) { SparseBitVector<128> tmp = rv[MBB]; tmp.set(preorder[MBB]); tmp &= backedge_source; calculated.set(preorder[MBB]); for (SparseBitVector<128>::iterator I = tmp.begin(); I != tmp.end(); ++I) { MachineBasicBlock* SrcMBB = rev_preorder[*I]; for (MachineBasicBlock::succ_iterator SI = SrcMBB->succ_begin(); SI != SrcMBB->succ_end(); ++SI) { MachineBasicBlock* TgtMBB = *SI; if (backedges.count(std::make_pair(SrcMBB, TgtMBB)) && !rv[MBB].test(preorder[TgtMBB])) { if (!calculated.test(preorder[TgtMBB])) computeBackedgeChain(mf, TgtMBB); tv[MBB].set(preorder[TgtMBB]); tv[MBB] |= tv[TgtMBB]; } } tv[MBB].reset(preorder[MBB]); } } bool LazyLiveness::runOnMachineFunction(MachineFunction &mf) { rv.clear(); tv.clear(); backedges.clear(); backedge_source.clear(); backedge_target.clear(); calculated.clear(); preorder.clear(); MRI = &mf.getRegInfo(); // Step 0: Compute preorder numbering for all MBBs. unsigned num = 0; for (df_iterator<MachineBasicBlock*> DI = df_begin(&*mf.begin()); DI != df_end(&*mf.end()); ++DI) { preorder[*DI] = num++; rev_preorder.push_back(*DI); } // Step 1: Compute the transitive closure of the CFG, ignoring backedges. for (po_iterator<MachineBasicBlock*> POI = po_begin(&*mf.begin()); POI != po_end(&*mf.begin()); ++POI) { MachineBasicBlock* MBB = *POI; SparseBitVector<128>& entry = rv[MBB]; entry.set(preorder[MBB]); for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(); SI != MBB->succ_end(); ++SI) { DenseMap<MachineBasicBlock*, SparseBitVector<128> >::iterator SII = rv.find(*SI); // Because we're iterating in postorder, any successor that does not yet // have an rv entry must be on a backedge. if (SII != rv.end()) { entry |= SII->second; } else { backedges.insert(std::make_pair(MBB, *SI)); backedge_source.set(preorder[MBB]); backedge_target.set(preorder[*SI]); } } } for (SparseBitVector<128>::iterator I = backedge_source.begin(); I != backedge_source.end(); ++I) computeBackedgeChain(mf, rev_preorder[*I]); for (po_iterator<MachineBasicBlock*> POI = po_begin(&*mf.begin()), POE = po_end(&*mf.begin()); POI != POE; ++POI) if (!backedge_target.test(preorder[*POI])) for (MachineBasicBlock::succ_iterator SI = (*POI)->succ_begin(); SI != (*POI)->succ_end(); ++SI) if (!backedges.count(std::make_pair(*POI, *SI)) && tv.count(*SI)) tv[*POI]= tv[*SI]; for (po_iterator<MachineBasicBlock*> POI = po_begin(&*mf.begin()), POE = po_end(&*mf.begin()); POI != POE; ++POI) tv[*POI].set(preorder[*POI]); return false; } bool LazyLiveness::vregLiveIntoMBB(unsigned vreg, MachineBasicBlock* MBB) { MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>(); MachineBasicBlock* DefMBB = MRI->def_begin(vreg)->getParent(); unsigned def = preorder[DefMBB]; unsigned max_dom = 0; for (df_iterator<MachineDomTreeNode*> DI = df_begin(MDT[DefMBB]); DI != df_end(MDT[DefMBB]); ++DI) if (preorder[DI->getBlock()] > max_dom) { max_dom = preorder[(*DI)->getBlock()]; } if (preorder[MBB] <= def || max_dom < preorder[MBB]) return false; SparseBitVector<128>::iterator I = tv[MBB].begin(); while (I != tv[MBB].end() && *I <= def) ++I; while (I != tv[MBB].end() && *I < max_dom) { for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(vreg); UI != MachineRegisterInfo::use_end(); ++UI) { MachineBasicBlock* UseMBB = UI->getParent(); if (rv[rev_preorder[*I]].test(preorder[UseMBB])) return true; unsigned t_dom = 0; for (df_iterator<MachineDomTreeNode*> DI = df_begin(MDT[rev_preorder[*I]]); DI != df_end(MDT[rev_preorder[*I]]); ++DI) if (preorder[DI->getBlock()] > t_dom) { max_dom = preorder[(*DI)->getBlock()]; } I = tv[MBB].begin(); while (I != tv[MBB].end() && *I < t_dom) ++I; } } return false; } <commit_msg>Now with less iterator invalidation, and other forms of crashing!<commit_after>//===- LazyLiveness.cpp - Lazy, CFG-invariant liveness information --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass implements a lazy liveness analysis as per "Fast Liveness Checking // for SSA-form Programs," by Boissinot, et al. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "lazyliveness" #include "llvm/CodeGen/LazyLiveness.h" #include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/PostOrderIterator.h" using namespace llvm; char LazyLiveness::ID = 0; static RegisterPass<LazyLiveness> X("lazy-liveness", "Lazy Liveness Analysis"); void LazyLiveness::computeBackedgeChain(MachineFunction& mf, MachineBasicBlock* MBB) { SparseBitVector<128> tmp = rv[MBB]; tmp.set(preorder[MBB]); tmp &= backedge_source; calculated.set(preorder[MBB]); for (SparseBitVector<128>::iterator I = tmp.begin(); I != tmp.end(); ++I) { MachineBasicBlock* SrcMBB = rev_preorder[*I]; for (MachineBasicBlock::succ_iterator SI = SrcMBB->succ_begin(); SI != SrcMBB->succ_end(); ++SI) { MachineBasicBlock* TgtMBB = *SI; if (backedges.count(std::make_pair(SrcMBB, TgtMBB)) && !rv[MBB].test(preorder[TgtMBB])) { if (!calculated.test(preorder[TgtMBB])) computeBackedgeChain(mf, TgtMBB); tv[MBB].set(preorder[TgtMBB]); tv[MBB] |= tv[TgtMBB]; } } tv[MBB].reset(preorder[MBB]); } } bool LazyLiveness::runOnMachineFunction(MachineFunction &mf) { rv.clear(); tv.clear(); backedges.clear(); backedge_source.clear(); backedge_target.clear(); calculated.clear(); preorder.clear(); MRI = &mf.getRegInfo(); // Step 0: Compute preorder numbering for all MBBs. unsigned num = 0; for (df_iterator<MachineBasicBlock*> DI = df_begin(&*mf.begin()); DI != df_end(&*mf.begin()); ++DI) { preorder[*DI] = num++; rev_preorder.push_back(*DI); } // Step 1: Compute the transitive closure of the CFG, ignoring backedges. for (po_iterator<MachineBasicBlock*> POI = po_begin(&*mf.begin()); POI != po_end(&*mf.begin()); ++POI) { MachineBasicBlock* MBB = *POI; SparseBitVector<128>& entry = rv[MBB]; entry.set(preorder[MBB]); for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(); SI != MBB->succ_end(); ++SI) { DenseMap<MachineBasicBlock*, SparseBitVector<128> >::iterator SII = rv.find(*SI); // Because we're iterating in postorder, any successor that does not yet // have an rv entry must be on a backedge. if (SII != rv.end()) { entry |= SII->second; } else { backedges.insert(std::make_pair(MBB, *SI)); backedge_source.set(preorder[MBB]); backedge_target.set(preorder[*SI]); } } } for (SparseBitVector<128>::iterator I = backedge_source.begin(); I != backedge_source.end(); ++I) computeBackedgeChain(mf, rev_preorder[*I]); for (po_iterator<MachineBasicBlock*> POI = po_begin(&*mf.begin()), POE = po_end(&*mf.begin()); POI != POE; ++POI) if (!backedge_target.test(preorder[*POI])) for (MachineBasicBlock::succ_iterator SI = (*POI)->succ_begin(); SI != (*POI)->succ_end(); ++SI) if (!backedges.count(std::make_pair(*POI, *SI)) && tv.count(*SI)) { SparseBitVector<128>& PBV = tv[*POI]; PBV = tv[*SI]; } for (po_iterator<MachineBasicBlock*> POI = po_begin(&*mf.begin()), POE = po_end(&*mf.begin()); POI != POE; ++POI) tv[*POI].set(preorder[*POI]); return false; } bool LazyLiveness::vregLiveIntoMBB(unsigned vreg, MachineBasicBlock* MBB) { MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>(); MachineBasicBlock* DefMBB = MRI->def_begin(vreg)->getParent(); unsigned def = preorder[DefMBB]; unsigned max_dom = 0; for (df_iterator<MachineDomTreeNode*> DI = df_begin(MDT[DefMBB]); DI != df_end(MDT[DefMBB]); ++DI) if (preorder[DI->getBlock()] > max_dom) { max_dom = preorder[(*DI)->getBlock()]; } if (preorder[MBB] <= def || max_dom < preorder[MBB]) return false; SparseBitVector<128>::iterator I = tv[MBB].begin(); while (I != tv[MBB].end() && *I <= def) ++I; while (I != tv[MBB].end() && *I < max_dom) { for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(vreg); UI != MachineRegisterInfo::use_end(); ++UI) { MachineBasicBlock* UseMBB = UI->getParent(); if (rv[rev_preorder[*I]].test(preorder[UseMBB])) return true; unsigned t_dom = 0; for (df_iterator<MachineDomTreeNode*> DI = df_begin(MDT[rev_preorder[*I]]); DI != df_end(MDT[rev_preorder[*I]]); ++DI) if (preorder[DI->getBlock()] > t_dom) { max_dom = preorder[(*DI)->getBlock()]; } I = tv[MBB].begin(); while (I != tv[MBB].end() && *I < t_dom) ++I; } } return false; } <|endoftext|>
<commit_before>#include <medAbstractLayeredView.h> #include <dtkCore/dtkSmartPointer.h> #include <medAbstractData.h> #include <medAbstractLayeredViewInteractor.h> #include <medLayeredViewFactory.h> class medAbstractLayeredViewPrivate { public: QList <dtkSmartPointer<medAbstractData> > layersDataList; QHash<dtkSmartPointer<medAbstractData>, medAbstractLayeredViewInteractor*> primaryInteractorsHash; QHash<dtkSmartPointer<medAbstractData>, QList<medAbstractInteractor*> > extraInteractorsHash; medAbstractLayeredViewNavigator* primaryNavigator; QList<medAbstractNavigator*> extraNavigators; unsigned int currentLayer; }; medAbstractLayeredView::medAbstractLayeredView(QObject *parent) : medAbstractView(parent), d (new medAbstractLayeredViewPrivate) { d->primaryNavigator = NULL; d->currentLayer = 0; } medAbstractLayeredView::~medAbstractLayeredView() { delete d; } void medAbstractLayeredView::removeInteractors(medAbstractData *data) { medAbstractLayeredViewInteractor* pInteractor = d->primaryInteractorsHash.take(data); pInteractor->removeData(); delete pInteractor; QList<medAbstractInteractor*> extraInt = d->extraInteractorsHash.take(data); foreach(medAbstractInteractor* extra, extraInt) { delete extra; } extraInt.clear(); } bool medAbstractLayeredView::initialiseInteractors(medAbstractData *data) { // primary medLayeredViewFactory* factory = medLayeredViewFactory::instance(); QStringList primaryInt = factory->interactorsAbleToHandle(this->identifier(), data->identifier()); if(primaryInt.isEmpty()) { qWarning() << "Unable to find any primary interactor for: " << this->identifier() << "and" << data->identifier(); return false; } else { medAbstractLayeredViewInteractor* interactor = factory->createInteractor(primaryInt.first(), this); interactor->setData(data); d->primaryInteractorsHash.insert(data, interactor); connect(this, SIGNAL(orientationChanged()), interactor, SLOT(updateWidgets())); } // extra QStringList extraInt = factory->additionalInteractorsAbleToHandle(this->identifier(), data->identifier()); if(!extraInt.isEmpty()) { QList<medAbstractInteractor*> extraIntList; foreach (QString i, extraInt) { medAbstractInteractor* interactor = factory->createAdditionalInteractor(i, this); interactor->setData(data); connect(this, SIGNAL(orientationChanged()), interactor, SLOT(updateWidgets())); extraIntList << interactor; } d->extraInteractorsHash.insert(data, extraIntList); } return true; } bool medAbstractLayeredView::initialiseNavigators() { // primary medLayeredViewFactory* factory = medLayeredViewFactory::instance(); QStringList primaryNav = factory->navigatorsAbleToHandle(this->identifier()); if(primaryNav.isEmpty()) { qWarning() << "Unable to find any primary navigator for: " << this->identifier(); return false; } else { d->primaryNavigator = factory->createNavigator(primaryNav.first(), this); connect(this, SIGNAL(orientationChanged()), d->primaryNavigator, SLOT(updateWidgets())); connect(this, SIGNAL(currentLayerChanged()), d->primaryNavigator, SLOT(updateWidgets())); } // extra QStringList extraNav = factory->additionalNavigatorsAbleToHandle(this->identifier()); if(!extraNav.isEmpty()) { foreach (QString n, extraNav) { medAbstractNavigator* nav = factory->createAdditionalNavigator(n, this); connect(this, SIGNAL(orientationChanged()), nav, SLOT(updateWidgets())); connect(this, SIGNAL(currentLayerChanged()), nav, SLOT(updateWidgets())); d->extraNavigators << nav; } } return true; } medAbstractLayeredViewInteractor* medAbstractLayeredView::primaryInteractor(medAbstractData* data) { if(d->primaryInteractorsHash.isEmpty()) return NULL; return d->primaryInteractorsHash.value(data); } QList<medAbstractInteractor*> medAbstractLayeredView::extraInteractors(medAbstractData* data) { return d->extraInteractorsHash.value(data); } medAbstractLayeredViewInteractor* medAbstractLayeredView::primaryInteractor(unsigned int layer) { return d->primaryInteractorsHash.value(this->layerData(layer)); } QList<medAbstractInteractor*> medAbstractLayeredView::extraInteractors(unsigned int layer) { return d->extraInteractorsHash.value(this->layerData(layer)); } medAbstractLayeredViewNavigator* medAbstractLayeredView::primaryNavigator() { return d->primaryNavigator; } QList<medAbstractNavigator*> medAbstractLayeredView::extraNavigators() { return d->extraNavigators; } void medAbstractLayeredView::addLayer(medAbstractData *data) { this->insertLayer(d->layersDataList.count(), data); } QList<dtkSmartPointer<medAbstractData> > medAbstractLayeredView::dataList() const { return d->layersDataList; } unsigned int medAbstractLayeredView::layer(medAbstractData * data) { return d->layersDataList.indexOf(data); } void medAbstractLayeredView::removeData(medAbstractData *data) { if(!d->layersDataList.contains(data)) return; this->removeInteractors(data); int layer = this->layer(data); d->layersDataList.removeAll(data); if(d->layersDataList.count() != 0 && layer == d->layersDataList.count()) { this->setCurrentLayer(layer -1); emit layerRemoved(layer); } else if(d->layersDataList.count() != 0) { this->setCurrentLayer(layer); emit layerRemoved(layer); } else this->~medAbstractLayeredView(); } void medAbstractLayeredView::removeLayer(unsigned int layer) { this->removeData(this->layerData(layer)); } void medAbstractLayeredView::removeLayer() { this->removeData(this->layerData(d->currentLayer)); } void medAbstractLayeredView::insertLayer(unsigned int layer, medAbstractData *data) { if(!data) { qWarning() << "Attempt to add a NULL data to the view: " << this; return; } if ( this->contains(data)) { qDebug() << "Attempt to add twice the same data to the view: " << this; return; } d->layersDataList.insert(layer, data); bool initSuccess = this->initialiseInteractors(data); if(!initSuccess) { d->layersDataList.removeOne(data); return; } this->setCurrentLayer(layer); if(this->layersCount() == 1) this->reset(); emit layerAdded(layer); } void medAbstractLayeredView::moveLayer(unsigned int fromLayer, unsigned int toLayer) { d->layersDataList.move(fromLayer, toLayer); //TODO I'm not sure we really want this. find out which signal emit. - RDE. } medAbstractData * medAbstractLayeredView::layerData(unsigned int layer) const { if (layer > (unsigned int)d->layersDataList.size()) { qWarning() << "Unable to retreive data at layer:" <<layer << "from: "<< this->description(); return NULL; } return d->layersDataList[layer]; } bool medAbstractLayeredView::contains(medAbstractData * data) const { return d->layersDataList.contains(data); } bool medAbstractLayeredView::contains(QString identifier) const { foreach(medAbstractData *data, d->layersDataList) { if(data->identifier() == identifier) return true; } return false; } unsigned int medAbstractLayeredView::layersCount() const { return d->layersDataList.count(); } void medAbstractLayeredView::setVisibility(bool visibility, unsigned int layer) { medAbstractLayeredViewInteractor* inter = this->primaryInteractor(layer); if(!inter) return; inter->setVisibility(visibility); emit visibilityChanged(visibility, layer); } void medAbstractLayeredView::setVisibility(bool visibility) { medAbstractLayeredViewInteractor* inter = this->primaryInteractor(d->currentLayer); if(!inter) return; inter->setVisibility(visibility); emit visibilityChanged(visibility, d->currentLayer); } bool medAbstractLayeredView::visibility(unsigned int layer) { medAbstractLayeredViewInteractor* inter = this->primaryInteractor(layer); if(!inter) return true; return inter->visibility(); } unsigned int medAbstractLayeredView::currentLayer() const { return d->currentLayer; } void medAbstractLayeredView::setCurrentLayer(unsigned int layer) { d->currentLayer = layer; emit currentLayerChanged(); } QImage medAbstractLayeredView::generateThumbnail(const QSize &size) { medAbstractLayeredViewInteractor *primaryInteractor = this->primaryInteractor(this->layerData(d->currentLayer)); if(!primaryInteractor) { qWarning()<< "unable to find any primary interactor for view" <<this->identifier() << "and data" << this->layerData(d->currentLayer)->identifier(); return QImage(); } return this->primaryInteractor(this->layerData(d->currentLayer))->generateThumbnail(size); } //TODO not sure we need this - RDE QList <medAbstractInteractor*> medAbstractLayeredView::currentInteractors() { QList <medAbstractInteractor*> interactors; interactors.append(this->primaryInteractor(d->currentLayer)); interactors.append(extraInteractors(d->currentLayer)); return interactors; } QList <medAbstractInteractor*> medAbstractLayeredView::interactors(unsigned int layer) { QList <medAbstractInteractor*> interactors; interactors << this->primaryInteractor(layer) << this->extraInteractors(layer); return interactors; } <commit_msg>correction in medAbstractLayeredView<commit_after>#include <medAbstractLayeredView.h> #include <dtkCore/dtkSmartPointer.h> #include <medAbstractData.h> #include <medAbstractLayeredViewInteractor.h> #include <medLayeredViewFactory.h> class medAbstractLayeredViewPrivate { public: QList <dtkSmartPointer<medAbstractData> > layersDataList; QHash<dtkSmartPointer<medAbstractData>, medAbstractLayeredViewInteractor*> primaryInteractorsHash; QHash<dtkSmartPointer<medAbstractData>, QList<medAbstractInteractor*> > extraInteractorsHash; medAbstractLayeredViewNavigator* primaryNavigator; QList<medAbstractNavigator*> extraNavigators; unsigned int currentLayer; }; medAbstractLayeredView::medAbstractLayeredView(QObject *parent) : medAbstractView(parent), d (new medAbstractLayeredViewPrivate) { d->primaryNavigator = NULL; d->currentLayer = 0; } medAbstractLayeredView::~medAbstractLayeredView() { delete d; } void medAbstractLayeredView::removeInteractors(medAbstractData *data) { medAbstractLayeredViewInteractor* pInteractor = d->primaryInteractorsHash.take(data); pInteractor->removeData(); delete pInteractor; QList<medAbstractInteractor*> extraInt = d->extraInteractorsHash.take(data); foreach(medAbstractInteractor* extra, extraInt) { delete extra; } extraInt.clear(); } bool medAbstractLayeredView::initialiseInteractors(medAbstractData *data) { // primary medLayeredViewFactory* factory = medLayeredViewFactory::instance(); QStringList primaryInt = factory->interactorsAbleToHandle(this->identifier(), data->identifier()); if(primaryInt.isEmpty()) { qWarning() << "Unable to find any primary interactor for: " << this->identifier() << "and" << data->identifier(); return false; } else { medAbstractLayeredViewInteractor* interactor = factory->createInteractor(primaryInt.first(), this); interactor->setData(data); d->primaryInteractorsHash.insert(data, interactor); connect(this, SIGNAL(orientationChanged()), interactor, SLOT(updateWidgets())); } // extra QStringList extraInt = factory->additionalInteractorsAbleToHandle(this->identifier(), data->identifier()); if(!extraInt.isEmpty()) { QList<medAbstractInteractor*> extraIntList; foreach (QString i, extraInt) { medAbstractInteractor* interactor = factory->createAdditionalInteractor(i, this); interactor->setData(data); connect(this, SIGNAL(orientationChanged()), interactor, SLOT(updateWidgets())); extraIntList << interactor; } d->extraInteractorsHash.insert(data, extraIntList); } return true; } bool medAbstractLayeredView::initialiseNavigators() { // primary medLayeredViewFactory* factory = medLayeredViewFactory::instance(); QStringList primaryNav = factory->navigatorsAbleToHandle(this->identifier()); if(primaryNav.isEmpty()) { qWarning() << "Unable to find any primary navigator for: " << this->identifier(); return false; } else { d->primaryNavigator = factory->createNavigator(primaryNav.first(), this); connect(this, SIGNAL(orientationChanged()), d->primaryNavigator, SLOT(updateWidgets())); connect(this, SIGNAL(currentLayerChanged()), d->primaryNavigator, SLOT(updateWidgets())); } // extra QStringList extraNav = factory->additionalNavigatorsAbleToHandle(this->identifier()); if(!extraNav.isEmpty()) { foreach (QString n, extraNav) { medAbstractNavigator* nav = factory->createAdditionalNavigator(n, this); connect(this, SIGNAL(orientationChanged()), nav, SLOT(updateWidgets())); connect(this, SIGNAL(currentLayerChanged()), nav, SLOT(updateWidgets())); d->extraNavigators << nav; } } return true; } medAbstractLayeredViewInteractor* medAbstractLayeredView::primaryInteractor(medAbstractData* data) { if(d->primaryInteractorsHash.isEmpty()) return NULL; return d->primaryInteractorsHash.value(data); } QList<medAbstractInteractor*> medAbstractLayeredView::extraInteractors(medAbstractData* data) { return d->extraInteractorsHash.value(data); } medAbstractLayeredViewInteractor* medAbstractLayeredView::primaryInteractor(unsigned int layer) { return d->primaryInteractorsHash.value(this->layerData(layer)); } QList<medAbstractInteractor*> medAbstractLayeredView::extraInteractors(unsigned int layer) { return d->extraInteractorsHash.value(this->layerData(layer)); } medAbstractLayeredViewNavigator* medAbstractLayeredView::primaryNavigator() { return d->primaryNavigator; } QList<medAbstractNavigator*> medAbstractLayeredView::extraNavigators() { return d->extraNavigators; } void medAbstractLayeredView::addLayer(medAbstractData *data) { this->insertLayer(d->layersDataList.count(), data); } QList<dtkSmartPointer<medAbstractData> > medAbstractLayeredView::dataList() const { return d->layersDataList; } unsigned int medAbstractLayeredView::layer(medAbstractData * data) { return d->layersDataList.indexOf(data); } void medAbstractLayeredView::removeData(medAbstractData *data) { if(!d->layersDataList.contains(data)) return; this->removeInteractors(data); int layer = this->layer(data); d->layersDataList.removeAll(data); if(d->layersDataList.count() != 0 && layer == d->layersDataList.count()) { this->setCurrentLayer(layer -1); emit layerRemoved(layer); } else if(d->layersDataList.count() != 0) { this->setCurrentLayer(layer); emit layerRemoved(layer); } else this->~medAbstractLayeredView(); } void medAbstractLayeredView::removeLayer(unsigned int layer) { this->removeData(this->layerData(layer)); } void medAbstractLayeredView::removeLayer() { this->removeData(this->layerData(d->currentLayer)); } void medAbstractLayeredView::insertLayer(unsigned int layer, medAbstractData *data) { if(!data) { qWarning() << "Attempt to add a NULL data to the view: " << this; return; } if ( this->contains(data)) { qDebug() << "Attempt to add twice the same data to the view: " << this; return; } d->layersDataList.insert(layer, data); bool initSuccess = this->initialiseInteractors(data); if(!initSuccess) { d->layersDataList.removeOne(data); return; } this->setCurrentLayer(layer); if(this->layersCount() == 1) this->reset(); emit layerAdded(layer); } void medAbstractLayeredView::moveLayer(unsigned int fromLayer, unsigned int toLayer) { d->layersDataList.move(fromLayer, toLayer); //TODO I'm not sure we really want this. find out which signal emit. - RDE. } medAbstractData * medAbstractLayeredView::layerData(unsigned int layer) const { if (layer >= (unsigned int)d->layersDataList.size()) { qWarning() << "Unable to retreive data at layer:" <<layer << "from: "<< this->description(); return NULL; } return d->layersDataList[layer]; } bool medAbstractLayeredView::contains(medAbstractData * data) const { return d->layersDataList.contains(data); } bool medAbstractLayeredView::contains(QString identifier) const { foreach(medAbstractData *data, d->layersDataList) { if(data->identifier() == identifier) return true; } return false; } unsigned int medAbstractLayeredView::layersCount() const { return d->layersDataList.count(); } void medAbstractLayeredView::setVisibility(bool visibility, unsigned int layer) { medAbstractLayeredViewInteractor* inter = this->primaryInteractor(layer); if(!inter) return; inter->setVisibility(visibility); emit visibilityChanged(visibility, layer); } void medAbstractLayeredView::setVisibility(bool visibility) { medAbstractLayeredViewInteractor* inter = this->primaryInteractor(d->currentLayer); if(!inter) return; inter->setVisibility(visibility); emit visibilityChanged(visibility, d->currentLayer); } bool medAbstractLayeredView::visibility(unsigned int layer) { medAbstractLayeredViewInteractor* inter = this->primaryInteractor(layer); if(!inter) return true; return inter->visibility(); } unsigned int medAbstractLayeredView::currentLayer() const { return d->currentLayer; } void medAbstractLayeredView::setCurrentLayer(unsigned int layer) { d->currentLayer = layer; emit currentLayerChanged(); } QImage medAbstractLayeredView::generateThumbnail(const QSize &size) { medAbstractLayeredViewInteractor *primaryInteractor = this->primaryInteractor(this->layerData(d->currentLayer)); if(!primaryInteractor) { qWarning()<< "unable to find any primary interactor for view" <<this->identifier() << "and data" << this->layerData(d->currentLayer)->identifier(); return QImage(); } return this->primaryInteractor(this->layerData(d->currentLayer))->generateThumbnail(size); } //TODO not sure we need this - RDE QList <medAbstractInteractor*> medAbstractLayeredView::currentInteractors() { QList <medAbstractInteractor*> interactors; interactors.append(this->primaryInteractor(d->currentLayer)); interactors.append(extraInteractors(d->currentLayer)); return interactors; } QList <medAbstractInteractor*> medAbstractLayeredView::interactors(unsigned int layer) { QList <medAbstractInteractor*> interactors; interactors << this->primaryInteractor(layer) << this->extraInteractors(layer); return interactors; } <|endoftext|>
<commit_before> /* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * SimpleNetwork.cc * * Description: See SimpleNetwork.hh * * $Id$ * */ #include "mem/ruby/network/simple/SimpleNetwork.hh" #include "mem/ruby/profiler/Profiler.hh" #include "mem/ruby/system/System.hh" #include "mem/ruby/network/simple/Switch.hh" #include "mem/ruby/common/NetDest.hh" #include "mem/ruby/network/simple/Topology.hh" #include "mem/protocol/TopologyType.hh" #include "mem/protocol/MachineType.hh" #include "mem/ruby/buffers/MessageBuffer.hh" #include "mem/protocol/Protocol.hh" #include "mem/gems_common/Map.hh" // ***BIG HACK*** - This is actually code that _should_ be in Network.cc // Note: Moved to Princeton Network // calls new to abstract away from the network /* Network* Network::createNetwork(int nodes) { return new SimpleNetwork(nodes); } */ SimpleNetwork::SimpleNetwork(const string & name) : Network(name) { m_virtual_networks = 0; m_topology_ptr = NULL; } void SimpleNetwork::init(const vector<string> & argv) { Network::init(argv); m_endpoint_switches.setSize(m_nodes); m_in_use.setSize(m_virtual_networks); m_ordered.setSize(m_virtual_networks); for (int i = 0; i < m_virtual_networks; i++) { m_in_use[i] = false; m_ordered[i] = false; } // Allocate to and from queues m_toNetQueues.setSize(m_nodes); m_fromNetQueues.setSize(m_nodes); for (int node = 0; node < m_nodes; node++) { m_toNetQueues[node].setSize(m_virtual_networks); m_fromNetQueues[node].setSize(m_virtual_networks); for (int j = 0; j < m_virtual_networks; j++) { cerr << "Creating new MessageBuffer for " << node << " " << j << endl; m_toNetQueues[node][j] = new MessageBuffer; m_fromNetQueues[node][j] = new MessageBuffer; } } // Setup the network switches // m_topology_ptr = new Topology(this, m_nodes); m_topology_ptr->makeTopology(); int number_of_switches = m_topology_ptr->numSwitches(); for (int i=0; i<number_of_switches; i++) { m_switch_ptr_vector.insertAtBottom(new Switch(i, this)); } m_topology_ptr->createLinks(false); // false because this isn't a reconfiguration } /* SimpleNetwork::SimpleNetwork(int nodes) { m_nodes = MachineType_base_number(MachineType_NUM); m_virtual_networks = RubyConfig::getNumberOfVirtualNetworks(); m_endpoint_switches.setSize(m_nodes); m_in_use.setSize(m_virtual_networks); m_ordered.setSize(m_virtual_networks); for (int i = 0; i < m_virtual_networks; i++) { m_in_use[i] = false; m_ordered[i] = false; } // Allocate to and from queues m_toNetQueues.setSize(m_nodes); m_fromNetQueues.setSize(m_nodes); for (int node = 0; node < m_nodes; node++) { m_toNetQueues[node].setSize(m_virtual_networks); m_fromNetQueues[node].setSize(m_virtual_networks); for (int j = 0; j < m_virtual_networks; j++) { m_toNetQueues[node][j] = new MessageBuffer; m_fromNetQueues[node][j] = new MessageBuffer; } } // Setup the network switches m_topology_ptr = new Topology(this, m_nodes); int number_of_switches = m_topology_ptr->numSwitches(); for (int i=0; i<number_of_switches; i++) { m_switch_ptr_vector.insertAtBottom(new Switch(i, this)); } m_topology_ptr->createLinks(false); // false because this isn't a reconfiguration } */ void SimpleNetwork::reset() { for (int node = 0; node < m_nodes; node++) { for (int j = 0; j < m_virtual_networks; j++) { m_toNetQueues[node][j]->clear(); m_fromNetQueues[node][j]->clear(); } } for(int i=0; i<m_switch_ptr_vector.size(); i++){ m_switch_ptr_vector[i]->clearBuffers(); } } SimpleNetwork::~SimpleNetwork() { for (int i = 0; i < m_nodes; i++) { m_toNetQueues[i].deletePointers(); m_fromNetQueues[i].deletePointers(); } m_switch_ptr_vector.deletePointers(); m_buffers_to_free.deletePointers(); delete m_topology_ptr; } // From a switch to an endpoint node void SimpleNetwork::makeOutLink(SwitchID src, NodeID dest, const NetDest& routing_table_entry, int link_latency, int link_weight, int bw_multiplier, bool isReconfiguration) { assert(dest < m_nodes); assert(src < m_switch_ptr_vector.size()); assert(m_switch_ptr_vector[src] != NULL); if(!isReconfiguration){ m_switch_ptr_vector[src]->addOutPort(m_fromNetQueues[dest], routing_table_entry, link_latency, bw_multiplier); m_endpoint_switches[dest] = m_switch_ptr_vector[src]; } else { m_switch_ptr_vector[src]->reconfigureOutPort(routing_table_entry); } } // From an endpoint node to a switch void SimpleNetwork::makeInLink(NodeID src, SwitchID dest, const NetDest& routing_table_entry, int link_latency, int bw_multiplier, bool isReconfiguration) { assert(src < m_nodes); if(!isReconfiguration){ m_switch_ptr_vector[dest]->addInPort(m_toNetQueues[src]); } else { // do nothing } } // From a switch to a switch void SimpleNetwork::makeInternalLink(SwitchID src, SwitchID dest, const NetDest& routing_table_entry, int link_latency, int link_weight, int bw_multiplier, bool isReconfiguration) { if(!isReconfiguration){ // Create a set of new MessageBuffers Vector<MessageBuffer*> queues; for (int i = 0; i < m_virtual_networks; i++) { // allocate a buffer MessageBuffer* buffer_ptr = new MessageBuffer; buffer_ptr->setOrdering(true); if (m_buffer_size > 0) { buffer_ptr->setSize(m_buffer_size); } queues.insertAtBottom(buffer_ptr); // remember to deallocate it m_buffers_to_free.insertAtBottom(buffer_ptr); } // Connect it to the two switches m_switch_ptr_vector[dest]->addInPort(queues); m_switch_ptr_vector[src]->addOutPort(queues, routing_table_entry, link_latency, bw_multiplier); } else { m_switch_ptr_vector[src]->reconfigureOutPort(routing_table_entry); } } void SimpleNetwork::checkNetworkAllocation(NodeID id, bool ordered, int network_num) { ASSERT(id < m_nodes); ASSERT(network_num < m_virtual_networks); if (ordered) { m_ordered[network_num] = true; } m_in_use[network_num] = true; } MessageBuffer* SimpleNetwork::getToNetQueue(NodeID id, bool ordered, int network_num) { checkNetworkAllocation(id, ordered, network_num); return m_toNetQueues[id][network_num]; } MessageBuffer* SimpleNetwork::getFromNetQueue(NodeID id, bool ordered, int network_num) { checkNetworkAllocation(id, ordered, network_num); return m_fromNetQueues[id][network_num]; } const Vector<Throttle*>* SimpleNetwork::getThrottles(NodeID id) const { assert(id >= 0); assert(id < m_nodes); assert(m_endpoint_switches[id] != NULL); return m_endpoint_switches[id]->getThrottles(); } void SimpleNetwork::printStats(ostream& out) const { out << endl; out << "Network Stats" << endl; out << "-------------" << endl; out << endl; for(int i=0; i<m_switch_ptr_vector.size(); i++) { m_switch_ptr_vector[i]->printStats(out); } } void SimpleNetwork::clearStats() { for(int i=0; i<m_switch_ptr_vector.size(); i++) { m_switch_ptr_vector[i]->clearStats(); } } void SimpleNetwork::printConfig(ostream& out) const { out << endl; out << "Network Configuration" << endl; out << "---------------------" << endl; out << "network: SIMPLE_NETWORK" << endl; out << "topology: " << m_topology_ptr->getName() << endl; out << endl; for (int i = 0; i < m_virtual_networks; i++) { out << "virtual_net_" << i << ": "; if (m_in_use[i]) { out << "active, "; if (m_ordered[i]) { out << "ordered" << endl; } else { out << "unordered" << endl; } } else { out << "inactive" << endl; } } out << endl; for(int i=0; i<m_switch_ptr_vector.size(); i++) { m_switch_ptr_vector[i]->printConfig(out); } m_topology_ptr->printConfig(out); } void SimpleNetwork::print(ostream& out) const { out << "[SimpleNetwork]"; } <commit_msg>removed stray debug print<commit_after> /* * Copyright (c) 1999-2008 Mark D. Hill and David A. Wood * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * SimpleNetwork.cc * * Description: See SimpleNetwork.hh * * $Id$ * */ #include "mem/ruby/network/simple/SimpleNetwork.hh" #include "mem/ruby/profiler/Profiler.hh" #include "mem/ruby/system/System.hh" #include "mem/ruby/network/simple/Switch.hh" #include "mem/ruby/common/NetDest.hh" #include "mem/ruby/network/simple/Topology.hh" #include "mem/protocol/TopologyType.hh" #include "mem/protocol/MachineType.hh" #include "mem/ruby/buffers/MessageBuffer.hh" #include "mem/protocol/Protocol.hh" #include "mem/gems_common/Map.hh" // ***BIG HACK*** - This is actually code that _should_ be in Network.cc // Note: Moved to Princeton Network // calls new to abstract away from the network /* Network* Network::createNetwork(int nodes) { return new SimpleNetwork(nodes); } */ SimpleNetwork::SimpleNetwork(const string & name) : Network(name) { m_virtual_networks = 0; m_topology_ptr = NULL; } void SimpleNetwork::init(const vector<string> & argv) { Network::init(argv); m_endpoint_switches.setSize(m_nodes); m_in_use.setSize(m_virtual_networks); m_ordered.setSize(m_virtual_networks); for (int i = 0; i < m_virtual_networks; i++) { m_in_use[i] = false; m_ordered[i] = false; } // Allocate to and from queues m_toNetQueues.setSize(m_nodes); m_fromNetQueues.setSize(m_nodes); for (int node = 0; node < m_nodes; node++) { m_toNetQueues[node].setSize(m_virtual_networks); m_fromNetQueues[node].setSize(m_virtual_networks); for (int j = 0; j < m_virtual_networks; j++) { m_toNetQueues[node][j] = new MessageBuffer; m_fromNetQueues[node][j] = new MessageBuffer; } } // Setup the network switches // m_topology_ptr = new Topology(this, m_nodes); m_topology_ptr->makeTopology(); int number_of_switches = m_topology_ptr->numSwitches(); for (int i=0; i<number_of_switches; i++) { m_switch_ptr_vector.insertAtBottom(new Switch(i, this)); } m_topology_ptr->createLinks(false); // false because this isn't a reconfiguration } /* SimpleNetwork::SimpleNetwork(int nodes) { m_nodes = MachineType_base_number(MachineType_NUM); m_virtual_networks = RubyConfig::getNumberOfVirtualNetworks(); m_endpoint_switches.setSize(m_nodes); m_in_use.setSize(m_virtual_networks); m_ordered.setSize(m_virtual_networks); for (int i = 0; i < m_virtual_networks; i++) { m_in_use[i] = false; m_ordered[i] = false; } // Allocate to and from queues m_toNetQueues.setSize(m_nodes); m_fromNetQueues.setSize(m_nodes); for (int node = 0; node < m_nodes; node++) { m_toNetQueues[node].setSize(m_virtual_networks); m_fromNetQueues[node].setSize(m_virtual_networks); for (int j = 0; j < m_virtual_networks; j++) { m_toNetQueues[node][j] = new MessageBuffer; m_fromNetQueues[node][j] = new MessageBuffer; } } // Setup the network switches m_topology_ptr = new Topology(this, m_nodes); int number_of_switches = m_topology_ptr->numSwitches(); for (int i=0; i<number_of_switches; i++) { m_switch_ptr_vector.insertAtBottom(new Switch(i, this)); } m_topology_ptr->createLinks(false); // false because this isn't a reconfiguration } */ void SimpleNetwork::reset() { for (int node = 0; node < m_nodes; node++) { for (int j = 0; j < m_virtual_networks; j++) { m_toNetQueues[node][j]->clear(); m_fromNetQueues[node][j]->clear(); } } for(int i=0; i<m_switch_ptr_vector.size(); i++){ m_switch_ptr_vector[i]->clearBuffers(); } } SimpleNetwork::~SimpleNetwork() { for (int i = 0; i < m_nodes; i++) { m_toNetQueues[i].deletePointers(); m_fromNetQueues[i].deletePointers(); } m_switch_ptr_vector.deletePointers(); m_buffers_to_free.deletePointers(); delete m_topology_ptr; } // From a switch to an endpoint node void SimpleNetwork::makeOutLink(SwitchID src, NodeID dest, const NetDest& routing_table_entry, int link_latency, int link_weight, int bw_multiplier, bool isReconfiguration) { assert(dest < m_nodes); assert(src < m_switch_ptr_vector.size()); assert(m_switch_ptr_vector[src] != NULL); if(!isReconfiguration){ m_switch_ptr_vector[src]->addOutPort(m_fromNetQueues[dest], routing_table_entry, link_latency, bw_multiplier); m_endpoint_switches[dest] = m_switch_ptr_vector[src]; } else { m_switch_ptr_vector[src]->reconfigureOutPort(routing_table_entry); } } // From an endpoint node to a switch void SimpleNetwork::makeInLink(NodeID src, SwitchID dest, const NetDest& routing_table_entry, int link_latency, int bw_multiplier, bool isReconfiguration) { assert(src < m_nodes); if(!isReconfiguration){ m_switch_ptr_vector[dest]->addInPort(m_toNetQueues[src]); } else { // do nothing } } // From a switch to a switch void SimpleNetwork::makeInternalLink(SwitchID src, SwitchID dest, const NetDest& routing_table_entry, int link_latency, int link_weight, int bw_multiplier, bool isReconfiguration) { if(!isReconfiguration){ // Create a set of new MessageBuffers Vector<MessageBuffer*> queues; for (int i = 0; i < m_virtual_networks; i++) { // allocate a buffer MessageBuffer* buffer_ptr = new MessageBuffer; buffer_ptr->setOrdering(true); if (m_buffer_size > 0) { buffer_ptr->setSize(m_buffer_size); } queues.insertAtBottom(buffer_ptr); // remember to deallocate it m_buffers_to_free.insertAtBottom(buffer_ptr); } // Connect it to the two switches m_switch_ptr_vector[dest]->addInPort(queues); m_switch_ptr_vector[src]->addOutPort(queues, routing_table_entry, link_latency, bw_multiplier); } else { m_switch_ptr_vector[src]->reconfigureOutPort(routing_table_entry); } } void SimpleNetwork::checkNetworkAllocation(NodeID id, bool ordered, int network_num) { ASSERT(id < m_nodes); ASSERT(network_num < m_virtual_networks); if (ordered) { m_ordered[network_num] = true; } m_in_use[network_num] = true; } MessageBuffer* SimpleNetwork::getToNetQueue(NodeID id, bool ordered, int network_num) { checkNetworkAllocation(id, ordered, network_num); return m_toNetQueues[id][network_num]; } MessageBuffer* SimpleNetwork::getFromNetQueue(NodeID id, bool ordered, int network_num) { checkNetworkAllocation(id, ordered, network_num); return m_fromNetQueues[id][network_num]; } const Vector<Throttle*>* SimpleNetwork::getThrottles(NodeID id) const { assert(id >= 0); assert(id < m_nodes); assert(m_endpoint_switches[id] != NULL); return m_endpoint_switches[id]->getThrottles(); } void SimpleNetwork::printStats(ostream& out) const { out << endl; out << "Network Stats" << endl; out << "-------------" << endl; out << endl; for(int i=0; i<m_switch_ptr_vector.size(); i++) { m_switch_ptr_vector[i]->printStats(out); } } void SimpleNetwork::clearStats() { for(int i=0; i<m_switch_ptr_vector.size(); i++) { m_switch_ptr_vector[i]->clearStats(); } } void SimpleNetwork::printConfig(ostream& out) const { out << endl; out << "Network Configuration" << endl; out << "---------------------" << endl; out << "network: SIMPLE_NETWORK" << endl; out << "topology: " << m_topology_ptr->getName() << endl; out << endl; for (int i = 0; i < m_virtual_networks; i++) { out << "virtual_net_" << i << ": "; if (m_in_use[i]) { out << "active, "; if (m_ordered[i]) { out << "ordered" << endl; } else { out << "unordered" << endl; } } else { out << "inactive" << endl; } } out << endl; for(int i=0; i<m_switch_ptr_vector.size(); i++) { m_switch_ptr_vector[i]->printConfig(out); } m_topology_ptr->printConfig(out); } void SimpleNetwork::print(ostream& out) const { out << "[SimpleNetwork]"; } <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "curve25519-donna.c" #include <nan.h> using namespace std; using namespace node; using namespace v8; static NAN_METHOD(DoCurve); extern "C" void init (Handle<Object>); static NAN_METHOD(DoCurve) { NanScope(); const char *usage = "usage: curve(a, b, c)"; if (args.Length() != 3) { return NanThrowError(usage); } unsigned char* arg0 = (unsigned char*) Buffer::Data(args[0]->ToObject()); unsigned char* arg1 = (unsigned char*) Buffer::Data(args[1]->ToObject()); unsigned char* arg2 = (unsigned char*) Buffer::Data(args[2]->ToObject()); curve25519_donna(arg0, arg1, arg2); } extern "C" void init (Handle<Object> target) { NanScope(); NODE_SET_METHOD(target, "curve", DoCurve); } NODE_MODULE(curve, init)<commit_msg>Update for nan v2<commit_after>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "curve25519-donna.c" #include <nan.h> using namespace std; using namespace node; using namespace v8; static NAN_METHOD(DoCurve); extern "C" void init (Handle<Object>); static NAN_METHOD(DoCurve) { Nan::HandleScope scope; const char *usage = "usage: curve(a, b, c)"; if (info.Length() != 3) { return Nan::ThrowSyntaxError(usage); } unsigned char* arg0 = (unsigned char*) Buffer::Data(info[0]->ToObject()); unsigned char* arg1 = (unsigned char*) Buffer::Data(info[1]->ToObject()); unsigned char* arg2 = (unsigned char*) Buffer::Data(info[2]->ToObject()); curve25519_donna(arg0, arg1, arg2); } extern "C" void init (Handle<Object> target) { Nan::HandleScope scope; Nan::SetMethod(target, "curve", DoCurve); } NODE_MODULE(curve, init) <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Brian McGillion ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "mercurialjobrunner.h" #include "mercurialplugin.h" #include "constants.h" #include "mercurialsettings.h" #include <vcsbase/vcsbaseoutputwindow.h> #include <vcsbase/vcsbaseeditor.h> #include <vcsbase/vcsbaseplugin.h> #include <utils/synchronousprocess.h> #include <QtCore/QProcess> #include <QtCore/QProcessEnvironment> #include <QtCore/QString> #include <QtCore/QDebug> using namespace Mercurial::Internal; using namespace Mercurial; HgTask::HgTask(const QString &repositoryRoot, const QStringList &arguments, bool emitRaw, const QVariant &cookie) : m_repositoryRoot(repositoryRoot), arguments(arguments), emitRaw(emitRaw), m_cookie(cookie), editor(0), m_unixTerminalDisabled(false) { } HgTask::HgTask(const QString &repositoryRoot, const QStringList &arguments, VCSBase::VCSBaseEditor *editor, const QVariant &cookie) : m_repositoryRoot(repositoryRoot), arguments(arguments), emitRaw(false), m_cookie(cookie), editor(editor), m_unixTerminalDisabled(false) { } void HgTask::emitSucceeded() { emit succeeded(m_cookie); } MercurialJobRunner::MercurialJobRunner() : plugin(MercurialPlugin::instance()), keepRunning(true) { VCSBase::VCSBaseOutputWindow *ow = VCSBase::VCSBaseOutputWindow::instance(); connect(this, SIGNAL(error(QString)), ow, SLOT(appendError(QString)), Qt::QueuedConnection); connect(this, SIGNAL(commandStarted(QString)), ow, SLOT(appendCommand(QString)), Qt::QueuedConnection); } MercurialJobRunner::~MercurialJobRunner() { stop(); } void MercurialJobRunner::stop() { mutex.lock(); keepRunning = false; //Create a dummy task to break the cycle QSharedPointer<HgTask> job(0); jobs.enqueue(job); waiter.wakeAll(); mutex.unlock(); wait(); } void MercurialJobRunner::restart() { stop(); mutex.lock(); keepRunning = true; mutex.unlock(); start(); } void MercurialJobRunner::getSettings() { const MercurialSettings &settings = MercurialPlugin::instance()->settings(); binary = settings.binary(); m_timeoutMS = settings.timeoutMilliSeconds(); standardArguments = settings.standardArguments(); } void MercurialJobRunner::enqueueJob(const QSharedPointer<HgTask> &job) { mutex.lock(); jobs.enqueue(job); waiter.wakeAll(); mutex.unlock(); } void MercurialJobRunner::run() { getSettings(); forever { mutex.lock(); while (jobs.count() == 0) waiter.wait(&mutex); if (!keepRunning) { jobs.clear(); mutex.unlock(); return; } QSharedPointer<HgTask> job = jobs.dequeue(); mutex.unlock(); task(job); } } QString MercurialJobRunner::msgStartFailed(const QString &binary, const QString &why) { return tr("Unable to start mercurial process '%1': %2").arg(binary, why); } QString MercurialJobRunner::msgTimeout(int timeoutSeconds) { return tr("Timed out after %1s waiting for mercurial process to finish.").arg(timeoutSeconds); } // Set environment for a hg process to run in locale "C". Note that there appears // to be a bug in hg that causes special characters to be garbled when running // in a different language, which seems to be independent from the encoding. void MercurialJobRunner::setProcessEnvironment(QProcess &p) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); VCSBase::VCSBasePlugin::setProcessEnvironment(&env); p.setProcessEnvironment(env); } void MercurialJobRunner::task(const QSharedPointer<HgTask> &job) { HgTask *taskData = job.data(); VCSBase::VCSBaseOutputWindow *outputWindow = VCSBase::VCSBaseOutputWindow::instance(); if (taskData->shouldEmit()) { //Call the job's signal so the Initator of the job can process the data //Because the QSharedPointer that holds the HgTask will go out of scope and hence be deleted //we have to block and wait until the signal is delivered connect(this, SIGNAL(output(QByteArray)), taskData, SIGNAL(rawData(QByteArray)), Qt::BlockingQueuedConnection); } else if (taskData->displayEditor()) { //An editor has been created to display the data so send it there connect(this, SIGNAL(output(QByteArray)), taskData->displayEditor(), SLOT(setPlainTextData(QByteArray)), Qt::QueuedConnection); } else { //Just output the data to the Mercurial output window connect(this, SIGNAL(output(QByteArray)), outputWindow, SLOT(appendData(QByteArray)), Qt::QueuedConnection); } const QStringList args = standardArguments + taskData->args(); emit commandStarted(VCSBase::VCSBaseOutputWindow::msgExecutionLogEntry(taskData->repositoryRoot(), binary, args)); //infom the user of what we are going to try and perform if (Constants::debug) qDebug() << Q_FUNC_INFO << "Repository root is " << taskData->repositoryRoot() << " terminal_disabled" << taskData->unixTerminalDisabled(); const unsigned processFlags = taskData->unixTerminalDisabled() ? unsigned(Utils::SynchronousProcess::UnixTerminalDisabled) : unsigned(0); QSharedPointer<QProcess> hgProcess = Utils::SynchronousProcess::createProcess(processFlags); hgProcess->setWorkingDirectory(taskData->repositoryRoot()); MercurialJobRunner::setProcessEnvironment(*hgProcess); hgProcess->start(binary, args); if (!hgProcess->waitForStarted()) { emit error(msgStartFailed(binary, hgProcess->errorString())); return; } hgProcess->closeWriteChannel(); QByteArray stdOutput; QByteArray stdErr; if (!Utils::SynchronousProcess::readDataFromProcess(*hgProcess, m_timeoutMS, &stdOutput, &stdErr, false)) { Utils::SynchronousProcess::stopProcess(*hgProcess); emit error(msgTimeout(m_timeoutMS / 1000)); return; } if (hgProcess->exitStatus() == QProcess::NormalExit && hgProcess->exitCode() == 0) { /* * sometimes success means output is actually on error channel (stderr) * e.g. "hg revert" outputs "no changes needed to 'file'" on stderr if file has not changed * from revision specified */ if (stdOutput.isEmpty()) stdOutput = stdErr; emit output(stdOutput); taskData->emitSucceeded(); } else { emit error(QString::fromLocal8Bit(stdErr)); } hgProcess->close(); //the signal connection is to last only for the duration of a job/task. next time a new //output signal connection must be made disconnect(this, SIGNAL(output(QByteArray)), 0, 0); } <commit_msg>Compile fix.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Brian McGillion ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "mercurialjobrunner.h" #include "mercurialplugin.h" #include "constants.h" #include "mercurialsettings.h" #include <vcsbase/vcsbaseoutputwindow.h> #include <vcsbase/vcsbaseeditor.h> #include <vcsbase/vcsbaseplugin.h> #include <utils/synchronousprocess.h> #include <QtCore/QProcess> #include <QtCore/QProcessEnvironment> #include <QtCore/QString> #include <QtCore/QDebug> using namespace Mercurial::Internal; using namespace Mercurial; HgTask::HgTask(const QString &repositoryRoot, const QStringList &arguments, bool emitRaw, const QVariant &cookie) : m_repositoryRoot(repositoryRoot), arguments(arguments), emitRaw(emitRaw), m_cookie(cookie), editor(0), m_unixTerminalDisabled(false) { } HgTask::HgTask(const QString &repositoryRoot, const QStringList &arguments, VCSBase::VCSBaseEditor *editor, const QVariant &cookie) : m_repositoryRoot(repositoryRoot), arguments(arguments), emitRaw(false), m_cookie(cookie), editor(editor), m_unixTerminalDisabled(false) { } void HgTask::emitSucceeded() { emit succeeded(m_cookie); } MercurialJobRunner::MercurialJobRunner() : plugin(MercurialPlugin::instance()), keepRunning(true) { VCSBase::VCSBaseOutputWindow *ow = VCSBase::VCSBaseOutputWindow::instance(); connect(this, SIGNAL(error(QString)), ow, SLOT(appendError(QString)), Qt::QueuedConnection); connect(this, SIGNAL(commandStarted(QString)), ow, SLOT(appendCommand(QString)), Qt::QueuedConnection); } MercurialJobRunner::~MercurialJobRunner() { stop(); } void MercurialJobRunner::stop() { mutex.lock(); keepRunning = false; //Create a dummy task to break the cycle QSharedPointer<HgTask> job(0); jobs.enqueue(job); waiter.wakeAll(); mutex.unlock(); wait(); } void MercurialJobRunner::restart() { stop(); mutex.lock(); keepRunning = true; mutex.unlock(); start(); } void MercurialJobRunner::getSettings() { const MercurialSettings &settings = MercurialPlugin::instance()->settings(); binary = settings.binary(); m_timeoutMS = settings.timeoutMilliSeconds(); standardArguments = settings.standardArguments(); } void MercurialJobRunner::enqueueJob(const QSharedPointer<HgTask> &job) { mutex.lock(); jobs.enqueue(job); waiter.wakeAll(); mutex.unlock(); } void MercurialJobRunner::run() { getSettings(); forever { mutex.lock(); while (jobs.count() == 0) waiter.wait(&mutex); if (!keepRunning) { jobs.clear(); mutex.unlock(); return; } QSharedPointer<HgTask> job = jobs.dequeue(); mutex.unlock(); task(job); } } QString MercurialJobRunner::msgStartFailed(const QString &binary, const QString &why) { return tr("Unable to start mercurial process '%1': %2").arg(binary, why); } QString MercurialJobRunner::msgTimeout(int timeoutSeconds) { return tr("Timed out after %1s waiting for mercurial process to finish.").arg(timeoutSeconds); } // Set environment for a hg process to run in locale "C". Note that there appears // to be a bug in hg that causes special characters to be garbled when running // in a different language, which seems to be independent from the encoding. void MercurialJobRunner::setProcessEnvironment(QProcess &p) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); VCSBase::VCSBasePlugin::setProcessEnvironment(&env, false); p.setProcessEnvironment(env); } void MercurialJobRunner::task(const QSharedPointer<HgTask> &job) { HgTask *taskData = job.data(); VCSBase::VCSBaseOutputWindow *outputWindow = VCSBase::VCSBaseOutputWindow::instance(); if (taskData->shouldEmit()) { //Call the job's signal so the Initator of the job can process the data //Because the QSharedPointer that holds the HgTask will go out of scope and hence be deleted //we have to block and wait until the signal is delivered connect(this, SIGNAL(output(QByteArray)), taskData, SIGNAL(rawData(QByteArray)), Qt::BlockingQueuedConnection); } else if (taskData->displayEditor()) { //An editor has been created to display the data so send it there connect(this, SIGNAL(output(QByteArray)), taskData->displayEditor(), SLOT(setPlainTextData(QByteArray)), Qt::QueuedConnection); } else { //Just output the data to the Mercurial output window connect(this, SIGNAL(output(QByteArray)), outputWindow, SLOT(appendData(QByteArray)), Qt::QueuedConnection); } const QStringList args = standardArguments + taskData->args(); emit commandStarted(VCSBase::VCSBaseOutputWindow::msgExecutionLogEntry(taskData->repositoryRoot(), binary, args)); //infom the user of what we are going to try and perform if (Constants::debug) qDebug() << Q_FUNC_INFO << "Repository root is " << taskData->repositoryRoot() << " terminal_disabled" << taskData->unixTerminalDisabled(); const unsigned processFlags = taskData->unixTerminalDisabled() ? unsigned(Utils::SynchronousProcess::UnixTerminalDisabled) : unsigned(0); QSharedPointer<QProcess> hgProcess = Utils::SynchronousProcess::createProcess(processFlags); hgProcess->setWorkingDirectory(taskData->repositoryRoot()); MercurialJobRunner::setProcessEnvironment(*hgProcess); hgProcess->start(binary, args); if (!hgProcess->waitForStarted()) { emit error(msgStartFailed(binary, hgProcess->errorString())); return; } hgProcess->closeWriteChannel(); QByteArray stdOutput; QByteArray stdErr; if (!Utils::SynchronousProcess::readDataFromProcess(*hgProcess, m_timeoutMS, &stdOutput, &stdErr, false)) { Utils::SynchronousProcess::stopProcess(*hgProcess); emit error(msgTimeout(m_timeoutMS / 1000)); return; } if (hgProcess->exitStatus() == QProcess::NormalExit && hgProcess->exitCode() == 0) { /* * sometimes success means output is actually on error channel (stderr) * e.g. "hg revert" outputs "no changes needed to 'file'" on stderr if file has not changed * from revision specified */ if (stdOutput.isEmpty()) stdOutput = stdErr; emit output(stdOutput); taskData->emitSucceeded(); } else { emit error(QString::fromLocal8Bit(stdErr)); } hgProcess->close(); //the signal connection is to last only for the duration of a job/task. next time a new //output signal connection must be made disconnect(this, SIGNAL(output(QByteArray)), 0, 0); } <|endoftext|>
<commit_before><commit_msg>Throttle TouchMove events the same as MouseMove events for the purposes of painting.<commit_after><|endoftext|>
<commit_before><commit_msg>Attempting to debug the IE8 chrome frame random failures by tracing out the last error code from the net::TestServer::WaitToFinish helper function.<commit_after><|endoftext|>
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #ifndef PARASOLS_GUARD_GRAPH_TEMPLATE_VOODOO_HH #define PARASOLS_GUARD_GRAPH_TEMPLATE_VOODOO_HH 1 #include <graph/graph.hh> #include <graph/bit_graph.hh> #include <type_traits> namespace parasols { template <unsigned...> struct GraphSizes; struct NoMoreGraphSizes { }; template <unsigned n_, unsigned... n_rest_> struct GraphSizes<n_, n_rest_...> { enum { n = n_ }; using Rest = GraphSizes<n_rest_...>; }; template <unsigned n_> struct GraphSizes<n_> { enum { n = n_ }; using Rest = NoMoreGraphSizes; }; template <unsigned n_> struct IndexSizes { using Type = typename std::conditional<n_ * bits_per_word <= 1ul << (8 * sizeof(unsigned char)), unsigned char, typename std::conditional<n_ * bits_per_word <= 1ul << (8 * sizeof(unsigned short)), unsigned short, std::false_type>::type>::type; }; template <template <unsigned, typename> class Algorithm_, typename Result_, unsigned... sizes_, typename... Params_> auto select_graph_size(const GraphSizes<sizes_...> &, const Graph & graph, Params_ && ... params) -> Result_ { if (graph.size() < GraphSizes<sizes_...>::n * bits_per_word) { Algorithm_<GraphSizes<sizes_...>::n, typename IndexSizes<GraphSizes<sizes_...>::n>::Type> algorithm{ graph, std::forward<Params_>(params)... }; return algorithm.run(); } else return select_graph_size<Algorithm_, Result_>(typename GraphSizes<sizes_...>::Rest(), graph, std::forward<Params_>(params)...); } template <template <unsigned, typename> class Algorithm_, typename Result_, typename... Params_> auto select_graph_size(const NoMoreGraphSizes &, const Graph &, Params_ && ...) -> Result_ { throw GraphTooBig(); } /* This is pretty horrible: in order to avoid dynamic allocation, select * the appropriate specialisation for our graph's size. */ static_assert(max_graph_words == 1024, "Need to update here if max_graph_size is changed."); using AllGraphSizes = GraphSizes<1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 64, 128, 256, 512, 1024>; } #endif <commit_msg>A bit more flexibility<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #ifndef PARASOLS_GUARD_GRAPH_TEMPLATE_VOODOO_HH #define PARASOLS_GUARD_GRAPH_TEMPLATE_VOODOO_HH 1 #include <graph/graph.hh> #include <graph/bit_graph.hh> #include <type_traits> namespace parasols { template <unsigned...> struct GraphSizes; struct NoMoreGraphSizes { }; template <unsigned n_, unsigned... n_rest_> struct GraphSizes<n_, n_rest_...> { enum { n = n_ }; using Rest = GraphSizes<n_rest_...>; }; template <unsigned n_> struct GraphSizes<n_> { enum { n = n_ }; using Rest = NoMoreGraphSizes; }; template <unsigned n_> struct IndexSizes { using Type = typename std::conditional<n_ * bits_per_word <= 1ul << (8 * sizeof(unsigned char)), unsigned char, typename std::conditional<n_ * bits_per_word <= 1ul << (8 * sizeof(unsigned short)), unsigned short, std::false_type>::type>::type; }; template <template <unsigned, typename> class Algorithm_, typename Result_, typename Graph_, unsigned... sizes_, typename... Params_> auto select_graph_size(const GraphSizes<sizes_...> &, const Graph_ & graph, Params_ && ... params) -> Result_ { if (graph.size() < GraphSizes<sizes_...>::n * bits_per_word) { Algorithm_<GraphSizes<sizes_...>::n, typename IndexSizes<GraphSizes<sizes_...>::n>::Type> algorithm{ graph, std::forward<Params_>(params)... }; return algorithm.run(); } else return select_graph_size<Algorithm_, Result_, Graph_>(typename GraphSizes<sizes_...>::Rest(), graph, std::forward<Params_>(params)...); } template <template <unsigned, typename> class Algorithm_, typename Result_, typename Graph_, typename... Params_> auto select_graph_size(const NoMoreGraphSizes &, const Graph_ &, Params_ && ...) -> Result_ { throw GraphTooBig(); } /* This is pretty horrible: in order to avoid dynamic allocation, select * the appropriate specialisation for our graph's size. */ static_assert(max_graph_words == 1024, "Need to update here if max_graph_size is changed."); using AllGraphSizes = GraphSizes<1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 64, 128, 256, 512, 1024>; } #endif <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <vector> #include "boost/regex.hpp" using namespace std; using namespace boost; static string xml_encode(const string& str) { string result; for (string::size_type pos = 0; pos < str.size(); ++pos) { switch (str[pos]) { case '&': result += "&amp;"; break; case '<': result += "&lt;"; break; case '>': result += "&gt;"; break; /* case '\"': result += "&quot;"; break; case '\'': result += "&apos;"; break; */ default: result += str[pos]; } } return result; } static void fatal(int rc, string type, string msg) { cout << type << ": " << msg << endl; exit(rc); } int main(int argc, char *argv[]) { if (argc != 3 && argc != 4) fatal(1, "Usage", string(argv[0]) + " [-l] <regex-file> <data-file>\n" "\t-l = treat data-file as a list of single-line inputs"); bool list = string(argv[1]) == "-l"; char *rf = argv[list ? 2 : 1], *df = argv[list ? 3 : 2]; vector<string> rspecs, rfrmts, dlines; ifstream rfile(rf); if (!rfile.good()) fatal(2, "ERROR", string("Cannot access ") + rf); int ri = 0; string rtmp1, rtmp2; do { getline(rfile, rtmp1); getline(rfile, rtmp2); if (rfile.eof()) break; if (rtmp1[0] != 'P' && rtmp1[0] != 'R' && rtmp1[0] != 'S') fatal(3, "ERROR", string("Bad regex specifier")); rspecs.push_back(rtmp1); rfrmts.push_back(rtmp2); ri++; } while (rfile.good()); ifstream dfile(df); if (!dfile.good()) fatal(3, "ERROR", string("Cannot access ") + df); int di = 0; string dtmp; do { getline(dfile, dtmp); if (dfile.eof()) break; dlines.push_back(dtmp); di++; } while (dfile.good()); if (list) { string data; for (int dj = 0; dj < di; dj++) { if (!data.empty()) data += "\n"; data += dlines[dj]; } dlines.assign(di = 1, data); } for (int rj = 0; rj < ri; rj++) { string regexp = rspecs[rj].substr(1); if (rj > 0) cout << string(40, '=') << endl; cout << rspecs[rj][0] << "REGEX[" << rj << "]: " << regexp << endl; cout << "XMLREG[" << rj << "]: " << xml_encode(regexp) << endl; cout << "FORMAT[" << rj << "]: " << rfrmts[rj] << endl; cout << "XMLFMT[" << rj << "]: " << xml_encode(rfrmts[rj]) << endl; cout << "RESULT[" << rj << "]: "; try { regex rx(regexp); cout << "Valid Regex" << endl; for (int dj = 0; dj < di; dj++) { if (rspecs[rj][0] == 'P') { match_results<string::const_iterator> mr; if (regex_search(dlines[dj], mr, rx)) dlines[dj] = mr.format(rfrmts[rj], boost::format_all); else // MATCH FAILED dlines[dj] = ""; } else { string res = regex_replace(dlines[dj], rx, rfrmts[rj], boost::format_all | boost::format_no_copy); if (!res.empty()) dlines[dj] = res; else // EMPTY RESULT if (rspecs[rj][0] == 'R') dlines[dj] = res; } cout << dlines[dj] << endl; } } catch (...) { cout << "EXCEPTION!" << endl; break; } } } <commit_msg>damn...simple typo, huge results<commit_after>#include <iostream> #include <fstream> #include <string> #include <vector> #include "boost/regex.hpp" using namespace std; using namespace boost; static string xml_encode(const string& str) { string result; for (string::size_type pos = 0; pos < str.size(); ++pos) { switch (str[pos]) { case '&': result += "&amp;"; break; case '<': result += "&lt;"; break; case '>': result += "&gt;"; break; /* case '\"': result += "&quot;"; break; case '\'': result += "&apos;"; break; */ default: result += str[pos]; } } return result; } static void fatal(int rc, string type, string msg) { cout << type << ": " << msg << endl; exit(rc); } int main(int argc, char *argv[]) { if (argc != 3 && argc != 4) fatal(1, "Usage", string(argv[0]) + " [-l] <regex-file> <data-file>\n" "\t-l = treat data-file as a list of single-line inputs"); bool list = string(argv[1]) == "-l"; char *rf = argv[list ? 2 : 1], *df = argv[list ? 3 : 2]; vector<string> rspecs, rfrmts, dlines; ifstream rfile(rf); if (!rfile.good()) fatal(2, "ERROR", string("Cannot access ") + rf); int ri = 0; string rtmp1, rtmp2; do { getline(rfile, rtmp1); getline(rfile, rtmp2); if (rfile.eof()) break; if (rtmp1[0] != 'P' && rtmp1[0] != 'R' && rtmp1[0] != 'S') fatal(3, "ERROR", string("Bad regex specifier")); rspecs.push_back(rtmp1); rfrmts.push_back(rtmp2); ri++; } while (rfile.good()); ifstream dfile(df); if (!dfile.good()) fatal(3, "ERROR", string("Cannot access ") + df); int di = 0; string dtmp; do { getline(dfile, dtmp); if (dfile.eof()) break; dlines.push_back(dtmp); di++; } while (dfile.good()); if (!list) { string data; for (int dj = 0; dj < di; dj++) { if (!data.empty()) data += "\n"; data += dlines[dj]; } dlines.assign(di = 1, data); } for (int rj = 0; rj < ri; rj++) { string regexp = rspecs[rj].substr(1); if (rj > 0) cout << string(40, '=') << endl; cout << rspecs[rj][0] << "REGEX[" << rj << "]: " << regexp << endl; cout << "XMLREG[" << rj << "]: " << xml_encode(regexp) << endl; cout << "FORMAT[" << rj << "]: " << rfrmts[rj] << endl; cout << "XMLFMT[" << rj << "]: " << xml_encode(rfrmts[rj]) << endl; cout << "RESULT[" << rj << "]: "; try { regex rx(regexp); cout << "Valid Regex" << endl; for (int dj = 0; dj < di; dj++) { if (rspecs[rj][0] == 'P') { match_results<string::const_iterator> mr; if (regex_search(dlines[dj], mr, rx)) dlines[dj] = mr.format(rfrmts[rj], boost::format_all); else // MATCH FAILED dlines[dj] = ""; } else { string res = regex_replace(dlines[dj], rx, rfrmts[rj], boost::format_all | boost::format_no_copy); if (!res.empty()) dlines[dj] = res; else // EMPTY RESULT if (rspecs[rj][0] == 'R') dlines[dj] = res; } cout << dlines[dj] << endl; } } catch (...) { cout << "EXCEPTION!" << endl; break; } } } <|endoftext|>
<commit_before>// // yas_audio_device_stream.cpp // #include "yas_audio_device.h" #if (TARGET_OS_MAC && !TARGET_OS_IPHONE) #include "yas_audio_format.h" using namespace yas; #pragma mark - property_info bool audio::device::stream::property_info::operator<(property_info const &info) const { if (property != info.property) { return property < info.property; } if (object_id != info.object_id) { return object_id < info.object_id; } if (address.mSelector != info.address.mSelector) { return address.mSelector < info.address.mSelector; } if (address.mScope != info.address.mScope) { return address.mScope < info.address.mScope; } return address.mElement < info.address.mElement; } #pragma mark - change_info audio::device::stream::change_info::change_info(std::vector<property_info> &&infos) : property_infos(infos) { } #pragma mark - private struct audio::device::stream::impl : base::impl { using listener_f = std::function<void(uint32_t const in_number_addresses, const AudioObjectPropertyAddress *const in_addresses)>; public: AudioStreamID _stream_id; AudioDeviceID _device_id; chaining::notifier<chaining_pair_t> _notifier; impl(AudioStreamID const stream_id, AudioDeviceID const device_id) : _stream_id(stream_id), _device_id(device_id) { } bool is_equal(std::shared_ptr<base::impl> const &rhs) const override { if (auto casted_rhs = std::dynamic_pointer_cast<audio::device::stream::impl>(rhs)) { return this->_stream_id == casted_rhs->_stream_id; } return false; } listener_f listener(stream const &stream) { auto weak_stream = to_weak(stream); return [weak_stream](uint32_t const address_count, const AudioObjectPropertyAddress *const addresses) { if (auto stream = weak_stream.lock()) { AudioStreamID const object_id = stream.stream_id(); std::vector<property_info> infos; for (uint32_t i = 0; i < address_count; i++) { if (addresses[i].mSelector == kAudioStreamPropertyVirtualFormat) { infos.emplace_back(property_info{.property = stream::property::virtual_format, .object_id = object_id, .address = addresses[i]}); } else if (addresses[i].mSelector == kAudioStreamPropertyIsActive) { infos.emplace_back(property_info{ .property = stream::property::is_active, .object_id = object_id, .address = addresses[i]}); } else if (addresses[i].mSelector == kAudioStreamPropertyStartingChannel) { infos.emplace_back(property_info{.property = stream::property::starting_channel, .object_id = object_id, .address = addresses[i]}); } } change_info change_info{std::move(infos)}; stream.impl_ptr<impl>()->_notifier.notify(std::make_pair(method::did_change, change_info)); } }; } void add_listener(AudioObjectPropertySelector const &selector, listener_f handler) { AudioObjectPropertyAddress const address = {.mSelector = selector, .mScope = kAudioObjectPropertyScopeGlobal, .mElement = kAudioObjectPropertyElementMaster}; raise_if_raw_audio_error( AudioObjectAddPropertyListenerBlock(this->_stream_id, &address, dispatch_get_main_queue(), ^(uint32_t address_count, const AudioObjectPropertyAddress *addresses) { handler(address_count, addresses); })); } }; #pragma mark - main audio::device::stream::stream(args args) : base(std::make_shared<impl>(args.stream_id, args.device_id)) { auto imp = impl_ptr<impl>(); auto listener = imp->listener(*this); imp->add_listener(kAudioStreamPropertyVirtualFormat, listener); imp->add_listener(kAudioStreamPropertyIsActive, listener); imp->add_listener(kAudioStreamPropertyStartingChannel, listener); } audio::device::stream::stream(std::nullptr_t) : base(nullptr) { } AudioStreamID audio::device::stream::stream_id() const { return impl_ptr<impl>()->_stream_id; } audio::device audio::device::stream::device() const { return device::device_for_id(impl_ptr<impl>()->_device_id); } bool audio::device::stream::is_active() const { auto data = _property_data<uint32_t>(stream_id(), kAudioStreamPropertyIsActive); if (data) { return *data->data() > 0; } return false; } audio::direction audio::device::stream::direction() const { auto data = _property_data<uint32_t>(stream_id(), kAudioStreamPropertyDirection); if (data) { if (*data->data() == 1) { return direction::input; } } return direction::output; } audio::format audio::device::stream::virtual_format() const { auto data = _property_data<AudioStreamBasicDescription>(stream_id(), kAudioStreamPropertyVirtualFormat); if (!data) { throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + " : can't get virtual format."); } return audio::format(*data->data()); } uint32_t audio::device::stream::starting_channel() const { auto data = _property_data<uint32_t>(stream_id(), kAudioStreamPropertyStartingChannel); if (data) { return *data->data(); } return 0; } chaining::chain_unsyncable_t<audio::device::stream::chaining_pair_t> audio::device::stream::chain() const { return impl_ptr<impl>()->_notifier.chain(); } chaining::chain<audio::device::stream::change_info, audio::device::stream::chaining_pair_t, audio::device::stream::chaining_pair_t, false> audio::device::stream::chain(method const method) const { return impl_ptr<impl>() ->_notifier.chain() .guard([method](auto const &pair) { return pair.first == method; }) .to([](audio::device::stream::chaining_pair_t const &pair) { return pair.second; }); } std::string yas::to_string(audio::device::stream::method const &method) { switch (method) { case audio::device::stream::method::did_change: return "did_change"; } } std::ostream &operator<<(std::ostream &os, yas::audio::device::stream::method const &value) { os << to_string(value); return os; } #endif <commit_msg>device_stream this<commit_after>// // yas_audio_device_stream.cpp // #include "yas_audio_device.h" #if (TARGET_OS_MAC && !TARGET_OS_IPHONE) #include "yas_audio_format.h" using namespace yas; #pragma mark - property_info bool audio::device::stream::property_info::operator<(property_info const &info) const { if (this->property != info.property) { return this->property < info.property; } if (this->object_id != info.object_id) { return this->object_id < info.object_id; } if (this->address.mSelector != info.address.mSelector) { return this->address.mSelector < info.address.mSelector; } if (this->address.mScope != info.address.mScope) { return this->address.mScope < info.address.mScope; } return this->address.mElement < info.address.mElement; } #pragma mark - change_info audio::device::stream::change_info::change_info(std::vector<property_info> &&infos) : property_infos(infos) { } #pragma mark - private struct audio::device::stream::impl : base::impl { using listener_f = std::function<void(uint32_t const in_number_addresses, const AudioObjectPropertyAddress *const in_addresses)>; public: AudioStreamID _stream_id; AudioDeviceID _device_id; chaining::notifier<chaining_pair_t> _notifier; impl(AudioStreamID const stream_id, AudioDeviceID const device_id) : _stream_id(stream_id), _device_id(device_id) { } bool is_equal(std::shared_ptr<base::impl> const &rhs) const override { if (auto casted_rhs = std::dynamic_pointer_cast<audio::device::stream::impl>(rhs)) { return this->_stream_id == casted_rhs->_stream_id; } return false; } listener_f listener(stream const &stream) { auto weak_stream = to_weak(stream); return [weak_stream](uint32_t const address_count, const AudioObjectPropertyAddress *const addresses) { if (auto stream = weak_stream.lock()) { AudioStreamID const object_id = stream.stream_id(); std::vector<property_info> infos; for (uint32_t i = 0; i < address_count; i++) { if (addresses[i].mSelector == kAudioStreamPropertyVirtualFormat) { infos.emplace_back(property_info{.property = stream::property::virtual_format, .object_id = object_id, .address = addresses[i]}); } else if (addresses[i].mSelector == kAudioStreamPropertyIsActive) { infos.emplace_back(property_info{ .property = stream::property::is_active, .object_id = object_id, .address = addresses[i]}); } else if (addresses[i].mSelector == kAudioStreamPropertyStartingChannel) { infos.emplace_back(property_info{.property = stream::property::starting_channel, .object_id = object_id, .address = addresses[i]}); } } change_info change_info{std::move(infos)}; stream.impl_ptr<impl>()->_notifier.notify(std::make_pair(method::did_change, change_info)); } }; } void add_listener(AudioObjectPropertySelector const &selector, listener_f handler) { AudioObjectPropertyAddress const address = {.mSelector = selector, .mScope = kAudioObjectPropertyScopeGlobal, .mElement = kAudioObjectPropertyElementMaster}; raise_if_raw_audio_error( AudioObjectAddPropertyListenerBlock(this->_stream_id, &address, dispatch_get_main_queue(), ^(uint32_t address_count, const AudioObjectPropertyAddress *addresses) { handler(address_count, addresses); })); } }; #pragma mark - main audio::device::stream::stream(args args) : base(std::make_shared<impl>(args.stream_id, args.device_id)) { auto imp = impl_ptr<impl>(); auto listener = imp->listener(*this); imp->add_listener(kAudioStreamPropertyVirtualFormat, listener); imp->add_listener(kAudioStreamPropertyIsActive, listener); imp->add_listener(kAudioStreamPropertyStartingChannel, listener); } audio::device::stream::stream(std::nullptr_t) : base(nullptr) { } AudioStreamID audio::device::stream::stream_id() const { return impl_ptr<impl>()->_stream_id; } audio::device audio::device::stream::device() const { return device::device_for_id(impl_ptr<impl>()->_device_id); } bool audio::device::stream::is_active() const { auto data = this->_property_data<uint32_t>(stream_id(), kAudioStreamPropertyIsActive); if (data) { return *data->data() > 0; } return false; } audio::direction audio::device::stream::direction() const { auto data = this->_property_data<uint32_t>(stream_id(), kAudioStreamPropertyDirection); if (data) { if (*data->data() == 1) { return direction::input; } } return direction::output; } audio::format audio::device::stream::virtual_format() const { auto data = this->_property_data<AudioStreamBasicDescription>(stream_id(), kAudioStreamPropertyVirtualFormat); if (!data) { throw std::runtime_error(std::string(__PRETTY_FUNCTION__) + " : can't get virtual format."); } return audio::format(*data->data()); } uint32_t audio::device::stream::starting_channel() const { auto data = this->_property_data<uint32_t>(stream_id(), kAudioStreamPropertyStartingChannel); if (data) { return *data->data(); } return 0; } chaining::chain_unsyncable_t<audio::device::stream::chaining_pair_t> audio::device::stream::chain() const { return impl_ptr<impl>()->_notifier.chain(); } chaining::chain<audio::device::stream::change_info, audio::device::stream::chaining_pair_t, audio::device::stream::chaining_pair_t, false> audio::device::stream::chain(method const method) const { return impl_ptr<impl>() ->_notifier.chain() .guard([method](auto const &pair) { return pair.first == method; }) .to([](audio::device::stream::chaining_pair_t const &pair) { return pair.second; }); } std::string yas::to_string(audio::device::stream::method const &method) { switch (method) { case audio::device::stream::method::did_change: return "did_change"; } } std::ostream &operator<<(std::ostream &os, yas::audio::device::stream::method const &value) { os << to_string(value); return os; } #endif <|endoftext|>
<commit_before>#include <unistd.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <signal.h> #include <sys/signalfd.h> #include <sys/eventfd.h> #include <pthread.h> #include <fcntl.h> #include <cstdlib> #include <cstring> #include <cstdio> #include <cstdint> using namespace std; volatile bool stop = false; void* thread_start(void* args) { int evfd = reinterpret_cast<uint64_t>(args); while(!stop) { sleep(5); uint64_t value = 5; write(evfd, &value, sizeof(value)); } return nullptr; } int main(int argc, char *argv[]) { printf("=======================================================================\n"); printf(" *****event processing demonstration, process id: [%d]*****\n", getpid()); printf(" to send SIGUSR1 to this process, please use below command in shell:\n"); printf(" while true; do kill -s SIGUSR1 %d 1>/dev/null 2>&1; if [ $? -ne 0 ]; then break; fi; sleep 5; done\n", getpid()); printf("=======================================================================\n"); constexpr int MAX_EVENTS = 10; struct epoll_event ev, events[MAX_EVENTS]; auto epollfd = epoll_create1(EPOLL_CLOEXEC); if(-1 == epollfd) { printf("failed to create epoll file descriptor\n"); return EXIT_FAILURE; } // create a notify between two threads // potentially mimic Event on Windows platform auto evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if(-1 == evfd) { printf("failed to create event file descriptor\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = evfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &ev)) { printf("failed to event file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add a timer firing every 60 seconds auto timerfd = timerfd_create(CLOCK_REALTIME, TFD_CLOEXEC | TFD_NONBLOCK); if(-1 == timerfd) { printf("failed to create file descriptor for timer\n"); return EXIT_FAILURE; } struct itimerspec timerspec; memset(&timerspec, 0, sizeof(timerspec)); timerspec.it_interval.tv_sec = 5; timerspec.it_value.tv_sec = 2; if(-1 == timerfd_settime(timerfd, 0, &timerspec, nullptr)) { printf("failed to start timer\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = timerfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev)) { printf("failed to add timer file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add signal SIGUSR1 sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGUSR1); sigprocmask(SIG_BLOCK, &mask, nullptr); auto sigfd = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC); if(-1 == sigfd) { printf("failed to create file descriptor for signal\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = sigfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, sigfd, &ev)) { printf("failed to add signal file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // IMPORTANT! // create another thread here so that SIGUSR1 will also be blocked in new thread pthread_t thread; if(pthread_create(&thread, nullptr, thread_start, reinterpret_cast<void*>(evfd)) == -1) { printf("failed to create a new thread\n"); return EXIT_FAILURE; } // add standard input file descriptor auto flags = fcntl(STDIN_FILENO, F_GETFL); flags |= O_NONBLOCK; if(-1 == fcntl(STDIN_FILENO, F_SETFL, flags)) { printf("failed to set NONBLOCK on standard input file descriptor\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = STDIN_FILENO; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev)) { printf("failed to stardard input file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } while(true) { auto nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1); for(auto i = 0; i < nfds; ++i) { if(timerfd == events[i].data.fd) { uint64_t value; read(timerfd, &value, sizeof(value)); printf("timer event received, value: %lld\n", value); } else if(sigfd == events[i].data.fd) { struct signalfd_siginfo fdsi; read(sigfd, &fdsi, sizeof(fdsi)); printf("signal event received, sender pid: %d, signal no: %d\n", fdsi.ssi_pid, fdsi.ssi_signo); } else if(evfd == events[i].data.fd) { uint64_t value; read(evfd, &value, sizeof(value)); printf("thread event received, value: %lld\n", value); } else if(STDIN_FILENO == events[i].data.fd) { constexpr int BUF_SIZE = 10; char buf[BUF_SIZE]; auto n = read(STDIN_FILENO, buf, sizeof(buf)); memset(buf + n, 0, sizeof(buf) - n); buf[sizeof(buf)-1] = '\0'; printf("standard input ready event received, value: %s", buf); }else { printf("unknown event received\n"); } } if(-1 == nfds) { printf("error on epoll waiting or interrupted, exit event loop\n"); break; } } stop = true; timerfd_settime(timerfd, 0, nullptr, nullptr); close(timerfd); close(sigfd); close(epollfd); pthread_join(thread, nullptr); close(evfd); return EXIT_SUCCESS; } <commit_msg>add socket<commit_after>#include <unistd.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <signal.h> #include <sys/signalfd.h> #include <sys/eventfd.h> #include <pthread.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <cstdlib> #include <cstring> #include <cstdio> #include <cstdint> using namespace std; volatile bool stop = false; void* thread_start(void* args) { int evfd = reinterpret_cast<uint64_t>(args); while(!stop) { sleep(5); uint64_t value = 5; write(evfd, &value, sizeof(value)); } return nullptr; } int main(int argc, char *argv[]) { printf("=======================================================================\n"); printf(" *****event processing demonstration, process id: [%d]*****\n", getpid()); printf(" **send SIGUSR1 to this process:\n"); printf(" while true; do kill -s SIGUSR1 %d 1>/dev/null 2>&1; if [ $? -ne 0 ]; then break; fi; sleep 5; done\n", getpid()); printf(" **connect to port 8080:\n"); printf(" while true; do nc localhost 8080 1>/dev/null 2>&1; if [ $? -ne 0 ]; then break; fi; sleep 5; done\n", getpid()); printf("=======================================================================\n"); constexpr int MAX_EVENTS = 10; struct epoll_event ev, events[MAX_EVENTS]; auto epollfd = epoll_create1(EPOLL_CLOEXEC); if(-1 == epollfd) { printf("failed to create epoll file descriptor\n"); return EXIT_FAILURE; } // create a notify between two threads // potentially mimic Event on Windows platform auto evfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); if(-1 == evfd) { printf("failed to create event file descriptor\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = evfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &ev)) { printf("failed to event file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add a timer firing every 60 seconds auto timerfd = timerfd_create(CLOCK_REALTIME, TFD_CLOEXEC | TFD_NONBLOCK); if(-1 == timerfd) { printf("failed to create file descriptor for timer\n"); return EXIT_FAILURE; } struct itimerspec timerspec; memset(&timerspec, 0, sizeof(timerspec)); timerspec.it_interval.tv_sec = 5; timerspec.it_value.tv_sec = 2; if(-1 == timerfd_settime(timerfd, 0, &timerspec, nullptr)) { printf("failed to start timer\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = timerfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev)) { printf("failed to add timer file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add signal SIGUSR1 sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGUSR1); sigprocmask(SIG_BLOCK, &mask, nullptr); auto sigfd = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC); if(-1 == sigfd) { printf("failed to create file descriptor for signal\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = sigfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, sigfd, &ev)) { printf("failed to add signal file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // IMPORTANT! // create another thread here so that SIGUSR1 will also be blocked in new thread pthread_t thread; if(pthread_create(&thread, nullptr, thread_start, reinterpret_cast<void*>(evfd)) == -1) { printf("failed to create a new thread\n"); return EXIT_FAILURE; } // add standard input file descriptor auto flags = fcntl(STDIN_FILENO, F_GETFL); flags |= O_NONBLOCK; if(-1 == fcntl(STDIN_FILENO, F_SETFL, flags)) { printf("failed to set NONBLOCK on standard input file descriptor\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = STDIN_FILENO; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev)) { printf("failed to add stardard input file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // add a listening socket to monitor auto sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if(-1 == sockfd) { printf("failed to create listening socket\n"); return EXIT_FAILURE; } int enable = 1; if(-1 == setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable))) { printf("failed to set socket option\n"); return EXIT_FAILURE; } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(8080); if(-1 == bind(sockfd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr))) { printf("failed to bind listening socket\n"); return EXIT_FAILURE; } constexpr int BACKLOG = 10; if(-1 == listen(sockfd, BACKLOG)) { printf("failed to listening socket\n"); return EXIT_FAILURE; } memset(&ev, 0, sizeof(ev)); ev.events = EPOLLIN; ev.data.fd = sockfd; if(-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev)) { printf("failed to add listening socket file descriptor to epoll monitoring\n"); return EXIT_FAILURE; } // start event loop while(true) { auto nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1); for(auto i = 0; i < nfds; ++i) { if(timerfd == events[i].data.fd) { uint64_t value; read(timerfd, &value, sizeof(value)); printf("timer event received, value: %lld\n", value); } else if(sigfd == events[i].data.fd) { struct signalfd_siginfo fdsi; read(sigfd, &fdsi, sizeof(fdsi)); printf("signal event received, sender pid: %d, signal no: %d\n", fdsi.ssi_pid, fdsi.ssi_signo); } else if(evfd == events[i].data.fd) { uint64_t value; read(evfd, &value, sizeof(value)); printf("thread event received, value: %lld\n", value); } else if(STDIN_FILENO == events[i].data.fd) { constexpr int BUF_SIZE = 10; char buf[BUF_SIZE]; auto n = read(STDIN_FILENO, buf, sizeof(buf)); memset(buf + n, 0, sizeof(buf) - n); buf[sizeof(buf)-1] = '\0'; printf("standard input ready event received, value: %s", buf); } else if(sockfd == events[i].data.fd) { auto cfd = accept(sockfd, nullptr, nullptr); close(cfd); printf("client connection event received, connection closed\n"); } else { printf("unknown event received\n"); } } if(-1 == nfds) { printf("error on epoll waiting or interrupted, exit event loop\n"); break; } } stop = true; timerfd_settime(timerfd, 0, nullptr, nullptr); close(timerfd); close(sigfd); close(epollfd); pthread_join(thread, nullptr); close(evfd); close(sockfd); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* This file is part of darktable, copyright (c) 2009--2011 johannes hanika. copyright (c) 2016 Pedro Côrte-Real darktable is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. darktable is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with darktable. If not, see <http://www.gnu.org/licenses/>. */ #include "RawSpeed-API.h" // for RawImage, RawImageData, iPoint2D, ImageMet... #include <cstddef> // for size_t #include <cstdint> // for uint16_t #include <cstdio> // for fprintf, stdout, stderr, printf #include <memory> // for unique_ptr #include <string> // for string, operator+ #include <sys/stat.h> // for stat #ifdef _OPENMP #include <omp.h> #endif // define this function, it is only declared in rawspeed: #ifdef _OPENMP int rawspeed_get_number_of_processor_cores() { return omp_get_num_procs(); } #else int __attribute__((const)) rawspeed_get_number_of_processor_cores() { return 1; } #endif using RawSpeed::CameraMetaData; using RawSpeed::FileReader; using RawSpeed::Buffer; using RawSpeed::RawParser; using RawSpeed::RawDecoder; using RawSpeed::RawImage; using RawSpeed::uchar8; using RawSpeed::uint32; using RawSpeed::iPoint2D; using RawSpeed::TYPE_USHORT16; using RawSpeed::TYPE_FLOAT32; using RawSpeed::RawspeedException; std::string find_cameras_xml(const char* argv0); std::string find_cameras_xml(const char *argv0) { struct stat statbuf; #ifdef RS_CAMERAS_XML_PATH static const char set_camfile[] = RS_CAMERAS_XML_PATH; if (stat(set_camfile, &statbuf)) { fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", set_camfile); } else { return set_camfile; } #endif const std::string self(argv0); // If we haven't been provided with a valid cameras.xml path on compile try // relative to argv[0] const std::size_t lastslash = self.find_last_of(R"(/\)"); const std::string bindir(self.substr(0, lastslash)); std::string found_camfile(bindir + "/../share/darktable/rawspeed/cameras.xml"); if (stat(found_camfile.c_str(), &statbuf)) { #ifndef __APPLE__ fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); #else fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); found_camfile = bindir + "/../Resources/share/darktable/rawspeed/cameras.xml"; if (stat(found_camfile.c_str(), &statbuf)) { fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); } #endif } // running from build dir? found_camfile = std::string(CMAKE_SOURCE_DIR "/data/cameras.xml"); if (stat(found_camfile.c_str(), &statbuf)) { #ifndef __APPLE__ fprintf(stderr, "ERROR: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); return nullptr; #else fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); found_camfile = bindir + "/../Resources/share/darktable/rawspeed/cameras.xml"; if (stat(found_camfile.c_str(), &statbuf)) { fprintf(stderr, "ERROR: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); return nullptr; } #endif } return found_camfile; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: darktable-rs-identify <file>\n"); return 0; } const std::string camfile = find_cameras_xml(argv[0]); if (camfile.empty()) { // fprintf(stderr, "ERROR: Couldn't find cameras.xml\n"); return 2; } // fprintf(stderr, "Using cameras.xml from '%s'\n", camfile); try { std::unique_ptr<const CameraMetaData> meta( new CameraMetaData(camfile.c_str())); if (!meta.get()) { fprintf(stderr, "ERROR: Couldn't get a CameraMetaData instance\n"); return 2; } #ifdef __AFL_HAVE_MANUAL_CONTROL __AFL_INIT(); #endif fprintf(stderr, "Loading file: \"%s\"\n", argv[1]); FileReader f(argv[1]); std::unique_ptr<Buffer> m(f.readFile()); RawParser t(m.get()); std::unique_ptr<RawDecoder> d(t.getDecoder(meta.get())); if (!d.get()) { fprintf(stderr, "ERROR: Couldn't get a RawDecoder instance\n"); return 2; } d->applyCrop = false; d->failOnUnknown = true; RawImage r = d->mRaw; d->decodeMetaData(meta.get()); fprintf(stdout, "make: %s\n", r->metadata.make.c_str()); fprintf(stdout, "model: %s\n", r->metadata.model.c_str()); fprintf(stdout, "canonical_make: %s\n", r->metadata.canonical_make.c_str()); fprintf(stdout, "canonical_model: %s\n", r->metadata.canonical_model.c_str()); fprintf(stdout, "canonical_alias: %s\n", r->metadata.canonical_alias.c_str()); d->checkSupport(meta.get()); d->decodeRaw(); d->decodeMetaData(meta.get()); r = d->mRaw; for (auto &error : r->errors) fprintf(stderr, "WARNING: [rawspeed] %s\n", error.c_str()); fprintf(stdout, "blackLevel: %d\n", r->blackLevel); fprintf(stdout, "whitePoint: %d\n", r->whitePoint); fprintf(stdout, "blackLevelSeparate: %d %d %d %d\n", r->blackLevelSeparate[0], r->blackLevelSeparate[1], r->blackLevelSeparate[2], r->blackLevelSeparate[3]); fprintf(stdout, "wbCoeffs: %f %f %f %f\n", r->metadata.wbCoeffs[0], r->metadata.wbCoeffs[1], r->metadata.wbCoeffs[2], r->metadata.wbCoeffs[3]); fprintf(stdout, "isCFA: %d\n", r->isCFA); uint32 filters = r->cfa.getDcrawFilter(); fprintf(stdout, "filters: %d (0x%x)\n", filters, filters); const uint32 bpp = r->getBpp(); fprintf(stdout, "bpp: %d\n", bpp); uint32 cpp = r->getCpp(); fprintf(stdout, "cpp: %d\n", cpp); fprintf(stdout, "dataType: %d\n", r->getDataType()); // dimensions of uncropped image const iPoint2D dimUncropped = r->getUncroppedDim(); fprintf(stdout, "dimUncropped: %dx%d\n", dimUncropped.x, dimUncropped.y); // dimensions of cropped image iPoint2D dimCropped = r->dim; fprintf(stdout, "dimCropped: %dx%d\n", dimCropped.x, dimCropped.y); // crop - Top,Left corner iPoint2D cropTL = r->getCropOffset(); fprintf(stdout, "cropOffset: %dx%d\n", cropTL.x, cropTL.y); fprintf(stdout, "fuji_rotation_pos: %d\n", r->metadata.fujiRotationPos); fprintf(stdout, "pixel_aspect_ratio: %f\n", r->metadata.pixelAspectRatio); double sum = 0.0f; { uchar8 *const data = r->getDataUncropped(0, 0); #ifdef _OPENMP #pragma omp parallel for default(none) schedule(static) reduction(+ : sum) #endif for (size_t k = 0; k < ((size_t)dimUncropped.y * dimUncropped.x * bpp); k++) { sum += (double)data[k]; } } fprintf(stdout, "Image byte sum: %lf\n", sum); fprintf(stdout, "Image byte avg: %lf\n", sum / (double)(dimUncropped.y * dimUncropped.x * bpp)); if (r->getDataType() == TYPE_FLOAT32) { sum = 0.0f; auto *const data = (float *)r->getDataUncropped(0, 0); #ifdef _OPENMP #pragma omp parallel for default(none) schedule(static) reduction(+ : sum) #endif for (size_t k = 0; k < ((size_t)dimUncropped.y * dimUncropped.x); k++) { sum += (double)data[k]; } fprintf(stdout, "Image float sum: %lf\n", sum); fprintf(stdout, "Image float avg: %lf\n", sum / (double)(dimUncropped.y * dimUncropped.x)); } else if (r->getDataType() == TYPE_USHORT16) { sum = 0.0f; auto *const data = (uint16_t *)r->getDataUncropped(0, 0); #ifdef _OPENMP #pragma omp parallel for default(none) schedule(static) reduction(+ : sum) #endif for (size_t k = 0; k < ((size_t)dimUncropped.y * dimUncropped.x); k++) { sum += (double)data[k]; } fprintf(stdout, "Image uint16_t sum: %lf\n", sum); fprintf(stdout, "Image uint16_t avg: %lf\n", sum / (double)(dimUncropped.y * dimUncropped.x)); } } catch (RawspeedException& e) { printf("ERROR: [rawspeed] %s\n", e.what()); /* if an exception is raised lets not retry or handle the specific ones, consider the file as corrupted */ return 0; } catch (...) { printf("Unhandled exception in rawspeed-identify\n"); return 3; } return 0; } // vim: shiftwidth=2 expandtab tabstop=2 cindent // kate: indent-mode cstyle; replace-tabs on; tab-indents: off; // kate: remove-trailing-space on; <commit_msg>rs-identify: like with rstest, only catch RawspeedException.<commit_after>/* This file is part of darktable, copyright (c) 2009--2011 johannes hanika. copyright (c) 2016 Pedro Côrte-Real darktable is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. darktable is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with darktable. If not, see <http://www.gnu.org/licenses/>. */ #include "RawSpeed-API.h" // for RawImage, RawImageData, iPoint2D, ImageMet... #include <cstddef> // for size_t #include <cstdint> // for uint16_t #include <cstdio> // for fprintf, stdout, stderr, printf #include <memory> // for unique_ptr #include <string> // for string, operator+ #include <sys/stat.h> // for stat #ifdef _OPENMP #include <omp.h> #endif // define this function, it is only declared in rawspeed: #ifdef _OPENMP int rawspeed_get_number_of_processor_cores() { return omp_get_num_procs(); } #else int __attribute__((const)) rawspeed_get_number_of_processor_cores() { return 1; } #endif using RawSpeed::CameraMetaData; using RawSpeed::FileReader; using RawSpeed::Buffer; using RawSpeed::RawParser; using RawSpeed::RawDecoder; using RawSpeed::RawImage; using RawSpeed::uchar8; using RawSpeed::uint32; using RawSpeed::iPoint2D; using RawSpeed::TYPE_USHORT16; using RawSpeed::TYPE_FLOAT32; using RawSpeed::RawspeedException; std::string find_cameras_xml(const char* argv0); std::string find_cameras_xml(const char *argv0) { struct stat statbuf; #ifdef RS_CAMERAS_XML_PATH static const char set_camfile[] = RS_CAMERAS_XML_PATH; if (stat(set_camfile, &statbuf)) { fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", set_camfile); } else { return set_camfile; } #endif const std::string self(argv0); // If we haven't been provided with a valid cameras.xml path on compile try // relative to argv[0] const std::size_t lastslash = self.find_last_of(R"(/\)"); const std::string bindir(self.substr(0, lastslash)); std::string found_camfile(bindir + "/../share/darktable/rawspeed/cameras.xml"); if (stat(found_camfile.c_str(), &statbuf)) { #ifndef __APPLE__ fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); #else fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); found_camfile = bindir + "/../Resources/share/darktable/rawspeed/cameras.xml"; if (stat(found_camfile.c_str(), &statbuf)) { fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); } #endif } // running from build dir? found_camfile = std::string(CMAKE_SOURCE_DIR "/data/cameras.xml"); if (stat(found_camfile.c_str(), &statbuf)) { #ifndef __APPLE__ fprintf(stderr, "ERROR: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); return nullptr; #else fprintf(stderr, "WARNING: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); found_camfile = bindir + "/../Resources/share/darktable/rawspeed/cameras.xml"; if (stat(found_camfile.c_str(), &statbuf)) { fprintf(stderr, "ERROR: Couldn't find cameras.xml in '%s'\n", found_camfile.c_str()); return nullptr; } #endif } return found_camfile; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: darktable-rs-identify <file>\n"); return 0; } const std::string camfile = find_cameras_xml(argv[0]); if (camfile.empty()) { // fprintf(stderr, "ERROR: Couldn't find cameras.xml\n"); return 2; } // fprintf(stderr, "Using cameras.xml from '%s'\n", camfile); try { std::unique_ptr<const CameraMetaData> meta( new CameraMetaData(camfile.c_str())); if (!meta.get()) { fprintf(stderr, "ERROR: Couldn't get a CameraMetaData instance\n"); return 2; } #ifdef __AFL_HAVE_MANUAL_CONTROL __AFL_INIT(); #endif fprintf(stderr, "Loading file: \"%s\"\n", argv[1]); FileReader f(argv[1]); std::unique_ptr<Buffer> m(f.readFile()); RawParser t(m.get()); std::unique_ptr<RawDecoder> d(t.getDecoder(meta.get())); if (!d.get()) { fprintf(stderr, "ERROR: Couldn't get a RawDecoder instance\n"); return 2; } d->applyCrop = false; d->failOnUnknown = true; RawImage r = d->mRaw; d->decodeMetaData(meta.get()); fprintf(stdout, "make: %s\n", r->metadata.make.c_str()); fprintf(stdout, "model: %s\n", r->metadata.model.c_str()); fprintf(stdout, "canonical_make: %s\n", r->metadata.canonical_make.c_str()); fprintf(stdout, "canonical_model: %s\n", r->metadata.canonical_model.c_str()); fprintf(stdout, "canonical_alias: %s\n", r->metadata.canonical_alias.c_str()); d->checkSupport(meta.get()); d->decodeRaw(); d->decodeMetaData(meta.get()); r = d->mRaw; for (auto &error : r->errors) fprintf(stderr, "WARNING: [rawspeed] %s\n", error.c_str()); fprintf(stdout, "blackLevel: %d\n", r->blackLevel); fprintf(stdout, "whitePoint: %d\n", r->whitePoint); fprintf(stdout, "blackLevelSeparate: %d %d %d %d\n", r->blackLevelSeparate[0], r->blackLevelSeparate[1], r->blackLevelSeparate[2], r->blackLevelSeparate[3]); fprintf(stdout, "wbCoeffs: %f %f %f %f\n", r->metadata.wbCoeffs[0], r->metadata.wbCoeffs[1], r->metadata.wbCoeffs[2], r->metadata.wbCoeffs[3]); fprintf(stdout, "isCFA: %d\n", r->isCFA); uint32 filters = r->cfa.getDcrawFilter(); fprintf(stdout, "filters: %d (0x%x)\n", filters, filters); const uint32 bpp = r->getBpp(); fprintf(stdout, "bpp: %d\n", bpp); uint32 cpp = r->getCpp(); fprintf(stdout, "cpp: %d\n", cpp); fprintf(stdout, "dataType: %d\n", r->getDataType()); // dimensions of uncropped image const iPoint2D dimUncropped = r->getUncroppedDim(); fprintf(stdout, "dimUncropped: %dx%d\n", dimUncropped.x, dimUncropped.y); // dimensions of cropped image iPoint2D dimCropped = r->dim; fprintf(stdout, "dimCropped: %dx%d\n", dimCropped.x, dimCropped.y); // crop - Top,Left corner iPoint2D cropTL = r->getCropOffset(); fprintf(stdout, "cropOffset: %dx%d\n", cropTL.x, cropTL.y); fprintf(stdout, "fuji_rotation_pos: %d\n", r->metadata.fujiRotationPos); fprintf(stdout, "pixel_aspect_ratio: %f\n", r->metadata.pixelAspectRatio); double sum = 0.0f; { uchar8 *const data = r->getDataUncropped(0, 0); #ifdef _OPENMP #pragma omp parallel for default(none) schedule(static) reduction(+ : sum) #endif for (size_t k = 0; k < ((size_t)dimUncropped.y * dimUncropped.x * bpp); k++) { sum += (double)data[k]; } } fprintf(stdout, "Image byte sum: %lf\n", sum); fprintf(stdout, "Image byte avg: %lf\n", sum / (double)(dimUncropped.y * dimUncropped.x * bpp)); if (r->getDataType() == TYPE_FLOAT32) { sum = 0.0f; auto *const data = (float *)r->getDataUncropped(0, 0); #ifdef _OPENMP #pragma omp parallel for default(none) schedule(static) reduction(+ : sum) #endif for (size_t k = 0; k < ((size_t)dimUncropped.y * dimUncropped.x); k++) { sum += (double)data[k]; } fprintf(stdout, "Image float sum: %lf\n", sum); fprintf(stdout, "Image float avg: %lf\n", sum / (double)(dimUncropped.y * dimUncropped.x)); } else if (r->getDataType() == TYPE_USHORT16) { sum = 0.0f; auto *const data = (uint16_t *)r->getDataUncropped(0, 0); #ifdef _OPENMP #pragma omp parallel for default(none) schedule(static) reduction(+ : sum) #endif for (size_t k = 0; k < ((size_t)dimUncropped.y * dimUncropped.x); k++) { sum += (double)data[k]; } fprintf(stdout, "Image uint16_t sum: %lf\n", sum); fprintf(stdout, "Image uint16_t avg: %lf\n", sum / (double)(dimUncropped.y * dimUncropped.x)); } } catch (RawspeedException& e) { printf("ERROR: [rawspeed] %s\n", e.what()); /* if an exception is raised lets not retry or handle the specific ones, consider the file as corrupted */ return 0; } return 0; } // vim: shiftwidth=2 expandtab tabstop=2 cindent // kate: indent-mode cstyle; replace-tabs on; tab-indents: off; // kate: remove-trailing-space on; <|endoftext|>
<commit_before>/* Copyright (C) 2003-2008 Grame Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France research@grame.fr This file is provided as an example of the MusicXML Library use. */ #ifdef VC6 # pragma warning (disable : 4786) #endif #include <iomanip> // setw()), set::precision(), ... #include <fstream> // ofstream, ofstream::open(), ofstream::close() #include "libmusicxml.h" #include "version.h" #include "utilities.h" #include "generalOptions.h" #include "mxmlOptions.h" #include "msrOptions.h" #include "lpsrOptions.h" #include "lilypondOptions.h" #include "xml2lilypondOptionsHandling.h" #include "mxmlTree2MsrSkeletonBuilderInterface.h" #include "mxmlTree2MsrTranslatorInterface.h" #include "msr2LpsrInterface.h" #include "lpsr2LilypondInterface.h" using namespace std; using namespace MusicXML2; #define TRACE_OPTIONS 0 //_______________________________________________________________________________ vector<string> handleOptionsAndArguments ( S_xml2lilypondOptionsHandler optionsHandler, int argc, char* argv [], indentedOstream& logIndentedOutputStream) { // analyse the options vector<string> argumentsVector = optionsHandler-> decipherOptionsAndArguments ( argc, argv); if (TRACE_OPTIONS) { // print the options values logIndentedOutputStream << "Options values:" << endl; gIndenter++; optionsHandler-> printOptionsValues ( logIndentedOutputStream); logIndentedOutputStream << endl; gIndenter--; } return argumentsVector; } S_msrScore runPass2a ( string inputSourceName, string outputFileName) { int outputFileNameSize = outputFileName.size (); S_msrScore mScore; if (inputSourceName == "-") { // input comes from standard input if (outputFileNameSize) mScore = mxmlFd2MsrSkeleton ( stdin, gMsrOptions, gLogIOstream); else mScore = mxmlFd2MsrSkeleton ( stdin, gMsrOptions, gLogIOstream); } else { // input comes from a file if (outputFileNameSize) { mScore = mxmlFile2MsrSkeleton ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } else { mScore = mxmlFile2MsrSkeleton ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } } return mScore; } void runPass2b ( string inputSourceName, string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); if (inputSourceName == "-") { // input comes from standard input if (outputFileNameSize) mScore = mxmlFd2Msr ( stdin, gMsrOptions, gLogIOstream); else mScore = mxmlFd2Msr ( stdin, gMsrOptions, gLogIOstream); } else { // input comes from a file if (outputFileNameSize) { mScore = mxmlFile2Msr ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } else { mScore = mxmlFile2Msr ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } } /* JMI if (! mScore) { gLogIOstream << "### Conversion from MusicCML to MSR failed ###" << endl << endl; // JMI return false; } */ // JMI return true; } S_lpsrScore runPass3 ( string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); S_lpsrScore lpScore; if (! gLilypondOptions->fNoLilypondCode) { if (outputFileNameSize) { lpScore = msr2Lpsr ( mScore, gMsrOptions, gLpsrOptions, gLogIOstream); } else { lpScore = msr2Lpsr ( mScore, gMsrOptions, gLpsrOptions, gLogIOstream); } } return lpScore; } void runPass4 ( string outputFileName, S_lpsrScore lpScore) { int outputFileNameSize = outputFileName.size (); if (! gLilypondOptions->fNoLilypondCode) { // open output file if need be // ------------------------------------------------------ ofstream outFileStream; if (outputFileNameSize) { if (gGeneralOptions->fTraceGeneral) gLogIOstream << endl << "Opening file '" << outputFileName << "' for writing" << endl; outFileStream.open ( outputFileName.c_str(), ofstream::out); // create an indented output stream for the LilyPond code // to be written to outFileStream indentedOstream lilypondCodeFileOutputStream ( outFileStream, gIndenter); // convert the LPSR score to LilyPond code lpsr2Lilypond ( lpScore, gMsrOptions, gLpsrOptions, gLogIOstream, lilypondCodeFileOutputStream); } else { // create an indented output stream for the LilyPond code // to be written to cout indentedOstream lilypondCodeCoutOutputStream ( cout, gIndenter); lpsr2Lilypond ( lpScore, gMsrOptions, gLpsrOptions, gLogIOstream, lilypondCodeCoutOutputStream); } if (outputFileNameSize) { if (gGeneralOptions->fTraceGeneral) gLogIOstream << endl << "Closing file '" << outputFileName << "'" << endl; outFileStream.close (); } } } //_______________________________________________________________________________ int main (int argc, char *argv[]) { /* JMI cerr << "argc = " << argc << endl; for (int i = 0; i < argc ; i++ ) { cerr << "argv[ " << i << "] = " << argv[i] << endl; } */ // initialize the components of MSR that we'll be using // ------------------------------------------------------ initializeMSR (); initializeLPSR (); // create the options handler // ------------------------------------------------------ S_xml2lilypondOptionsHandler optionsHandler = xml2lilypondOptionsHandler::create ( gLogIOstream); // analyze the command line options and arguments // ------------------------------------------------------ vector<string> argumentsVector = handleOptionsAndArguments ( optionsHandler, argc, argv, gLogIOstream); // print the resulting options if (TRACE_OPTIONS) { gLogIOstream << optionsHandler << endl << endl; } string inputSourceName = gGeneralOptions->fInputSourceName; string outputFileName = gGeneralOptions->fOutputFileName; int outputFileNameSize = outputFileName.size (); // welcome message // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { gLogIOstream << "This is xml2Lilypond v" << currentVersionNumber () << " from libmusicxml2 v" << musicxmllibVersionStr () << endl; gLogIOstream << "Launching conversion of "; if (inputSourceName == "-") gLogIOstream << "standard input"; else gLogIOstream << "\"" << inputSourceName << "\""; gLogIOstream << " to LilyPond" << endl; gLogIOstream << "Time is " << gGeneralOptions->fTranslationDate << endl; gLogIOstream << "LilyPond code will be written to "; if (outputFileNameSize) { gLogIOstream << outputFileName; } else { gLogIOstream << "standard output"; } gLogIOstream << endl << endl; gLogIOstream << "The command line is:" << endl; gIndenter++; gLogIOstream << optionsHandler-> getCommandLineWithLongOptions () << endl; gIndenter--; gLogIOstream << "or:" << endl; gIndenter++; gLogIOstream << optionsHandler-> getCommandLineWithShortOptions () << endl << endl; gIndenter--; } // print the chosen LilyPond options // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { optionsHandler-> printOptionsValues ( gLogIOstream); } // acknoledge end of command line analysis // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { gLogIOstream << endl << "The command line options and arguments have been analyzed" << endl; } // create the MSR skeleton from MusicXML contents (pass 2a) // ------------------------------------------------------ S_msrScore mScore = runPass2a ( inputSourceName, outputFileName); if (! mScore) { gLogIOstream << "### Conversion from MusicCML to an MSR skeleton failed ###" << endl << endl; exit (1); } else if (! gGeneralOptions->fExit2a) { // create the MSR from MusicXML contents (pass 2b) // ------------------------------------------------------ runPass2b ( inputSourceName, outputFileName, mScore); if (! gGeneralOptions->fExit2b) { // create the LPSR from the MSR (pass 3) // ------------------------------------------------------ S_lpsrScore lpScore = runPass3 ( outputFileName, mScore); if (! lpScore) { gLogIOstream << "### Conversion from MSR to LPSR failed ###" << endl << endl; return 1; } else if (! gGeneralOptions->fExit3) { // generate LilyPond code from the LPSR (pass 4) // ------------------------------------------------------ runPass4 ( outputFileName, lpScore); } } } // print timing information // ------------------------------------------------------ if (gGeneralOptions->fDisplayCPUusage) timing::gTiming.print ( gLogIOstream); // over! // ------------------------------------------------------ if (! true) { // JMI gLogIOstream << "### Conversion from LPSR to LilyPond code failed ###" << endl << endl; return 1; } return 0; } <commit_msg>skeleton 46<commit_after>/* Copyright (C) 2003-2008 Grame Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France research@grame.fr This file is provided as an example of the MusicXML Library use. */ #ifdef VC6 # pragma warning (disable : 4786) #endif #include <iomanip> // setw()), set::precision(), ... #include <fstream> // ofstream, ofstream::open(), ofstream::close() #include "libmusicxml.h" #include "version.h" #include "utilities.h" #include "generalOptions.h" #include "mxmlOptions.h" #include "msrOptions.h" #include "lpsrOptions.h" #include "lilypondOptions.h" #include "xml2lilypondOptionsHandling.h" #include "mxmlTree2MsrSkeletonBuilderInterface.h" #include "mxmlTree2MsrTranslatorInterface.h" #include "msr2LpsrInterface.h" #include "lpsr2LilypondInterface.h" using namespace std; using namespace MusicXML2; #define TRACE_OPTIONS 0 //_______________________________________________________________________________ vector<string> handleOptionsAndArguments ( S_xml2lilypondOptionsHandler optionsHandler, int argc, char* argv [], indentedOstream& logIndentedOutputStream) { // analyse the options vector<string> argumentsVector = optionsHandler-> decipherOptionsAndArguments ( argc, argv); if (TRACE_OPTIONS) { // print the options values logIndentedOutputStream << "Options values:" << endl; gIndenter++; optionsHandler-> printOptionsValues ( logIndentedOutputStream); logIndentedOutputStream << endl; gIndenter--; } return argumentsVector; } S_msrScore runPass2a ( string inputSourceName, string outputFileName) { int outputFileNameSize = outputFileName.size (); S_msrScore mScore; if (inputSourceName == "-") { // input comes from standard input if (outputFileNameSize) mScore = mxmlFd2MsrSkeleton ( stdin, gMsrOptions, gLogIOstream); else mScore = mxmlFd2MsrSkeleton ( stdin, gMsrOptions, gLogIOstream); } else { // input comes from a file if (outputFileNameSize) { mScore = mxmlFile2MsrSkeleton ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } else { mScore = mxmlFile2MsrSkeleton ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } } return mScore; } void runPass2b ( string inputSourceName, string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); if (inputSourceName == "-") { // input comes from standard input if (outputFileNameSize) mScore = mxmlFd2Msr ( stdin, gMsrOptions, gLogIOstream); else mScore = mxmlFd2Msr ( stdin, gMsrOptions, gLogIOstream); } else { // input comes from a file if (outputFileNameSize) { mScore = mxmlFile2Msr ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } else { mScore = mxmlFile2Msr ( inputSourceName.c_str(), gMsrOptions, gLogIOstream); } } /* JMI if (! mScore) { gLogIOstream << "### Conversion from MusicCML to MSR failed ###" << endl << endl; // JMI return false; } */ // JMI return true; } S_lpsrScore runPass3 ( string outputFileName, S_msrScore mScore) { int outputFileNameSize = outputFileName.size (); S_lpsrScore lpScore; if (! gLilypondOptions->fNoLilypondCode) { if (outputFileNameSize) { lpScore = msr2Lpsr ( mScore, gMsrOptions, gLpsrOptions, gLogIOstream); } else { lpScore = msr2Lpsr ( mScore, gMsrOptions, gLpsrOptions, gLogIOstream); } } return lpScore; } void runPass4 ( string outputFileName, S_lpsrScore lpScore) { int outputFileNameSize = outputFileName.size (); if (! gLilypondOptions->fNoLilypondCode) { // open output file if need be // ------------------------------------------------------ ofstream outFileStream; if (outputFileNameSize) { if (gGeneralOptions->fTraceGeneral) gLogIOstream << endl << "Opening file '" << outputFileName << "' for writing" << endl; outFileStream.open ( outputFileName.c_str(), ofstream::out); // create an indented output stream for the LilyPond code // to be written to outFileStream indentedOstream lilypondCodeFileOutputStream ( outFileStream, gIndenter); // convert the LPSR score to LilyPond code lpsr2Lilypond ( lpScore, gMsrOptions, gLpsrOptions, gLogIOstream, lilypondCodeFileOutputStream); } else { // create an indented output stream for the LilyPond code // to be written to cout indentedOstream lilypondCodeCoutOutputStream ( cout, gIndenter); lpsr2Lilypond ( lpScore, gMsrOptions, gLpsrOptions, gLogIOstream, lilypondCodeCoutOutputStream); } if (outputFileNameSize) { if (gGeneralOptions->fTraceGeneral) gLogIOstream << endl << "Closing file '" << outputFileName << "'" << endl; outFileStream.close (); } } } void convertMusicXMLToLilypond ( string inputSourceName, string outputFileName) { // create the MSR skeleton from MusicXML contents (pass 2a) // ------------------------------------------------------ S_msrScore mScore = runPass2a ( inputSourceName, outputFileName); if (! mScore) { gLogIOstream << "### Conversion from MusicCML to an MSR skeleton failed ###" << endl << endl; exit (1); } if (gGeneralOptions->fExit2a) return; // create the MSR from MusicXML contents (pass 2b) // ------------------------------------------------------ runPass2b ( inputSourceName, outputFileName, mScore); if (gGeneralOptions->fExit2b) return; // create the LPSR from the MSR (pass 3) // ------------------------------------------------------ S_lpsrScore lpScore = runPass3 ( outputFileName, mScore); if (! lpScore) { gLogIOstream << "### Conversion from MSR to LPSR failed ###" << endl << endl; exit (2); } if (gGeneralOptions->fExit3) return; // generate LilyPond code from the LPSR (pass 4) // ------------------------------------------------------ runPass4 ( outputFileName, lpScore); } //_______________________________________________________________________________ int main (int argc, char *argv[]) { /* JMI cerr << "argc = " << argc << endl; for (int i = 0; i < argc ; i++ ) { cerr << "argv[ " << i << "] = " << argv[i] << endl; } */ // initialize the components of MSR that we'll be using // ------------------------------------------------------ initializeMSR (); initializeLPSR (); // create the options handler // ------------------------------------------------------ S_xml2lilypondOptionsHandler optionsHandler = xml2lilypondOptionsHandler::create ( gLogIOstream); // analyze the command line options and arguments // ------------------------------------------------------ vector<string> argumentsVector = handleOptionsAndArguments ( optionsHandler, argc, argv, gLogIOstream); // print the resulting options if (TRACE_OPTIONS) { gLogIOstream << optionsHandler << endl << endl; } string inputSourceName = gGeneralOptions->fInputSourceName; string outputFileName = gGeneralOptions->fOutputFileName; int outputFileNameSize = outputFileName.size (); // welcome message // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { gLogIOstream << "This is xml2Lilypond v" << currentVersionNumber () << " from libmusicxml2 v" << musicxmllibVersionStr () << endl; gLogIOstream << "Launching conversion of "; if (inputSourceName == "-") gLogIOstream << "standard input"; else gLogIOstream << "\"" << inputSourceName << "\""; gLogIOstream << " to LilyPond" << endl; gLogIOstream << "Time is " << gGeneralOptions->fTranslationDate << endl; gLogIOstream << "LilyPond code will be written to "; if (outputFileNameSize) { gLogIOstream << outputFileName; } else { gLogIOstream << "standard output"; } gLogIOstream << endl << endl; gLogIOstream << "The command line is:" << endl; gIndenter++; gLogIOstream << optionsHandler-> getCommandLineWithLongOptions () << endl; gIndenter--; gLogIOstream << "or:" << endl; gIndenter++; gLogIOstream << optionsHandler-> getCommandLineWithShortOptions () << endl << endl; gIndenter--; } // print the chosen LilyPond options // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { optionsHandler-> printOptionsValues ( gLogIOstream); } // acknoledge end of command line analysis // ------------------------------------------------------ if (gGeneralOptions->fTraceGeneral) { gLogIOstream << endl << "The command line options and arguments have been analyzed" << endl; } // do the translation // ------------------------------------------------------ convertMusicXMLToLilypond ( inputSourceName, outputFileName); // print timing information // ------------------------------------------------------ if (gGeneralOptions->fDisplayCPUusage) timing::gTiming.print ( gLogIOstream); // over! // ------------------------------------------------------ if (! true) { // JMI gLogIOstream << "### Conversion from LPSR to LilyPond code failed ###" << endl << endl; return 1; } return 0; } <|endoftext|>
<commit_before>//===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the InstructionSelect class. //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/GlobalISel/InstructionSelector.h" #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetSubtargetInfo.h" #define DEBUG_TYPE "instruction-select" using namespace llvm; char InstructionSelect::ID = 0; INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) InstructionSelect::InstructionSelect() : MachineFunctionPass(ID) { initializeInstructionSelectPass(*PassRegistry::getPassRegistry()); } void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } static void reportSelectionError(const MachineInstr *MI, const Twine &Message) { const MachineFunction &MF = *MI->getParent()->getParent(); std::string ErrStorage; raw_string_ostream Err(ErrStorage); Err << Message << ":\nIn function: " << MF.getName() << '\n'; if (MI) Err << *MI << '\n'; report_fatal_error(Err.str()); } bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) { // If the ISel pipeline failed, do not bother running that pass. if (MF.getProperties().hasProperty( MachineFunctionProperties::Property::FailedISel)) return false; DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n'); const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>(); const InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector(); assert(ISel && "Cannot work without InstructionSelector"); // FIXME: freezeReservedRegs is now done in IRTranslator, but there are many // other MF/MFI fields we need to initialize. const MachineRegisterInfo &MRI = MF.getRegInfo(); #ifndef NDEBUG // Check that our input is fully legal: we require the function to have the // Legalized property, so it should be. // FIXME: This should be in the MachineVerifier, but it can't use the // LegalizerInfo as it's currently in the separate GlobalISel library. // The RegBankSelected property is already checked in the verifier. Note // that it has the same layering problem, but we only use inline methods so // end up not needing to link against the GlobalISel library. if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) for (const MachineBasicBlock &MBB : MF) for (const MachineInstr &MI : MBB) if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) reportSelectionError(&MI, "Instruction is not legal"); #endif // FIXME: We could introduce new blocks and will need to fix the outer loop. // Until then, keep track of the number of blocks to assert that we don't. const size_t NumBlocks = MF.size(); bool Failed = false; for (MachineBasicBlock *MBB : post_order(&MF)) { if (MBB->empty()) continue; // Select instructions in reverse block order. We permit erasing so have // to resort to manually iterating and recognizing the begin (rend) case. bool ReachedBegin = false; for (auto MII = std::prev(MBB->end()), Begin = MBB->begin(); !ReachedBegin;) { #ifndef NDEBUG // Keep track of the insertion range for debug printing. const auto AfterIt = std::next(MII); #endif // Select this instruction. MachineInstr &MI = *MII; // And have our iterator point to the next instruction, if there is one. if (MII == Begin) ReachedBegin = true; else --MII; DEBUG(dbgs() << "Selecting: \n " << MI); if (!ISel->select(MI)) { if (TPC.isGlobalISelAbortEnabled()) // FIXME: It would be nice to dump all inserted instructions. It's // not // obvious how, esp. considering select() can insert after MI. reportSelectionError(&MI, "Cannot select"); Failed = true; break; } // Dump the range of instructions that MI expanded into. DEBUG({ auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII); dbgs() << "Into:\n"; for (auto &InsertedMI : make_range(InsertedBegin, AfterIt)) dbgs() << " " << InsertedMI; dbgs() << '\n'; }); } } // Now that selection is complete, there are no more generic vregs. Verify // that the size of the now-constrained vreg is unchanged and that it has a // register class. for (auto &VRegToType : MRI.getVRegToType()) { unsigned VReg = VRegToType.first; auto *RC = MRI.getRegClassOrNull(VReg); auto *MI = MRI.def_instr_begin(VReg) == MRI.def_instr_end() ? nullptr : &*MRI.def_instr_begin(VReg); if (!RC) { if (TPC.isGlobalISelAbortEnabled()) reportSelectionError(MI, "VReg as no regclass after selection"); Failed = true; break; } if (VRegToType.second.isValid() && VRegToType.second.getSizeInBits() > (RC->getSize() * 8)) { if (TPC.isGlobalISelAbortEnabled()) reportSelectionError( MI, "VReg has explicit size different from class size"); Failed = true; break; } } MRI.getVRegToType().clear(); if (!TPC.isGlobalISelAbortEnabled() && (Failed || MF.size() != NumBlocks)) { MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); return false; } assert(MF.size() == NumBlocks && "Inserting blocks is not supported yet"); // FIXME: Should we accurately track changes? return true; } <commit_msg>GlobalISel: Fix text wrapping in a comment. NFC<commit_after>//===- llvm/CodeGen/GlobalISel/InstructionSelect.cpp - InstructionSelect ---==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the InstructionSelect class. //===----------------------------------------------------------------------===// #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/GlobalISel/InstructionSelector.h" #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Target/TargetSubtargetInfo.h" #define DEBUG_TYPE "instruction-select" using namespace llvm; char InstructionSelect::ID = 0; INITIALIZE_PASS_BEGIN(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) INITIALIZE_PASS_END(InstructionSelect, DEBUG_TYPE, "Select target instructions out of generic instructions", false, false) InstructionSelect::InstructionSelect() : MachineFunctionPass(ID) { initializeInstructionSelectPass(*PassRegistry::getPassRegistry()); } void InstructionSelect::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetPassConfig>(); MachineFunctionPass::getAnalysisUsage(AU); } static void reportSelectionError(const MachineInstr *MI, const Twine &Message) { const MachineFunction &MF = *MI->getParent()->getParent(); std::string ErrStorage; raw_string_ostream Err(ErrStorage); Err << Message << ":\nIn function: " << MF.getName() << '\n'; if (MI) Err << *MI << '\n'; report_fatal_error(Err.str()); } bool InstructionSelect::runOnMachineFunction(MachineFunction &MF) { // If the ISel pipeline failed, do not bother running that pass. if (MF.getProperties().hasProperty( MachineFunctionProperties::Property::FailedISel)) return false; DEBUG(dbgs() << "Selecting function: " << MF.getName() << '\n'); const TargetPassConfig &TPC = getAnalysis<TargetPassConfig>(); const InstructionSelector *ISel = MF.getSubtarget().getInstructionSelector(); assert(ISel && "Cannot work without InstructionSelector"); // FIXME: freezeReservedRegs is now done in IRTranslator, but there are many // other MF/MFI fields we need to initialize. const MachineRegisterInfo &MRI = MF.getRegInfo(); #ifndef NDEBUG // Check that our input is fully legal: we require the function to have the // Legalized property, so it should be. // FIXME: This should be in the MachineVerifier, but it can't use the // LegalizerInfo as it's currently in the separate GlobalISel library. // The RegBankSelected property is already checked in the verifier. Note // that it has the same layering problem, but we only use inline methods so // end up not needing to link against the GlobalISel library. if (const LegalizerInfo *MLI = MF.getSubtarget().getLegalizerInfo()) for (const MachineBasicBlock &MBB : MF) for (const MachineInstr &MI : MBB) if (isPreISelGenericOpcode(MI.getOpcode()) && !MLI->isLegal(MI, MRI)) reportSelectionError(&MI, "Instruction is not legal"); #endif // FIXME: We could introduce new blocks and will need to fix the outer loop. // Until then, keep track of the number of blocks to assert that we don't. const size_t NumBlocks = MF.size(); bool Failed = false; for (MachineBasicBlock *MBB : post_order(&MF)) { if (MBB->empty()) continue; // Select instructions in reverse block order. We permit erasing so have // to resort to manually iterating and recognizing the begin (rend) case. bool ReachedBegin = false; for (auto MII = std::prev(MBB->end()), Begin = MBB->begin(); !ReachedBegin;) { #ifndef NDEBUG // Keep track of the insertion range for debug printing. const auto AfterIt = std::next(MII); #endif // Select this instruction. MachineInstr &MI = *MII; // And have our iterator point to the next instruction, if there is one. if (MII == Begin) ReachedBegin = true; else --MII; DEBUG(dbgs() << "Selecting: \n " << MI); if (!ISel->select(MI)) { if (TPC.isGlobalISelAbortEnabled()) // FIXME: It would be nice to dump all inserted instructions. It's // not obvious how, esp. considering select() can insert after MI. reportSelectionError(&MI, "Cannot select"); Failed = true; break; } // Dump the range of instructions that MI expanded into. DEBUG({ auto InsertedBegin = ReachedBegin ? MBB->begin() : std::next(MII); dbgs() << "Into:\n"; for (auto &InsertedMI : make_range(InsertedBegin, AfterIt)) dbgs() << " " << InsertedMI; dbgs() << '\n'; }); } } // Now that selection is complete, there are no more generic vregs. Verify // that the size of the now-constrained vreg is unchanged and that it has a // register class. for (auto &VRegToType : MRI.getVRegToType()) { unsigned VReg = VRegToType.first; auto *RC = MRI.getRegClassOrNull(VReg); auto *MI = MRI.def_instr_begin(VReg) == MRI.def_instr_end() ? nullptr : &*MRI.def_instr_begin(VReg); if (!RC) { if (TPC.isGlobalISelAbortEnabled()) reportSelectionError(MI, "VReg as no regclass after selection"); Failed = true; break; } if (VRegToType.second.isValid() && VRegToType.second.getSizeInBits() > (RC->getSize() * 8)) { if (TPC.isGlobalISelAbortEnabled()) reportSelectionError( MI, "VReg has explicit size different from class size"); Failed = true; break; } } MRI.getVRegToType().clear(); if (!TPC.isGlobalISelAbortEnabled() && (Failed || MF.size() != NumBlocks)) { MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); return false; } assert(MF.size() == NumBlocks && "Inserting blocks is not supported yet"); // FIXME: Should we accurately track changes? return true; } <|endoftext|>
<commit_before>/* Copyright (C) 2003 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <my_global.h> #include "manager.h" #include "priv.h" #include "thread_registry.h" #include "listener.h" #include "instance_map.h" #include "options.h" #include "user_map.h" #include "log.h" #include "guardian.h" #include <my_sys.h> #include <m_string.h> #include <signal.h> #include <thr_alarm.h> #ifndef __WIN__ #include <sys/wait.h> #endif static int create_pid_file(const char *pid_file_name) { if (FILE *pid_file= my_fopen(pid_file_name, O_WRONLY | O_CREAT | O_BINARY, MYF(0))) { fprintf(pid_file, "%d\n", (int) getpid()); my_fclose(pid_file, MYF(0)); return 0; } log_error("can't create pid file %s: errno=%d, %s", pid_file_name, errno, strerror(errno)); return 1; } #ifndef __WIN__ void set_signals(sigset_t *mask) { /* block signals */ sigemptyset(mask); sigaddset(mask, SIGINT); sigaddset(mask, SIGTERM); sigaddset(mask, SIGPIPE); sigaddset(mask, SIGHUP); signal(SIGPIPE, SIG_IGN); /* We want this signal to be blocked in all theads but the signal one. It is needed for the thr_alarm subsystem to work. */ sigaddset(mask,THR_SERVER_ALARM); /* all new threads will inherite this signal mask */ pthread_sigmask(SIG_BLOCK, mask, NULL); /* In our case the signal thread also implements functions of alarm thread. Here we init alarm thread functionality. We suppose that we won't have more then 10 alarms at the same time. */ init_thr_alarm(10); } #else bool have_signal; void onsignal(int signo) { have_signal= true; } void set_signals(sigset_t *set) { signal(SIGINT, onsignal); signal(SIGTERM, onsignal); have_signal= false; } int my_sigwait(const sigset_t *set, int *sig) { while (!have_signal) { Sleep(100); } return 0; } #endif /* manager - entry point to the main instance manager process: start listener thread, write pid file and enter into signal handling. See also comments in mysqlmanager.cc to picture general Instance Manager architecture. */ void manager(const Options &options) { Thread_registry thread_registry; /* All objects created in the manager() function live as long as thread_registry lives, and thread_registry is alive until there are working threads. */ User_map user_map; Instance_map instance_map(options.default_mysqld_path); Guardian_thread guardian_thread(thread_registry, &instance_map, options.monitoring_interval); Listener_thread_args listener_args(thread_registry, options, user_map, instance_map); manager_pid= getpid(); instance_map.guardian= &guardian_thread; if (instance_map.init() || user_map.init()) return; if (instance_map.load()) { log_error("Cannot init instances repository. This might be caused by " "the wrong config file options. For instance, missing mysqld " "binary. Aborting."); return; } if (user_map.load(options.password_file_name)) return; /* write pid file */ if (create_pid_file(options.pid_file_name)) return; sigset_t mask; set_signals(&mask); /* create the listener */ { pthread_t listener_thd_id; pthread_attr_t listener_thd_attr; int rc; pthread_attr_init(&listener_thd_attr); pthread_attr_setdetachstate(&listener_thd_attr, PTHREAD_CREATE_DETACHED); rc= pthread_create(&listener_thd_id, &listener_thd_attr, listener, &listener_args); pthread_attr_destroy(&listener_thd_attr); if (rc) { log_error("manager(): pthread_create(listener) failed"); goto err; } } /* create guardian thread */ { pthread_t guardian_thd_id; pthread_attr_t guardian_thd_attr; int rc; /* NOTE: Guardian should be shutdown first. Only then all other threads need to be stopped. This should be done, as guardian is responsible for shutting down the instances, and this is a long operation. */ pthread_attr_init(&guardian_thd_attr); pthread_attr_setdetachstate(&guardian_thd_attr, PTHREAD_CREATE_DETACHED); rc= pthread_create(&guardian_thd_id, &guardian_thd_attr, guardian, &guardian_thread); pthread_attr_destroy(&guardian_thd_attr); if (rc) { log_error("manager(): pthread_create(guardian) failed"); goto err; } } /* To work nicely with LinuxThreads, the signal thread is the first thread in the process. */ int signo; bool shutdown_complete; shutdown_complete= FALSE; /* init list of guarded instances */ guardian_thread.lock(); guardian_thread.init(); guardian_thread.unlock(); /* After the list of guarded instances have been initialized, Guardian should start them. */ pthread_cond_signal(&guardian_thread.COND_guardian); while (!shutdown_complete) { int status= 0; if ((status= my_sigwait(&mask, &signo)) != 0) { log_error("sigwait() failed"); goto err; } #ifndef __WIN__ if (THR_SERVER_ALARM == signo) process_alarm(signo); else #endif { if (!guardian_thread.is_stopped()) { bool stop_instances= true; guardian_thread.request_shutdown(stop_instances); pthread_cond_signal(&guardian_thread.COND_guardian); } else { thread_registry.deliver_shutdown(); shutdown_complete= TRUE; } } } err: /* delete the pid file */ my_delete(options.pid_file_name, MYF(0)); #ifndef __WIN__ /* free alarm structures */ end_thr_alarm(1); /* don't pthread_exit to kill all threads who did not shut down in time */ #endif } <commit_msg>Fix im tests on powermacg5: temporarily fix for problem with Darwin kernels. For more details see bug 2030. Will push a proper fix later<commit_after>/* Copyright (C) 2003 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <my_global.h> #include "manager.h" #include "priv.h" #include "thread_registry.h" #include "listener.h" #include "instance_map.h" #include "options.h" #include "user_map.h" #include "log.h" #include "guardian.h" #include <my_sys.h> #include <m_string.h> #include <signal.h> #include <thr_alarm.h> #ifndef __WIN__ #include <sys/wait.h> #endif static int create_pid_file(const char *pid_file_name) { if (FILE *pid_file= my_fopen(pid_file_name, O_WRONLY | O_CREAT | O_BINARY, MYF(0))) { fprintf(pid_file, "%d\n", (int) getpid()); my_fclose(pid_file, MYF(0)); return 0; } log_error("can't create pid file %s: errno=%d, %s", pid_file_name, errno, strerror(errno)); return 1; } #ifndef __WIN__ void set_signals(sigset_t *mask) { /* block signals */ sigemptyset(mask); sigaddset(mask, SIGINT); sigaddset(mask, SIGTERM); sigaddset(mask, SIGPIPE); sigaddset(mask, SIGHUP); signal(SIGPIPE, SIG_IGN); /* We want this signal to be blocked in all theads but the signal one. It is needed for the thr_alarm subsystem to work. */ sigaddset(mask,THR_SERVER_ALARM); /* all new threads will inherite this signal mask */ pthread_sigmask(SIG_BLOCK, mask, NULL); /* In our case the signal thread also implements functions of alarm thread. Here we init alarm thread functionality. We suppose that we won't have more then 10 alarms at the same time. */ init_thr_alarm(10); } #else bool have_signal; void onsignal(int signo) { have_signal= true; } void set_signals(sigset_t *set) { signal(SIGINT, onsignal); signal(SIGTERM, onsignal); have_signal= false; } int my_sigwait(const sigset_t *set, int *sig) { while (!have_signal) { Sleep(100); } return 0; } #endif /* manager - entry point to the main instance manager process: start listener thread, write pid file and enter into signal handling. See also comments in mysqlmanager.cc to picture general Instance Manager architecture. */ void manager(const Options &options) { Thread_registry thread_registry; /* All objects created in the manager() function live as long as thread_registry lives, and thread_registry is alive until there are working threads. */ User_map user_map; Instance_map instance_map(options.default_mysqld_path); Guardian_thread guardian_thread(thread_registry, &instance_map, options.monitoring_interval); Listener_thread_args listener_args(thread_registry, options, user_map, instance_map); manager_pid= getpid(); instance_map.guardian= &guardian_thread; if (instance_map.init() || user_map.init()) return; if (instance_map.load()) { log_error("Cannot init instances repository. This might be caused by " "the wrong config file options. For instance, missing mysqld " "binary. Aborting."); return; } if (user_map.load(options.password_file_name)) return; /* write pid file */ if (create_pid_file(options.pid_file_name)) return; sigset_t mask; set_signals(&mask); /* create the listener */ { pthread_t listener_thd_id; pthread_attr_t listener_thd_attr; int rc; pthread_attr_init(&listener_thd_attr); pthread_attr_setdetachstate(&listener_thd_attr, PTHREAD_CREATE_DETACHED); rc= pthread_create(&listener_thd_id, &listener_thd_attr, listener, &listener_args); pthread_attr_destroy(&listener_thd_attr); if (rc) { log_error("manager(): pthread_create(listener) failed"); goto err; } } /* create guardian thread */ { pthread_t guardian_thd_id; pthread_attr_t guardian_thd_attr; int rc; /* NOTE: Guardian should be shutdown first. Only then all other threads need to be stopped. This should be done, as guardian is responsible for shutting down the instances, and this is a long operation. */ pthread_attr_init(&guardian_thd_attr); pthread_attr_setdetachstate(&guardian_thd_attr, PTHREAD_CREATE_DETACHED); rc= pthread_create(&guardian_thd_id, &guardian_thd_attr, guardian, &guardian_thread); pthread_attr_destroy(&guardian_thd_attr); if (rc) { log_error("manager(): pthread_create(guardian) failed"); goto err; } } /* To work nicely with LinuxThreads, the signal thread is the first thread in the process. */ int signo; bool shutdown_complete; shutdown_complete= FALSE; /* init list of guarded instances */ guardian_thread.lock(); guardian_thread.init(); guardian_thread.unlock(); /* After the list of guarded instances have been initialized, Guardian should start them. */ pthread_cond_signal(&guardian_thread.COND_guardian); while (!shutdown_complete) { int status= 0; if ((status= my_sigwait(&mask, &signo)) != 0) { log_error("sigwait() failed"); goto err; } #ifndef __WIN__ #ifdef IGNORE_SIGHUP_SIGQUIT if ( SIGHUP == signo ) continue; #endif if (THR_SERVER_ALARM == signo) process_alarm(signo); else #endif { if (!guardian_thread.is_stopped()) { bool stop_instances= true; guardian_thread.request_shutdown(stop_instances); pthread_cond_signal(&guardian_thread.COND_guardian); } else { thread_registry.deliver_shutdown(); shutdown_complete= TRUE; } } } err: /* delete the pid file */ my_delete(options.pid_file_name, MYF(0)); #ifndef __WIN__ /* free alarm structures */ end_thr_alarm(1); /* don't pthread_exit to kill all threads who did not shut down in time */ #endif } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| 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. * ******************************************************************************/ #define CAF_SUITE make_config_value_field #include "caf/make_config_value_field.hpp" #include "caf/test/dsl.hpp" #include "caf/config_option_set.hpp" #include "caf/config_value_object_access.hpp" using namespace caf; namespace { struct foobar { int foo = 0; std::string bar; foobar() = default; foobar(int foo, std::string bar) : foo(foo), bar(std::move(bar)) { // nop } }; std::string to_string(const foobar& x) { return deep_to_string(std::forward_as_tuple(x.foo, x.bar)); } bool operator==(const foobar& x, const foobar& y) { return x.foo == y.foo && x.bar == y.bar; } bool foo_valid(const int& x) { return x >= 0; } int get_foo_fun(foobar x) { return x.foo; } void set_foo_fun(foobar& x, const int& value) { x.foo = value; } struct get_foo_t { int operator()(const foobar& x) const noexcept { return x.foo; } }; struct set_foo_t { int& operator()(foobar& x, int value) const noexcept { x.foo = value; return x.foo; } }; struct foobar_trait { using object_type = foobar; static std::string type_name() { return "foobar"; } static span<config_value_field<object_type>*> fields() { static auto singleton = make_config_value_field_storage( make_config_value_field("foo", &foobar::foo, 123), make_config_value_field("bar", &foobar::bar)); return singleton.fields(); } }; struct foobar_foobar { foobar x; foobar y; foobar_foobar() = default; foobar_foobar(foobar x, foobar y) : x(x), y(y) { // nop } }; std::string to_string(const foobar_foobar& x) { return deep_to_string(std::forward_as_tuple(x.x, x.y)); } bool operator==(const foobar_foobar& x, const foobar_foobar& y) { return x.x == y.x && x.y == y.y; } struct foobar_foobar_trait { using object_type = foobar_foobar; static std::string type_name() { return "foobar-foobar"; } static span<config_value_field<object_type>*> fields() { static auto singleton = make_config_value_field_storage( make_config_value_field("x", &foobar_foobar::x), make_config_value_field("y", &foobar_foobar::y)); return singleton.fields(); } }; struct fixture { get_foo_t get_foo; set_foo_t set_foo; config_option_set opts; void test_foo_field(config_value_field<foobar>& foo_field) { foobar x; CAF_CHECK_EQUAL(foo_field.name(), "foo"); CAF_REQUIRE(foo_field.has_default()); CAF_CHECK(foo_field.valid(x)); CAF_CHECK_EQUAL(foo_field.get(x), config_value(0)); foo_field.set_default(x); CAF_CHECK_EQUAL(foo_field.get(x), config_value(42)); CAF_CHECK(not foo_field.type_check(config_value(1.))); CAF_CHECK(foo_field.type_check(config_value(-1))); foo_field.set(x, config_value(-1)); CAF_CHECK_EQUAL(foo_field.get(x), config_value(-1)); CAF_CHECK(not foo_field.valid(x)); string_view input = "123"; string_parser_state ps{input.begin(), input.end()}; foo_field.parse_cli(ps, x); CAF_CHECK_EQUAL(ps.code, pec::success); CAF_CHECK_EQUAL(foo_field.get(x), config_value(123)); } template <class T> expected<T> read(std::vector<std::string> args) { settings cfg; auto res = opts.parse(cfg, args); if (res.first != pec::success) return make_error(res.first, *res.second); auto x = get_if<T>(&cfg, "value"); if (x == none) return sec::invalid_argument; return *x; }; }; } // namespace namespace caf { template <> struct config_value_access<foobar> : config_value_object_access<foobar_trait> { }; template <> struct config_value_access<foobar_foobar> : config_value_object_access<foobar_foobar_trait> {}; } // namespace caf CAF_TEST_FIXTURE_SCOPE(make_config_value_field_tests, fixture) CAF_TEST(construction from pointer to member) { make_config_value_field("foo", &foobar::foo); make_config_value_field("foo", &foobar::foo, none); make_config_value_field("foo", &foobar::foo, none, nullptr); make_config_value_field("foo", &foobar::foo, 42); make_config_value_field("foo", &foobar::foo, 42, nullptr); make_config_value_field("foo", &foobar::foo, 42, foo_valid); make_config_value_field("foo", &foobar::foo, 42, [](const int& x) { return x != 0; }); } CAF_TEST(pointer to member access) { auto foo_field = make_config_value_field("foo", &foobar::foo, 42, foo_valid); test_foo_field(foo_field); } CAF_TEST(construction from getter and setter) { auto get_foo_lambda = [](const foobar& x) { return x.foo; }; auto set_foo_lambda = [](foobar& x, int value) { x.foo = value; }; make_config_value_field("foo", get_foo, set_foo); make_config_value_field("foo", get_foo_fun, set_foo); make_config_value_field("foo", get_foo_fun, set_foo_fun); make_config_value_field("foo", get_foo_lambda, set_foo_lambda); } CAF_TEST(getter and setter access) { auto foo_field = make_config_value_field("foo", get_foo, set_foo, 42, foo_valid); test_foo_field(foo_field); } CAF_TEST(oject access from dictionary - foobar) { settings x; put(x, "my-value.bar", "hello"); CAF_MESSAGE("without foo member"); { CAF_REQUIRE(holds_alternative<foobar>(x, "my-value")); CAF_REQUIRE(get_if<foobar>(&x, "my-value") != caf::none); auto fb = get<foobar>(x, "my-value"); CAF_CHECK_EQUAL(fb.foo, 123); CAF_CHECK_EQUAL(fb.bar, "hello"); CAF_MESSAGE("with foo member"); } put(x, "my-value.foo", 42); { CAF_REQUIRE(holds_alternative<foobar>(x, "my-value")); CAF_REQUIRE(get_if<foobar>(&x, "my-value") != caf::none); auto fb = get<foobar>(x, "my-value"); CAF_CHECK_EQUAL(fb.foo, 42); CAF_CHECK_EQUAL(fb.bar, "hello"); CAF_MESSAGE("with foo member"); } } CAF_TEST(oject access from dictionary - foobar_foobar) { settings x; put(x, "my-value.x.foo", 1); put(x, "my-value.x.bar", "hello"); put(x, "my-value.y.bar", "world"); CAF_REQUIRE(holds_alternative<foobar_foobar>(x, "my-value")); CAF_REQUIRE(get_if<foobar_foobar>(&x, "my-value") != caf::none); auto fbfb = get<foobar_foobar>(x, "my-value"); CAF_CHECK_EQUAL(fbfb.x.foo, 1); CAF_CHECK_EQUAL(fbfb.x.bar, "hello"); CAF_CHECK_EQUAL(fbfb.y.foo, 123); CAF_CHECK_EQUAL(fbfb.y.bar, "world"); } CAF_TEST(object access from CLI arguments - foobar) { opts.add<foobar>("value,v", "some value"); CAF_CHECK_EQUAL(read<foobar>({"--value={foo = 1, bar = hello}"}), foobar(1, "hello")); CAF_CHECK_EQUAL(read<foobar>({"-v{bar = \"hello\"}"}), foobar(123, "hello")); CAF_CHECK_EQUAL(read<foobar>({"-v", "{foo = 1, bar =hello ,}"}), foobar(1, "hello")); } CAF_TEST(object access from CLI arguments - foobar_foobar) { using fbfb = foobar_foobar; opts.add<fbfb>("value,v", "some value"); CAF_CHECK_EQUAL(read<fbfb>({"-v{x={bar = hello},y={foo=1,bar=world!},}"}), fbfb({123, "hello"}, {1, "world!"})); } CAF_TEST_FIXTURE_SCOPE_END() <commit_msg>Fix build on MSVC<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| 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. * ******************************************************************************/ #define CAF_SUITE make_config_value_field #include "caf/make_config_value_field.hpp" #include "caf/test/dsl.hpp" #include "caf/config_option_set.hpp" #include "caf/config_value_object_access.hpp" using namespace caf; namespace { struct foobar { int foo = 0; std::string bar; foobar() = default; foobar(int foo, std::string bar) : foo(foo), bar(std::move(bar)) { // nop } }; std::string to_string(const foobar& x) { return deep_to_string(std::forward_as_tuple(x.foo, x.bar)); } bool operator==(const foobar& x, const foobar& y) { return x.foo == y.foo && x.bar == y.bar; } bool foo_valid(const int& x) { return x >= 0; } int get_foo_fun(foobar x) { return x.foo; } void set_foo_fun(foobar& x, const int& value) { x.foo = value; } struct get_foo_t { int operator()(const foobar& x) const noexcept { return x.foo; } }; struct set_foo_t { int& operator()(foobar& x, int value) const noexcept { x.foo = value; return x.foo; } }; struct foobar_trait { using object_type = foobar; static std::string type_name() { return "foobar"; } static span<config_value_field<object_type>*> fields() { static auto singleton = make_config_value_field_storage( make_config_value_field("foo", &foobar::foo, 123), make_config_value_field("bar", &foobar::bar)); return singleton.fields(); } }; struct foobar_foobar { foobar x; foobar y; foobar_foobar() = default; foobar_foobar(foobar x, foobar y) : x(x), y(y) { // nop } }; std::string to_string(const foobar_foobar& x) { return deep_to_string(std::forward_as_tuple(x.x, x.y)); } bool operator==(const foobar_foobar& x, const foobar_foobar& y) { return x.x == y.x && x.y == y.y; } struct foobar_foobar_trait { using object_type = foobar_foobar; static std::string type_name() { return "foobar-foobar"; } static span<config_value_field<object_type>*> fields() { static auto singleton = make_config_value_field_storage( make_config_value_field("x", &foobar_foobar::x), make_config_value_field("y", &foobar_foobar::y)); return singleton.fields(); } }; struct fixture { get_foo_t get_foo; set_foo_t set_foo; config_option_set opts; void test_foo_field(config_value_field<foobar>& foo_field) { foobar x; CAF_CHECK_EQUAL(foo_field.name(), "foo"); CAF_REQUIRE(foo_field.has_default()); CAF_CHECK(foo_field.valid(x)); CAF_CHECK_EQUAL(foo_field.get(x), config_value(0)); foo_field.set_default(x); CAF_CHECK_EQUAL(foo_field.get(x), config_value(42)); CAF_CHECK(!foo_field.type_check(config_value(1.))); CAF_CHECK(foo_field.type_check(config_value(-1))); foo_field.set(x, config_value(-1)); CAF_CHECK_EQUAL(foo_field.get(x), config_value(-1)); CAF_CHECK(!foo_field.valid(x)); string_view input = "123"; string_parser_state ps{input.begin(), input.end()}; foo_field.parse_cli(ps, x); CAF_CHECK_EQUAL(ps.code, pec::success); CAF_CHECK_EQUAL(foo_field.get(x), config_value(123)); } template <class T> expected<T> read(std::vector<std::string> args) { settings cfg; auto res = opts.parse(cfg, args); if (res.first != pec::success) return make_error(res.first, *res.second); auto x = get_if<T>(&cfg, "value"); if (x == none) return sec::invalid_argument; return *x; }; }; } // namespace namespace caf { template <> struct config_value_access<foobar> : config_value_object_access<foobar_trait> { }; template <> struct config_value_access<foobar_foobar> : config_value_object_access<foobar_foobar_trait> {}; } // namespace caf CAF_TEST_FIXTURE_SCOPE(make_config_value_field_tests, fixture) CAF_TEST(construction from pointer to member) { make_config_value_field("foo", &foobar::foo); make_config_value_field("foo", &foobar::foo, none); make_config_value_field("foo", &foobar::foo, none, nullptr); make_config_value_field("foo", &foobar::foo, 42); make_config_value_field("foo", &foobar::foo, 42, nullptr); make_config_value_field("foo", &foobar::foo, 42, foo_valid); make_config_value_field("foo", &foobar::foo, 42, [](const int& x) { return x != 0; }); } CAF_TEST(pointer to member access) { auto foo_field = make_config_value_field("foo", &foobar::foo, 42, foo_valid); test_foo_field(foo_field); } CAF_TEST(construction from getter and setter) { auto get_foo_lambda = [](const foobar& x) { return x.foo; }; auto set_foo_lambda = [](foobar& x, int value) { x.foo = value; }; make_config_value_field("foo", get_foo, set_foo); make_config_value_field("foo", get_foo_fun, set_foo); make_config_value_field("foo", get_foo_fun, set_foo_fun); make_config_value_field("foo", get_foo_lambda, set_foo_lambda); } CAF_TEST(getter and setter access) { auto foo_field = make_config_value_field("foo", get_foo, set_foo, 42, foo_valid); test_foo_field(foo_field); } CAF_TEST(oject access from dictionary - foobar) { settings x; put(x, "my-value.bar", "hello"); CAF_MESSAGE("without foo member"); { CAF_REQUIRE(holds_alternative<foobar>(x, "my-value")); CAF_REQUIRE(get_if<foobar>(&x, "my-value") != caf::none); auto fb = get<foobar>(x, "my-value"); CAF_CHECK_EQUAL(fb.foo, 123); CAF_CHECK_EQUAL(fb.bar, "hello"); CAF_MESSAGE("with foo member"); } put(x, "my-value.foo", 42); { CAF_REQUIRE(holds_alternative<foobar>(x, "my-value")); CAF_REQUIRE(get_if<foobar>(&x, "my-value") != caf::none); auto fb = get<foobar>(x, "my-value"); CAF_CHECK_EQUAL(fb.foo, 42); CAF_CHECK_EQUAL(fb.bar, "hello"); CAF_MESSAGE("with foo member"); } } CAF_TEST(oject access from dictionary - foobar_foobar) { settings x; put(x, "my-value.x.foo", 1); put(x, "my-value.x.bar", "hello"); put(x, "my-value.y.bar", "world"); CAF_REQUIRE(holds_alternative<foobar_foobar>(x, "my-value")); CAF_REQUIRE(get_if<foobar_foobar>(&x, "my-value") != caf::none); auto fbfb = get<foobar_foobar>(x, "my-value"); CAF_CHECK_EQUAL(fbfb.x.foo, 1); CAF_CHECK_EQUAL(fbfb.x.bar, "hello"); CAF_CHECK_EQUAL(fbfb.y.foo, 123); CAF_CHECK_EQUAL(fbfb.y.bar, "world"); } CAF_TEST(object access from CLI arguments - foobar) { opts.add<foobar>("value,v", "some value"); CAF_CHECK_EQUAL(read<foobar>({"--value={foo = 1, bar = hello}"}), foobar(1, "hello")); CAF_CHECK_EQUAL(read<foobar>({"-v{bar = \"hello\"}"}), foobar(123, "hello")); CAF_CHECK_EQUAL(read<foobar>({"-v", "{foo = 1, bar =hello ,}"}), foobar(1, "hello")); } CAF_TEST(object access from CLI arguments - foobar_foobar) { using fbfb = foobar_foobar; opts.add<fbfb>("value,v", "some value"); CAF_CHECK_EQUAL(read<fbfb>({"-v{x={bar = hello},y={foo=1,bar=world!},}"}), fbfb({123, "hello"}, {1, "world!"})); } CAF_TEST_FIXTURE_SCOPE_END() <|endoftext|>
<commit_before>#pragma once #define BTS_SYMBOL "BTS" #define BTS_ADDRESS_PREFIX "BTS" #define BTS_MAX_SYMBOL_NAME_LENGTH 16 #define BTS_MAX_ASSET_NAME_LENGTH 127 #define BTS_MAX_SHARE_SUPPLY 1000000000000ll #define BTS_MAX_PAY_RATE 10000 /* 100% */ #define BTS_MAX_SIG_CHECK_DEPTH 2 #define BTS_MIN_DELEGATE_COUNT 10 /** * Don't allow the delegates to publish a limit that would * make the network unable to operate. */ #define BTS_MIN_TRANSACTION_SIZE_LIMIT 1024 #define BTS_MAX_BLOCK_INTERVAL 30 /* seconds */ #define BTS_DEFAULT_BLOCK_INTERVAL 5 /* seconds */ #define BTS_DEFAULT_MAX_TRANSACTION_SIZE 2048 #define BTS_DEFAULT_MAX_BLOCK_SIZE (BTS_DEFAULT_MAX_TRANSACTION_SIZE*BTS_DEFAULT_BLOCK_INTERVAL*10) #define BTS_DEFAULT_MAX_TIME_UNTIL_EXPIRATION (60*60*24) // seconds, aka: 1 day #define BTS_DEFAULT_MAINTENANCE_INTERVAL (60*60*24) // seconds, aka: 1 day #define BTS_DEFAULT_MAX_UNDO_HISTORY 1024 #define BTS_MIN_BLOCK_SIZE_LIMIT (BTS_MIN_TRANSACTION_SIZE_LIMIT*5) // 5 transactions per block #define BTS_MIN_TRANSACTION_EXPIRATION_LIMIT (BTS_MAX_BLOCK_INTERVAL * 5) // 5 transactions per block #define BTS_BLOCKCHAIN_MAX_SHARES (1000*1000*int64_t(1000)*1000*int64_t(1000)) #define BTS_BLOCKCHAIN_PRECISION 100000 #define BTS_BLOCKCHAIN_PRECISION_DIGITS 5 #define BTS_INITIAL_SUPPLY BTS_BLOCKCHAIN_MAX_SHARES #define BTS_DEFAULT_TRANSFER_FEE (1*BTS_BLOCKCHAIN_PRECISION) #define BTS_MAX_INSTANCE_ID (uint64_t(-1)>>16) /** NOTE: making this a power of 2 (say 2^15) would greatly accelerate fee calcs */ #define BTS_MAX_MARKET_FEE_PERCENT 10000 #define BTS_MAX_FEED_PRODUCERS 200 #define BTS_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES 10 #define BTS_MIN_COLLATERAL_RATIO 1001 // lower than this could result in divide by 0 #define BTS_MAX_COLLATERAL_RATIO 32000 // higher than this is unnecessary and may exceed int16 storage #define BTS_DEFAULT_INITIAL_COLLATERAL_RATIO 2000 #define BTS_DEFAULT_MAINTENANCE_COLLATERAL_RATIO 1750 #define BTS_DEFAULT_MARGIN_PERIOD_SEC (30*60*60*24) #define BTS_DEFAULT_WITNESS_PAY (50*BTS_BLOCKCHAIN_PRECISION) #define BTS_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC (60*60*24*7*4) // Four weeks #define BTS_DEFAULT_GENESIS_PROPOSAL_REVIEW_PERIOD_SEC (60*60*24*7*2) // Two weeks <commit_msg>Explicitly specify type for BTS_MAX_SHARE_SUPPLY<commit_after>#pragma once #define BTS_SYMBOL "BTS" #define BTS_ADDRESS_PREFIX "BTS" #define BTS_MAX_SYMBOL_NAME_LENGTH 16 #define BTS_MAX_ASSET_NAME_LENGTH 127 #define BTS_MAX_SHARE_SUPPLY int64_t(1000000000000ll) #define BTS_MAX_PAY_RATE 10000 /* 100% */ #define BTS_MAX_SIG_CHECK_DEPTH 2 #define BTS_MIN_DELEGATE_COUNT 10 /** * Don't allow the delegates to publish a limit that would * make the network unable to operate. */ #define BTS_MIN_TRANSACTION_SIZE_LIMIT 1024 #define BTS_MAX_BLOCK_INTERVAL 30 /* seconds */ #define BTS_DEFAULT_BLOCK_INTERVAL 5 /* seconds */ #define BTS_DEFAULT_MAX_TRANSACTION_SIZE 2048 #define BTS_DEFAULT_MAX_BLOCK_SIZE (BTS_DEFAULT_MAX_TRANSACTION_SIZE*BTS_DEFAULT_BLOCK_INTERVAL*10) #define BTS_DEFAULT_MAX_TIME_UNTIL_EXPIRATION (60*60*24) // seconds, aka: 1 day #define BTS_DEFAULT_MAINTENANCE_INTERVAL (60*60*24) // seconds, aka: 1 day #define BTS_DEFAULT_MAX_UNDO_HISTORY 1024 #define BTS_MIN_BLOCK_SIZE_LIMIT (BTS_MIN_TRANSACTION_SIZE_LIMIT*5) // 5 transactions per block #define BTS_MIN_TRANSACTION_EXPIRATION_LIMIT (BTS_MAX_BLOCK_INTERVAL * 5) // 5 transactions per block #define BTS_BLOCKCHAIN_MAX_SHARES (1000*1000*int64_t(1000)*1000*int64_t(1000)) #define BTS_BLOCKCHAIN_PRECISION 100000 #define BTS_BLOCKCHAIN_PRECISION_DIGITS 5 #define BTS_INITIAL_SUPPLY BTS_BLOCKCHAIN_MAX_SHARES #define BTS_DEFAULT_TRANSFER_FEE (1*BTS_BLOCKCHAIN_PRECISION) #define BTS_MAX_INSTANCE_ID (uint64_t(-1)>>16) /** NOTE: making this a power of 2 (say 2^15) would greatly accelerate fee calcs */ #define BTS_MAX_MARKET_FEE_PERCENT 10000 #define BTS_MAX_FEED_PRODUCERS 200 #define BTS_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES 10 #define BTS_MIN_COLLATERAL_RATIO 1001 // lower than this could result in divide by 0 #define BTS_MAX_COLLATERAL_RATIO 32000 // higher than this is unnecessary and may exceed int16 storage #define BTS_DEFAULT_INITIAL_COLLATERAL_RATIO 2000 #define BTS_DEFAULT_MAINTENANCE_COLLATERAL_RATIO 1750 #define BTS_DEFAULT_MARGIN_PERIOD_SEC (30*60*60*24) #define BTS_DEFAULT_WITNESS_PAY (50*BTS_BLOCKCHAIN_PRECISION) #define BTS_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC (60*60*24*7*4) // Four weeks #define BTS_DEFAULT_GENESIS_PROPOSAL_REVIEW_PERIOD_SEC (60*60*24*7*2) // Two weeks <|endoftext|>
<commit_before><commit_msg>resolved fdo#80166 check input against date acceptance pattern plausibility<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: e3dundo.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 04:55:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _E3D_UNDO_HXX #include "e3dundo.hxx" #endif #ifndef _SVDMODEL_HXX #include "svdmodel.hxx" #endif #ifndef _OUTLOBJ_HXX #include "outlobj.hxx" #endif #ifndef _E3D_VIEW3D_HXX #include "view3d.hxx" #endif #ifndef _E3D_SCENE3D_HXX #include "scene3d.hxx" #endif /************************************************************************/ TYPEINIT1(E3dUndoAction, SfxUndoAction); /************************************************************************\ |* |* Destruktor der Basisklasse |* \************************************************************************/ E3dUndoAction::~E3dUndoAction () { } /************************************************************************\ |* |* Repeat gibt es nicht |* \************************************************************************/ BOOL E3dUndoAction::CanRepeat(SfxRepeatTarget&) const { return FALSE; } /************************************************************************/ TYPEINIT1(E3dRotateUndoAction, E3dUndoAction); /************************************************************************ E3dRotateUndoAction ************************************************************************/ /************************************************************************\ |* |* Undodestruktor fuer 3D-Rotation |* \************************************************************************/ E3dRotateUndoAction::~E3dRotateUndoAction () { } /************************************************************************\ |* |* Undo fuer 3D-Rotation ueber die Rotationsmatrizen |* \************************************************************************/ void E3dRotateUndoAction::Undo () { pMy3DObj->SetTransform(aMyOldRotation); pMy3DObj->GetScene()->CorrectSceneDimensions(); } /************************************************************************\ |* |* Undo fuer 3D-Rotation ueber die Rotationsmatrizen |* \************************************************************************/ void E3dRotateUndoAction::Redo () { pMy3DObj->SetTransform(aMyNewRotation); pMy3DObj->GetScene()->CorrectSceneDimensions(); } /************************************************************************* |* |* E3dAttributesUndoAction |* \************************************************************************/ TYPEINIT1(E3dAttributesUndoAction, SdrUndoAction); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ E3dAttributesUndoAction::E3dAttributesUndoAction( SdrModel &rModel, E3dView* p3dView, E3dObject* pInObject, const SfxItemSet& rNewSet, const SfxItemSet& rOldSet, BOOL bUseSubObj) : SdrUndoAction( rModel ), pObject ( pInObject ), pView ( p3dView ), bUseSubObjects(bUseSubObj), aNewSet ( rNewSet ), aOldSet ( rOldSet ) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ E3dAttributesUndoAction::~E3dAttributesUndoAction() { } /************************************************************************* |* |* Undo() |* Implementiert ueber Set3DAttributes(), um die Attribute nur an einer |* Stelle pflegen zu muessen! |* \************************************************************************/ void E3dAttributesUndoAction::Undo() { //pObject->SetItemSetAndBroadcast(aOldSet); pObject->SetMergedItemSetAndBroadcast(aOldSet); if(pObject->ISA(E3dObject)) { E3dScene* pScene = ((E3dObject*)pObject)->GetScene(); if(pScene) pScene->CorrectSceneDimensions(); } } /************************************************************************* |* |* Redo() |* \************************************************************************/ void E3dAttributesUndoAction::Redo() { //pObject->SetItemSetAndBroadcast(aNewSet); pObject->SetMergedItemSetAndBroadcast(aNewSet); if(pObject->ISA(E3dObject)) { E3dScene* pScene = ((E3dObject*)pObject)->GetScene(); if(pScene) pScene->CorrectSceneDimensions(); } } /************************************************************************* |* |* Mehrfaches Undo nicht moeglich |* \************************************************************************/ BOOL E3dAttributesUndoAction::CanRepeat(SfxRepeatTarget& /*rView*/) const { return FALSE; } /************************************************************************* |* |* Mehrfaches Undo nicht moeglich |* \************************************************************************/ void E3dAttributesUndoAction::Repeat() { } <commit_msg>INTEGRATION: CWS vgbugs07 (1.7.352); FILE MERGED 2007/06/04 13:26:51 vg 1.7.352.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: e3dundo.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:02:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _E3D_UNDO_HXX #include <svx/e3dundo.hxx> #endif #ifndef _SVDMODEL_HXX #include <svx/svdmodel.hxx> #endif #ifndef _OUTLOBJ_HXX #include <svx/outlobj.hxx> #endif #ifndef _E3D_VIEW3D_HXX #include <svx/view3d.hxx> #endif #ifndef _E3D_SCENE3D_HXX #include <svx/scene3d.hxx> #endif /************************************************************************/ TYPEINIT1(E3dUndoAction, SfxUndoAction); /************************************************************************\ |* |* Destruktor der Basisklasse |* \************************************************************************/ E3dUndoAction::~E3dUndoAction () { } /************************************************************************\ |* |* Repeat gibt es nicht |* \************************************************************************/ BOOL E3dUndoAction::CanRepeat(SfxRepeatTarget&) const { return FALSE; } /************************************************************************/ TYPEINIT1(E3dRotateUndoAction, E3dUndoAction); /************************************************************************ E3dRotateUndoAction ************************************************************************/ /************************************************************************\ |* |* Undodestruktor fuer 3D-Rotation |* \************************************************************************/ E3dRotateUndoAction::~E3dRotateUndoAction () { } /************************************************************************\ |* |* Undo fuer 3D-Rotation ueber die Rotationsmatrizen |* \************************************************************************/ void E3dRotateUndoAction::Undo () { pMy3DObj->SetTransform(aMyOldRotation); pMy3DObj->GetScene()->CorrectSceneDimensions(); } /************************************************************************\ |* |* Undo fuer 3D-Rotation ueber die Rotationsmatrizen |* \************************************************************************/ void E3dRotateUndoAction::Redo () { pMy3DObj->SetTransform(aMyNewRotation); pMy3DObj->GetScene()->CorrectSceneDimensions(); } /************************************************************************* |* |* E3dAttributesUndoAction |* \************************************************************************/ TYPEINIT1(E3dAttributesUndoAction, SdrUndoAction); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ E3dAttributesUndoAction::E3dAttributesUndoAction( SdrModel &rModel, E3dView* p3dView, E3dObject* pInObject, const SfxItemSet& rNewSet, const SfxItemSet& rOldSet, BOOL bUseSubObj) : SdrUndoAction( rModel ), pObject ( pInObject ), pView ( p3dView ), bUseSubObjects(bUseSubObj), aNewSet ( rNewSet ), aOldSet ( rOldSet ) { } /************************************************************************* |* |* Destruktor |* \************************************************************************/ E3dAttributesUndoAction::~E3dAttributesUndoAction() { } /************************************************************************* |* |* Undo() |* Implementiert ueber Set3DAttributes(), um die Attribute nur an einer |* Stelle pflegen zu muessen! |* \************************************************************************/ void E3dAttributesUndoAction::Undo() { //pObject->SetItemSetAndBroadcast(aOldSet); pObject->SetMergedItemSetAndBroadcast(aOldSet); if(pObject->ISA(E3dObject)) { E3dScene* pScene = ((E3dObject*)pObject)->GetScene(); if(pScene) pScene->CorrectSceneDimensions(); } } /************************************************************************* |* |* Redo() |* \************************************************************************/ void E3dAttributesUndoAction::Redo() { //pObject->SetItemSetAndBroadcast(aNewSet); pObject->SetMergedItemSetAndBroadcast(aNewSet); if(pObject->ISA(E3dObject)) { E3dScene* pScene = ((E3dObject*)pObject)->GetScene(); if(pScene) pScene->CorrectSceneDimensions(); } } /************************************************************************* |* |* Mehrfaches Undo nicht moeglich |* \************************************************************************/ BOOL E3dAttributesUndoAction::CanRepeat(SfxRepeatTarget& /*rView*/) const { return FALSE; } /************************************************************************* |* |* Mehrfaches Undo nicht moeglich |* \************************************************************************/ void E3dAttributesUndoAction::Repeat() { } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File GsLib.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: wrapper of functions around GSLib routines // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_COMMUNICATION_GSLIB_HPP #define NEKTAR_LIB_UTILITIES_COMMUNICATION_GSLIB_HPP #include <iostream> using namespace std; #include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp> #include <LibUtilities/BasicUtils/SharedArray.hpp> #ifdef NEKTAR_USE_MPI #include <LibUtilities/Communication/CommMpi.h> #endif using namespace Nektar; namespace Gs { typedef enum { gs_double, gs_float, gs_int, gs_long, gs_dom_n } gs_dom; typedef enum { gs_add, gs_mul, gs_min, gs_max, gs_bpr, gs_op_n } gs_op; typedef enum { mode_plain, mode_vec, mode_many, mode_dry_run } gs_mode; typedef struct { void *ptr; size_t n,max; } array; typedef array buffer; #ifdef NEKTAR_USE_MPI typedef MPI_Comm comm_ext; typedef MPI_Request comm_req; #else typedef int comm_ext; typedef int comm_req; #endif struct comm { unsigned int id; unsigned int np; comm_ext c; }; typedef struct { unsigned int n; /* number of messages */ unsigned int *p; /* message source/dest proc */ unsigned int *size; /* size of message */ unsigned int total; /* sum of message sizes */ } pw_comm_data; typedef struct { pw_comm_data comm[2]; const unsigned int *map[2]; comm_req *req; unsigned int buffer_size; } pw_data; typedef struct { const unsigned int *scatter_map, *gather_map; unsigned int size_r, size_r1, size_r2; unsigned int size_sk, size_s, size_total; unsigned int p1, p2; unsigned int nrecvn; } cr_stage_data; typedef struct { cr_stage_data *stage[2]; unsigned int nstages; unsigned int buffer_size, stage_buffer_size; } cr_data; typedef struct { const unsigned int *map_to_buf[2], *map_from_buf[2]; unsigned int buffer_size; } allreduce_data; typedef void exec_fun( void *data, gs_mode mode, unsigned vn, gs_dom dom, gs_op op, unsigned transpose, const void *execdata, const struct comm *comm, char *buf); typedef struct { struct comm comm; const unsigned int *map_local[2]; /* 0=unflagged, 1=all */ const unsigned int *flagged_primaries; pw_data *pwd; cr_data *crd; allreduce_data *ard; unsigned int buffer_size; void *execdata; exec_fun *exec; } gs_data; extern "C" { void nektar_gs(void *u, gs_dom dom, gs_op op, unsigned transpose, gs_data *gsh, buffer *buf); gs_data *nektar_gs_setup(const long *id, unsigned int n, const struct comm *comm); void nektar_gs_free(gs_data *gsh); void nektar_gs_unique(const long *id, unsigned int n, const struct comm *comm); } /** * @brief Initialise Gather-Scatter map. * * On each process an array of IDs for each global degree of freedom is * supplied which corresponds to a unique numbering of universal degrees of * freedom. This is used to initialise the GSLib mapping between process- * boundary degrees of freedom on different processes. * @param pId Array of integers providing universal IDs for each * global DOF on the process. * @param pComm Communication object used for inter-process * communication. * @return GSLib data structure containing mapping information. */ static inline gs_data* Init ( const Nektar::Array<OneD, long> pId, const LibUtilities::CommSharedPtr& pComm) { #ifdef NEKTAR_USE_MPI if (pComm->GetSize() == 1) { return 0; } LibUtilities::CommMpiSharedPtr vCommMpi = boost::dynamic_pointer_cast<LibUtilities::CommMpi> (pComm); ASSERTL1(vCommMpi, "Failed to cast MPI Comm object."); comm vComm; MPI_Comm_dup(vCommMpi->GetComm(), &vComm.c); vComm.id = vCommMpi->GetRank(); vComm.np = vCommMpi->GetSize(); return nektar_gs_setup(pId.get(),pId.num_elements(), &vComm); #else return 0; #endif } /** * @brief Updates pId to negate all-but-one references to each universal ID. * * The array of universal IDs corresponding to the process-local DOF are * updated such that the ID of only one instance of each universal ID * remains positive. This allows the consistent formulation of universally * -distributed dot products, for which the contributions of each DOF must * be included only once. */ static inline void Unique(const Nektar::Array<OneD, long> pId, const LibUtilities::CommSharedPtr& pComm) { #ifdef NEKTAR_USE_MPI if (pComm->GetSize() == 1) { return; } LibUtilities::CommMpiSharedPtr vCommMpi = boost::dynamic_pointer_cast<LibUtilities::CommMpi> (pComm); ASSERTL1(vCommMpi, "Failed to cast MPI Comm object."); comm vComm; vComm.c = vCommMpi->GetComm(); vComm.id = vCommMpi->GetRank(); vComm.np = vCommMpi->GetSize(); nektar_gs_unique(pId.get(), pId.num_elements(), &vComm); #endif } /** * @brief Deallocates the GSLib mapping data. */ static inline void Finalise (gs_data *pGsh) { #ifdef NEKTAR_USE_MPI if (pGsh) { nektar_gs_free(pGsh); } #endif } /** * @brief Performs a gather-scatter operation of the provided values. * * The */ static inline void Gather(Nektar::Array<OneD, NekDouble> pU, gs_op pOp, gs_data *pGsh, Nektar::Array<OneD, NekDouble> pBuffer = NullNekDouble1DArray) { #ifdef NEKTAR_USE_MPI if (!pGsh) { return; } if (pBuffer.num_elements() == 0) { nektar_gs(pU.get(), gs_double, pOp, false, pGsh, 0); } else { array buf; buf.ptr = &pBuffer[0]; buf.n = pBuffer.num_elements(); nektar_gs(pU.get(), gs_double, pOp, false, pGsh, &buf); } #endif } } #endif <commit_msg>Updated gslib structs and function prototypes.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File GsLib.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: wrapper of functions around GSLib routines // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_COMMUNICATION_GSLIB_HPP #define NEKTAR_LIB_UTILITIES_COMMUNICATION_GSLIB_HPP #include <iostream> using namespace std; #include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp> #include <LibUtilities/BasicUtils/SharedArray.hpp> #ifdef NEKTAR_USE_MPI #include <LibUtilities/Communication/CommMpi.h> #endif using namespace Nektar; namespace Gs { typedef enum { gs_double, gs_float, gs_int, gs_long, gs_dom_n } gs_dom; typedef enum { gs_add, gs_mul, gs_min, gs_max, gs_bpr, gs_op_n } gs_op; typedef enum { mode_plain, mode_vec, mode_many, mode_dry_run } gs_mode; typedef struct { void *ptr; size_t n,max; } array; typedef array buffer; #ifdef NEKTAR_USE_MPI typedef MPI_Comm comm_ext; typedef MPI_Request comm_req; #else typedef int comm_ext; typedef int comm_req; #endif struct comm { unsigned int id; unsigned int np; comm_ext c; }; typedef struct { unsigned int n; /* number of messages */ unsigned int *p; /* message source/dest proc */ unsigned int *size; /* size of message */ unsigned int total; /* sum of message sizes */ } pw_comm_data; typedef struct { pw_comm_data comm[2]; const unsigned int *map[2]; comm_req *req; unsigned int buffer_size; } pw_data; typedef struct { const unsigned int *scatter_map, *gather_map; unsigned int size_r, size_r1, size_r2; unsigned int size_sk, size_s, size_total; unsigned int p1, p2; unsigned int nrecvn; } cr_stage; typedef struct { cr_stage *stage[2]; unsigned int nstages; unsigned int buffer_size, stage_buffer_size; } cr_data; typedef struct { const unsigned int *map_to_buf[2], *map_from_buf[2]; unsigned int buffer_size; } allreduce_data; typedef void exec_fun( void *data, gs_mode mode, unsigned vn, gs_dom dom, gs_op op, unsigned transpose, const void *execdata, const struct comm *comm, char *buf); typedef void fin_fun(void *data); typedef struct { unsigned int buffer_size, mem_size; void *data; exec_fun *exec; fin_fun *fin; } gs_remote; typedef struct { struct comm comm; const unsigned int *map_local[2]; /* 0=unflagged, 1=all */ const unsigned int *flagged_primaries; gs_remote r; unsigned int handle_size; } gs_data; typedef enum {gs_auto, gs_pairwise, gs_crystal_router, gs_all_reduce} gs_method; extern "C" { void nektar_gs(void *u, gs_dom dom, gs_op op, unsigned transpose, gs_data *gsh, buffer *buf); gs_data *nektar_gs_setup(const long *id, unsigned int n, const struct comm *comm, int unique, gs_method method, int verbose); void nektar_gs_free(gs_data *gsh); void nektar_gs_unique(const long *id, unsigned int n, const struct comm *comm); } /** * @brief Initialise Gather-Scatter map. * * On each process an array of IDs for each global degree of freedom is * supplied which corresponds to a unique numbering of universal degrees of * freedom. This is used to initialise the GSLib mapping between process- * boundary degrees of freedom on different processes. * @param pId Array of integers providing universal IDs for each * global DOF on the process. * @param pComm Communication object used for inter-process * communication. * @return GSLib data structure containing mapping information. */ static inline gs_data* Init ( const Nektar::Array<OneD, long> pId, const LibUtilities::CommSharedPtr& pComm) { #ifdef NEKTAR_USE_MPI if (pComm->GetSize() == 1) { return 0; } LibUtilities::CommMpiSharedPtr vCommMpi = boost::dynamic_pointer_cast<LibUtilities::CommMpi> (pComm); ASSERTL1(vCommMpi, "Failed to cast MPI Comm object."); comm vComm; MPI_Comm_dup(vCommMpi->GetComm(), &vComm.c); vComm.id = vCommMpi->GetRank(); vComm.np = vCommMpi->GetSize(); return nektar_gs_setup(pId.get(),pId.num_elements(), &vComm, 0, gs_auto, 1); #else return 0; #endif } /** * @brief Updates pId to negate all-but-one references to each universal ID. * * The array of universal IDs corresponding to the process-local DOF are * updated such that the ID of only one instance of each universal ID * remains positive. This allows the consistent formulation of universally * -distributed dot products, for which the contributions of each DOF must * be included only once. */ static inline void Unique(const Nektar::Array<OneD, long> pId, const LibUtilities::CommSharedPtr& pComm) { #ifdef NEKTAR_USE_MPI if (pComm->GetSize() == 1) { return; } LibUtilities::CommMpiSharedPtr vCommMpi = boost::dynamic_pointer_cast<LibUtilities::CommMpi> (pComm); ASSERTL1(vCommMpi, "Failed to cast MPI Comm object."); comm vComm; vComm.c = vCommMpi->GetComm(); vComm.id = vCommMpi->GetRank(); vComm.np = vCommMpi->GetSize(); nektar_gs_unique(pId.get(), pId.num_elements(), &vComm); #endif } /** * @brief Deallocates the GSLib mapping data. */ static inline void Finalise (gs_data *pGsh) { #ifdef NEKTAR_USE_MPI if (pGsh) { nektar_gs_free(pGsh); } #endif } /** * @brief Performs a gather-scatter operation of the provided values. * * The */ static inline void Gather(Nektar::Array<OneD, NekDouble> pU, gs_op pOp, gs_data *pGsh, Nektar::Array<OneD, NekDouble> pBuffer = NullNekDouble1DArray) { #ifdef NEKTAR_USE_MPI if (!pGsh) { return; } if (pBuffer.num_elements() == 0) { nektar_gs(pU.get(), gs_double, pOp, false, pGsh, 0); } else { array buf; buf.ptr = &pBuffer[0]; buf.n = pBuffer.num_elements(); nektar_gs(pU.get(), gs_double, pOp, false, pGsh, &buf); } #endif } } #endif <|endoftext|>