text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2014 Jrmy Ansel // Licensed under the MIT license. See LICENSE.txt #include "config.h" #include <string> #include <fstream> #include <algorithm> #include <cctype> using namespace std; Config g_config; Config::Config() { this->AspectRatioPreserved = true; this->MultisamplingAntialiasingEnabled = true; this->AnisotropicFilteringEnabled = true; this->WireframeFillMode = false; this->Concourse3DScale = 0.6f; ifstream file("ddraw.cfg"); if (file.is_open()) { string line; while (std::getline(file, line)) { if (!line.length()) { continue; } if (line[0] == '#' || line[0] == ';' || (line[0] == '/' && line[1] == '/')) { continue; } int pos = line.find("="); string name = line.substr(0, pos); name.erase(remove_if(name.begin(), name.end(), std::isspace), name.end()); string value = line.substr(pos + 1); value.erase(remove_if(value.begin(), value.end(), std::isspace), value.end()); if (!name.length() || !value.length()) { continue; } if (name == "PreserveAspectRatio") { this->AspectRatioPreserved = stoi(value) != 0; } else if (name == "EnableMultisamplingAntialiasing") { this->MultisamplingAntialiasingEnabled = stoi(value) != 0; } else if (name == "EnableAnisotropicFiltering") { this->AnisotropicFilteringEnabled = stoi(value) != 0; } else if (name == "FillWireframe") { this->WireframeFillMode = stoi(value) != 0; } else if (name == "Concourse3DScale") { this->Concourse3DScale = stof(value); } } } } <commit_msg>Set MSAA off by default<commit_after>// Copyright (c) 2014 Jrmy Ansel // Licensed under the MIT license. See LICENSE.txt #include "config.h" #include <string> #include <fstream> #include <algorithm> #include <cctype> using namespace std; Config g_config; Config::Config() { this->AspectRatioPreserved = true; this->MultisamplingAntialiasingEnabled = false; this->AnisotropicFilteringEnabled = true; this->WireframeFillMode = false; this->Concourse3DScale = 0.6f; ifstream file("ddraw.cfg"); if (file.is_open()) { string line; while (std::getline(file, line)) { if (!line.length()) { continue; } if (line[0] == '#' || line[0] == ';' || (line[0] == '/' && line[1] == '/')) { continue; } int pos = line.find("="); string name = line.substr(0, pos); name.erase(remove_if(name.begin(), name.end(), std::isspace), name.end()); string value = line.substr(pos + 1); value.erase(remove_if(value.begin(), value.end(), std::isspace), value.end()); if (!name.length() || !value.length()) { continue; } if (name == "PreserveAspectRatio") { this->AspectRatioPreserved = stoi(value) != 0; } else if (name == "EnableMultisamplingAntialiasing") { this->MultisamplingAntialiasingEnabled = stoi(value) != 0; } else if (name == "EnableAnisotropicFiltering") { this->AnisotropicFilteringEnabled = stoi(value) != 0; } else if (name == "FillWireframe") { this->WireframeFillMode = stoi(value) != 0; } else if (name == "Concourse3DScale") { this->Concourse3DScale = stof(value); } } } } <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "BenchTimer.h" #include "SamplePipeControllers.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkGPipe.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkStream.h" #include "SkTArray.h" #include "picture_utils.h" const int DEFAULT_REPEATS = 100; const int DEFAULT_TILE_WIDTH = 256; const int DEFAULT_TILE_HEIGHT = 256; struct Options; static void run_simple_benchmark(SkPicture* picture, const Options&); struct Options { int fRepeats; void (*fBenchmark) (SkPicture*, const Options& options); int fTileWidth; int fTileHeight; double fTileWidthPercentage; double fTileHeightPercentage; Options() : fRepeats(DEFAULT_REPEATS), fBenchmark(run_simple_benchmark), fTileWidth(DEFAULT_TILE_WIDTH), fTileHeight(DEFAULT_TILE_HEIGHT), fTileWidthPercentage(0), fTileHeightPercentage(0){} }; static void usage(const char* argv0) { SkDebugf("SkPicture benchmarking tool\n"); SkDebugf("\n" "Usage: \n" " %s <inputDir>...\n" " [--repeat] [--tile width height]" , argv0); SkDebugf("\n\n"); SkDebugf( " inputDir: A list of directories and files to use as input.\n" " Files are expected to have the .skp extension.\n\n"); SkDebugf( " --pipe : " "Set to use piping." " Default is to not use piping.\n"); SkDebugf( " --repeat : " "Set the number of times to repeat each test." " Default is %i.\n", DEFAULT_REPEATS); SkDebugf( " --tile width[%] height[%]: " "Set to use the tiling size and specify the dimensions of each tile.\n" " Default is to not use tiling\n"); SkDebugf( " --unflatten: " "Set to do a picture unflattening benchmark. Default is not to do this.\n"); } static void run_simple_benchmark(SkPicture* picture, const Options& options) { SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, picture->width(), picture->height()); SkCanvas canvas(bitmap); // We throw this away to remove first time effects (such as paging in this // program) canvas.drawPicture(*picture); BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { canvas.drawPicture(*picture); } timer.end(); printf("simple: cmsecs = %6.2f\n", timer.fWall / options.fRepeats); } struct TileInfo { SkBitmap* fBitmap; SkCanvas* fCanvas; }; static void clip_tile(SkPicture* picture, const TileInfo& tile) { SkRect clip = SkRect::MakeWH(SkIntToScalar(picture->width()), SkIntToScalar(picture->height())); tile.fCanvas->clipRect(clip); } static void setup_single_tile(SkPicture* picture, const SkBitmap& bitmap, const Options& options, SkTArray<TileInfo>* tiles, int tile_x_start, int tile_y_start) { TileInfo& tile = tiles->push_back(); tile.fBitmap = new SkBitmap(); SkIRect rect = SkIRect::MakeXYWH(tile_x_start, tile_y_start, options.fTileWidth, options.fTileHeight); bitmap.extractSubset(tile.fBitmap, rect); tile.fCanvas = new SkCanvas(*(tile.fBitmap)); tile.fCanvas->translate(SkIntToScalar(-tile_x_start), SkIntToScalar(-tile_y_start)); clip_tile(picture, tile); } static void setup_tiles(SkPicture* picture, const SkBitmap& bitmap, const Options& options, SkTArray<TileInfo>* tiles) { for (int tile_y_start = 0; tile_y_start < picture->height(); tile_y_start += options.fTileHeight) { for (int tile_x_start = 0; tile_x_start < picture->width(); tile_x_start += options.fTileWidth) { setup_single_tile(picture, bitmap, options, tiles, tile_x_start, tile_y_start); } } } static void run_tile_benchmark(SkPicture* picture, const Options& options) { SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, picture->width(), picture->height()); SkTArray<TileInfo> tiles; setup_tiles(picture, bitmap, options, &tiles); // We throw this away to remove first time effects (such as paging in this // program) for (int j = 0; j < tiles.count(); ++j) { tiles[j].fCanvas->drawPicture(*picture); } BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { for (int j = 0; j < tiles.count(); ++j) { tiles[j].fCanvas->drawPicture(*picture); } } timer.end(); for (int i = 0; i < tiles.count(); ++i) { delete tiles[i].fCanvas; delete tiles[i].fBitmap; } printf("%i_tiles_%ix%i: cmsecs = %6.2f\n", tiles.count(), options.fTileWidth, options.fTileHeight, timer.fWall / options.fRepeats); } static void pipe_run(SkPicture* picture, SkCanvas* canvas) { PipeController pipeController(canvas); SkGPipeWriter writer; SkCanvas* pipeCanvas = writer.startRecording(&pipeController); pipeCanvas->drawPicture(*picture); writer.endRecording(); } static void run_pipe_benchmark(SkPicture* picture, const Options& options) { SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, picture->width(), picture->height()); SkCanvas canvas(bitmap); // We throw this away to remove first time effects (such as paging in this // program) pipe_run(picture, &canvas); BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { pipe_run(picture, &canvas); } timer.end(); printf("pipe: cmsecs = %6.2f\n", timer.fWall / options.fRepeats); } static void run_unflatten_benchmark(SkPicture* commands, const Options& options) { BenchTimer timer = BenchTimer(NULL); double wall_time = 0; for (int i = 0; i < options.fRepeats + 1; ++i) { SkPicture replayer; SkCanvas* recorder = replayer.beginRecording(commands->width(), commands->height()); recorder->drawPicture(*commands); timer.start(); replayer.endRecording(); timer.end(); // We want to ignore first time effects if (i > 0) { wall_time += timer.fWall; } } printf("unflatten: cmsecs = %6.4f\n", wall_time / options.fRepeats); } static void run_single_benchmark(const SkString& inputPath, Options* options) { SkFILEStream inputStream; inputStream.setPath(inputPath.c_str()); if (!inputStream.isValid()) { SkDebugf("Could not open file %s\n", inputPath.c_str()); return; } SkPicture picture(&inputStream); SkString filename; sk_tools::get_basename(&filename, inputPath); printf("running bench [%i %i] %s ", picture.width(), picture.height(), filename.c_str()); if (options->fTileWidthPercentage > 0) { options->fTileWidth = sk_float_ceil2int(options->fTileWidthPercentage * picture.width() / 100); } if (options->fTileHeightPercentage > 0) { options->fTileHeight = sk_float_ceil2int(options->fTileHeightPercentage * picture.height() / 100); } options->fBenchmark(&picture, *options); } static bool is_percentage(char* const string) { SkString skString(string); return skString.endsWith("%"); } static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs, Options* options) { const char* argv0 = argv[0]; char* const* stop = argv + argc; for (++argv; argv < stop; ++argv) { if (0 == strcmp(*argv, "--repeat")) { ++argv; if (argv < stop) { options->fRepeats = atoi(*argv); if (options->fRepeats < 1) { SkDebugf("--repeat must be given a value > 0\n"); exit(-1); } } else { SkDebugf("Missing arg for --repeat\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--tile")) { options->fBenchmark = run_tile_benchmark; ++argv; if (argv < stop) { if (is_percentage(*argv)) { options->fTileWidthPercentage = atof(*argv); if (!(options->fTileWidthPercentage > 0)) { SkDebugf("--tile must be given a width percentage > 0\n"); exit(-1); } } else { options->fTileWidth = atoi(*argv); if (!(options->fTileWidth > 0)) { SkDebugf("--tile must be given a width > 0\n"); exit(-1); } } } else { SkDebugf("Missing width for --tile\n"); usage(argv0); exit(-1); } ++argv; if (argv < stop) { if (is_percentage(*argv)) { options->fTileHeightPercentage = atof(*argv); if (!(options->fTileHeightPercentage > 0)) { SkDebugf( "--tile must be given a height percentage > 0\n"); exit(-1); } } else { options->fTileHeight = atoi(*argv); if (!(options->fTileHeight > 0)) { SkDebugf("--tile must be given a height > 0\n"); exit(-1); } } } else { SkDebugf("Missing height for --tile\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--pipe")) { options->fBenchmark = run_pipe_benchmark; } else if (0 == strcmp(*argv, "--unflatten")) { options->fBenchmark = run_unflatten_benchmark; } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) { usage(argv0); exit(0); } else { inputs->push_back(SkString(*argv)); } } if (inputs->count() < 1) { usage(argv0); exit(-1); } } static void process_input(const SkString& input, Options* options) { SkOSFile::Iter iter(input.c_str(), "skp"); SkString inputFilename; if (iter.next(&inputFilename)) { do { SkString inputPath; sk_tools::make_filepath(&inputPath, input.c_str(), inputFilename); run_single_benchmark(inputPath, options); } while(iter.next(&inputFilename)); } else { run_single_benchmark(input, options); } } int main(int argc, char* const argv[]) { SkTArray<SkString> inputs; Options options; parse_commandline(argc, argv, &inputs, &options); for (int i = 0; i < inputs.count(); ++i) { process_input(inputs[i], &options); } } <commit_msg>Changed cmsecs to msecs to be consistent with bench.<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "BenchTimer.h" #include "SamplePipeControllers.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkGPipe.h" #include "SkOSFile.h" #include "SkPicture.h" #include "SkStream.h" #include "SkTArray.h" #include "picture_utils.h" const int DEFAULT_REPEATS = 100; const int DEFAULT_TILE_WIDTH = 256; const int DEFAULT_TILE_HEIGHT = 256; struct Options; static void run_simple_benchmark(SkPicture* picture, const Options&); struct Options { int fRepeats; void (*fBenchmark) (SkPicture*, const Options& options); int fTileWidth; int fTileHeight; double fTileWidthPercentage; double fTileHeightPercentage; Options() : fRepeats(DEFAULT_REPEATS), fBenchmark(run_simple_benchmark), fTileWidth(DEFAULT_TILE_WIDTH), fTileHeight(DEFAULT_TILE_HEIGHT), fTileWidthPercentage(0), fTileHeightPercentage(0){} }; static void usage(const char* argv0) { SkDebugf("SkPicture benchmarking tool\n"); SkDebugf("\n" "Usage: \n" " %s <inputDir>...\n" " [--repeat] [--tile width height]" , argv0); SkDebugf("\n\n"); SkDebugf( " inputDir: A list of directories and files to use as input.\n" " Files are expected to have the .skp extension.\n\n"); SkDebugf( " --pipe : " "Set to use piping." " Default is to not use piping.\n"); SkDebugf( " --repeat : " "Set the number of times to repeat each test." " Default is %i.\n", DEFAULT_REPEATS); SkDebugf( " --tile width[%] height[%]: " "Set to use the tiling size and specify the dimensions of each tile.\n" " Default is to not use tiling\n"); SkDebugf( " --unflatten: " "Set to do a picture unflattening benchmark. Default is not to do this.\n"); } static void run_simple_benchmark(SkPicture* picture, const Options& options) { SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, picture->width(), picture->height()); SkCanvas canvas(bitmap); // We throw this away to remove first time effects (such as paging in this // program) canvas.drawPicture(*picture); BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { canvas.drawPicture(*picture); } timer.end(); printf("simple: msecs = %6.2f\n", timer.fWall / options.fRepeats); } struct TileInfo { SkBitmap* fBitmap; SkCanvas* fCanvas; }; static void clip_tile(SkPicture* picture, const TileInfo& tile) { SkRect clip = SkRect::MakeWH(SkIntToScalar(picture->width()), SkIntToScalar(picture->height())); tile.fCanvas->clipRect(clip); } static void setup_single_tile(SkPicture* picture, const SkBitmap& bitmap, const Options& options, SkTArray<TileInfo>* tiles, int tile_x_start, int tile_y_start) { TileInfo& tile = tiles->push_back(); tile.fBitmap = new SkBitmap(); SkIRect rect = SkIRect::MakeXYWH(tile_x_start, tile_y_start, options.fTileWidth, options.fTileHeight); bitmap.extractSubset(tile.fBitmap, rect); tile.fCanvas = new SkCanvas(*(tile.fBitmap)); tile.fCanvas->translate(SkIntToScalar(-tile_x_start), SkIntToScalar(-tile_y_start)); clip_tile(picture, tile); } static void setup_tiles(SkPicture* picture, const SkBitmap& bitmap, const Options& options, SkTArray<TileInfo>* tiles) { for (int tile_y_start = 0; tile_y_start < picture->height(); tile_y_start += options.fTileHeight) { for (int tile_x_start = 0; tile_x_start < picture->width(); tile_x_start += options.fTileWidth) { setup_single_tile(picture, bitmap, options, tiles, tile_x_start, tile_y_start); } } } static void run_tile_benchmark(SkPicture* picture, const Options& options) { SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, picture->width(), picture->height()); SkTArray<TileInfo> tiles; setup_tiles(picture, bitmap, options, &tiles); // We throw this away to remove first time effects (such as paging in this // program) for (int j = 0; j < tiles.count(); ++j) { tiles[j].fCanvas->drawPicture(*picture); } BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { for (int j = 0; j < tiles.count(); ++j) { tiles[j].fCanvas->drawPicture(*picture); } } timer.end(); for (int i = 0; i < tiles.count(); ++i) { delete tiles[i].fCanvas; delete tiles[i].fBitmap; } printf("%i_tiles_%ix%i: msecs = %6.2f\n", tiles.count(), options.fTileWidth, options.fTileHeight, timer.fWall / options.fRepeats); } static void pipe_run(SkPicture* picture, SkCanvas* canvas) { PipeController pipeController(canvas); SkGPipeWriter writer; SkCanvas* pipeCanvas = writer.startRecording(&pipeController); pipeCanvas->drawPicture(*picture); writer.endRecording(); } static void run_pipe_benchmark(SkPicture* picture, const Options& options) { SkBitmap bitmap; sk_tools::setup_bitmap(&bitmap, picture->width(), picture->height()); SkCanvas canvas(bitmap); // We throw this away to remove first time effects (such as paging in this // program) pipe_run(picture, &canvas); BenchTimer timer = BenchTimer(NULL); timer.start(); for (int i = 0; i < options.fRepeats; ++i) { pipe_run(picture, &canvas); } timer.end(); printf("pipe: msecs = %6.2f\n", timer.fWall / options.fRepeats); } static void run_unflatten_benchmark(SkPicture* commands, const Options& options) { BenchTimer timer = BenchTimer(NULL); double wall_time = 0; for (int i = 0; i < options.fRepeats + 1; ++i) { SkPicture replayer; SkCanvas* recorder = replayer.beginRecording(commands->width(), commands->height()); recorder->drawPicture(*commands); timer.start(); replayer.endRecording(); timer.end(); // We want to ignore first time effects if (i > 0) { wall_time += timer.fWall; } } printf("unflatten: msecs = %6.4f\n", wall_time / options.fRepeats); } static void run_single_benchmark(const SkString& inputPath, Options* options) { SkFILEStream inputStream; inputStream.setPath(inputPath.c_str()); if (!inputStream.isValid()) { SkDebugf("Could not open file %s\n", inputPath.c_str()); return; } SkPicture picture(&inputStream); SkString filename; sk_tools::get_basename(&filename, inputPath); printf("running bench [%i %i] %s ", picture.width(), picture.height(), filename.c_str()); if (options->fTileWidthPercentage > 0) { options->fTileWidth = sk_float_ceil2int(options->fTileWidthPercentage * picture.width() / 100); } if (options->fTileHeightPercentage > 0) { options->fTileHeight = sk_float_ceil2int(options->fTileHeightPercentage * picture.height() / 100); } options->fBenchmark(&picture, *options); } static bool is_percentage(char* const string) { SkString skString(string); return skString.endsWith("%"); } static void parse_commandline(int argc, char* const argv[], SkTArray<SkString>* inputs, Options* options) { const char* argv0 = argv[0]; char* const* stop = argv + argc; for (++argv; argv < stop; ++argv) { if (0 == strcmp(*argv, "--repeat")) { ++argv; if (argv < stop) { options->fRepeats = atoi(*argv); if (options->fRepeats < 1) { SkDebugf("--repeat must be given a value > 0\n"); exit(-1); } } else { SkDebugf("Missing arg for --repeat\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--tile")) { options->fBenchmark = run_tile_benchmark; ++argv; if (argv < stop) { if (is_percentage(*argv)) { options->fTileWidthPercentage = atof(*argv); if (!(options->fTileWidthPercentage > 0)) { SkDebugf("--tile must be given a width percentage > 0\n"); exit(-1); } } else { options->fTileWidth = atoi(*argv); if (!(options->fTileWidth > 0)) { SkDebugf("--tile must be given a width > 0\n"); exit(-1); } } } else { SkDebugf("Missing width for --tile\n"); usage(argv0); exit(-1); } ++argv; if (argv < stop) { if (is_percentage(*argv)) { options->fTileHeightPercentage = atof(*argv); if (!(options->fTileHeightPercentage > 0)) { SkDebugf( "--tile must be given a height percentage > 0\n"); exit(-1); } } else { options->fTileHeight = atoi(*argv); if (!(options->fTileHeight > 0)) { SkDebugf("--tile must be given a height > 0\n"); exit(-1); } } } else { SkDebugf("Missing height for --tile\n"); usage(argv0); exit(-1); } } else if (0 == strcmp(*argv, "--pipe")) { options->fBenchmark = run_pipe_benchmark; } else if (0 == strcmp(*argv, "--unflatten")) { options->fBenchmark = run_unflatten_benchmark; } else if (0 == strcmp(*argv, "--help") || 0 == strcmp(*argv, "-h")) { usage(argv0); exit(0); } else { inputs->push_back(SkString(*argv)); } } if (inputs->count() < 1) { usage(argv0); exit(-1); } } static void process_input(const SkString& input, Options* options) { SkOSFile::Iter iter(input.c_str(), "skp"); SkString inputFilename; if (iter.next(&inputFilename)) { do { SkString inputPath; sk_tools::make_filepath(&inputPath, input.c_str(), inputFilename); run_single_benchmark(inputPath, options); } while(iter.next(&inputFilename)); } else { run_single_benchmark(input, options); } } int main(int argc, char* const argv[]) { SkTArray<SkString> inputs; Options options; parse_commandline(argc, argv, &inputs, &options); for (int i = 0; i < inputs.count(); ++i) { process_input(inputs[i], &options); } } <|endoftext|>
<commit_before>#include <algorithm> #include <atomic> #include <iostream> #include <limits> #include <utility> #include <vector> #include <getopt.h> #include <signal.h> #include <unistd.h> #include <zcm/zcm-cpp.hpp> using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { string infile = ""; string outfile = ""; bool verify = false; bool init(int argc, char *argv[]) { struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "output", required_argument, 0, 'o' }, { "verify", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "ho:v", long_opts, 0)) >= 0) { switch (c) { case 'o': outfile = string(optarg); break; case 'v': verify = true; break; case 'h': default: usage(); return false; }; } if (optind != argc - 1) { cerr << "Please specify a logfile" << endl; usage(); return false; } infile = string(argv[optind]); if (outfile.empty() && !verify) { cerr << "Must specify output file or verify mode" << endl; return false; } return true; } void usage() { cerr << "usage: zcm-log-repair [options] [FILE]" << endl << "" << endl << " Reads packets from a ZCM log file and writes them to an output " << " log file ensuring that all events are stored in recv_utime order." << endl << " This is generally only required if the original log was captured" << endl << " using multiple zcm shards and the user requires a strict ordering" << endl << " of events in the log." << endl << "" << endl << "Options:" << endl << "" << endl << " -h, --help Shows this help text and exits" << endl << " -o, --output=filename specify output file" << endl << " -v, --verify verify input log is monotonic in timestamp" << endl << endl; } }; struct LogRepair { Args args; zcm::LogFile* logIn = nullptr; zcm::LogFile* logOut = nullptr; const zcm::LogEvent* event; off_t length; off_t offset; vector<pair<int64_t, off_t>> timestamps; size_t progress; LogRepair() { } ~LogRepair() { if (logIn) delete logIn; if (logOut) delete logOut; } bool init(int argc, char *argv[]) { if (!args.init(argc, argv)) return false; logIn = new zcm::LogFile(args.infile, "r"); if (!logIn->good()) { cerr << "Error: Failed to open '" << args.infile << "'" << endl; return false; } if (!args.verify) { logOut = new zcm::LogFile(args.outfile, "w"); if (!logOut->good()) { cerr << "Error: Failed to create output log" << endl; return false; } } fseeko(logIn->getFilePtr(), 0, SEEK_END); length = ftello(logIn->getFilePtr()); fseeko(logIn->getFilePtr(), 0, SEEK_SET); return true; } int run() { // XXX: Note we are reading ALL of the event timestamps into memory, so // this will use something like 16 * num_events memory. In some use // cases that won't be ideal, so if people are running into that, we // can try a different approach. cout << "Reading log" << endl; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; offset = ftello(logIn->getFilePtr()); event = logIn->readNextEvent(); if (!event) break; if (args.verify && !timestamps.empty() && event->timestamp < timestamps.back().first) { cerr << endl << "Detected nonmonotonic timestamp at event " << timestamps.size() << endl; return 1; } timestamps.emplace_back(event->timestamp, offset); size_t p = (size_t)((100 * offset) / length); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Read " << timestamps.size() << " events" << endl; logIn->close(); if (args.verify) return 0; sort(timestamps.begin(), timestamps.end()); cout << "Writing new log" << endl; progress = 0; cout << progress << "%" << flush; for (size_t i = 0; i < timestamps.size(); ++i) { if (done) return 1; logOut->writeEvent(logIn->readEventAtOffset(timestamps[i].second)); size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Flushing to disk" << endl; delete logOut; cout << "Verifying output" << endl; logOut = new zcm::LogFile(args.verify ? args.infile : args.outfile, "r"); if (!logOut->good()) { cerr << "Error: Failed to open log for verification" << endl; return 1; } size_t i = 0; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; event = logOut->readNextEvent(); if (!event) break; if (event->timestamp != timestamps[i++].first) { cerr << endl << "Error: output log timestamp mismatch" << endl; cerr << "Expected " << timestamps[i].first << " got " << event->timestamp << " (idx " << i << ")" << endl; return 1; } size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } if (i < timestamps.size()) { cerr << endl << "Error: output log was missing " << timestamps.size() - i << " events" << endl; } logOut->close(); return 0; } }; int main(int argc, char* argv[]) { LogRepair lr; if (!lr.init(argc, argv)) return 1; // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); int ret = lr.run(); if (ret == 0) { cout << endl << "Success" << endl; } else { cerr << endl << "Failure" << endl; } return ret; } <commit_msg>fixing it<commit_after>#include <algorithm> #include <atomic> #include <iostream> #include <limits> #include <utility> #include <vector> #include <getopt.h> #include <signal.h> #include <unistd.h> #include <zcm/zcm-cpp.hpp> using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { string infile = ""; string outfile = ""; bool verify = false; bool init(int argc, char *argv[]) { struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "output", required_argument, 0, 'o' }, { "verify", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "ho:v", long_opts, 0)) >= 0) { switch (c) { case 'o': outfile = string(optarg); break; case 'v': verify = true; break; case 'h': default: usage(); return false; }; } if (optind != argc - 1) { cerr << "Please specify a logfile" << endl; usage(); return false; } infile = string(argv[optind]); if (outfile.empty() && !verify) { cerr << "Must specify output file or verify mode" << endl; return false; } return true; } void usage() { cerr << "usage: zcm-log-repair [options] [FILE]" << endl << "" << endl << " Reads packets from a ZCM log file and writes them to an output " << " log file ensuring that all events are stored in recv_utime order." << endl << " This is generally only required if the original log was captured" << endl << " using multiple zcm shards and the user requires a strict ordering" << endl << " of events in the log." << endl << "" << endl << "Options:" << endl << "" << endl << " -h, --help Shows this help text and exits" << endl << " -o, --output=filename specify output file" << endl << " -v, --verify verify input log is monotonic in timestamp" << endl << endl; } }; struct LogRepair { Args args; zcm::LogFile* logIn = nullptr; zcm::LogFile* logOut = nullptr; const zcm::LogEvent* event; off_t length; off_t offset; vector<pair<int64_t, off_t>> timestamps; size_t progress; LogRepair() { } ~LogRepair() { if (logIn) delete logIn; if (logOut) delete logOut; } bool init(int argc, char *argv[]) { if (!args.init(argc, argv)) return false; logIn = new zcm::LogFile(args.infile, "r"); if (!logIn->good()) { cerr << "Error: Failed to open '" << args.infile << "'" << endl; return false; } if (!args.verify) { logOut = new zcm::LogFile(args.outfile, "w"); if (!logOut->good()) { cerr << "Error: Failed to create output log" << endl; return false; } } fseeko(logIn->getFilePtr(), 0, SEEK_END); length = ftello(logIn->getFilePtr()); fseeko(logIn->getFilePtr(), 0, SEEK_SET); timestamps.reserve(1e6); return true; } int run() { // XXX: Note we are reading ALL of the event timestamps into memory, so // this will use something like 16 * num_events memory. In some use // cases that won't be ideal, so if people are running into that, we // can try a different approach. cout << "Reading log" << endl; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; offset = ftello(logIn->getFilePtr()); event = logIn->readNextEvent(); if (!event) break; if (args.verify && !timestamps.empty() && event->timestamp < timestamps.back().first) { cerr << endl << "Detected nonmonotonic timestamp at event " << timestamps.size() << endl; return 1; } timestamps.emplace_back(event->timestamp, offset); if (timestamps.size() == timestamps.capacity()) { timestamps.reserve(timestamps.capacity() * 2); } size_t p = (size_t)((100 * offset) / length); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Read " << timestamps.size() << " events" << endl; if (args.verify) return 0; sort(timestamps.begin(), timestamps.end()); cout << "Writing new log" << endl; progress = 0; cout << progress << "%" << flush; for (size_t i = 0; i < timestamps.size(); ++i) { if (done) return 1; logOut->writeEvent(logIn->readEventAtOffset(timestamps[i].second)); size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Flushing to disk" << endl; delete logOut; cout << "Verifying output" << endl; logOut = new zcm::LogFile(args.verify ? args.infile : args.outfile, "r"); if (!logOut->good()) { cerr << "Error: Failed to open log for verification" << endl; return 1; } size_t i = 0; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; event = logOut->readNextEvent(); if (!event) break; if (event->timestamp != timestamps[i++].first) { cerr << endl << "Error: output log timestamp mismatch" << endl; cerr << "Expected " << timestamps[i].first << " got " << event->timestamp << " (idx " << i << ")" << endl; return 1; } size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } if (i < timestamps.size()) { cerr << endl << "Error: output log was missing " << timestamps.size() - i << " events" << endl; } return 0; } }; int main(int argc, char* argv[]) { LogRepair lr; if (!lr.init(argc, argv)) return 1; // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); int ret = lr.run(); if (ret == 0) { cout << endl << "Success" << endl; } else { cerr << endl << "Failure" << endl; } return ret; } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 * Alessio Sclocco <a.sclocco@vu.nl> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <string> #include <limits> using std::string; using std::numeric_limits; #ifndef OBSERVATION_HPP #define OBSERVATION_HPP namespace AstroData { template< typename T > class Observation { public: Observation(string name, string dataType); ~Observation(); // General observation parameters inline void setNrSeconds(unsigned int seconds); inline void setNrStations(unsigned int nrStations); inline void setNrBeams(unsigned int beams); inline void setNrSamplesPerSecond(unsigned int samples); inline void setNrSamplesPerPaddedSecond(unsigned int samples); void setNrChannels(unsigned int channels); inline void setNrPaddedChannels(unsigned int channels); // Frequency parameters inline void setMinFreq(float freq); inline void setMaxFreq(float freq); inline void setChannelBandwidth(float bandwidth); // Statistical properties inline void setMinValue(T value); inline void setMaxValue(T value); inline void setAverage(unsigned int channel, double avg); inline void setVariance(unsigned int channel, double var); inline void setStdDev(unsigned int channel, double dev); // Dispersion measures inline void setNrDMs(unsigned int dms); inline void setNrPaddedDMs(unsigned int dms); inline void setFirstDM(float dm); inline void setDMStep(float step); // Periods inline void setNrPeriods(unsigned int periods); inline void setNrPaddedPeriods(unsigned int periods); inline void setNrBins(unsigned int bins); inline void setNrPaddedBins(unsigned int bins); inline void setFirstPeriod(unsigned int period); inline void setPeriodStep(unsigned int step); inline string getName(); inline string getDataType(); // General observation parameters inline unsigned int getNrSeconds(); inline unsigned int getNrStations(); inline unsigned int getNrBeams(); inline unsigned int getNrSamplesPerSecond(); inline float getSamplingRate(); inline unsigned int getNrSamplesPerPaddedSecond(); inline unsigned int getNrChannels(); inline unsigned int getNrPaddedChannels(); // Frequency parameters inline float getMinFreq(); inline float getMaxFreq(); inline float getChannelBandwidth(); // Statistical properties inline T getMinValue(); inline T getMaxValue(); inline double getAverage(unsigned int channel); inline double getVariance(unsigned int channel); inline double getStdDev(unsigned int channel); // Dispersion measures inline unsigned int getNrDMs(); inline unsigned int getNrPaddedDMs(); inline float getFirstDM(); inline float getDMStep(); // Periods inline unsigned int getNrPeriods(); inline unsigned int getNrPaddedPeriods(); inline unsigned int getNrBins(); inline unsigned int getNrPaddedBins(); inline unsigned int getFirstPeriod(); inline unsigned int getPeriodStep(); private: string name; string dataType; unsigned int nrSeconds; unsigned int nrStations; unsigned int nrBeams; unsigned int nrSamplesPerSecond; float samplingRate; unsigned int nrSamplesPerPaddedSecond; unsigned int nrChannels; unsigned int nrPaddedChannels; float minFreq; float maxFreq; float channelBandwidth; T minValue; T maxValue; double *average; double *variance; double *stdDev; unsigned int nrDMs; unsigned int nrPaddedDMs; float firstDM; float DMStep; unsigned int nrPeriods; unsigned int nrPaddedPeriods; unsigned int nrBins; unsigned int nrPaddedBins; unsigned int firstPeriod; unsigned int periodStep; }; // Implementation template< typename T > Observation< T >::Observation(string name, string dataType) : name(name), dataType(dataType), nrSeconds(0), nrStations(0), nrBeams(0), nrSamplesPerSecond(0), samplingRate(0.0f), nrSamplesPerPaddedSecond(0), nrChannels(0), nrPaddedChannels(0), minFreq(0.0f), maxFreq(0.0f), channelBandwidth(0.0f), minValue(numeric_limits< T >::max()), maxValue(numeric_limits< T >::min()), average(0.0), variance(0.0), stdDev(0.0), nrDMs(0), nrPaddedDMs(0), firstDM(0.0f), DMStep(0.0f), nrPeriods(0), nrPaddedPeriods(0), nrBins(0), nrPaddedBins(0), firstPeriod(0), periodStep(0) {} template< typename T > Observation< T >::~Observation() { delete [] average; delete [] variance; delete [] stdDev; } template< typename T > inline void Observation< T >::setNrSeconds(unsigned int seconds) { nrSeconds = seconds; } template< typename T > inline void Observation< T >::setNrStations(unsigned int stations) { nrStations = stations; } template< typename T > inline void Observation< T >::setNrBeams(unsigned int beams) { nrBeams = beams; } template< typename T > inline void Observation< T >::setNrSamplesPerSecond(unsigned int samples) { nrSamplesPerSecond = samples; samplingRate = 1.0f / samples; } template< typename T > inline void Observation< T >::setNrSamplesPerPaddedSecond(unsigned int samples) { nrSamplesPerPaddedSecond = samples; } template< typename T > void Observation< T >::setNrChannels(unsigned int channels) { nrChannels = channels; average = new double [channels]; variance = new double [channels]; stdDev = new double [channels]; } template< typename T > void Observation< T >::setNrPaddedChannels(unsigned int channels) { nrPaddedChannels = channels; } template< typename T > inline void Observation< T >::setMinFreq(float freq) { minFreq = freq; } template< typename T > inline void Observation< T >::setMaxFreq(float freq) { maxFreq = freq; } template< typename T > inline void Observation< T >::setChannelBandwidth(float bandwidth) { channelBandwidth = bandwidth; } template< typename T > inline void Observation< T >::setMinValue(T value) { minValue = value; } template< typename T > inline void Observation< T >::setMaxValue(T value) { maxValue = value; } template< typename T > inline void Observation< T >::setAverage(unsigned int channel, double avg) { average[channel] = avg; } template< typename T > inline void Observation< T >::setVariance(unsigned int channel, double var) { variance[channel] = var; } template< typename T > inline void Observation< T >::setStdDev(unsigned int channel, double dev) { stdDev[channel] = dev; } template< typename T > inline void Observation< T >::setNrDMs(unsigned int dms) { nrDMs = dms; } template< typename T > inline void Observation< T >::setNrPaddedDMs(unsigned int dms) { nrPaddedDMs = dms; } template< typename T > inline void Observation< T >::setFirstDM(float dm) { firstDM = dm; } template< typename T > inline void Observation< T >::setDMStep(float step) { DMStep = step; } template< typename T > inline void Observation< T >::setNrPeriods(unsigned int periods) { nrPeriods = periods; } template< typename T > inline void Observation< T >::setNrPaddedPeriods(unsigned int periods) { nrPaddedPeriods = periods; } template< typename T > inline void Observation< T >::setNrBins(unsigned int bins) { nrBins = bins; } template< typename T > inline void Observation< T >::setNrPaddedBins(unsigned int bins) { nrPaddedBins = bins; } template< typename T > inline void Observation< T >::setFirstPeriod(unsigned int period) { firstPeriod = period; } template< typename T > inline void Observation< T >::setPeriodStep(unsigned int step) { periodStep = step; } template< typename T > inline string Observation< T >::getName() { return name; } template< typename T > inline string Observation< T >::getDataType() { return dataType; } template< typename T > inline unsigned int Observation< T >::getNrSeconds() { return nrSeconds; } template< typename T > inline unsigned int Observation< T >::getNrStations() { return nrStations; } template< typename T > inline unsigned int Observation< T >::getNrBeams() { return nrBeams; } template< typename T > inline unsigned int Observation< T >::getNrSamplesPerSecond() { return nrSamplesPerSecond; } template< typename T > inline float Observation< T >::getSamplingRate() { return samplingRate; } template< typename T > inline unsigned int Observation< T >::getNrSamplesPerPaddedSecond() { return nrSamplesPerPaddedSecond; } template< typename T > inline unsigned int Observation< T >::getNrChannels() { return nrChannels; } template< typename T > inline unsigned int Observation< T >::getNrPaddedChannels() { return nrPaddedChannels; } template< typename T > inline float Observation< T >::getMinFreq() { return minFreq; } template< typename T > inline float Observation< T >::getMaxFreq() { return maxFreq; } template< typename T > inline float Observation< T >::getChannelBandwidth() { return channelBandwidth; } template< typename T > inline T Observation< T >::getMinValue() { return minValue; } template< typename T > inline T Observation< T >::getMaxValue() { return maxValue; } template< typename T > inline double Observation< T >::getAverage(unsigned int channel) { return average[channel]; } template< typename T > inline double Observation< T >::getVariance(unsigned int channel) { return variance[channel]; } template< typename T > inline double Observation< T >::getStdDev(unsigned int channel) { return stdDev[channel]; } template< typename T > inline unsigned int Observation< T >::getNrDMs() { return nrDMs; } template< typename T > inline unsigned int Observation< T >::getNrPaddedDMs() { return nrPaddedDMs; } template< typename T > inline float Observation< T >::getFirstDM() { return firstDM; } template< typename T > inline float Observation< T >::getDMStep() { return DMStep; } template< typename T > inline unsigned int Observation< T >::getNrPeriods() { return nrPeriods; } template< typename T > inline unsigned int Observation< T >::getNrPaddedPeriods() { return nrPaddedPeriods; } template< typename T > inline unsigned int Observation< T >::getNrBins() { return nrBins; } template< typename T > inline unsigned int Observation< T >::getNrPaddedBins() { return nrPaddedBins; } template< typename T > inline unsigned int Observation< T >::getFirstPeriod() { return firstPeriod; } template< typename T > inline unsigned int Observation< T >::getPeriodStep() { return periodStep; } } // AstroData #endif // OBSERVATION_HPP <commit_msg>Forgot to change 0.0 with 0 while initializing the statistical data.<commit_after>/* * Copyright (C) 2012 * Alessio Sclocco <a.sclocco@vu.nl> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <string> #include <limits> using std::string; using std::numeric_limits; #ifndef OBSERVATION_HPP #define OBSERVATION_HPP namespace AstroData { template< typename T > class Observation { public: Observation(string name, string dataType); ~Observation(); // General observation parameters inline void setNrSeconds(unsigned int seconds); inline void setNrStations(unsigned int nrStations); inline void setNrBeams(unsigned int beams); inline void setNrSamplesPerSecond(unsigned int samples); inline void setNrSamplesPerPaddedSecond(unsigned int samples); void setNrChannels(unsigned int channels); inline void setNrPaddedChannels(unsigned int channels); // Frequency parameters inline void setMinFreq(float freq); inline void setMaxFreq(float freq); inline void setChannelBandwidth(float bandwidth); // Statistical properties inline void setMinValue(T value); inline void setMaxValue(T value); inline void setAverage(unsigned int channel, double avg); inline void setVariance(unsigned int channel, double var); inline void setStdDev(unsigned int channel, double dev); // Dispersion measures inline void setNrDMs(unsigned int dms); inline void setNrPaddedDMs(unsigned int dms); inline void setFirstDM(float dm); inline void setDMStep(float step); // Periods inline void setNrPeriods(unsigned int periods); inline void setNrPaddedPeriods(unsigned int periods); inline void setNrBins(unsigned int bins); inline void setNrPaddedBins(unsigned int bins); inline void setFirstPeriod(unsigned int period); inline void setPeriodStep(unsigned int step); inline string getName(); inline string getDataType(); // General observation parameters inline unsigned int getNrSeconds(); inline unsigned int getNrStations(); inline unsigned int getNrBeams(); inline unsigned int getNrSamplesPerSecond(); inline float getSamplingRate(); inline unsigned int getNrSamplesPerPaddedSecond(); inline unsigned int getNrChannels(); inline unsigned int getNrPaddedChannels(); // Frequency parameters inline float getMinFreq(); inline float getMaxFreq(); inline float getChannelBandwidth(); // Statistical properties inline T getMinValue(); inline T getMaxValue(); inline double getAverage(unsigned int channel); inline double getVariance(unsigned int channel); inline double getStdDev(unsigned int channel); // Dispersion measures inline unsigned int getNrDMs(); inline unsigned int getNrPaddedDMs(); inline float getFirstDM(); inline float getDMStep(); // Periods inline unsigned int getNrPeriods(); inline unsigned int getNrPaddedPeriods(); inline unsigned int getNrBins(); inline unsigned int getNrPaddedBins(); inline unsigned int getFirstPeriod(); inline unsigned int getPeriodStep(); private: string name; string dataType; unsigned int nrSeconds; unsigned int nrStations; unsigned int nrBeams; unsigned int nrSamplesPerSecond; float samplingRate; unsigned int nrSamplesPerPaddedSecond; unsigned int nrChannels; unsigned int nrPaddedChannels; float minFreq; float maxFreq; float channelBandwidth; T minValue; T maxValue; double *average; double *variance; double *stdDev; unsigned int nrDMs; unsigned int nrPaddedDMs; float firstDM; float DMStep; unsigned int nrPeriods; unsigned int nrPaddedPeriods; unsigned int nrBins; unsigned int nrPaddedBins; unsigned int firstPeriod; unsigned int periodStep; }; // Implementation template< typename T > Observation< T >::Observation(string name, string dataType) : name(name), dataType(dataType), nrSeconds(0), nrStations(0), nrBeams(0), nrSamplesPerSecond(0), samplingRate(0.0f), nrSamplesPerPaddedSecond(0), nrChannels(0), nrPaddedChannels(0), minFreq(0.0f), maxFreq(0.0f), channelBandwidth(0.0f), minValue(numeric_limits< T >::max()), maxValue(numeric_limits< T >::min()), average(0), variance(0), stdDev(0), nrDMs(0), nrPaddedDMs(0), firstDM(0.0f), DMStep(0.0f), nrPeriods(0), nrPaddedPeriods(0), nrBins(0), nrPaddedBins(0), firstPeriod(0), periodStep(0) {} template< typename T > Observation< T >::~Observation() { delete [] average; delete [] variance; delete [] stdDev; } template< typename T > inline void Observation< T >::setNrSeconds(unsigned int seconds) { nrSeconds = seconds; } template< typename T > inline void Observation< T >::setNrStations(unsigned int stations) { nrStations = stations; } template< typename T > inline void Observation< T >::setNrBeams(unsigned int beams) { nrBeams = beams; } template< typename T > inline void Observation< T >::setNrSamplesPerSecond(unsigned int samples) { nrSamplesPerSecond = samples; samplingRate = 1.0f / samples; } template< typename T > inline void Observation< T >::setNrSamplesPerPaddedSecond(unsigned int samples) { nrSamplesPerPaddedSecond = samples; } template< typename T > void Observation< T >::setNrChannels(unsigned int channels) { nrChannels = channels; average = new double [channels]; variance = new double [channels]; stdDev = new double [channels]; } template< typename T > void Observation< T >::setNrPaddedChannels(unsigned int channels) { nrPaddedChannels = channels; } template< typename T > inline void Observation< T >::setMinFreq(float freq) { minFreq = freq; } template< typename T > inline void Observation< T >::setMaxFreq(float freq) { maxFreq = freq; } template< typename T > inline void Observation< T >::setChannelBandwidth(float bandwidth) { channelBandwidth = bandwidth; } template< typename T > inline void Observation< T >::setMinValue(T value) { minValue = value; } template< typename T > inline void Observation< T >::setMaxValue(T value) { maxValue = value; } template< typename T > inline void Observation< T >::setAverage(unsigned int channel, double avg) { average[channel] = avg; } template< typename T > inline void Observation< T >::setVariance(unsigned int channel, double var) { variance[channel] = var; } template< typename T > inline void Observation< T >::setStdDev(unsigned int channel, double dev) { stdDev[channel] = dev; } template< typename T > inline void Observation< T >::setNrDMs(unsigned int dms) { nrDMs = dms; } template< typename T > inline void Observation< T >::setNrPaddedDMs(unsigned int dms) { nrPaddedDMs = dms; } template< typename T > inline void Observation< T >::setFirstDM(float dm) { firstDM = dm; } template< typename T > inline void Observation< T >::setDMStep(float step) { DMStep = step; } template< typename T > inline void Observation< T >::setNrPeriods(unsigned int periods) { nrPeriods = periods; } template< typename T > inline void Observation< T >::setNrPaddedPeriods(unsigned int periods) { nrPaddedPeriods = periods; } template< typename T > inline void Observation< T >::setNrBins(unsigned int bins) { nrBins = bins; } template< typename T > inline void Observation< T >::setNrPaddedBins(unsigned int bins) { nrPaddedBins = bins; } template< typename T > inline void Observation< T >::setFirstPeriod(unsigned int period) { firstPeriod = period; } template< typename T > inline void Observation< T >::setPeriodStep(unsigned int step) { periodStep = step; } template< typename T > inline string Observation< T >::getName() { return name; } template< typename T > inline string Observation< T >::getDataType() { return dataType; } template< typename T > inline unsigned int Observation< T >::getNrSeconds() { return nrSeconds; } template< typename T > inline unsigned int Observation< T >::getNrStations() { return nrStations; } template< typename T > inline unsigned int Observation< T >::getNrBeams() { return nrBeams; } template< typename T > inline unsigned int Observation< T >::getNrSamplesPerSecond() { return nrSamplesPerSecond; } template< typename T > inline float Observation< T >::getSamplingRate() { return samplingRate; } template< typename T > inline unsigned int Observation< T >::getNrSamplesPerPaddedSecond() { return nrSamplesPerPaddedSecond; } template< typename T > inline unsigned int Observation< T >::getNrChannels() { return nrChannels; } template< typename T > inline unsigned int Observation< T >::getNrPaddedChannels() { return nrPaddedChannels; } template< typename T > inline float Observation< T >::getMinFreq() { return minFreq; } template< typename T > inline float Observation< T >::getMaxFreq() { return maxFreq; } template< typename T > inline float Observation< T >::getChannelBandwidth() { return channelBandwidth; } template< typename T > inline T Observation< T >::getMinValue() { return minValue; } template< typename T > inline T Observation< T >::getMaxValue() { return maxValue; } template< typename T > inline double Observation< T >::getAverage(unsigned int channel) { return average[channel]; } template< typename T > inline double Observation< T >::getVariance(unsigned int channel) { return variance[channel]; } template< typename T > inline double Observation< T >::getStdDev(unsigned int channel) { return stdDev[channel]; } template< typename T > inline unsigned int Observation< T >::getNrDMs() { return nrDMs; } template< typename T > inline unsigned int Observation< T >::getNrPaddedDMs() { return nrPaddedDMs; } template< typename T > inline float Observation< T >::getFirstDM() { return firstDM; } template< typename T > inline float Observation< T >::getDMStep() { return DMStep; } template< typename T > inline unsigned int Observation< T >::getNrPeriods() { return nrPeriods; } template< typename T > inline unsigned int Observation< T >::getNrPaddedPeriods() { return nrPaddedPeriods; } template< typename T > inline unsigned int Observation< T >::getNrBins() { return nrBins; } template< typename T > inline unsigned int Observation< T >::getNrPaddedBins() { return nrPaddedBins; } template< typename T > inline unsigned int Observation< T >::getFirstPeriod() { return firstPeriod; } template< typename T > inline unsigned int Observation< T >::getPeriodStep() { return periodStep; } } // AstroData #endif // OBSERVATION_HPP <|endoftext|>
<commit_before>#include "wintoastlib.h" using namespace WinToastLib; class CustomHandler : public IWinToastHandler { public: void toastActivated() const { std::wcout << L"The user clicked in this toast" << std::endl; exit(0); } void toastActivated(int actionIndex) const { std::wcout << L"The user clicked on action #" << actionIndex << std::endl; exit(16 + actionIndex); } void toastDismissed(WinToastDismissalReason state) const { switch (state) { case UserCanceled: std::wcout << L"The user dismissed this toast" << std::endl; exit(1); break; case TimedOut: std::wcout << L"The toast has timed out" << std::endl; exit(2); break; case ApplicationHidden: std::wcout << L"The application hid the toast using ToastNotifier.hide()" << std::endl; exit(3); break; default: std::wcout << L"Toast not activated" << std::endl; exit(4); break; } } void toastFailed() const { std::wcout << L"Error showing current toast" << std::endl; exit(5); } }; int wmain(int argc, LPWSTR *argv) { if (WinToast::isCompatible()) { std::wcerr << L"Error, your system in not supported!" << std::endl; return 6; } LPWSTR appName = L"Console WinToast Example", appUserModelID = L"WinToast Console Example", text = L"Hello, world!", imagePath = NULL; std::vector<std::wstring> actions; INT64 expiration; int i; for (i = 1; i < argc; i++) if (!wcscmp(L"-image", argv[i])) imagePath = argv[++i]; else if (!wcscmp(L"-action", argv[i])) actions.push_back(argv[++i]); else if (!wcscmp(L"-expire-ms", argv[i])) expiration = wcstol(argv[++i], NULL, 10); else if (!wcscmp(L"-app-name", argv[i])) appName = argv[++i]; else if (!wcscmp(L"-app-user-model-id", argv[i]) || !wcscmp(L"-app-id", argv[i])) appUserModelID = argv[++i]; else if (argv[i][0] == L'-') { std::wcout << L"Unhandled option: " << argv[i] << std::endl; return 7; } else if (i + 1 == argc) text = argv[i]; else { std::wcerr << L"Cannot handle multiple texts for now" << std::endl; return 8; } WinToast::instance()->setAppName(appName); WinToast::instance()->setAppUserModelId(appUserModelID); bool wasLinkCreated = false; if (!WinToast::instance()->initialize(&wasLinkCreated)) { std::wcerr << L"Error, your system in not compatible!" << std::endl; return 9; } if (wasLinkCreated) { WCHAR exePath[MAX_PATH]{L'\0'}; DWORD written = GetModuleFileNameExW(GetCurrentProcess(), nullptr, exePath, MAX_PATH); STARTUPINFOW si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(pi)); Sleep(3000); BOOL b = CreateProcessW(exePath, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if (b) { DWORD code = 1; WaitForSingleObject(pi.hProcess, INFINITE); if (!GetExitCodeProcess(pi.hProcess, &code)) std::wcerr << "Could not get exit code of child process!" << std::endl; CloseHandle(pi.hProcess); exit(code); } } WinToastTemplate templ; if (imagePath == NULL) templ = WinToastTemplate(WinToastTemplate::Text01); else { templ = WinToastTemplate(WinToastTemplate::ImageAndText01); templ.setImagePath(imagePath); } templ.setTextField(text, WinToastTemplate::FirstLine); for (auto const &action : actions) templ.addAction(action); if (expiration) templ.setExpiration(expiration); if (WinToast::instance()->showToast(templ, new CustomHandler()) < 0) { std::wcerr << L"Could not launch your toast notification!"; return 10; } // Give the handler a chance for 15 seconds (or the expiration plus 1 second) Sleep(expiration ? expiration + 1000 : 15000); exit(2); } <commit_msg>Just some clean & refactor to preserve the same style.<commit_after>#include "wintoastlib.h" using namespace WinToastLib; class CustomHandler : public IWinToastHandler { public: void toastActivated() const { std::wcout << L"The user clicked in this toast" << std::endl; exit(0); } void toastActivated(int actionIndex) const { std::wcout << L"The user clicked on action #" << actionIndex << std::endl; exit(16 + actionIndex); } void toastDismissed(WinToastDismissalReason state) const { switch (state) { case UserCanceled: std::wcout << L"The user dismissed this toast" << std::endl; exit(1); break; case TimedOut: std::wcout << L"The toast has timed out" << std::endl; exit(2); break; case ApplicationHidden: std::wcout << L"The application hid the toast using ToastNotifier.hide()" << std::endl; exit(3); break; default: std::wcout << L"Toast not activated" << std::endl; exit(4); break; } } void toastFailed() const { std::wcout << L"Error showing current toast" << std::endl; exit(5); } }; int wmain(int argc, LPWSTR *argv) { if (!WinToast::isCompatible()) { std::wcerr << L"Error, your system in not supported!" << std::endl; return 6; } LPWSTR appName = L"Console WinToast Example", appUserModelID = L"WinToast Console Example", text = L"Hello, world!", imagePath = NULL; std::vector<std::wstring> actions; INT64 expiration = 0; int i; for (i = 1; i < argc; i++) if (!wcscmp(L"-image", argv[i])) imagePath = argv[++i]; else if (!wcscmp(L"-action", argv[i])) actions.push_back(argv[++i]); else if (!wcscmp(L"-expire-ms", argv[i])) expiration = wcstol(argv[++i], NULL, 10); else if (!wcscmp(L"-app-name", argv[i])) appName = argv[++i]; else if (!wcscmp(L"-app-user-model-id", argv[i]) || !wcscmp(L"-app-id", argv[i])) appUserModelID = argv[++i]; else if (argv[i][0] == L'-') { std::wcout << L"Unhandled option: " << argv[i] << std::endl; return 7; } else if (i + 1 == argc) text = argv[i]; else { std::wcerr << L"Cannot handle multiple texts for now" << std::endl; return 8; } WinToast::instance()->setAppName(appName); WinToast::instance()->setAppUserModelId(appUserModelID); bool wasLinkCreated = false; if (!WinToast::instance()->initialize(&wasLinkCreated)) { std::wcerr << L"Error, your system in not compatible!" << std::endl; return 9; } if (wasLinkCreated) { WCHAR exePath[MAX_PATH]{L'\0'}; DWORD written = GetModuleFileNameExW(GetCurrentProcess(), nullptr, exePath, MAX_PATH); STARTUPINFOW si; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(pi)); Sleep(3000); BOOL b = CreateProcessW(exePath, GetCommandLineW(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if (b) { DWORD code = 1; WaitForSingleObject(pi.hProcess, INFINITE); if (!GetExitCodeProcess(pi.hProcess, &code)) std::wcerr << "Could not get exit code of child process!" << std::endl; CloseHandle(pi.hProcess); exit(code); } } WinToastTemplate templ((imagePath == NULL) ? WinToastTemplate::ImageAndText01 : WinToastTemplate::Text01); templ.setImagePath(imagePath); templ.setTextField(text, WinToastTemplate::FirstLine); for (auto const &action : actions) templ.addAction(action); if (expiration) templ.setExpiration(expiration); if (WinToast::instance()->showToast(templ, new CustomHandler()) < 0) { std::wcerr << L"Could not launch your toast notification!"; return 10; } // Give the handler a chance for 15 seconds (or the expiration plus 1 second) Sleep(expiration ? expiration + 1000 : 15000); exit(2); } <|endoftext|>
<commit_before>//============================================================================ // vSMC/example/rng/include/rng_test.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2015, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_EXAMPLE_RNG_TEST_HPP #define VSMC_EXAMPLE_RNG_TEST_HPP #ifndef VSMC_RNG_TEST_C_API #define VSMC_RNG_TEST_C_API 0 #endif #ifndef VSMC_RNG_TEST_MKL #define VSMC_RNG_TEST_MKL 0 #endif #include <vsmc/rng/rng.hpp> #include <vsmc/utility/stop_watch.hpp> #if VSMC_RNG_TEST_C_API #include <vsmc/vsmc.h> #if VSMC_HAS_MKL #include <vsmc/rng/mkl_brng.hpp> #endif #endif #define VSMC_RNG_TEST_PRE(prog) \ std::size_t N = 1000000; \ std::string prog_name(#prog); \ if (argc > 1) \ N = static_cast<std::size_t>(std::atoi(argv[1])); \ vsmc::Vector<std::string> names; \ vsmc::Vector<std::size_t> size; \ vsmc::Vector<vsmc::StopWatch> sw; #define VSMC_RNG_TEST(RNGType) rng_test<RNGType>(N, #RNGType, names, size, sw); #define VSMC_RNG_TEST_POST rng_output_sw(prog_name, names, size, sw); template <typename RNGType> inline void rng_test(std::size_t N, const std::string &name, vsmc::Vector<std::string> &names, vsmc::Vector<std::size_t> &size, vsmc::Vector<vsmc::StopWatch> &sw) { names.push_back(name); size.push_back(sizeof(RNGType)); RNGType rng; vsmc::StopWatch watch; double result = 0; vsmc::Vector<double> r(N); vsmc::Vector<typename RNGType::result_type> u(N); MKL_INT n = static_cast<MKL_INT>(N); MKL_INT m = 1000; #if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL #if VSMC_RNG_TEST_MKL MKL_INT brng = rng.stream().get_stream_state_brng(); #else MKL_INT brng = vsmc::mkl_brng<RNGType>(); #endif VSLStreamStatePtr stream = nullptr; vslNewStream(&stream, brng, 1); size.back() += vslGetStreamSize(stream); #endif std::uniform_real_distribution<double> runif_std(0, 1); watch.reset(); watch.start(); for (std::size_t i = 0; i != N; ++i) r[i] = runif_std(rng); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); vsmc::UniformRealDistributionType<RNGType, double> runif_vsmc(0, 1); watch.reset(); watch.start(); for (std::size_t i = 0; i != N; ++i) r[i] = runif_vsmc(rng); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); vsmc::uniform_real_distribution(rng, N, r.data(), 0.0, 1.0); watch.reset(); watch.start(); vsmc::uniform_real_distribution(rng, N, r.data(), 0.0, 1.0); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); #if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL vdRngUniform(VSL_RNG_METHOD_UNIFORM_STD, stream, m, r.data(), 0, 1); watch.reset(); watch.start(); vdRngUniform(VSL_RNG_METHOD_UNIFORM_STD, stream, n, r.data(), 0, 1); watch.stop(); sw.push_back(watch); result += r.back(); #endif std::normal_distribution<double> rnorm_std(0, 1); watch.reset(); watch.start(); for (std::size_t i = 0; i != N; ++i) r[i] = rnorm_std(rng); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); vsmc::NormalDistribution<double> rnorm_vsmc(0, 1); watch.reset(); watch.start(); for (std::size_t i = 0; i != N; ++i) r[i] = rnorm_vsmc(rng); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); vsmc::normal_distribution(rng, N, r.data(), 0.0, 1.0); watch.reset(); watch.start(); vsmc::normal_distribution(rng, N, r.data(), 0.0, 1.0); watch.stop(); sw.push_back(watch); result += r.back(); #if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL vdRngGaussian( VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, stream, m, r.data(), 0, 1); watch.reset(); watch.start(); vdRngGaussian( VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, stream, n, r.data(), 0, 1); watch.stop(); sw.push_back(watch); result += r.back(); #endif #if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL vslDeleteStream(&stream); #endif std::ofstream rnd("rnd"); rnd << result << std::endl; rnd.close(); } inline void rng_output_sw(const std::string &prog_name, const vsmc::Vector<std::string> &names, const vsmc::Vector<std::size_t> &size, const vsmc::Vector<vsmc::StopWatch> &sw) { std::size_t N = names.size(); std::size_t R = sw.size() / N; std::size_t lwid = 165; int twid = 15; int swid = 5; int Twid = twid * static_cast<int>(R); int nwid = static_cast<int>(lwid) - swid - Twid; std::cout << std::string(lwid, '=') << std::endl; std::cout << std::left << std::setw(nwid) << prog_name; std::cout << std::right << std::setw(swid) << "Size"; switch (R) { case 1: // Only time std::cout << std::right << std::setw(twid) << "Time (ms)"; break; case 2: // rng_dist std::cout << std::right << std::setw(twid) << "C++"; std::cout << std::right << std::setw(twid) << "C"; break; case 6: // rng_test without c api or mkl std::cout << std::right << std::setw(twid) << "U01 (STD)"; std::cout << std::right << std::setw(twid) << "U01 (vSMC)"; std::cout << std::right << std::setw(twid) << "U01 (Batch)"; std::cout << std::right << std::setw(twid) << "Normal (STD)"; std::cout << std::right << std::setw(twid) << "Normal (vSMC)"; std::cout << std::right << std::setw(twid) << "Normal (Batch)"; break; case 8: // rng_test with c api and mkl std::cout << std::right << std::setw(twid) << "U01 (STD)"; std::cout << std::right << std::setw(twid) << "U01 (vSMC)"; std::cout << std::right << std::setw(twid) << "U01 (Batch)"; std::cout << std::right << std::setw(twid) << "U01 (MKL)"; std::cout << std::right << std::setw(twid) << "Normal (STD)"; std::cout << std::right << std::setw(twid) << "Normal (vSMC)"; std::cout << std::right << std::setw(twid) << "Normal (Batch)"; std::cout << std::right << std::setw(twid) << "Normal (MKL)"; break; } std::cout << std::endl; std::cout << std::string(lwid, '-') << std::endl; for (std::size_t i = 0; i != N; ++i) { std::cout << std::left << std::setw(nwid) << names[i]; std::cout << std::right << std::setw(swid) << size[i]; for (std::size_t r = 0; r != R; ++r) { double time = sw[i * R + r].milliseconds(); std::cout << std::right << std::setw(twid) << std::fixed << time; } std::cout << std::endl; } std::cout << std::string(lwid, '=') << std::endl; } #endif // VSMC_EXAMPLE_RNG_TEST_HPP <commit_msg>explicit cast<commit_after>//============================================================================ // vSMC/example/rng/include/rng_test.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2015, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_EXAMPLE_RNG_TEST_HPP #define VSMC_EXAMPLE_RNG_TEST_HPP #ifndef VSMC_RNG_TEST_C_API #define VSMC_RNG_TEST_C_API 0 #endif #ifndef VSMC_RNG_TEST_MKL #define VSMC_RNG_TEST_MKL 0 #endif #include <vsmc/rng/rng.hpp> #include <vsmc/utility/stop_watch.hpp> #if VSMC_RNG_TEST_C_API #include <vsmc/vsmc.h> #if VSMC_HAS_MKL #include <vsmc/rng/mkl_brng.hpp> #endif #endif #define VSMC_RNG_TEST_PRE(prog) \ std::size_t N = 1000000; \ std::string prog_name(#prog); \ if (argc > 1) \ N = static_cast<std::size_t>(std::atoi(argv[1])); \ vsmc::Vector<std::string> names; \ vsmc::Vector<std::size_t> size; \ vsmc::Vector<vsmc::StopWatch> sw; #define VSMC_RNG_TEST(RNGType) rng_test<RNGType>(N, #RNGType, names, size, sw); #define VSMC_RNG_TEST_POST rng_output_sw(prog_name, names, size, sw); template <typename RNGType> inline void rng_test(std::size_t N, const std::string &name, vsmc::Vector<std::string> &names, vsmc::Vector<std::size_t> &size, vsmc::Vector<vsmc::StopWatch> &sw) { names.push_back(name); size.push_back(sizeof(RNGType)); RNGType rng; vsmc::StopWatch watch; double result = 0; vsmc::Vector<double> r(N); vsmc::Vector<typename RNGType::result_type> u(N); MKL_INT n = static_cast<MKL_INT>(N); MKL_INT m = 1000; #if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL #if VSMC_RNG_TEST_MKL MKL_INT brng = rng.stream().get_stream_state_brng(); #else MKL_INT brng = vsmc::mkl_brng<RNGType>(); #endif VSLStreamStatePtr stream = nullptr; vslNewStream(&stream, brng, 1); size.back() += static_cast<std::size_t>(vslGetStreamSize(stream)); #endif std::uniform_real_distribution<double> runif_std(0, 1); watch.reset(); watch.start(); for (std::size_t i = 0; i != N; ++i) r[i] = runif_std(rng); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); vsmc::UniformRealDistributionType<RNGType, double> runif_vsmc(0, 1); watch.reset(); watch.start(); for (std::size_t i = 0; i != N; ++i) r[i] = runif_vsmc(rng); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); vsmc::uniform_real_distribution(rng, N, r.data(), 0.0, 1.0); watch.reset(); watch.start(); vsmc::uniform_real_distribution(rng, N, r.data(), 0.0, 1.0); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); #if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL vdRngUniform(VSL_RNG_METHOD_UNIFORM_STD, stream, m, r.data(), 0, 1); watch.reset(); watch.start(); vdRngUniform(VSL_RNG_METHOD_UNIFORM_STD, stream, n, r.data(), 0, 1); watch.stop(); sw.push_back(watch); result += r.back(); #endif std::normal_distribution<double> rnorm_std(0, 1); watch.reset(); watch.start(); for (std::size_t i = 0; i != N; ++i) r[i] = rnorm_std(rng); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); vsmc::NormalDistribution<double> rnorm_vsmc(0, 1); watch.reset(); watch.start(); for (std::size_t i = 0; i != N; ++i) r[i] = rnorm_vsmc(rng); watch.stop(); sw.push_back(watch); result += vsmc::math::asum(N, r.data(), 1); vsmc::normal_distribution(rng, N, r.data(), 0.0, 1.0); watch.reset(); watch.start(); vsmc::normal_distribution(rng, N, r.data(), 0.0, 1.0); watch.stop(); sw.push_back(watch); result += r.back(); #if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL vdRngGaussian( VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, stream, m, r.data(), 0, 1); watch.reset(); watch.start(); vdRngGaussian( VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, stream, n, r.data(), 0, 1); watch.stop(); sw.push_back(watch); result += r.back(); #endif #if VSMC_RNG_TEST_C_API && VSMC_HAS_MKL vslDeleteStream(&stream); #endif std::ofstream rnd("rnd"); rnd << result << std::endl; rnd.close(); } inline void rng_output_sw(const std::string &prog_name, const vsmc::Vector<std::string> &names, const vsmc::Vector<std::size_t> &size, const vsmc::Vector<vsmc::StopWatch> &sw) { std::size_t N = names.size(); std::size_t R = sw.size() / N; std::size_t lwid = 165; int twid = 15; int swid = 5; int Twid = twid * static_cast<int>(R); int nwid = static_cast<int>(lwid) - swid - Twid; std::cout << std::string(lwid, '=') << std::endl; std::cout << std::left << std::setw(nwid) << prog_name; std::cout << std::right << std::setw(swid) << "Size"; switch (R) { case 1: // Only time std::cout << std::right << std::setw(twid) << "Time (ms)"; break; case 2: // rng_dist std::cout << std::right << std::setw(twid) << "C++"; std::cout << std::right << std::setw(twid) << "C"; break; case 6: // rng_test without c api or mkl std::cout << std::right << std::setw(twid) << "U01 (STD)"; std::cout << std::right << std::setw(twid) << "U01 (vSMC)"; std::cout << std::right << std::setw(twid) << "U01 (Batch)"; std::cout << std::right << std::setw(twid) << "Normal (STD)"; std::cout << std::right << std::setw(twid) << "Normal (vSMC)"; std::cout << std::right << std::setw(twid) << "Normal (Batch)"; break; case 8: // rng_test with c api and mkl std::cout << std::right << std::setw(twid) << "U01 (STD)"; std::cout << std::right << std::setw(twid) << "U01 (vSMC)"; std::cout << std::right << std::setw(twid) << "U01 (Batch)"; std::cout << std::right << std::setw(twid) << "U01 (MKL)"; std::cout << std::right << std::setw(twid) << "Normal (STD)"; std::cout << std::right << std::setw(twid) << "Normal (vSMC)"; std::cout << std::right << std::setw(twid) << "Normal (Batch)"; std::cout << std::right << std::setw(twid) << "Normal (MKL)"; break; } std::cout << std::endl; std::cout << std::string(lwid, '-') << std::endl; for (std::size_t i = 0; i != N; ++i) { std::cout << std::left << std::setw(nwid) << names[i]; std::cout << std::right << std::setw(swid) << size[i]; for (std::size_t r = 0; r != R; ++r) { double time = sw[i * R + r].milliseconds(); std::cout << std::right << std::setw(twid) << std::fixed << time; } std::cout << std::endl; } std::cout << std::string(lwid, '=') << std::endl; } #endif // VSMC_EXAMPLE_RNG_TEST_HPP <|endoftext|>
<commit_before>/** * @file compmanager.cpp * @brief COSSB component manager * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details */ #include "manager.hpp" #include "container.hpp" #include "broker.hpp" #include "driver.hpp" namespace cossb { namespace manager { bool component_manager::install(const char* component_name) { if(cossb_component_container->add(component_name, new driver::component_driver(component_name))) { interface::icomponent* pComponent = cossb_component_container->get_component(component_name); pComponent->setup(); /*if(pComponent->setup()) { //string publish = pComponent->get_profile()->get(profile::section::info, "publish").asString("undefined"); //cossb_component_broker->regist(pComponent,publish.c_str()); }*/ } return true; } types::returntype component_manager::uninstall(const char* component_name) { interface::icomponent* pComponent = cossb_component_container->get_component(component_name); if(pComponent) { pComponent->stop(); cossb_component_container->remove(component_name); } return types::returntype::SUCCESS; } types::returntype component_manager::run(const char* component_name) { return types::returntype::SUCCESS; } types::returntype component_manager::run() { return types::returntype::SUCCESS; } types::returntype component_manager::stop(const char* component_name) { return types::returntype::SUCCESS; } types::returntype component_manager::stop() { return types::returntype::SUCCESS; } int component_manager::count() { return 0; } } /* namespace manager */ } /* namespace cossb */ <commit_msg>add remove function<commit_after>/** * @file compmanager.cpp * @brief COSSB component manager * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details */ #include "manager.hpp" #include "container.hpp" #include "broker.hpp" #include "driver.hpp" namespace cossb { namespace manager { component_manager::~component_manager() { stop(); } bool component_manager::install(const char* component_name) { if(cossb_component_container->add(component_name, new driver::component_driver(component_name))) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->setup(); return true; } } return false; } types::returntype component_manager::uninstall(const char* component_name) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->stop(); cossb_component_container->remove(component_name); return types::returntype::SUCCESS; } return types::returntype::FAIL; } types::returntype component_manager::run(const char* component_name) { if(cossb_component_container->exist(component_name)) { cossb_component_container->get_driver(component_name)->run(); return types::returntype::SUCCESS; } return types::returntype::FAIL; } types::returntype component_manager::run() { return types::returntype::SUCCESS; } types::returntype component_manager::stop(const char* component_name) { return types::returntype::SUCCESS; } types::returntype component_manager::stop() { return types::returntype::SUCCESS; } int component_manager::count() { return 0; } } /* namespace manager */ } /* namespace cossb */ <|endoftext|>
<commit_before>/* Copyright (c) 2014, Kai Klindworth All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 "manual_region_optimizer.h" #include <omp.h> #include "disparity_region.h" #include "genericfunctions.h" #include "disparity_utils.h" void manual_region_optimizer::optimize(std::vector<unsigned char>& damping_history, std::vector<std::vector<float>>& optimization_vectors_base, std::vector<std::vector<float>>& optimization_vectors_match, region_container& base, region_container& match, const disparity_hypothesis_weight_vector& base_eval, std::function<float(const disparity_region&, const region_container&, const region_container&, int)> prop_eval, int delta) { //std::cout << "base" << std::endl; refreshOptimizationBaseValues(optimization_vectors_base, base, match, base_eval, delta); refreshOptimizationBaseValues(optimization_vectors_match, match, base, base_eval, delta); //std::cout << "optimize" << std::endl; std::random_device random_dev; std::mt19937 random_gen(random_dev()); //FIXME each threads needs a own copy std::uniform_int_distribution<> random_dist(0, 1); const int dispMin = base.task.dispMin; const int crange = base.task.range_size(); cv::Mat_<float> temp_results(crange, 1, 100.0f); const std::size_t regions_count = base.regions.size(); //pragma omp parallel for default(none) shared(base, match, prop_eval, delta) private(random_dist, random_gen, temp_results) for(std::size_t j = 0; j < regions_count; ++j) { disparity_region& baseRegion = base.regions[j]; temp_results = cv::Mat_<float>(crange, 1, 5500.0f); //TODO: try another mt safe with less memory allocations... disparity_range drange = task_subrange(base.task, baseRegion.base_disparity, delta); for(short d = drange.start(); d <= drange.end(); ++d) { if(!baseRegion.corresponding_regions[d-dispMin].empty()) temp_results(d-dispMin) = prop_eval(baseRegion, base, match, d); } short ndisparity = min_idx(temp_results, baseRegion.disparity - dispMin) + dispMin; //damping if(ndisparity != baseRegion.disparity) damping_history[j] += 1; if(damping_history[j] < 2) { baseRegion.disparity = ndisparity; /*EstimationStep step; step.disparity = baseRegion.disparity; baseRegion.results.push_back(step);*/ } else { if(random_dist(random_gen) == 1) { baseRegion.disparity = ndisparity; /*EstimationStep step; step.disparity = baseRegion.disparity; baseRegion.results.push_back(step);*/ } else damping_history[j] = 0; } } } void manual_region_optimizer::training() { std::cout << "training" << std::endl; } void manual_region_optimizer::reset(const region_container &left, const region_container &right) { damping_history_left.resize(left.regions.size()); std::fill(damping_history_left.begin(), damping_history_left.end(), 0); damping_history_right.resize(right.regions.size()); std::fill(damping_history_right.begin(), damping_history_right.end(), 0); optimization_vectors_left.resize(left.regions.size()); optimization_vectors_right.resize(right.regions.size()); } void manual_region_optimizer::run(region_container &left, region_container &right, const optimizer_settings &config, int refinement) { reset(left, right); for(int i = 0; i < config.rounds; ++i) { std::cout << "optimization round" << std::endl; optimize(damping_history_left, optimization_vectors_left, optimization_vectors_right, left, right, config.base_eval, config.prop_eval, refinement); refresh_warped_regions(left); optimize(damping_history_right, optimization_vectors_right, optimization_vectors_left, right, left, config.base_eval, config.prop_eval, refinement); refresh_warped_regions(right); } for(int i = 0; i < config.rounds; ++i) { std::cout << "optimization round2" << std::endl; optimize(damping_history_left, optimization_vectors_left, optimization_vectors_right, left, right, config.base_eval2, config.prop_eval2, refinement); refresh_warped_regions(left); optimize(damping_history_right, optimization_vectors_right, optimization_vectors_left, right, left, config.base_eval2, config.prop_eval2, refinement); refresh_warped_regions(right); } if(config.rounds == 0) { refreshOptimizationBaseValues(optimization_vectors_left, left, right, config.base_eval, refinement); refreshOptimizationBaseValues(optimization_vectors_right, right, left, config.base_eval, refinement); } } float calculate_end_result(const float *raw_results, const disparity_hypothesis_weight_vector& wv) { return raw_results[0] * wv.costs + raw_results[1] * wv.occ_avg + raw_results[2] * wv.neighbor_pot + raw_results[3] * wv.lr_pot + raw_results[4] * wv.neighbor_color_pot; //return raw_results[0] * wv.costs + raw_results[1] * wv.occ_avg + raw_results[2] * wv.lr_pot + raw_results[3] * wv.neighbor_color_pot; } float calculate_end_result(int disp_idx, const float *raw_results, const disparity_hypothesis_weight_vector &wv) { std::size_t idx_offset = disp_idx*disparity_features_calculator::vector_size_per_disp; const float *result_ptr = raw_results + idx_offset; return calculate_end_result(result_ptr, wv); } void refreshOptimizationBaseValues(std::vector<std::vector<float>>& optimization_vectors, region_container& base, const region_container& match, const disparity_hypothesis_weight_vector& stat_eval, int delta) { cv::Mat disp = disparity_by_segments(base); cv::Mat occmap = disparity::occlusion_stat<short>(disp, 1.0); int pot_trunc = 10; const short dispMin = base.task.dispMin; const short dispRange = base.task.dispMax - base.task.dispMin + 1; std::vector<disparity_features_calculator> hyp_vec(omp_get_max_threads(), disparity_features_calculator(base, match)); std::vector<cv::Mat_<unsigned char>> occmaps(omp_get_max_threads()); for(std::size_t i = 0; i < occmaps.size(); ++i) { occmaps[i] = occmap.clone(); //hyp_vec.emplace_back(base.regions, match.regions); } std::size_t regions_count = base.regions.size(); #pragma omp parallel for for(std::size_t i = 0; i < regions_count; ++i) { disparity_region& baseRegion = base.regions[i]; int thread_idx = omp_get_thread_num(); intervals::substract_region_value<unsigned char>(occmaps[thread_idx], baseRegion.warped_interval, 1); baseRegion.optimization_energy = cv::Mat_<float>(dispRange, 1, 100.0f); disparity_range drange = task_subrange(base.task, baseRegion.base_disparity, delta); hyp_vec[thread_idx](occmaps[thread_idx], baseRegion, pot_trunc, drange , optimization_vectors[i]); for(short d = drange.start(); d <= drange.end(); ++d) { std::vector<corresponding_region>& cregionvec = baseRegion.corresponding_regions[d-dispMin]; if(!cregionvec.empty()) baseRegion.optimization_energy(d-dispMin) = calculate_end_result((d - drange.start()), optimization_vectors[i].data(), stat_eval); } intervals::add_region_value<unsigned char>(occmaps[thread_idx], baseRegion.warped_interval, 1); } } <commit_msg>started to implement derived feature_calculators<commit_after>/* Copyright (c) 2014, Kai Klindworth All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 "manual_region_optimizer.h" #include <omp.h> #include "disparity_region.h" #include "genericfunctions.h" #include "disparity_utils.h" void manual_region_optimizer::optimize(std::vector<unsigned char>& damping_history, std::vector<std::vector<float>>& optimization_vectors_base, std::vector<std::vector<float>>& optimization_vectors_match, region_container& base, region_container& match, const disparity_hypothesis_weight_vector& base_eval, std::function<float(const disparity_region&, const region_container&, const region_container&, int)> prop_eval, int delta) { //std::cout << "base" << std::endl; refreshOptimizationBaseValues(optimization_vectors_base, base, match, base_eval, delta); refreshOptimizationBaseValues(optimization_vectors_match, match, base, base_eval, delta); //std::cout << "optimize" << std::endl; std::random_device random_dev; std::mt19937 random_gen(random_dev()); //FIXME each threads needs a own copy std::uniform_int_distribution<> random_dist(0, 1); const int dispMin = base.task.dispMin; const int crange = base.task.range_size(); cv::Mat_<float> temp_results(crange, 1, 100.0f); const std::size_t regions_count = base.regions.size(); //pragma omp parallel for default(none) shared(base, match, prop_eval, delta) private(random_dist, random_gen, temp_results) for(std::size_t j = 0; j < regions_count; ++j) { disparity_region& baseRegion = base.regions[j]; temp_results = cv::Mat_<float>(crange, 1, 5500.0f); //TODO: try another mt safe with less memory allocations... disparity_range drange = task_subrange(base.task, baseRegion.base_disparity, delta); for(short d = drange.start(); d <= drange.end(); ++d) { if(!baseRegion.corresponding_regions[d-dispMin].empty()) temp_results(d-dispMin) = prop_eval(baseRegion, base, match, d); } short ndisparity = min_idx(temp_results, baseRegion.disparity - dispMin) + dispMin; //damping if(ndisparity != baseRegion.disparity) damping_history[j] += 1; if(damping_history[j] < 2) { baseRegion.disparity = ndisparity; /*EstimationStep step; step.disparity = baseRegion.disparity; baseRegion.results.push_back(step);*/ } else { if(random_dist(random_gen) == 1) { baseRegion.disparity = ndisparity; /*EstimationStep step; step.disparity = baseRegion.disparity; baseRegion.results.push_back(step);*/ } else damping_history[j] = 0; } } } void manual_region_optimizer::training() { std::cout << "training" << std::endl; } void manual_region_optimizer::reset(const region_container &left, const region_container &right) { damping_history_left.resize(left.regions.size()); std::fill(damping_history_left.begin(), damping_history_left.end(), 0); damping_history_right.resize(right.regions.size()); std::fill(damping_history_right.begin(), damping_history_right.end(), 0); optimization_vectors_left.resize(left.regions.size()); optimization_vectors_right.resize(right.regions.size()); } void manual_region_optimizer::run(region_container &left, region_container &right, const optimizer_settings &config, int refinement) { reset(left, right); for(int i = 0; i < config.rounds; ++i) { std::cout << "optimization round" << std::endl; optimize(damping_history_left, optimization_vectors_left, optimization_vectors_right, left, right, config.base_eval, config.prop_eval, refinement); refresh_warped_regions(left); optimize(damping_history_right, optimization_vectors_right, optimization_vectors_left, right, left, config.base_eval, config.prop_eval, refinement); refresh_warped_regions(right); } for(int i = 0; i < config.rounds; ++i) { std::cout << "optimization round2" << std::endl; optimize(damping_history_left, optimization_vectors_left, optimization_vectors_right, left, right, config.base_eval2, config.prop_eval2, refinement); refresh_warped_regions(left); optimize(damping_history_right, optimization_vectors_right, optimization_vectors_left, right, left, config.base_eval2, config.prop_eval2, refinement); refresh_warped_regions(right); } if(config.rounds == 0) { refreshOptimizationBaseValues(optimization_vectors_left, left, right, config.base_eval, refinement); refreshOptimizationBaseValues(optimization_vectors_right, right, left, config.base_eval, refinement); } } float calculate_end_result(const float *raw_results, const disparity_hypothesis_weight_vector& wv) { return raw_results[0] * wv.costs + raw_results[1] * wv.occ_avg + raw_results[2] * wv.neighbor_pot + raw_results[3] * wv.lr_pot + raw_results[4] * wv.neighbor_color_pot; //return raw_results[0] * wv.costs + raw_results[1] * wv.occ_avg + raw_results[2] * wv.lr_pot + raw_results[3] * wv.neighbor_color_pot; } float calculate_end_result(int disp_idx, const float *raw_results, const disparity_hypothesis_weight_vector &wv) { std::size_t idx_offset = disp_idx*disparity_features_calculator::vector_size_per_disp; const float *result_ptr = raw_results + idx_offset; return calculate_end_result(result_ptr, wv); } class manual_optimizer_feature_calculator : public disparity_features_calculator { public: manual_optimizer_feature_calculator(const region_container& left_regions, const region_container& right_regions) : disparity_features_calculator(left_regions, right_regions) { } void update(const cv::Mat_<unsigned char>& occmap, short pot_trunc, const disparity_region& baseRegion, const disparity_range& drange, const disparity_hypothesis_weight_vector& wv) { const int range = drange.size(); cost_values.resize(range); //rel_cost_values.resize(range); //cost_temp.resize(range); //disp_costs.resize(range); //cost /*region_descriptors::segment_boxfilter(cost_temp, warp_costs, baseRegion.lineIntervals, drange.start(), drange.end()); for(int i = 0; i < range; ++i) disp_costs[i] = (cost_temp[i].first != 0) ? baseRegion.disparity_costs(i)/(float)cost_temp[i].second * cost_temp[i].first : 0;*/ update_occ_avg(occmap, baseRegion, pot_trunc, drange); update_average_neighbor_values(baseRegion, pot_trunc, drange); update_lr_pot(baseRegion, pot_trunc, drange); for(int i = 0; i < range; ++i) cost_values[i] = baseRegion.disparity_costs((drange.start()+i)-baseRegion.disparity_offset); //create_min_version(cost_values.begin(), cost_values.end(), rel_cost_values.begin()); //update_result_vector(result_vector, baseRegion, drange); //new end_results.resize(drange.size()); for(int i = 0; i < drange.size(); ++i) end_results[i] = cost_values[i] * wv.costs + lr_pot_values[i] * wv.lr_pot + neighbor_color_pot_values[i] * wv.neighbor_color_pot + neighbor_pot_values[i] * wv.neighbor_pot + occ_avg_values[i] * wv.occ_avg; } float calculate_optimization_energy(int disp_idx) { return end_results[disp_idx]; } protected: std::vector<float> end_results; }; void refreshOptimizationBaseValues(std::vector<std::vector<float>>& optimization_vectors, region_container& base, const region_container& match, const disparity_hypothesis_weight_vector& stat_eval, int delta) { cv::Mat disp = disparity_by_segments(base); cv::Mat occmap = disparity::occlusion_stat<short>(disp, 1.0); int pot_trunc = 10; const short dispMin = base.task.dispMin; const short dispRange = base.task.dispMax - base.task.dispMin + 1; std::vector<disparity_features_calculator> hyp_vec(omp_get_max_threads(), disparity_features_calculator(base, match)); std::vector<cv::Mat_<unsigned char>> occmaps(omp_get_max_threads()); for(std::size_t i = 0; i < occmaps.size(); ++i) { occmaps[i] = occmap.clone(); //hyp_vec.emplace_back(base.regions, match.regions); } std::size_t regions_count = base.regions.size(); #pragma omp parallel for for(std::size_t i = 0; i < regions_count; ++i) { disparity_region& baseRegion = base.regions[i]; int thread_idx = omp_get_thread_num(); intervals::substract_region_value<unsigned char>(occmaps[thread_idx], baseRegion.warped_interval, 1); baseRegion.optimization_energy = cv::Mat_<float>(dispRange, 1, 100.0f); disparity_range drange = task_subrange(base.task, baseRegion.base_disparity, delta); hyp_vec[thread_idx](occmaps[thread_idx], baseRegion, pot_trunc, drange , optimization_vectors[i]); for(short d = drange.start(); d <= drange.end(); ++d) { std::vector<corresponding_region>& cregionvec = baseRegion.corresponding_regions[d-dispMin]; if(!cregionvec.empty()) baseRegion.optimization_energy(d-dispMin) = calculate_end_result((d - drange.start()), optimization_vectors[i].data(), stat_eval); } intervals::add_region_value<unsigned char>(occmaps[thread_idx], baseRegion.warped_interval, 1); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2018. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <cstdio> #include <cstring> #include <cstdlib> #include <string.hpp> #include <string_view.hpp> #include "test.hpp" namespace { void test_small(){ std::string s("asdf"); auto sv = static_cast<std::string_view>(s); CHECK(!sv.empty(), "String mustn't be empty"); CHECK(sv.size() == 4, "Invalid size"); CHECK(sv == static_cast<std::string_view>(s), "Invalid content"); CHECK(sv[0] == 'a', "invalid operator[]"); CHECK(sv[1] == 's', "invalid operator[]"); CHECK(sv[2] == 'd', "invalid operator[]"); CHECK(sv[3] == 'f', "invalid operator[]"); CHECK(*sv.begin() == 'a', "invalid begin()"); sv.remove_prefix(1); CHECK(!sv.empty(), "String mustn't be empty"); CHECK(sv.size() == 3, "Invalid size"); CHECK(sv != static_cast<std::string_view>(s), "Invalid content"); CHECK(sv[0] == 's', "invalid operator[]"); CHECK(sv[1] == 'd', "invalid operator[]"); CHECK(sv[2] == 'f', "invalid operator[]"); CHECK(*sv.begin() == 's', "invalid operator[]"); } void test_suffix(){ std::string base("asdfpop"); std::string s("asdfpop"); auto sv = static_cast<std::string_view>(s); sv.remove_suffix(3); CHECK(!sv.empty(), "String mustn't be empty"); CHECK(sv.size() == 4, "Invalid size"); CHECK(sv != static_cast<std::string_view>(base), "Invalid content"); CHECK(sv[0] == 'a', "invalid operator[]"); CHECK(sv[1] == 's', "invalid operator[]"); CHECK(sv[2] == 'd', "invalid operator[]"); CHECK(sv[3] == 'f', "invalid operator[]"); CHECK(*sv.begin() == 'a', "invalid begin()"); CHECK(*(sv.end()-1) == 'f', "invalid end()"); } void test_empty(){ std::string_view s; CHECK(s.empty(), "String must be empty"); CHECK(s.size() == 0, "Invalid size"); } } //end of anonymous namespace void string_view_tests(){ test_small(); test_suffix(); test_empty(); } <commit_msg>Complete tests for string_view<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2018. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <cstdio> #include <cstring> #include <cstdlib> #include <string.hpp> #include <string_view.hpp> #include "test.hpp" namespace { void test_small(){ std::string s("asdf"); auto sv = static_cast<std::string_view>(s); CHECK(!sv.empty(), "String mustn't be empty"); CHECK(sv.size() == 4, "Invalid size"); CHECK(sv == static_cast<std::string_view>(s), "Invalid content"); CHECK(sv[0] == 'a', "invalid operator[]"); CHECK(sv[1] == 's', "invalid operator[]"); CHECK(sv[2] == 'd', "invalid operator[]"); CHECK(sv[3] == 'f', "invalid operator[]"); CHECK(*sv.begin() == 'a', "invalid begin()"); sv.remove_prefix(1); CHECK(!sv.empty(), "String mustn't be empty"); CHECK(sv.size() == 3, "Invalid size"); CHECK(sv != static_cast<std::string_view>(s), "Invalid content"); CHECK(sv[0] == 's', "invalid operator[]"); CHECK(sv[1] == 'd', "invalid operator[]"); CHECK(sv[2] == 'f', "invalid operator[]"); CHECK(*sv.begin() == 's', "invalid operator[]"); } void test_suffix(){ std::string base("asdfpop"); std::string s("asdfpop"); auto sv = static_cast<std::string_view>(s); sv.remove_suffix(3); CHECK(!sv.empty(), "String mustn't be empty"); CHECK(sv.size() == 4, "Invalid size"); CHECK(sv != static_cast<std::string_view>(base), "Invalid content"); CHECK(sv[0] == 'a', "invalid operator[]"); CHECK(sv[1] == 's', "invalid operator[]"); CHECK(sv[2] == 'd', "invalid operator[]"); CHECK(sv[3] == 'f', "invalid operator[]"); CHECK(*sv.begin() == 'a', "invalid begin()"); CHECK(*(sv.end()-1) == 'f', "invalid end()"); } void test_empty(){ std::string_view s; CHECK(s.empty(), "String must be empty"); CHECK(s.size() == 0, "Invalid size"); } void test_compare(){ std::string sa = "bcd"; std::string sb = "bcde"; std::string sc = "abcd"; std::string sd = "abcde"; std::string se = "bcd"; std::string_view a = sa; std::string_view b = sb; std::string_view c = sc; std::string_view d = sd; std::string_view e = se; CHECK(a == a, "Invalid operator=="); CHECK(a == e, "Invalid operator=="); CHECK(e == a, "Invalid operator=="); CHECK(a != b, "Invalid operator!="); CHECK(a != c, "Invalid operator!="); CHECK(a != d, "Invalid operator!="); CHECK(a.compare(a) == 0, "Invalid std::string_view::compare"); CHECK(a.compare(b) == -1, "Invalid std::string_view::compare"); CHECK(a.compare(c) == 1, "Invalid std::string_view::compare"); CHECK(a.compare(d) == 1, "Invalid std::string_view::compare"); CHECK(a.compare(e) == 0, "Invalid std::string_view::compare"); CHECK(b.compare(a) == 1, "Invalid std::string_view::compare"); CHECK(b.compare(b) == 0, "Invalid std::string_view::compare"); CHECK(b.compare(c) == 1, "Invalid std::string_view::compare"); CHECK(b.compare(d) == 1, "Invalid std::string_view::compare"); CHECK(b.compare(e) == 1, "Invalid std::string_view::compare"); CHECK(c.compare(a) == -1, "Invalid std::string_view::compare"); CHECK(c.compare(b) == -1, "Invalid std::string_view::compare"); CHECK(c.compare(c) == 0, "Invalid std::string_view::compare"); CHECK(c.compare(d) == -1, "Invalid std::string_view::compare"); CHECK(c.compare(e) == -1, "Invalid std::string_view::compare"); CHECK(d.compare(a) == -1, "Invalid std::string_view::compare"); CHECK(d.compare(b) == -1, "Invalid std::string_view::compare"); CHECK(d.compare(c) == 1, "Invalid std::string_view::compare"); CHECK(d.compare(d) == 0, "Invalid std::string_view::compare"); CHECK(d.compare(e) == -1, "Invalid std::string_view::compare"); CHECK(e.compare(a) == 0, "Invalid std::string_view::compare"); CHECK(e.compare(b) == -1, "Invalid std::string_view::compare"); CHECK(e.compare(c) == 1, "Invalid std::string_view::compare"); CHECK(e.compare(d) == 1, "Invalid std::string_view::compare"); CHECK(e.compare(e) == 0, "Invalid std::string_view::compare"); } } //end of anonymous namespace void string_view_tests(){ test_small(); test_suffix(); test_empty(); test_compare(); } <|endoftext|>
<commit_before><commit_msg>Review fixes<commit_after><|endoftext|>
<commit_before>/* Copyright (C) 2000 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 */ /* Get hostname for an IP. Hostnames are checked with reverse name lookup and checked that they doesn't resemble an ip. */ #include "mysql_priv.h" #include "hash_filo.h" #include <m_ctype.h> #ifdef __cplusplus extern "C" { // Because of SCO 3.2V4.2 #endif #if !defined( __WIN__) && !defined(OS2) #ifdef HAVE_SYS_UN_H #include <sys/un.h> #endif #include <netdb.h> #include <sys/utsname.h> #endif // __WIN__ #ifdef __cplusplus } #endif class host_entry :public hash_filo_element { public: char ip[sizeof(((struct in_addr *) 0)->s_addr)]; uint errors; char *hostname; }; static hash_filo *hostname_cache; static pthread_mutex_t LOCK_hostname; void hostname_cache_refresh() { hostname_cache->clear(); } bool hostname_cache_init() { host_entry tmp; uint offset= (uint) ((char*) (&tmp.ip) - (char*) &tmp); if (!(hostname_cache=new hash_filo(HOST_CACHE_SIZE, offset, sizeof(struct in_addr),NULL, (hash_free_key) free, &my_charset_latin1))) return 1; hostname_cache->clear(); (void) pthread_mutex_init(&LOCK_hostname,MY_MUTEX_INIT_SLOW); return 0; } void hostname_cache_free() { if (hostname_cache) { (void) pthread_mutex_destroy(&LOCK_hostname); delete hostname_cache; hostname_cache= 0; } } static void add_hostname(struct in_addr *in,const char *name) { if (!(specialflag & SPECIAL_NO_HOST_CACHE)) { VOID(pthread_mutex_lock(&hostname_cache->lock)); host_entry *entry; if (!(entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0))) { uint length=name ? (uint) strlen(name) : 0; if ((entry=(host_entry*) malloc(sizeof(host_entry)+length+1))) { char *new_name; memcpy_fixed(&entry->ip, &in->s_addr, sizeof(in->s_addr)); if (length) memcpy(new_name= (char *) (entry+1), name, length+1); else new_name=0; entry->hostname=new_name; entry->errors=0; (void) hostname_cache->add(entry); } } VOID(pthread_mutex_unlock(&hostname_cache->lock)); } } inline void add_wrong_ip(struct in_addr *in) { add_hostname(in,NullS); } void inc_host_errors(struct in_addr *in) { VOID(pthread_mutex_lock(&hostname_cache->lock)); host_entry *entry; if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0))) entry->errors++; VOID(pthread_mutex_unlock(&hostname_cache->lock)); } void reset_host_errors(struct in_addr *in) { VOID(pthread_mutex_lock(&hostname_cache->lock)); host_entry *entry; if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0))) entry->errors=0; VOID(pthread_mutex_unlock(&hostname_cache->lock)); } my_string ip_to_hostname(struct in_addr *in, uint *errors) { uint i; host_entry *entry; DBUG_ENTER("ip_to_hostname"); /* Check first if we have name in cache */ *errors=0; if (!(specialflag & SPECIAL_NO_HOST_CACHE)) { VOID(pthread_mutex_lock(&hostname_cache->lock)); if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0))) { char *name; if (!entry->hostname) name=0; // Don't allow connection else name=my_strdup(entry->hostname,MYF(0)); *errors= entry->errors; VOID(pthread_mutex_unlock(&hostname_cache->lock)); DBUG_RETURN(name); } VOID(pthread_mutex_unlock(&hostname_cache->lock)); } struct hostent *hp, *check; char *name; LINT_INIT(check); #if defined(HAVE_GETHOSTBYADDR_R) && defined(HAVE_SOLARIS_STYLE_GETHOST) char buff[GETHOSTBYADDR_BUFF_SIZE],buff2[GETHOSTBYNAME_BUFF_SIZE]; int tmp_errno; struct hostent tmp_hostent, tmp_hostent2; #ifdef HAVE_purify bzero(buff,sizeof(buff)); // Bug in purify #endif if (!(hp=gethostbyaddr_r((char*) in,sizeof(*in), AF_INET, &tmp_hostent,buff,sizeof(buff),&tmp_errno))) { DBUG_PRINT("error",("gethostbyaddr_r returned %d",tmp_errno)); return 0; } if (!(check=my_gethostbyname_r(hp->h_name,&tmp_hostent2,buff2,sizeof(buff2), &tmp_errno))) { DBUG_PRINT("error",("gethostbyname_r returned %d",tmp_errno)); /* Don't cache responses when the DSN server is down, as otherwise transient DNS failure may leave any number of clients (those that attempted to connect during the outage) unable to connect indefinitely. */ if (tmp_errno == HOST_NOT_FOUND || tmp_error == NO_DATA) add_wrong_ip(in); my_gethostbyname_r_free(); DBUG_RETURN(0); } if (!hp->h_name[0]) { DBUG_PRINT("error",("Got an empty hostname")); add_wrong_ip(in); my_gethostbyname_r_free(); DBUG_RETURN(0); // Don't allow empty hostnames } if (!(name=my_strdup(hp->h_name,MYF(0)))) { my_gethostbyname_r_free(); DBUG_RETURN(0); // out of memory } my_gethostbyname_r_free(); #else VOID(pthread_mutex_lock(&LOCK_hostname)); if (!(hp=gethostbyaddr((char*) in,sizeof(*in), AF_INET))) { VOID(pthread_mutex_unlock(&LOCK_hostname)); DBUG_PRINT("error",("gethostbyaddr returned %d",errno)); goto err; } if (!hp->h_name[0]) // Don't allow empty hostnames { VOID(pthread_mutex_unlock(&LOCK_hostname)); DBUG_PRINT("error",("Got an empty hostname")); goto err; } if (!(name=my_strdup(hp->h_name,MYF(0)))) { VOID(pthread_mutex_unlock(&LOCK_hostname)); DBUG_RETURN(0); // out of memory } check=gethostbyname(name); VOID(pthread_mutex_unlock(&LOCK_hostname)); if (!check) { DBUG_PRINT("error",("gethostbyname returned %d",errno)); my_free(name,MYF(0)); DBUG_RETURN(0); } #endif /* Don't accept hostnames that starts with digits because they may be false ip:s */ if (my_isdigit(&my_charset_latin1,name[0])) { char *pos; for (pos= name+1 ; my_isdigit(&my_charset_latin1,*pos); pos++) ; if (*pos == '.') { DBUG_PRINT("error",("mysqld doesn't accept hostnames that starts with a number followed by a '.'")); my_free(name,MYF(0)); goto err; } } /* Check that 'gethostbyname' returned the used ip */ for (i=0; check->h_addr_list[i]; i++) { if (*(uint32*)(check->h_addr_list)[i] == in->s_addr) { add_hostname(in,name); DBUG_RETURN(name); } } DBUG_PRINT("error",("Couldn't verify hostname with gethostbyname")); my_free(name,MYF(0)); err: add_wrong_ip(in); DBUG_RETURN(0); } <commit_msg>- fixed typo in variable name that caused compile errors on many platforms (tmp_error -> tmp_errno)<commit_after>/* Copyright (C) 2000 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 */ /* Get hostname for an IP. Hostnames are checked with reverse name lookup and checked that they doesn't resemble an ip. */ #include "mysql_priv.h" #include "hash_filo.h" #include <m_ctype.h> #ifdef __cplusplus extern "C" { // Because of SCO 3.2V4.2 #endif #if !defined( __WIN__) && !defined(OS2) #ifdef HAVE_SYS_UN_H #include <sys/un.h> #endif #include <netdb.h> #include <sys/utsname.h> #endif // __WIN__ #ifdef __cplusplus } #endif class host_entry :public hash_filo_element { public: char ip[sizeof(((struct in_addr *) 0)->s_addr)]; uint errors; char *hostname; }; static hash_filo *hostname_cache; static pthread_mutex_t LOCK_hostname; void hostname_cache_refresh() { hostname_cache->clear(); } bool hostname_cache_init() { host_entry tmp; uint offset= (uint) ((char*) (&tmp.ip) - (char*) &tmp); if (!(hostname_cache=new hash_filo(HOST_CACHE_SIZE, offset, sizeof(struct in_addr),NULL, (hash_free_key) free, &my_charset_latin1))) return 1; hostname_cache->clear(); (void) pthread_mutex_init(&LOCK_hostname,MY_MUTEX_INIT_SLOW); return 0; } void hostname_cache_free() { if (hostname_cache) { (void) pthread_mutex_destroy(&LOCK_hostname); delete hostname_cache; hostname_cache= 0; } } static void add_hostname(struct in_addr *in,const char *name) { if (!(specialflag & SPECIAL_NO_HOST_CACHE)) { VOID(pthread_mutex_lock(&hostname_cache->lock)); host_entry *entry; if (!(entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0))) { uint length=name ? (uint) strlen(name) : 0; if ((entry=(host_entry*) malloc(sizeof(host_entry)+length+1))) { char *new_name; memcpy_fixed(&entry->ip, &in->s_addr, sizeof(in->s_addr)); if (length) memcpy(new_name= (char *) (entry+1), name, length+1); else new_name=0; entry->hostname=new_name; entry->errors=0; (void) hostname_cache->add(entry); } } VOID(pthread_mutex_unlock(&hostname_cache->lock)); } } inline void add_wrong_ip(struct in_addr *in) { add_hostname(in,NullS); } void inc_host_errors(struct in_addr *in) { VOID(pthread_mutex_lock(&hostname_cache->lock)); host_entry *entry; if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0))) entry->errors++; VOID(pthread_mutex_unlock(&hostname_cache->lock)); } void reset_host_errors(struct in_addr *in) { VOID(pthread_mutex_lock(&hostname_cache->lock)); host_entry *entry; if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0))) entry->errors=0; VOID(pthread_mutex_unlock(&hostname_cache->lock)); } my_string ip_to_hostname(struct in_addr *in, uint *errors) { uint i; host_entry *entry; DBUG_ENTER("ip_to_hostname"); /* Check first if we have name in cache */ *errors=0; if (!(specialflag & SPECIAL_NO_HOST_CACHE)) { VOID(pthread_mutex_lock(&hostname_cache->lock)); if ((entry=(host_entry*) hostname_cache->search((gptr) &in->s_addr,0))) { char *name; if (!entry->hostname) name=0; // Don't allow connection else name=my_strdup(entry->hostname,MYF(0)); *errors= entry->errors; VOID(pthread_mutex_unlock(&hostname_cache->lock)); DBUG_RETURN(name); } VOID(pthread_mutex_unlock(&hostname_cache->lock)); } struct hostent *hp, *check; char *name; LINT_INIT(check); #if defined(HAVE_GETHOSTBYADDR_R) && defined(HAVE_SOLARIS_STYLE_GETHOST) char buff[GETHOSTBYADDR_BUFF_SIZE],buff2[GETHOSTBYNAME_BUFF_SIZE]; int tmp_errno; struct hostent tmp_hostent, tmp_hostent2; #ifdef HAVE_purify bzero(buff,sizeof(buff)); // Bug in purify #endif if (!(hp=gethostbyaddr_r((char*) in,sizeof(*in), AF_INET, &tmp_hostent,buff,sizeof(buff),&tmp_errno))) { DBUG_PRINT("error",("gethostbyaddr_r returned %d",tmp_errno)); return 0; } if (!(check=my_gethostbyname_r(hp->h_name,&tmp_hostent2,buff2,sizeof(buff2), &tmp_errno))) { DBUG_PRINT("error",("gethostbyname_r returned %d",tmp_errno)); /* Don't cache responses when the DSN server is down, as otherwise transient DNS failure may leave any number of clients (those that attempted to connect during the outage) unable to connect indefinitely. */ if (tmp_errno == HOST_NOT_FOUND || tmp_errno == NO_DATA) add_wrong_ip(in); my_gethostbyname_r_free(); DBUG_RETURN(0); } if (!hp->h_name[0]) { DBUG_PRINT("error",("Got an empty hostname")); add_wrong_ip(in); my_gethostbyname_r_free(); DBUG_RETURN(0); // Don't allow empty hostnames } if (!(name=my_strdup(hp->h_name,MYF(0)))) { my_gethostbyname_r_free(); DBUG_RETURN(0); // out of memory } my_gethostbyname_r_free(); #else VOID(pthread_mutex_lock(&LOCK_hostname)); if (!(hp=gethostbyaddr((char*) in,sizeof(*in), AF_INET))) { VOID(pthread_mutex_unlock(&LOCK_hostname)); DBUG_PRINT("error",("gethostbyaddr returned %d",errno)); goto err; } if (!hp->h_name[0]) // Don't allow empty hostnames { VOID(pthread_mutex_unlock(&LOCK_hostname)); DBUG_PRINT("error",("Got an empty hostname")); goto err; } if (!(name=my_strdup(hp->h_name,MYF(0)))) { VOID(pthread_mutex_unlock(&LOCK_hostname)); DBUG_RETURN(0); // out of memory } check=gethostbyname(name); VOID(pthread_mutex_unlock(&LOCK_hostname)); if (!check) { DBUG_PRINT("error",("gethostbyname returned %d",errno)); my_free(name,MYF(0)); DBUG_RETURN(0); } #endif /* Don't accept hostnames that starts with digits because they may be false ip:s */ if (my_isdigit(&my_charset_latin1,name[0])) { char *pos; for (pos= name+1 ; my_isdigit(&my_charset_latin1,*pos); pos++) ; if (*pos == '.') { DBUG_PRINT("error",("mysqld doesn't accept hostnames that starts with a number followed by a '.'")); my_free(name,MYF(0)); goto err; } } /* Check that 'gethostbyname' returned the used ip */ for (i=0; check->h_addr_list[i]; i++) { if (*(uint32*)(check->h_addr_list)[i] == in->s_addr) { add_hostname(in,name); DBUG_RETURN(name); } } DBUG_PRINT("error",("Couldn't verify hostname with gethostbyname")); my_free(name,MYF(0)); err: add_wrong_ip(in); DBUG_RETURN(0); } <|endoftext|>
<commit_before>#include "Pipeline.h" #include <QTime> #include <QCoreApplication> // Remove sleep function that only works on linux // http://stackoverflow.com/questions/3752742/how-do-i-create-a-pause-wait-function-using-qt void delay( int secondsToWait ) { QTime dieTime = QTime::currentTime().addSecs( secondsToWait ); while( QTime::currentTime() < dieTime ) { QCoreApplication::processEvents( QEventLoop::AllEvents, 100 ); } } Pipeline::Pipeline() { m_processing_name = "Script"; } Pipeline::~Pipeline() { } void Pipeline::setPipelineParameters(para_Model_AutoTract* para_m) { m_para_m = para_m; } void Pipeline::setPipelineSoftwares(soft_Model_AutoTract* soft_m) { m_soft_m = soft_m; } void Pipeline::setPlainTextEdit(QPlainTextEdit* plainTextEdit) { m_plainTextEdit = plainTextEdit; } QProcess* Pipeline::getMainScriptProcess() { return m_mainScriptProcess; } void Pipeline::createProcessingDirectory() { QDir output_dir(m_para_m->getpara_output_dir_lineEdit()); if(!output_dir.exists(m_processing_name)) { output_dir.mkdir(m_processing_name); } m_processing_path = output_dir.filePath(m_processing_name); } QString Pipeline::createModuleDirectory(QString directory_name) { QDir output_dir(m_para_m->getpara_output_dir_lineEdit()); if(!output_dir.exists(directory_name)) { output_dir.mkdir(directory_name); } return output_dir.filePath(directory_name); } void Pipeline::initializeMainScript() { m_script = "#!/usr/bin/env python\n\n"; m_script += "import os\n"; m_script += "import sys\n"; m_script += "import signal\n"; m_script += "import logging\n"; m_script += "import subprocess\n"; m_script += "import datetime\n"; m_script += "import shutil\n\n"; } void Pipeline::defineSignalHandler() { m_script += "def signal_handler(signal, frame):\n"; m_script += "\tprint('***************You pressed Ctrl+C!******************')\n"; m_script += "\tif runningProcess.poll!=1:\n"; m_script += "\t\trunningProcess.terminate()\n"; m_script += "\tsys.exit(0)\n\n"; m_script += "signal.signal(signal.SIGINT, signal_handler)\n"; m_script += "signal.signal(signal.SIGTERM, signal_handler)\n\n"; } void Pipeline::initializeLogging() { m_script += "log = \"" + m_log_path + "\"\n"; m_script += "logFile = open(log, \"w\") \n\n"; m_script += "logger = logging.getLogger('AutoTract')\n"; m_script += "logger.setLevel(logging.DEBUG)\n\n"; m_script += "fileHandler = logging.FileHandler(log)\n"; m_script += "fileHandler.setLevel(logging.DEBUG)\n"; m_script += "fileFormatter = logging.Formatter('%(message)s')\n"; m_script += "fileHandler.setFormatter(fileFormatter)\n\n"; m_script += "consoleHandler = logging.StreamHandler()\n"; m_script += "consoleHandler.setLevel(logging.DEBUG)\n"; m_script += "consoleFormatter = logging.Formatter('%(message)s')\n"; m_script += "consoleHandler.setFormatter(consoleFormatter)\n\n"; m_script += "logger.addHandler(fileHandler)\n"; m_script += "logger.addHandler(consoleHandler)\n\n"; } void Pipeline::writeMainScript() { initializeMainScript(); m_script += m_importingModules; defineSignalHandler(); initializeLogging(); m_script += "os.environ['ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS'] = '" + QString::number(m_para_m->getpara_nbCores_spinBox()) + "' \n"; m_script += "start = datetime.datetime.now()\n\n"; m_script += "logger.info(sys.executable)\n"; m_script += m_runningModules + "\n"; m_script += "end = datetime.datetime.now()\n\n"; m_script += "elapsedTime = (end - start).seconds\n"; m_script += "hours = elapsedTime/(60*60)\n"; m_script += "elapsedTime -= hours*(60*60)\n\n"; m_script += "minutes = elapsedTime/60\n"; m_script += "elapsedTime -= minutes*60\n\n"; m_script += "seconds = elapsedTime\n\n"; m_script += "logger.info('Pipeline took %s hour(s), %s minute(s) and %s second(s)', hours, minutes, seconds)\n"; QDir* processing_dir = new QDir(m_processing_path); m_main_path = processing_dir->filePath("main.py"); std::ofstream* script_stream = new std::ofstream((m_main_path.toStdString()).c_str()); *script_stream << m_script.toStdString() << std::endl; script_stream->close(); chmod((m_main_path.toStdString()).c_str(), 0755); } void Pipeline::writeRegistration() { QString directory_name = "1.Registration"; QString directory_path = createModuleDirectory(directory_name); QString module_name = "Registration"; m_registration = new::Registration(module_name); //m_registration->setOverwriting(m_para_m->getpara_overwrite_checkBox()); m_registration->setModuleDirectory(directory_path); m_registration->setProcessingDirectory(m_processing_path); m_registration->setDisplacementFieldPath(m_displacementFieldPath); m_registration->setScriptParameters(m_para_m); m_registration->setScriptSoftwares(m_soft_m); /*m_registration->setStoppingIfError(m_parameters->getStoppingIfError());*/ m_registration->update(); m_importingModules += "import " + module_name + "\n"; m_runningModules += module_name + ".run()\n"; } void Pipeline::writeMaskCreation() { QString directory_name = "2.MaskCreation"; QString directory_path = createModuleDirectory(directory_name); QString module_name = "MaskCreation"; m_maskCreation = new::MaskCreation(module_name); m_maskCreation->setScriptParameters(m_para_m); m_maskCreation->setScriptSoftwares(m_soft_m); m_maskCreation->setOutputDirectory(directory_name); //m_maskCreation->setOverwriting(m_para_m->getpara_overwrite_checkBox()); QString wmPath = m_para_m->getpara_inputWMmask_lineEdit() ; if( !wmPath.isEmpty() ) { m_maskCreation->setWMMaskPath( wmPath ) ; } QString csfPath = m_para_m->getpara_inputCSFmask_lineEdit() ; if( !csfPath.isEmpty() ) { m_maskCreation->setCSFMaskPath( csfPath ) ; } m_maskCreation->setModuleDirectory(directory_path); m_maskCreation->setProcessingDirectory(m_processing_path); /*m_maskCreation->setStoppingIfError(m_parameters->getStoppingIfError());*/ m_maskCreation->update(); m_importingModules += "import " + module_name + "\n"; m_runningModules += module_name + ".run()\n"; } void Pipeline::writeProcess() { QString directory_name = "3.PostProcess"; QString directory_path = createModuleDirectory(directory_name); QString module_name = "PostProcess"; m_process = new::TractPopulationProcess(module_name); //m_process->setOverwriting(m_para_m->getpara_overwrite_checkBox()); m_process->setModuleDirectory(directory_path); m_process->setProcessingDirectory(m_processing_path); m_process->setScriptParameters(m_para_m); m_process->setScriptSoftwares(m_soft_m); if( m_para_m->getpara_displacementField_lineEdit() != "" ) { m_process->SetDisplacementFieldPath( m_para_m->getpara_displacementField_lineEdit() ); } else { m_process->SetDisplacementFieldPath(m_displacementFieldPath); } m_process->update(); m_importingModules += "import " + module_name + "\n"; m_runningModules += module_name + ".run()\n"; } void Pipeline::writeClassification() { if(!m_para_m->getpara_enable_trafic_checkBox() || m_soft_m->getsoft_docker_lineEdit().isEmpty()) { return; } QString directory_name = "4.Classification"; QString directory_path = createModuleDirectory(directory_name); QString module_name = "Classification"; m_classification = new::Classification(module_name); m_classification->setModuleDirectory(directory_path); m_classification->setProcessingDirectory(m_processing_path); m_classification->setPostProcessPath(createModuleDirectory(QString("3.PostProcess"))); m_classification->setLogPath(m_log_path); m_classification->setDisplacementFieldPath(m_displacementFieldPath); m_classification->setScriptParameters(m_para_m); m_classification->setScriptSoftwares(m_soft_m); m_classification->update(); m_importingModules += "import subprocess\n"; QString python_path = m_soft_m->getsoft_python_lineEdit(); if(python_path[0] == '~') python_path.replace(0, 1, QDir::homePath()); //Launching in subprocess because of logging conflict/bug with the docker-py library m_runningModules += "args = ['" + python_path + "', '-c', 'import sys; sys.path.append(\\'" + m_processing_path + "\\'); import Classification; Classification.run()']\n"; m_runningModules += "logger.info('Starting Classification subprocess:')\n"; m_runningModules += "logger.debug(subprocess.list2cmdline(args))\n"; m_runningModules += "runningProcess = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n"; m_runningModules += "runningProcess.communicate()\n"; } void Pipeline::writeSingleTractProcess() { QString module_name = "SingleTractProcess"; m_singleTractProcess = new::SingleTractProcess(module_name); m_singleTractProcess->setProcessingDirectory(m_processing_path); m_singleTractProcess->setLog(m_log_path); m_singleTractProcess->setScriptParameters(m_para_m); m_singleTractProcess->setScriptSoftwares(m_soft_m); /*m_singleTractProcess->setOverwriting(m_parameters->getOverwriting()); m_singleTractProcess->setStoppingIfError(m_parameters->getStoppingIfError());*/ m_singleTractProcess->update(); } void Pipeline::cleanUp() { } void Pipeline::writePipeline() { m_importingModules = ""; m_runningModules = ""; createProcessingDirectory(); QDir* output_dir = new QDir(m_para_m->getpara_output_dir_lineEdit()); QFileInfo fi(m_para_m->getpara_output_dir_lineEdit()); QString base = fi.baseName(); m_log_path = output_dir->filePath(base + ".log"); m_displacementFieldPath = m_para_m->getpara_output_dir_lineEdit() + "/" + "1.Registration" + "/displacementField.nrrd"; writeRegistration(); writeMaskCreation(); writeProcess(); writeSingleTractProcess(); writeClassification(); writeMainScript(); } void Pipeline::runPipeline() { QString command; //if(!(m_para_m->getpara_computingSystem_comboBox()).compare("local", Qt::CaseInsensitive) || !(m_para_m->getpara_computingSystem_comboBox()).compare("killdevil interactive", Qt::CaseInsensitive)) //{ command = m_main_path; //} // if(!(m_para_m->getpara_computingSystem_comboBox()).compare("killdevil", Qt::CaseInsensitive)) // { // command = "bsub -q day -M 4 -n 1 -R \"span[hosts=1]\" python " + m_main_path; // } QString python_path = m_soft_m->getsoft_python_lineEdit(); QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); if(python_path!="") { if(python_path[0] == '~') python_path.replace(0,1,QDir::homePath()); QString pythonDirectory_path = ((QFileInfo(python_path)).absoluteDir()).path(); env.insert("PATH", pythonDirectory_path + ":" + env.value("PATH")); env.insert("PYTHONPATH", ""); } m_mainScriptProcess = new QProcess; m_mainScriptProcess->setProcessEnvironment(env); m_mainScriptProcess->start(command); m_mainScriptProcess->waitForStarted(); m_mainScriptProcess->waitForFinished(); m_timer.start(); while (!m_mainScriptProcess->waitForFinished()) { delay(1); } if(!(m_para_m->getpara_computingSystem_comboBox()).compare("killdevil", Qt::CaseInsensitive)) { bool jobRunning = true; QString output(m_mainScriptProcess->readAllStandardOutput()); QRegExp regExp("(<{1})([0-9]{1,})(>{1})"); regExp.indexIn(output); m_jobID = regExp.cap(2); std::cout<<"jobID = "<<m_jobID.toStdString()<<std::endl; QProcess* bjobs_process = new::QProcess(); while(jobRunning) { bjobs_process->start("bjobs " + m_jobID); while (!bjobs_process->waitForFinished()) { delay(1); } QString bjobs_output(bjobs_process->readAllStandardOutput()); if(bjobs_output.contains("DONE") || bjobs_output.contains("EXIT")) { jobRunning = false; } delay(1); } } if(m_mainScriptProcess->exitCode()==0) { cleanUp(); } // end of pipeline, send a signal } void Pipeline::stopPipeline() { if(m_para_m->getpara_computingSystem_comboBox() == "killdevil") { QProcess* bkill_process = new::QProcess(); bkill_process->start("bkill " + m_jobID); while (!bkill_process->waitForFinished()) { delay(1); } } m_mainScriptProcess->terminate(); } <commit_msg>ENH: Remove condition for docker in class script<commit_after>#include "Pipeline.h" #include <QTime> #include <QCoreApplication> // Remove sleep function that only works on linux // http://stackoverflow.com/questions/3752742/how-do-i-create-a-pause-wait-function-using-qt void delay( int secondsToWait ) { QTime dieTime = QTime::currentTime().addSecs( secondsToWait ); while( QTime::currentTime() < dieTime ) { QCoreApplication::processEvents( QEventLoop::AllEvents, 100 ); } } Pipeline::Pipeline() { m_processing_name = "Script"; } Pipeline::~Pipeline() { } void Pipeline::setPipelineParameters(para_Model_AutoTract* para_m) { m_para_m = para_m; } void Pipeline::setPipelineSoftwares(soft_Model_AutoTract* soft_m) { m_soft_m = soft_m; } void Pipeline::setPlainTextEdit(QPlainTextEdit* plainTextEdit) { m_plainTextEdit = plainTextEdit; } QProcess* Pipeline::getMainScriptProcess() { return m_mainScriptProcess; } void Pipeline::createProcessingDirectory() { QDir output_dir(m_para_m->getpara_output_dir_lineEdit()); if(!output_dir.exists(m_processing_name)) { output_dir.mkdir(m_processing_name); } m_processing_path = output_dir.filePath(m_processing_name); } QString Pipeline::createModuleDirectory(QString directory_name) { QDir output_dir(m_para_m->getpara_output_dir_lineEdit()); if(!output_dir.exists(directory_name)) { output_dir.mkdir(directory_name); } return output_dir.filePath(directory_name); } void Pipeline::initializeMainScript() { m_script = "#!/usr/bin/env python\n\n"; m_script += "import os\n"; m_script += "import sys\n"; m_script += "import signal\n"; m_script += "import logging\n"; m_script += "import subprocess\n"; m_script += "import datetime\n"; m_script += "import shutil\n\n"; } void Pipeline::defineSignalHandler() { m_script += "def signal_handler(signal, frame):\n"; m_script += "\tprint('***************You pressed Ctrl+C!******************')\n"; m_script += "\tif runningProcess.poll!=1:\n"; m_script += "\t\trunningProcess.terminate()\n"; m_script += "\tsys.exit(0)\n\n"; m_script += "signal.signal(signal.SIGINT, signal_handler)\n"; m_script += "signal.signal(signal.SIGTERM, signal_handler)\n\n"; } void Pipeline::initializeLogging() { m_script += "log = \"" + m_log_path + "\"\n"; m_script += "logFile = open(log, \"w\") \n\n"; m_script += "logger = logging.getLogger('AutoTract')\n"; m_script += "logger.setLevel(logging.DEBUG)\n\n"; m_script += "fileHandler = logging.FileHandler(log)\n"; m_script += "fileHandler.setLevel(logging.DEBUG)\n"; m_script += "fileFormatter = logging.Formatter('%(message)s')\n"; m_script += "fileHandler.setFormatter(fileFormatter)\n\n"; m_script += "consoleHandler = logging.StreamHandler()\n"; m_script += "consoleHandler.setLevel(logging.DEBUG)\n"; m_script += "consoleFormatter = logging.Formatter('%(message)s')\n"; m_script += "consoleHandler.setFormatter(consoleFormatter)\n\n"; m_script += "logger.addHandler(fileHandler)\n"; m_script += "logger.addHandler(consoleHandler)\n\n"; } void Pipeline::writeMainScript() { initializeMainScript(); m_script += m_importingModules; defineSignalHandler(); initializeLogging(); m_script += "os.environ['ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS'] = '" + QString::number(m_para_m->getpara_nbCores_spinBox()) + "' \n"; m_script += "start = datetime.datetime.now()\n\n"; m_script += "logger.info(sys.executable)\n"; m_script += m_runningModules + "\n"; m_script += "end = datetime.datetime.now()\n\n"; m_script += "elapsedTime = (end - start).seconds\n"; m_script += "hours = elapsedTime/(60*60)\n"; m_script += "elapsedTime -= hours*(60*60)\n\n"; m_script += "minutes = elapsedTime/60\n"; m_script += "elapsedTime -= minutes*60\n\n"; m_script += "seconds = elapsedTime\n\n"; m_script += "logger.info('Pipeline took %s hour(s), %s minute(s) and %s second(s)', hours, minutes, seconds)\n"; QDir* processing_dir = new QDir(m_processing_path); m_main_path = processing_dir->filePath("main.py"); std::ofstream* script_stream = new std::ofstream((m_main_path.toStdString()).c_str()); *script_stream << m_script.toStdString() << std::endl; script_stream->close(); chmod((m_main_path.toStdString()).c_str(), 0755); } void Pipeline::writeRegistration() { QString directory_name = "1.Registration"; QString directory_path = createModuleDirectory(directory_name); QString module_name = "Registration"; m_registration = new::Registration(module_name); //m_registration->setOverwriting(m_para_m->getpara_overwrite_checkBox()); m_registration->setModuleDirectory(directory_path); m_registration->setProcessingDirectory(m_processing_path); m_registration->setDisplacementFieldPath(m_displacementFieldPath); m_registration->setScriptParameters(m_para_m); m_registration->setScriptSoftwares(m_soft_m); /*m_registration->setStoppingIfError(m_parameters->getStoppingIfError());*/ m_registration->update(); m_importingModules += "import " + module_name + "\n"; m_runningModules += module_name + ".run()\n"; } void Pipeline::writeMaskCreation() { QString directory_name = "2.MaskCreation"; QString directory_path = createModuleDirectory(directory_name); QString module_name = "MaskCreation"; m_maskCreation = new::MaskCreation(module_name); m_maskCreation->setScriptParameters(m_para_m); m_maskCreation->setScriptSoftwares(m_soft_m); m_maskCreation->setOutputDirectory(directory_name); //m_maskCreation->setOverwriting(m_para_m->getpara_overwrite_checkBox()); QString wmPath = m_para_m->getpara_inputWMmask_lineEdit() ; if( !wmPath.isEmpty() ) { m_maskCreation->setWMMaskPath( wmPath ) ; } QString csfPath = m_para_m->getpara_inputCSFmask_lineEdit() ; if( !csfPath.isEmpty() ) { m_maskCreation->setCSFMaskPath( csfPath ) ; } m_maskCreation->setModuleDirectory(directory_path); m_maskCreation->setProcessingDirectory(m_processing_path); /*m_maskCreation->setStoppingIfError(m_parameters->getStoppingIfError());*/ m_maskCreation->update(); m_importingModules += "import " + module_name + "\n"; m_runningModules += module_name + ".run()\n"; } void Pipeline::writeProcess() { QString directory_name = "3.PostProcess"; QString directory_path = createModuleDirectory(directory_name); QString module_name = "PostProcess"; m_process = new::TractPopulationProcess(module_name); //m_process->setOverwriting(m_para_m->getpara_overwrite_checkBox()); m_process->setModuleDirectory(directory_path); m_process->setProcessingDirectory(m_processing_path); m_process->setScriptParameters(m_para_m); m_process->setScriptSoftwares(m_soft_m); if( m_para_m->getpara_displacementField_lineEdit() != "" ) { m_process->SetDisplacementFieldPath( m_para_m->getpara_displacementField_lineEdit() ); } else { m_process->SetDisplacementFieldPath(m_displacementFieldPath); } m_process->update(); m_importingModules += "import " + module_name + "\n"; m_runningModules += module_name + ".run()\n"; } void Pipeline::writeClassification() { QString directory_name = "4.Classification"; QString directory_path = createModuleDirectory(directory_name); QString module_name = "Classification"; m_classification = new::Classification(module_name); m_classification->setModuleDirectory(directory_path); m_classification->setProcessingDirectory(m_processing_path); m_classification->setPostProcessPath(createModuleDirectory(QString("3.PostProcess"))); m_classification->setLogPath(m_log_path); m_classification->setDisplacementFieldPath(m_displacementFieldPath); m_classification->setScriptParameters(m_para_m); m_classification->setScriptSoftwares(m_soft_m); m_classification->update(); m_importingModules += "import subprocess\n"; QString python_path = m_soft_m->getsoft_python_lineEdit(); if(python_path[0] == '~') python_path.replace(0, 1, QDir::homePath()); //Launching in subprocess because of logging conflict/bug with the docker-py library m_runningModules += "args = ['" + python_path + "', '-c', 'import sys; sys.path.append(\\'" + m_processing_path + "\\'); import Classification; Classification.run()']\n"; m_runningModules += "logger.info('Starting Classification subprocess:')\n"; m_runningModules += "logger.debug(subprocess.list2cmdline(args))\n"; m_runningModules += "runningProcess = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n"; m_runningModules += "runningProcess.communicate()\n"; } void Pipeline::writeSingleTractProcess() { QString module_name = "SingleTractProcess"; m_singleTractProcess = new::SingleTractProcess(module_name); m_singleTractProcess->setProcessingDirectory(m_processing_path); m_singleTractProcess->setLog(m_log_path); m_singleTractProcess->setScriptParameters(m_para_m); m_singleTractProcess->setScriptSoftwares(m_soft_m); /*m_singleTractProcess->setOverwriting(m_parameters->getOverwriting()); m_singleTractProcess->setStoppingIfError(m_parameters->getStoppingIfError());*/ m_singleTractProcess->update(); } void Pipeline::cleanUp() { } void Pipeline::writePipeline() { m_importingModules = ""; m_runningModules = ""; createProcessingDirectory(); QDir* output_dir = new QDir(m_para_m->getpara_output_dir_lineEdit()); QFileInfo fi(m_para_m->getpara_output_dir_lineEdit()); QString base = fi.baseName(); m_log_path = output_dir->filePath(base + ".log"); m_displacementFieldPath = m_para_m->getpara_output_dir_lineEdit() + "/" + "1.Registration" + "/displacementField.nrrd"; writeRegistration(); writeMaskCreation(); writeProcess(); writeSingleTractProcess(); writeClassification(); writeMainScript(); } void Pipeline::runPipeline() { QString command; //if(!(m_para_m->getpara_computingSystem_comboBox()).compare("local", Qt::CaseInsensitive) || !(m_para_m->getpara_computingSystem_comboBox()).compare("killdevil interactive", Qt::CaseInsensitive)) //{ command = m_main_path; //} // if(!(m_para_m->getpara_computingSystem_comboBox()).compare("killdevil", Qt::CaseInsensitive)) // { // command = "bsub -q day -M 4 -n 1 -R \"span[hosts=1]\" python " + m_main_path; // } QString python_path = m_soft_m->getsoft_python_lineEdit(); QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); if(python_path!="") { if(python_path[0] == '~') python_path.replace(0,1,QDir::homePath()); QString pythonDirectory_path = ((QFileInfo(python_path)).absoluteDir()).path(); env.insert("PATH", pythonDirectory_path + ":" + env.value("PATH")); env.insert("PYTHONPATH", ""); } m_mainScriptProcess = new QProcess; m_mainScriptProcess->setProcessEnvironment(env); m_mainScriptProcess->start(command); m_mainScriptProcess->waitForStarted(); m_mainScriptProcess->waitForFinished(); m_timer.start(); while (!m_mainScriptProcess->waitForFinished()) { delay(1); } if(!(m_para_m->getpara_computingSystem_comboBox()).compare("killdevil", Qt::CaseInsensitive)) { bool jobRunning = true; QString output(m_mainScriptProcess->readAllStandardOutput()); QRegExp regExp("(<{1})([0-9]{1,})(>{1})"); regExp.indexIn(output); m_jobID = regExp.cap(2); std::cout<<"jobID = "<<m_jobID.toStdString()<<std::endl; QProcess* bjobs_process = new::QProcess(); while(jobRunning) { bjobs_process->start("bjobs " + m_jobID); while (!bjobs_process->waitForFinished()) { delay(1); } QString bjobs_output(bjobs_process->readAllStandardOutput()); if(bjobs_output.contains("DONE") || bjobs_output.contains("EXIT")) { jobRunning = false; } delay(1); } } if(m_mainScriptProcess->exitCode()==0) { cleanUp(); } // end of pipeline, send a signal } void Pipeline::stopPipeline() { if(m_para_m->getpara_computingSystem_comboBox() == "killdevil") { QProcess* bkill_process = new::QProcess(); bkill_process->start("bkill " + m_jobID); while (!bkill_process->waitForFinished()) { delay(1); } } m_mainScriptProcess->terminate(); } <|endoftext|>
<commit_before>#ifndef CV_ADAPTERS_ROWRANGE_HPP #define CV_ADAPTERS_ROWRANGE_HPP #include <iterator> #include <opencv2/core/core.hpp> namespace cv { template <typename T> class RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T> { public: RowRangeConstIterator() : data() , row() , position() {} RowRangeConstIterator(const cv::Mat_<T>& m, int index) : data(m) , row() , position(index) { CV_DbgAssert(position >= 0 && position <= data.rows); } // Dereference const cv::Mat_<T>& operator*() const { setRow(); return row; } const cv::Mat_<T>* operator->() const { setRow(); return &row; } // Logical comparison bool operator==(const RowRangeConstIterator& that) const { return this->position == that.position; } bool operator!=(const RowRangeConstIterator& that) const { return !(*this == that); } bool operator<(const RowRangeConstIterator& that) const { return this->position < that.position; } bool operator>(const RowRangeConstIterator& that) const { return this->position > that.position; } bool operator<=(const RowRangeConstIterator& that) const { return !(*this > that); } bool operator>=(const RowRangeConstIterator& that) const { return !(*this < that); } // Increment RowRangeConstIterator& operator++() { ++position; return *this; } RowRangeConstIterator operator++(int) const { RowRangeConstIterator tmp(*this); ++(*this); return tmp; } protected: void setRow() const { row = data.row(position); } cv::Mat_<T> data; mutable cv::Mat_<T> row; int position; }; template <typename T> class RowRangeIterator : public RowRangeConstIterator<T> { public: RowRangeIterator() : RowRangeConstIterator<T>() {} RowRangeIterator(const cv::Mat_<T>& m, int index) : RowRangeConstIterator<T>(m, index) {} // Dereference cv::Mat_<T>& operator*() const { this->setRow(); return this->row; } cv::Mat_<T>* operator->() const { this->setRow(); return &this->row; } }; template <typename T> class RowRange { public: typedef RowRangeConstIterator<T> const_iterator; typedef RowRangeIterator<T> iterator; RowRange(cv::Mat m) : data(m) { CV_Assert(m.type() == cv::DataType<T>::type); } RowRange(cv::Mat_<T> m) : data(m) {} const_iterator begin() const { return const_iterator(data, 0); } iterator begin() { return iterator(data, 0); } const_iterator end() const { return const_iterator(data, data.rows); } iterator end() { return iterator(data, data.rows); } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } private: cv::Mat_<T> data; }; template <typename T> RowRange<T> make_RowRange(cv::Mat_<T> m) { return RowRange<T>(m); } } // namespace cv #endif /* CV_ADAPTERS_ROWRANGE_HPP */ <commit_msg>Implementing operators as free functions.<commit_after>#ifndef CV_ADAPTERS_ROWRANGE_HPP #define CV_ADAPTERS_ROWRANGE_HPP #include <iterator> #include <opencv2/core/core.hpp> namespace cv { template <typename T> class RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T> { public: RowRangeConstIterator() : data() , row() , position() {} RowRangeConstIterator(const cv::Mat_<T>& m, int index) : data(m) , row() , position(index) { CV_DbgAssert(position >= 0 && position <= data.rows); } // Dereference const cv::Mat_<T>& operator*() const { setRow(); return row; } const cv::Mat_<T>* operator->() const { setRow(); return &row; } // Logical comparison template <typename U> friend bool operator==(const RowRangeConstIterator<U>&, const RowRangeConstIterator<U>&); template <typename U> friend bool operator<(const RowRangeConstIterator<U>&, const RowRangeConstIterator<U>&); // Increment RowRangeConstIterator& operator++() { ++position; return *this; } RowRangeConstIterator operator++(int) const { RowRangeConstIterator tmp(*this); ++(*this); return tmp; } protected: void setRow() const { row = data.row(position); } cv::Mat_<T> data; mutable cv::Mat_<T> row; int position; }; template <typename T> bool operator==(const RowRangeConstIterator<T>& left, const RowRangeConstIterator<T>& right) { return left.position == right.position; } template <typename T> bool operator!=(const RowRangeConstIterator<T>& left, const RowRangeConstIterator<T>& right) { return !(left == right); } template <typename T> bool operator<(const RowRangeConstIterator<T>& left, const RowRangeConstIterator<T>& right) { return left.position < right.position; } template <typename T> bool operator<=(const RowRangeConstIterator<T>& left, const RowRangeConstIterator<T>& right) { return (left < right) || (left == right); } template <typename T> bool operator>=(const RowRangeConstIterator<T>& left, const RowRangeConstIterator<T>& right) { return !(left < right); } template <typename T> bool operator>(const RowRangeConstIterator<T>& left, const RowRangeConstIterator<T>& right) { return !(left <= right); } template <typename T> class RowRangeIterator : public RowRangeConstIterator<T> { public: RowRangeIterator() : RowRangeConstIterator<T>() {} RowRangeIterator(const cv::Mat_<T>& m, int index) : RowRangeConstIterator<T>(m, index) {} // Dereference cv::Mat_<T>& operator*() const { this->setRow(); return this->row; } cv::Mat_<T>* operator->() const { this->setRow(); return &this->row; } }; template <typename T> class RowRange { public: typedef RowRangeConstIterator<T> const_iterator; typedef RowRangeIterator<T> iterator; RowRange(cv::Mat m) : data(m) { CV_Assert(m.type() == cv::DataType<T>::type); } RowRange(cv::Mat_<T> m) : data(m) {} const_iterator begin() const { return const_iterator(data, 0); } iterator begin() { return iterator(data, 0); } const_iterator end() const { return const_iterator(data, data.rows); } iterator end() { return iterator(data, data.rows); } const_iterator cbegin() const { return begin(); } const_iterator cend() const { return end(); } private: cv::Mat_<T> data; }; template <typename T> RowRange<T> make_RowRange(cv::Mat_<T> m) { return RowRange<T>(m); } } // namespace cv #endif /* CV_ADAPTERS_ROWRANGE_HPP */ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief binary-compatible std::complex faster implementation * * For some reason, the compilers are not inlining std::complex * operations, resulting in way slower code. This template is * binary-compatible so it can be reinterpreted as to one another * and its operations can be inlined easily. This results in much * faster code for FFT for instance. */ #pragma once namespace etl { /*! * \brief Complex number implementation * * This implementation is binary-compatible with std::complex. This * implementation is not opaque like std::complex and its operation can be * inlined. */ template <typename T> struct complex { using value_type = T; value_type real; value_type imag; constexpr complex(const T& re = T(), const T& im = T()) : real(re), imag(im) {} constexpr complex(const complex& rhs) : real(rhs.real), imag(rhs.imag) {} complex& operator=(const T& rhs) noexcept { real = rhs; imag = 0.0; return *this; } complex& operator=(const complex& rhs) noexcept { real = rhs.real; imag = rhs.imag; return *this; } complex& operator=(const std::complex<T>& rhs) noexcept { real = rhs.real(); imag = rhs.imag(); return *this; } void operator+=(const complex& rhs) { real += rhs.real; imag += rhs.imag; } void operator-=(const complex& rhs) { real -= rhs.real; imag -= rhs.imag; } void operator*=(const complex& rhs) { T ac = real * rhs.real; T bd = imag * rhs.imag; T bc = imag * rhs.real; T ad = real * rhs.imag; real = ac - bd; imag = bc + ad; } void operator/=(const complex& rhs) { T ac = real * rhs.real; T bd = imag * rhs.imag; T bc = imag * rhs.real; T ad = real * rhs.imag; T frac = rhs.real * rhs.real + rhs.imag * rhs.imag; real = (ac + bd) / frac; imag = (bc - ad) / frac; } }; template <typename T> inline bool operator==(const complex<T>& lhs, const complex<T>& rhs) { return lhs.real == rhs.real && lhs.imag == rhs.imag; } template <typename T> inline bool operator!=(const complex<T>& lhs, const complex<T>& rhs) { return !(lhs == rhs); } template <typename T> inline complex<T> operator-(const complex<T>& rhs) { return {-rhs.real, -rhs.imag}; } template <typename T> inline complex<T> operator+(const complex<T>& lhs, const complex<T>& rhs) { return {lhs.real + rhs.real, lhs.imag + rhs.imag}; } template <typename T> inline complex<T> operator-(const complex<T>& lhs, const complex<T>& rhs) { return {lhs.real - rhs.real, lhs.imag - rhs.imag}; } template <typename T> inline complex<T> operator*(const complex<T>& lhs, const complex<T>& rhs) { T ac = lhs.real * rhs.real; T bd = lhs.imag * rhs.imag; T bc = lhs.imag * rhs.real; T ad = lhs.real * rhs.imag; return {ac - bd, bc + ad}; } template <typename T> inline complex<T> operator*(const complex<T>& lhs, T rhs) { return {lhs.real * rhs, lhs.imag * rhs}; } template <typename T> inline complex<T> operator*(T lhs, const complex<T>& rhs) { return {lhs * rhs.real, lhs * rhs.imag}; } template <typename T> inline complex<T> operator/(const complex<T>& lhs, T rhs) { return {lhs.real / rhs, lhs.imag / rhs}; } template <typename T> inline complex<T> operator/(const complex<T>& lhs, const complex<T>& rhs) { T ac = lhs.real * rhs.real; T bd = lhs.imag * rhs.imag; T bc = lhs.imag * rhs.real; T ad = lhs.real * rhs.imag; T frac = rhs.real * rhs.real + rhs.imag * rhs.imag; return {(ac + bd) / frac, (bc - ad) / frac}; } //inverse template <typename T> inline complex<T> inverse(complex<T> x) { return {x.imag, x.real}; } //inverse of the conj template <typename T> inline complex<T> inverse_conj(complex<T> x) { return {-x.imag, x.real}; } //conj of the inverse template <typename T> inline complex<T> conj_inverse(complex<T> x) { return {x.imag, -x.real}; } template <typename T> inline complex<T> conj(const complex<T>& rhs) { return {rhs.real, -rhs.imag}; } //Common API to etl::complex and std::complex template<typename T> inline T get_imag(const std::complex<T>& c){ return c.imag(); } template<typename T> inline T get_imag(const etl::complex<T>& c){ return c.imag; } template<typename T> inline T get_real(const std::complex<T>& c){ return c.real(); } template<typename T> inline T get_real(const etl::complex<T>& c){ return c.real; } template<typename T> inline std::complex<T> get_conj(const std::complex<T>& c){ return std::conj(c); } template<typename T> inline etl::complex<T> get_conj(const etl::complex<T>& c){ return {c.real, -c.imag}; } } //end of namespace etl <commit_msg>Complete doc<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief binary-compatible std::complex faster implementation * * For some reason, the compilers are not inlining std::complex * operations, resulting in way slower code. This template is * binary-compatible so it can be reinterpreted as to one another * and its operations can be inlined easily. This results in much * faster code for FFT for instance. */ #pragma once namespace etl { /*! * \brief Complex number implementation * * This implementation is binary-compatible with std::complex. This * implementation is not opaque like std::complex and its operation can be * inlined. */ template <typename T> struct complex { using value_type = T; ///< The value type value_type real; ///< The real part value_type imag; ///< The imaginary part /*! * \brief Construct a complex number * \param re The real part * \param im The imaginary part */ constexpr complex(const T& re = T(), const T& im = T()) : real(re), imag(im) {} /*! * \brief Construct a complex number by copy * \param rhs The complex to copy from */ constexpr complex(const complex& rhs) : real(rhs.real), imag(rhs.imag) {} /*! * \brief Assign a real part to the complex number * \param rhs The real part * \return a reference to this */ complex& operator=(const T& rhs) noexcept { real = rhs; imag = 0.0; return *this; } /*! * \brief Assign a complex number by copy * \param rhs The complex number to copy * \return a reference to this */ complex& operator=(const complex& rhs) noexcept { real = rhs.real; imag = rhs.imag; return *this; } /*! * \brief Assign a complex number by copy * \param rhs The complex number to copy * \return a reference to this */ complex& operator=(const std::complex<T>& rhs) noexcept { real = rhs.real(); imag = rhs.imag(); return *this; } /*! * \brief Adds a complex number * \param rhs The complex number to add * \return a reference to this */ void operator+=(const complex& rhs) { real += rhs.real; imag += rhs.imag; } /*! * \brief Subtracts a complex number * \param rhs The complex number to add * \return a reference to this */ void operator-=(const complex& rhs) { real -= rhs.real; imag -= rhs.imag; } /*! * \brief Multipliies a complex number * \param rhs The complex number to add * \return a reference to this */ void operator*=(const complex& rhs) { T ac = real * rhs.real; T bd = imag * rhs.imag; T bc = imag * rhs.real; T ad = real * rhs.imag; real = ac - bd; imag = bc + ad; } /*! * \brief Divides a complex number * \param rhs The complex number to add * \return a reference to this */ void operator/=(const complex& rhs) { T ac = real * rhs.real; T bd = imag * rhs.imag; T bc = imag * rhs.real; T ad = real * rhs.imag; T frac = rhs.real * rhs.real + rhs.imag * rhs.imag; real = (ac + bd) / frac; imag = (bc - ad) / frac; } }; /*! * \brief Test two complex numbers for equality * \param lhs The left hand side complex * \param rhs The right hand side complex * \return true if the numbers are equals, false otherwise */ template <typename T> inline bool operator==(const complex<T>& lhs, const complex<T>& rhs) { return lhs.real == rhs.real && lhs.imag == rhs.imag; } /*! * \brief Test two complex numbers for inequality * \param lhs The left hand side complex * \param rhs The right hand side complex * \return true if the numbers are not equals, false otherwise */ template <typename T> inline bool operator!=(const complex<T>& lhs, const complex<T>& rhs) { return !(lhs == rhs); } /*! * \brief Returns a complex number with the value of -rhs * \param rhs The right hand side complex * \return a complex number with the value of -rhs */ template <typename T> inline complex<T> operator-(const complex<T>& rhs) { return {-rhs.real, -rhs.imag}; } /*! * \brief Computes the addition of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the addition of the two complex numbers */ template <typename T> inline complex<T> operator+(const complex<T>& lhs, const complex<T>& rhs) { return {lhs.real + rhs.real, lhs.imag + rhs.imag}; } /*! * \brief Computes the subtraction of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the subtraction of the two complex numbers */ template <typename T> inline complex<T> operator-(const complex<T>& lhs, const complex<T>& rhs) { return {lhs.real - rhs.real, lhs.imag - rhs.imag}; } /*! * \brief Computes the multiplication of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of the two complex numbers */ template <typename T> inline complex<T> operator*(const complex<T>& lhs, const complex<T>& rhs) { T ac = lhs.real * rhs.real; T bd = lhs.imag * rhs.imag; T bc = lhs.imag * rhs.real; T ad = lhs.real * rhs.imag; return {ac - bd, bc + ad}; } /*! * \brief Computes the multiplication of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator*(const complex<T>& lhs, T rhs) { return {lhs.real * rhs, lhs.imag * rhs}; } /*! * \brief Computes the multiplication of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator*(T lhs, const complex<T>& rhs) { return {lhs * rhs.real, lhs * rhs.imag}; } /*! * \brief Computes the division of a complex number and a scalar * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the multiplication of a complex number and a scalar */ template <typename T> inline complex<T> operator/(const complex<T>& lhs, T rhs) { return {lhs.real / rhs, lhs.imag / rhs}; } /*! * \brief Computes the division of two complex numbers * \param lhs The left hand side complex * \param rhs The right hand side complex * \return a new complex with the value of the division of the two complex numbers */ template <typename T> inline complex<T> operator/(const complex<T>& lhs, const complex<T>& rhs) { T ac = lhs.real * rhs.real; T bd = lhs.imag * rhs.imag; T bc = lhs.imag * rhs.real; T ad = lhs.real * rhs.imag; T frac = rhs.real * rhs.real + rhs.imag * rhs.imag; return {(ac + bd) / frac, (bc - ad) / frac}; } /*! * \brief Returns the inverse of the complex number * \param c The complex number * \return The inverse of the complex number */ template <typename T> inline complex<T> inverse(complex<T> x) { return {x.imag, x.real}; } /*! * \brief Returns the inverse of the conjugate of the complex number * \param c The complex number * \return The inverse of the conjugate of the complex number */ template <typename T> inline complex<T> inverse_conj(complex<T> x) { return {-x.imag, x.real}; } /*! * \brief Returns the conjugate of the inverse of the complex number * \param c The complex number * \return The conjugate of the inverse of the complex number */ template <typename T> inline complex<T> conj_inverse(complex<T> x) { return {x.imag, -x.real}; } /*! * \brief Returns the conjugate of the complex number * \param c The complex number * \return The conjugate of the complex number */ template <typename T> inline complex<T> conj(const complex<T>& c) { return {c.real, -c.imag}; } /*! * \brief Returns the imaginary part of the given complex number * \param c The complex number * \return the imaginary part of the given complex number */ template<typename T> inline T get_imag(const std::complex<T>& c){ return c.imag(); } /*! * \brief Returns the imaginary part of the given complex number * \param c The complex number * \return the imaginary part of the given complex number */ template<typename T> inline T get_imag(const etl::complex<T>& c){ return c.imag; } /*! * \brief Returns the real part of the given complex number * \param c The complex number * \return the real part of the given complex number */ template<typename T> inline T get_real(const std::complex<T>& c){ return c.real(); } /*! * \brief Returns the real part of the given complex number * \param c The complex number * \return the real part of the given complex number */ template<typename T> inline T get_real(const etl::complex<T>& c){ return c.real; } /*! * \brief Returns the conjugate of the given complex number * \param c The complex number * \return the conjugate of the given complex number */ template<typename T> inline std::complex<T> get_conj(const std::complex<T>& c){ return std::conj(c); } /*! * \brief Returns the conjugate of the given complex number * \param c The complex number * \return the conjugate of the given complex number */ template<typename T> inline etl::complex<T> get_conj(const etl::complex<T>& c){ return {c.real, -c.imag}; } } //end of namespace etl <|endoftext|>
<commit_before>#ifndef GCN_KEY_HPP #define GCN_KEY_HPP #include <string> namespace gcn { /** * */ class Key { public: /** * */ Key(char character); /** * */ Key(int scancode); /** * */ char getCharacter(); /** * */ int getScanCode(); protected: char mCharacter; int mScanCode; }; // end Key } // end gcn #endif // end GCN_KEY_HPP <commit_msg>Added function and renamed functions. Character is now called Ascii. Added functions are isLetter(), isNumber(), isCharacter().<commit_after>#ifndef GCN_KEY_HPP #define GCN_KEY_HPP #include <string> namespace gcn { /** * */ class Key { public: Key(){}; /** * */ Key(unsigned char ascii); /** * */ Key(int scancode); /** * */ void setAscii(unsigned char ascii); /** * */ char getAscii(); /** * */ void setScancode(int scancode); /** * */ int getScancode(); /** * */ bool isCharacter(); /** * */ bool isNumber(); /** * */ bool isLetter(); protected: unsigned char mAscii; int mScancode; }; // end Key } // end gcn #endif // end GCN_KEY_HPP <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2014-2017 David Medina and Tim Warburton * * 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 */ #ifndef OCCA_MEMORY_HEADER #define OCCA_MEMORY_HEADER #include <iostream> #include "occa/defines.hpp" #include "occa/tools/properties.hpp" namespace occa { class kernel_v; class kernel; class memory_v; class memory; class device_v; class device; class kernelArg; typedef std::map<hash_t,occa::memory> hashedMemoryMap_t; typedef hashedMemoryMap_t::iterator hashedMemoryMapIterator; typedef hashedMemoryMap_t::const_iterator cHashedMemoryMapIterator; namespace uvaFlag { static const int none = 0; static const int isManaged = (1 << 0); static const int inDevice = (1 << 1); static const int isStale = (1 << 2); } //---[ memory_v ]--------------------- class memory_v { public: int memInfo; occa::properties properties; void *handle, *uvaPtr; occa::device_v *dHandle; udim_t size; memory_v(const occa::properties &properties_); void initFrom(const memory_v &m); bool isManaged() const; bool inDevice() const; bool isStale() const; void* uvaHandle(); //---[ Virtual Methods ]------------ virtual ~memory_v() = 0; virtual void free() = 0; virtual void* getHandle(const occa::properties &props) const = 0; virtual kernelArg makeKernelArg() const = 0; virtual void copyTo(void *dest, const udim_t bytes, const udim_t offset = 0, const occa::properties &props = occa::properties()) const = 0; virtual void copyFrom(const void *src, const udim_t bytes, const udim_t offset = 0, const occa::properties &props = occa::properties()) = 0; virtual void copyFrom(const memory_v *src, const udim_t bytes, const udim_t destOffset = 0, const udim_t srcOffset = 0, const occa::properties &props = occa::properties()) = 0; virtual void detach() = 0; //================================== //---[ Friend Functions ]----------- friend void memcpy(void *dest, void *src, const dim_t bytes, const occa::properties &props); friend void startManaging(void *ptr); friend void stopManaging(void *ptr); friend void syncToDevice(void *ptr, const dim_t bytes); friend void syncFromDevice(void *ptr, const dim_t bytes); friend void syncMemToDevice(occa::memory_v *mem, const dim_t bytes, const dim_t offset); friend void syncMemFromDevice(occa::memory_v *mem, const dim_t bytes, const dim_t offset); }; //==================================== //---[ memory ]----------------------- class memory { friend class occa::device; friend class occa::kernelArg; private: memory_v *mHandle; public: memory(); memory(void *uvaPtr); memory(memory_v *mHandle_); memory(const memory &m); memory& operator = (const memory &m); bool isInitialized() const; memory& swap(memory &m); memory_v* getMHandle() const; device_v* getDHandle() const; occa::device getDevice() const; operator kernelArg() const; const std::string& mode() const; udim_t size() const; bool isManaged() const; bool inDevice() const; bool isStale() const; void* getHandle(const occa::properties &props = occa::properties()) const; void setupUva(); void startManaging(); void stopManaging(); void syncToDevice(const dim_t bytes, const dim_t offset); void syncFromDevice(const dim_t bytes, const dim_t offset); bool uvaIsStale() const; void uvaMarkStale(); void uvaMarkFresh(); void copyFrom(const void *src, const dim_t bytes = -1, const dim_t offset = 0, const occa::properties &props = occa::properties()); void copyFrom(const memory src, const dim_t bytes = -1, const dim_t destOffset = 0, const dim_t srcOffset = 0, const occa::properties &props = occa::properties()); void copyTo(void *dest, const dim_t bytes = -1, const dim_t offset = 0, const occa::properties &props = occa::properties()) const; void copyTo(const memory dest, const dim_t bytes = -1, const dim_t destOffset = 0, const dim_t srcOffset = 0, const occa::properties &props = occa::properties()) const; void copyFrom(const void *src, const occa::properties &props); void copyFrom(const memory src, const occa::properties &props); void copyTo(void *dest, const occa::properties &props) const; void copyTo(const memory dest, const occa::properties &props) const; void free(); void detach(); void deleteRefs(const bool freeMemory = false); }; //==================================== } #endif <commit_msg>[Memory] Added entries method<commit_after>/* The MIT License (MIT) * * Copyright (c) 2014-2017 David Medina and Tim Warburton * * 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 */ #ifndef OCCA_MEMORY_HEADER #define OCCA_MEMORY_HEADER #include <iostream> #include "occa/defines.hpp" #include "occa/tools/properties.hpp" namespace occa { class kernel_v; class kernel; class memory_v; class memory; class device_v; class device; class kernelArg; typedef std::map<hash_t,occa::memory> hashedMemoryMap_t; typedef hashedMemoryMap_t::iterator hashedMemoryMapIterator; typedef hashedMemoryMap_t::const_iterator cHashedMemoryMapIterator; namespace uvaFlag { static const int none = 0; static const int isManaged = (1 << 0); static const int inDevice = (1 << 1); static const int isStale = (1 << 2); } //---[ memory_v ]--------------------- class memory_v { public: int memInfo; occa::properties properties; void *handle, *uvaPtr; occa::device_v *dHandle; udim_t size; memory_v(const occa::properties &properties_); void initFrom(const memory_v &m); bool isManaged() const; bool inDevice() const; bool isStale() const; void* uvaHandle(); //---[ Virtual Methods ]------------ virtual ~memory_v() = 0; virtual void free() = 0; virtual void* getHandle(const occa::properties &props) const = 0; virtual kernelArg makeKernelArg() const = 0; virtual void copyTo(void *dest, const udim_t bytes, const udim_t offset = 0, const occa::properties &props = occa::properties()) const = 0; virtual void copyFrom(const void *src, const udim_t bytes, const udim_t offset = 0, const occa::properties &props = occa::properties()) = 0; virtual void copyFrom(const memory_v *src, const udim_t bytes, const udim_t destOffset = 0, const udim_t srcOffset = 0, const occa::properties &props = occa::properties()) = 0; virtual void detach() = 0; //================================== //---[ Friend Functions ]----------- friend void memcpy(void *dest, void *src, const dim_t bytes, const occa::properties &props); friend void startManaging(void *ptr); friend void stopManaging(void *ptr); friend void syncToDevice(void *ptr, const dim_t bytes); friend void syncFromDevice(void *ptr, const dim_t bytes); friend void syncMemToDevice(occa::memory_v *mem, const dim_t bytes, const dim_t offset); friend void syncMemFromDevice(occa::memory_v *mem, const dim_t bytes, const dim_t offset); }; //==================================== //---[ memory ]----------------------- class memory { friend class occa::device; friend class occa::kernelArg; private: memory_v *mHandle; public: memory(); memory(void *uvaPtr); memory(memory_v *mHandle_); memory(const memory &m); memory& operator = (const memory &m); bool isInitialized() const; memory& swap(memory &m); memory_v* getMHandle() const; device_v* getDHandle() const; occa::device getDevice() const; operator kernelArg() const; const std::string& mode() const; udim_t size() const; template <class TM> udim_t entries() const { if (mHandle == NULL) { return 0; } return (mHandle->size / sizeof(TM)); } bool isManaged() const; bool inDevice() const; bool isStale() const; void* getHandle(const occa::properties &props = occa::properties()) const; void setupUva(); void startManaging(); void stopManaging(); void syncToDevice(const dim_t bytes, const dim_t offset); void syncFromDevice(const dim_t bytes, const dim_t offset); bool uvaIsStale() const; void uvaMarkStale(); void uvaMarkFresh(); void copyFrom(const void *src, const dim_t bytes = -1, const dim_t offset = 0, const occa::properties &props = occa::properties()); void copyFrom(const memory src, const dim_t bytes = -1, const dim_t destOffset = 0, const dim_t srcOffset = 0, const occa::properties &props = occa::properties()); void copyTo(void *dest, const dim_t bytes = -1, const dim_t offset = 0, const occa::properties &props = occa::properties()) const; void copyTo(const memory dest, const dim_t bytes = -1, const dim_t destOffset = 0, const dim_t srcOffset = 0, const occa::properties &props = occa::properties()) const; void copyFrom(const void *src, const occa::properties &props); void copyFrom(const memory src, const occa::properties &props); void copyTo(void *dest, const occa::properties &props) const; void copyTo(const memory dest, const occa::properties &props) const; void free(); void detach(); void deleteRefs(const bool freeMemory = false); }; //==================================== } #endif <|endoftext|>
<commit_before>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Precompute some window lengths. const size_t half_length_add_1 = half_length + 1; const size_t length_sub_1 = 2 * half_length; const size_t length = length_sub_1 + 1; // Ensure the result will fit. assert(std::distance(src_begin, src_end) <= std::distance(dest_begin, dest_end)); // Window length cannot exceed input data with reflection. assert(half_length_add_1 <= std::distance(src_begin, src_end)); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(length); // Iterators in source and destination I1 src_pos = src_begin; I1 dest_pos = dest_begin; // Get the initial window in sequential order with reflection // Insert elements in order to the multiset for sorting. // Store all multiset iterators into the deque in sequential order. { std::deque<T> window_init(half_length_add_1); for (size_t j = half_length_add_1; j > 0;) { window_init[--j] = *src_pos; ++src_pos; } for (size_t j = 0; j < half_length; ++j) { window_iters[j] = sorted_window.insert(window_init[j]); } for (size_t j = half_length; j < length; ++j) { window_iters[j] = sorted_window.insert(window_init.back()); window_init.pop_back(); } } // Window position corresponding to this rank. const size_t rank_pos = static_cast<size_t>(boost::math::round(rank * length_sub_1)); typename multiset::iterator rank_point = sorted_window.begin(); std::advance(rank_point, rank_pos); // Roll window forward one value at a time. typename multiset::iterator prev_iter; T prev_value; T rank_value = *rank_point; *dest_pos = rank_value; T next_value; size_t window_reflect_pos = length_sub_1; bool src_not_empty = ( src_pos != src_end ); while ( src_not_empty || ( window_reflect_pos > 0 ) ) { prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); // Determine next value to add to window. // Handle special cases like reflection at the end. if ( src_not_empty ) { next_value = *src_pos; ++src_pos; src_not_empty = ( src_pos != src_end ); } else { window_reflect_pos -= 2; next_value = *(window_iters[window_reflect_pos]); } // Remove old value and add new value to the window. // Handle special cases where `rank_pos` may have an adjusted position // due to where the old and new values are inserted. if ( ( rank_value < prev_value ) && ( rank_value <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( rank_value >= prev_value ) && ( rank_value > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); --rank_point; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( rank_value < prev_value ) && ( rank_value > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); --rank_point; } else if ( ( rank_value >= prev_value ) && ( rank_value <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); ++rank_point; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); ++rank_point; } } // Store rank value in the destination. *(++dest_pos) = rank_value = *rank_point; } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); ++i) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <commit_msg>Add missing `.`s [ci skip]<commit_after>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Precompute some window lengths. const size_t half_length_add_1 = half_length + 1; const size_t length_sub_1 = 2 * half_length; const size_t length = length_sub_1 + 1; // Ensure the result will fit. assert(std::distance(src_begin, src_end) <= std::distance(dest_begin, dest_end)); // Window length cannot exceed input data with reflection. assert(half_length_add_1 <= std::distance(src_begin, src_end)); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(length); // Iterators in source and destination. I1 src_pos = src_begin; I1 dest_pos = dest_begin; // Get the initial window in sequential order with reflection. // Insert elements in order to the multiset for sorting. // Store all multiset iterators into the deque in sequential order. { std::deque<T> window_init(half_length_add_1); for (size_t j = half_length_add_1; j > 0;) { window_init[--j] = *src_pos; ++src_pos; } for (size_t j = 0; j < half_length; ++j) { window_iters[j] = sorted_window.insert(window_init[j]); } for (size_t j = half_length; j < length; ++j) { window_iters[j] = sorted_window.insert(window_init.back()); window_init.pop_back(); } } // Window position corresponding to this rank. const size_t rank_pos = static_cast<size_t>(boost::math::round(rank * length_sub_1)); typename multiset::iterator rank_point = sorted_window.begin(); std::advance(rank_point, rank_pos); // Roll window forward one value at a time. typename multiset::iterator prev_iter; T prev_value; T rank_value = *rank_point; *dest_pos = rank_value; T next_value; size_t window_reflect_pos = length_sub_1; bool src_not_empty = ( src_pos != src_end ); while ( src_not_empty || ( window_reflect_pos > 0 ) ) { prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); // Determine next value to add to window. // Handle special cases like reflection at the end. if ( src_not_empty ) { next_value = *src_pos; ++src_pos; src_not_empty = ( src_pos != src_end ); } else { window_reflect_pos -= 2; next_value = *(window_iters[window_reflect_pos]); } // Remove old value and add new value to the window. // Handle special cases where `rank_pos` may have an adjusted position // due to where the old and new values are inserted. if ( ( rank_value < prev_value ) && ( rank_value <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( rank_value >= prev_value ) && ( rank_value > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); --rank_point; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( rank_value < prev_value ) && ( rank_value > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); --rank_point; } else if ( ( rank_value >= prev_value ) && ( rank_value <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); ++rank_point; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); ++rank_point; } } // Store rank value in the destination. *(++dest_pos) = rank_value = *rank_point; } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); ++i) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <|endoftext|>
<commit_before>#include "data_header.hpp" #include "point_to_int64.hpp" #include "scales.hpp" #include "../defines.hpp" #include "../coding/file_reader.hpp" #include "../coding/file_writer.hpp" #include "../coding/file_container.hpp" #include "../coding/write_to_sink.hpp" #include "../coding/varint.hpp" #include "../base/start_mem_debug.hpp" namespace feature { serial::CodingParams DataHeader::GetCodingParams(int scaleIndex) const { return serial::CodingParams(m_codingParams.GetCoordBits() - (m_scales.back() - m_scales[scaleIndex]) / 2, m_codingParams.GetBasePointUint64()); } m2::RectD const DataHeader::GetBounds() const { return Int64ToRect(m_bounds, m_codingParams.GetCoordBits()); } void DataHeader::SetBounds(m2::RectD const & r) { m_bounds = RectToInt64(r, m_codingParams.GetCoordBits()); } pair<int, int> DataHeader::GetScaleRange() const { using namespace scales; int const low = 0; int const high = GetUpperScale(); int const worldH = GetUpperWorldScale(); MapType const type = GetType(); switch (type) { case world: return make_pair(low, worldH); case worldcoasts: return make_pair(low, high); default: ASSERT_EQUAL(type, country, ()); return make_pair(worldH + 1, high); // Uncomment this to test countries drawing in all scales. //return make_pair(low, high); } } void DataHeader::Save(FileWriter & w) const { m_codingParams.Save(w); WriteVarInt(w, m_bounds.first); WriteVarInt(w, m_bounds.second); WriteVarUint(w, m_scales.size()); w.Write(m_scales.data(), m_scales.size()); WriteVarInt(w, static_cast<int32_t>(m_type)); } void DataHeader::Load(ModelReaderPtr const & r) { ReaderSource<ModelReaderPtr> src(r); m_codingParams.Load(src); m_bounds.first = ReadVarInt<int64_t>(src); m_bounds.second = ReadVarInt<int64_t>(src); uint32_t const count = ReadVarUint<uint32_t>(src); m_scales.resize(count); src.Read(m_scales.data(), count); m_type = static_cast<MapType>(ReadVarInt<int32_t>(src)); m_ver = v2; } void DataHeader::LoadVer1(ModelReaderPtr const & r) { ReaderSource<ModelReaderPtr> src(r); int64_t const base = ReadPrimitiveFromSource<int64_t>(src); m_codingParams = serial::CodingParams(POINT_COORD_BITS, base); m_bounds.first = ReadVarInt<int64_t>(src) + base; m_bounds.second = ReadVarInt<int64_t>(src) + base; uint32_t const count = 4; m_scales.resize(count); src.Read(m_scales.data(), count); m_type = country; m_ver = v1; } } <commit_msg>Draw countries in all scales: low scale = 1. See index.hpp hack.<commit_after>#include "data_header.hpp" #include "point_to_int64.hpp" #include "scales.hpp" #include "../defines.hpp" #include "../coding/file_reader.hpp" #include "../coding/file_writer.hpp" #include "../coding/file_container.hpp" #include "../coding/write_to_sink.hpp" #include "../coding/varint.hpp" #include "../base/start_mem_debug.hpp" namespace feature { serial::CodingParams DataHeader::GetCodingParams(int scaleIndex) const { return serial::CodingParams(m_codingParams.GetCoordBits() - (m_scales.back() - m_scales[scaleIndex]) / 2, m_codingParams.GetBasePointUint64()); } m2::RectD const DataHeader::GetBounds() const { return Int64ToRect(m_bounds, m_codingParams.GetCoordBits()); } void DataHeader::SetBounds(m2::RectD const & r) { m_bounds = RectToInt64(r, m_codingParams.GetCoordBits()); } pair<int, int> DataHeader::GetScaleRange() const { using namespace scales; int const low = 0; int const high = GetUpperScale(); int const worldH = GetUpperWorldScale(); MapType const type = GetType(); switch (type) { case world: return make_pair(low, worldH); case worldcoasts: return make_pair(low, high); default: ASSERT_EQUAL(type, country, ()); return make_pair(worldH + 1, high); // Uncomment this to test countries drawing in all scales. //return make_pair(1, high); } } void DataHeader::Save(FileWriter & w) const { m_codingParams.Save(w); WriteVarInt(w, m_bounds.first); WriteVarInt(w, m_bounds.second); WriteVarUint(w, m_scales.size()); w.Write(m_scales.data(), m_scales.size()); WriteVarInt(w, static_cast<int32_t>(m_type)); } void DataHeader::Load(ModelReaderPtr const & r) { ReaderSource<ModelReaderPtr> src(r); m_codingParams.Load(src); m_bounds.first = ReadVarInt<int64_t>(src); m_bounds.second = ReadVarInt<int64_t>(src); uint32_t const count = ReadVarUint<uint32_t>(src); m_scales.resize(count); src.Read(m_scales.data(), count); m_type = static_cast<MapType>(ReadVarInt<int32_t>(src)); m_ver = v2; } void DataHeader::LoadVer1(ModelReaderPtr const & r) { ReaderSource<ModelReaderPtr> src(r); int64_t const base = ReadPrimitiveFromSource<int64_t>(src); m_codingParams = serial::CodingParams(POINT_COORD_BITS, base); m_bounds.first = ReadVarInt<int64_t>(src) + base; m_bounds.second = ReadVarInt<int64_t>(src) + base; uint32_t const count = 4; m_scales.resize(count); src.Read(m_scales.data(), count); m_type = country; m_ver = v1; } } <|endoftext|>
<commit_before>//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tools is meant for use with the various LLVM profiling instrumentation // passes. It reads in the data file produced by executing an instrumented // program, and outputs a nice report. // //===----------------------------------------------------------------------===// #include "ProfileInfo.h" #include "llvm/Module.h" #include "llvm/Assembly/AsmAnnotationWriter.h" #include "llvm/Bytecode/Reader.h" #include "Support/CommandLine.h" #include <iostream> #include <cstdio> #include <map> #include <set> namespace { cl::opt<std::string> BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"), cl::Required); cl::opt<std::string> ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"), cl::Optional, cl::init("llvmprof.out")); cl::opt<bool> PrintAnnotatedLLVM("annotated-llvm", cl::desc("Print LLVM code with frequency annotations")); cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"), cl::aliasopt(PrintAnnotatedLLVM)); } // PairSecondSort - A sorting predicate to sort by the second element of a pair. template<class T> struct PairSecondSortReverse : public std::binary_function<std::pair<T, unsigned>, std::pair<T, unsigned>, bool> { bool operator()(const std::pair<T, unsigned> &LHS, const std::pair<T, unsigned> &RHS) const { return LHS.second > RHS.second; } }; namespace { class ProfileAnnotator : public AssemblyAnnotationWriter { std::map<const Function *, unsigned> &FuncFreqs; std::map<const BasicBlock*, unsigned> &BlockFreqs; public: ProfileAnnotator(std::map<const Function *, unsigned> &FF, std::map<const BasicBlock*, unsigned> &BF) : FuncFreqs(FF), BlockFreqs(BF) {} virtual void emitFunctionAnnot(const Function *F, std::ostream &OS) { OS << ";;; %" << F->getName() << " called " << FuncFreqs[F] << " times.\n;;;\n"; } virtual void emitBasicBlockAnnot(const BasicBlock *BB, std::ostream &OS) { if (BlockFreqs.empty()) return; if (unsigned Count = BlockFreqs[BB]) OS << ";;; Executed " << Count << " times.\n"; else OS << ";;; Never executed!\n"; } }; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n"); // Read in the bytecode file... std::string ErrorMessage; Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage); if (M == 0) { std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage << "\n"; return 1; } // Read the profiling information ProfileInfo PI(argv[0], ProfileDataFile, *M); std::map<const Function *, unsigned> FuncFreqs; std::map<const BasicBlock*, unsigned> BlockFreqs; // Output a report. Eventually, there will be multiple reports selectable on // the command line, for now, just keep things simple. // Emit the most frequent function table... std::vector<std::pair<Function*, unsigned> > FunctionCounts; PI.getFunctionCounts(FunctionCounts); FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end()); // Sort by the frequency, backwards. std::sort(FunctionCounts.begin(), FunctionCounts.end(), PairSecondSortReverse<Function*>()); unsigned long long TotalExecutions = 0; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) TotalExecutions += FunctionCounts[i].second; std::cout << "===" << std::string(73, '-') << "===\n" << "LLVM profiling output for execution"; if (PI.getNumExecutions() != 1) std::cout << "s"; std::cout << ":\n"; for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) { std::cout << " "; if (e != 1) std::cout << i+1 << ". "; std::cout << PI.getExecution(i) << "\n"; } std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Function execution frequencies:\n\n"; // Print out the function frequencies... printf(" ## Frequency\n"); for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) { if (FunctionCounts[i].second == 0) { printf("\n NOTE: %d function%s never executed!\n", e-i, e-i-1 ? "s were" : " was"); break; } printf("%3d. %5u/%llu %s\n", i+1, FunctionCounts[i].second, TotalExecutions, FunctionCounts[i].first->getName().c_str()); } std::set<Function*> FunctionsToPrint; // If we have block count information, print out the LLVM module with // frequency annotations. if (PI.hasAccurateBlockCounts()) { std::vector<std::pair<BasicBlock*, unsigned> > Counts; PI.getBlockCounts(Counts); TotalExecutions = 0; for (unsigned i = 0, e = Counts.size(); i != e; ++i) TotalExecutions += Counts[i].second; // Sort by the frequency, backwards. std::sort(Counts.begin(), Counts.end(), PairSecondSortReverse<BasicBlock*>()); std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Top 20 most frequently executed basic blocks:\n\n"; // Print out the function frequencies... printf(" ## %%%% \tFrequency\n"); unsigned BlocksToPrint = Counts.size(); if (BlocksToPrint > 20) BlocksToPrint = 20; for (unsigned i = 0; i != BlocksToPrint; ++i) { Function *F = Counts[i].first->getParent(); printf("%3d. %5.2f%% %5u/%llu\t%s() - %s\n", i+1, Counts[i].second/(double)TotalExecutions*100, Counts[i].second, TotalExecutions, F->getName().c_str(), Counts[i].first->getName().c_str()); FunctionsToPrint.insert(F); } BlockFreqs.insert(Counts.begin(), Counts.end()); } if (PrintAnnotatedLLVM) { std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Annotated LLVM code for the module:\n\n"; if (FunctionsToPrint.empty()) for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) FunctionsToPrint.insert(I); ProfileAnnotator PA(FuncFreqs, BlockFreqs); for (std::set<Function*>::iterator I = FunctionsToPrint.begin(), E = FunctionsToPrint.end(); I != E; ++I) (*I)->print(std::cout, &PA); } return 0; } <commit_msg>Simplify code<commit_after>//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tools is meant for use with the various LLVM profiling instrumentation // passes. It reads in the data file produced by executing an instrumented // program, and outputs a nice report. // //===----------------------------------------------------------------------===// #include "ProfileInfo.h" #include "llvm/Module.h" #include "llvm/Assembly/AsmAnnotationWriter.h" #include "llvm/Bytecode/Reader.h" #include "Support/CommandLine.h" #include <iostream> #include <cstdio> #include <map> #include <set> namespace { cl::opt<std::string> BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"), cl::Required); cl::opt<std::string> ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"), cl::Optional, cl::init("llvmprof.out")); cl::opt<bool> PrintAnnotatedLLVM("annotated-llvm", cl::desc("Print LLVM code with frequency annotations")); cl::alias PrintAnnotated2("A", cl::desc("Alias for --annotated-llvm"), cl::aliasopt(PrintAnnotatedLLVM)); } // PairSecondSort - A sorting predicate to sort by the second element of a pair. template<class T> struct PairSecondSortReverse : public std::binary_function<std::pair<T, unsigned>, std::pair<T, unsigned>, bool> { bool operator()(const std::pair<T, unsigned> &LHS, const std::pair<T, unsigned> &RHS) const { return LHS.second > RHS.second; } }; namespace { class ProfileAnnotator : public AssemblyAnnotationWriter { std::map<const Function *, unsigned> &FuncFreqs; std::map<const BasicBlock*, unsigned> &BlockFreqs; public: ProfileAnnotator(std::map<const Function *, unsigned> &FF, std::map<const BasicBlock*, unsigned> &BF) : FuncFreqs(FF), BlockFreqs(BF) {} virtual void emitFunctionAnnot(const Function *F, std::ostream &OS) { OS << ";;; %" << F->getName() << " called " << FuncFreqs[F] << " times.\n;;;\n"; } virtual void emitBasicBlockAnnot(const BasicBlock *BB, std::ostream &OS) { if (BlockFreqs.empty()) return; if (unsigned Count = BlockFreqs[BB]) OS << ";;; Executed " << Count << " times.\n"; else OS << ";;; Never executed!\n"; } }; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n"); // Read in the bytecode file... std::string ErrorMessage; Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage); if (M == 0) { std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage << "\n"; return 1; } // Read the profiling information ProfileInfo PI(argv[0], ProfileDataFile, *M); std::map<const Function *, unsigned> FuncFreqs; std::map<const BasicBlock*, unsigned> BlockFreqs; // Output a report. Eventually, there will be multiple reports selectable on // the command line, for now, just keep things simple. // Emit the most frequent function table... std::vector<std::pair<Function*, unsigned> > FunctionCounts; PI.getFunctionCounts(FunctionCounts); FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end()); // Sort by the frequency, backwards. std::sort(FunctionCounts.begin(), FunctionCounts.end(), PairSecondSortReverse<Function*>()); unsigned long long TotalExecutions = 0; for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) TotalExecutions += FunctionCounts[i].second; std::cout << "===" << std::string(73, '-') << "===\n" << "LLVM profiling output for execution"; if (PI.getNumExecutions() != 1) std::cout << "s"; std::cout << ":\n"; for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) { std::cout << " "; if (e != 1) std::cout << i+1 << ". "; std::cout << PI.getExecution(i) << "\n"; } std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Function execution frequencies:\n\n"; // Print out the function frequencies... printf(" ## Frequency\n"); for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) { if (FunctionCounts[i].second == 0) { printf("\n NOTE: %d function%s never executed!\n", e-i, e-i-1 ? "s were" : " was"); break; } printf("%3d. %5u/%llu %s\n", i+1, FunctionCounts[i].second, TotalExecutions, FunctionCounts[i].first->getName().c_str()); } std::set<Function*> FunctionsToPrint; // If we have block count information, print out the LLVM module with // frequency annotations. if (PI.hasAccurateBlockCounts()) { std::vector<std::pair<BasicBlock*, unsigned> > Counts; PI.getBlockCounts(Counts); TotalExecutions = 0; for (unsigned i = 0, e = Counts.size(); i != e; ++i) TotalExecutions += Counts[i].second; // Sort by the frequency, backwards. std::sort(Counts.begin(), Counts.end(), PairSecondSortReverse<BasicBlock*>()); std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Top 20 most frequently executed basic blocks:\n\n"; // Print out the function frequencies... printf(" ## %%%% \tFrequency\n"); unsigned BlocksToPrint = Counts.size(); if (BlocksToPrint > 20) BlocksToPrint = 20; for (unsigned i = 0; i != BlocksToPrint; ++i) { Function *F = Counts[i].first->getParent(); printf("%3d. %5.2f%% %5u/%llu\t%s() - %s\n", i+1, Counts[i].second/(double)TotalExecutions*100, Counts[i].second, TotalExecutions, F->getName().c_str(), Counts[i].first->getName().c_str()); FunctionsToPrint.insert(F); } BlockFreqs.insert(Counts.begin(), Counts.end()); } if (PrintAnnotatedLLVM) { std::cout << "\n===" << std::string(73, '-') << "===\n"; std::cout << "Annotated LLVM code for the module:\n\n"; ProfileAnnotator PA(FuncFreqs, BlockFreqs); if (FunctionsToPrint.empty()) M->print(std::cout, &PA); else // Print just a subset of the functions... for (std::set<Function*>::iterator I = FunctionsToPrint.begin(), E = FunctionsToPrint.end(); I != E; ++I) (*I)->print(std::cout, &PA); } return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ncw is the nodecast worker, client of the nodecast server ** Copyright (C) 2010-2012 Frédéric Logier <frederic@logier.org> ** ** https://github.com/nodecast/ncw ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU Affero General Public License as ** published by the Free Software Foundation, either version 3 of the ** License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ****************************************************************************/ #include "service.h" Service::Service() : Worker() { qDebug() << "Service::Service constructer"; child_process = new QProcess(); m_mutex = new QMutex; timer = new QTimer(); connect(timer, SIGNAL(timeout()), this, SLOT(watchdog ()), Qt::DirectConnection); timer->start (5000); } Service::~Service() { delete(child_process); } //void Service::init(QString child_exec, QString a_service_name) void Service::init(ncw_params ncw) { QDateTime timestamp = QDateTime::currentDateTime(); m_child_exec = ncw.child_exec; m_service_name = ncw.worker_name; m_node_uuid = ncw.node_uuid; m_node_password = ncw.node_password; BSONObj tracker = BSON("type" << "service" << "name" << m_service_name.toStdString() << "command" << m_child_exec.toStdString() << "action" << "register" << "pid" << QCoreApplication::applicationPid() << "timestamp" << timestamp.toTime_t()); emit return_tracker(tracker); qDebug() << "!!!! EXEC PROCESS : " << ncw.child_exec; child_process->start(m_child_exec); connect(child_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()), Qt::DirectConnection); qDebug() << "PID : " << child_process->pid(); } void Service::watchdog() { if (child_process->state() == QProcess::NotRunning) { /*** child is dead, so we exit the worker */ qDebug() << "CHILD IS DEAD"; qApp->exit(); } QDateTime timestamp = QDateTime::currentDateTime(); BSONObj tracker = BSON("type" << "service" << "action" << "watchdog" << "timestamp" << timestamp.toTime_t()); emit return_tracker(tracker); } //void Service::get_pubsub(bson::bo data) void Service::get_pubsub(string data) { std::cout << "Service::get_pubsub data : " << data << std::endl; QString payload = QString::fromStdString(data); payload.remove(QRegExp("([^@]*@).*")); qDebug() << "PAYLOAD : " << payload; //child_process->write(data.toString().data()); child_process->write(payload.toAscii()); child_process->write("\n"); //child_process->waitForBytesWritten(100000); } void Service::s_job_receive(bson::bo data) { qDebug() << "Service::s_job_receive"; //m_mutex->lock(); BSONElement r_datas = data.getField("data"); BSONElement session_uuid = data.getField("session_uuid"); m_session_uuid = QString::fromStdString(session_uuid.str()); //data.getField("step_id").Obj().getObjectID(step_id); std::cout << "BE SESSION UUID " << session_uuid << std::endl; std::cout << "QS SESSION UUID " << m_session_uuid.toStdString() << std::endl; //be step_id; //data.getObjectID (step_id); std::cout << "RECEIVE MESSAGE : " << data << std::endl; QString param; QDateTime timestamp = QDateTime::currentDateTime(); BSONObjBuilder b_tracker; b_tracker << "type" << "service"; b_tracker.append(session_uuid); b_tracker << "name" << m_service_name.toStdString() << "action" << "receive" << "timestamp" << timestamp.toTime_t(); BSONObj tracker = b_tracker.obj(); emit push_payload(tracker); param.append(" ").append(QString::fromStdString(r_datas.str())); QByteArray q_datas = r_datas.valuestr(); qDebug() << "!!!! SEND PAYLOAD TO STDIN : " << q_datas; child_process->write(q_datas); child_process->write("\n"); //child_process->waitForBytesWritten(100000); } void Service::readyReadStandardOutput() { QByteArray service_stdout = child_process->readAllStandardOutput(); QString json = service_stdout; json = json.simplified(); std::cout << "STDOUT : " << json.toStdString() << std::endl; std::cout << "m_session_uuid : " << m_session_uuid.toStdString() << std::endl; BSONObjBuilder b_datas; BSONObj b_out; QDateTime timestamp = QDateTime::currentDateTime(); try { b_out = mongo::fromjson(json.toAscii()); std::cout << "b_out : " << b_out << std::endl; if (b_out.hasField("action") && (b_out.getField("action").str().compare("create") == 0 || b_out.getField("action").str().compare("publish") == 0 || b_out.getField("action").str().compare("replay") == 0)) { qDebug() << "WORKER SERVICE BEFORE CREATE PAYLOAD EMIT"; emit push_payload(b_out); qDebug() << "WORKER SERVICE AFTER CREATE PAYLOAD EMIT"; return; } else if (!m_session_uuid.isEmpty() && b_out.hasField("action") && b_out.getField("action").str().compare("get_file") == 0) { qDebug() << "WORKER SERVICE BEFORE GET FILE PAYLOAD EMIT"; b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "node_uuid" << m_node_uuid.toStdString(); b_datas << "node_password" << m_node_password.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "get_file" << "timestamp" << timestamp.toTime_t(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; qDebug() << "WORKER SERVICE AFTER GET FILE PAYLOAD BEFORE EMIT"; emit get_stream(s_datas); qDebug() << "WORKER SERVICE AFTER GET FILE PAYLOAD EMIT"; return; } else if (!m_session_uuid.isEmpty()) { b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "terminate" << "timestamp" << timestamp.toTime_t() << "datas" << b_out; } } catch (mongo::MsgAssertionException &e) { std::cout << "m_session_uuid : " << m_session_uuid.toStdString() << std::endl; std::cout << "m_service_name : " << m_service_name.toStdString() << std::endl; std::cout << "error on parsing JSON : " << e.what() << std::endl; if (!m_session_uuid.isEmpty()) { b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "terminate" << "timestamp" << timestamp.toTime_t() << "datas" << json.toStdString(); } } BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; if (s_datas.isValid() && s_datas.objsize() > 0) { qDebug() << "WORKER PROCESS BEFORE EMIT"; emit push_payload(s_datas); qDebug() << "WORKER PROCESS AFTER EMIT"; } //m_mutex->unlock(); } <commit_msg>remove the tag filter in the pubsub payload<commit_after>/**************************************************************************** ** ncw is the nodecast worker, client of the nodecast server ** Copyright (C) 2010-2012 Frédéric Logier <frederic@logier.org> ** ** https://github.com/nodecast/ncw ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU Affero General Public License as ** published by the Free Software Foundation, either version 3 of the ** License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Affero General Public License for more details. ** ** You should have received a copy of the GNU Affero General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. ****************************************************************************/ #include "service.h" Service::Service() : Worker() { qDebug() << "Service::Service constructer"; child_process = new QProcess(); m_mutex = new QMutex; timer = new QTimer(); connect(timer, SIGNAL(timeout()), this, SLOT(watchdog ()), Qt::DirectConnection); timer->start (5000); } Service::~Service() { delete(child_process); } //void Service::init(QString child_exec, QString a_service_name) void Service::init(ncw_params ncw) { QDateTime timestamp = QDateTime::currentDateTime(); m_child_exec = ncw.child_exec; m_service_name = ncw.worker_name; m_node_uuid = ncw.node_uuid; m_node_password = ncw.node_password; BSONObj tracker = BSON("type" << "service" << "name" << m_service_name.toStdString() << "command" << m_child_exec.toStdString() << "action" << "register" << "pid" << QCoreApplication::applicationPid() << "timestamp" << timestamp.toTime_t()); emit return_tracker(tracker); qDebug() << "!!!! EXEC PROCESS : " << ncw.child_exec; child_process->start(m_child_exec); connect(child_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readyReadStandardOutput()), Qt::DirectConnection); qDebug() << "PID : " << child_process->pid(); } void Service::watchdog() { if (child_process->state() == QProcess::NotRunning) { /*** child is dead, so we exit the worker */ qDebug() << "CHILD IS DEAD"; qApp->exit(); } QDateTime timestamp = QDateTime::currentDateTime(); BSONObj tracker = BSON("type" << "service" << "action" << "watchdog" << "timestamp" << timestamp.toTime_t()); emit return_tracker(tracker); } //void Service::get_pubsub(bson::bo data) void Service::get_pubsub(string data) { std::cout << "Service::get_pubsub data : " << data << std::endl; QString payload = QString::fromStdString(data); QRegExp filter("([^@]*@).*"); payload.remove(filter.cap(1)); qDebug() << "PAYLOAD : " << payload; //child_process->write(data.toString().data()); child_process->write(payload.toAscii()); child_process->write("\n"); //child_process->waitForBytesWritten(100000); } void Service::s_job_receive(bson::bo data) { qDebug() << "Service::s_job_receive"; //m_mutex->lock(); BSONElement r_datas = data.getField("data"); BSONElement session_uuid = data.getField("session_uuid"); m_session_uuid = QString::fromStdString(session_uuid.str()); //data.getField("step_id").Obj().getObjectID(step_id); std::cout << "BE SESSION UUID " << session_uuid << std::endl; std::cout << "QS SESSION UUID " << m_session_uuid.toStdString() << std::endl; //be step_id; //data.getObjectID (step_id); std::cout << "RECEIVE MESSAGE : " << data << std::endl; QString param; QDateTime timestamp = QDateTime::currentDateTime(); BSONObjBuilder b_tracker; b_tracker << "type" << "service"; b_tracker.append(session_uuid); b_tracker << "name" << m_service_name.toStdString() << "action" << "receive" << "timestamp" << timestamp.toTime_t(); BSONObj tracker = b_tracker.obj(); emit push_payload(tracker); param.append(" ").append(QString::fromStdString(r_datas.str())); QByteArray q_datas = r_datas.valuestr(); qDebug() << "!!!! SEND PAYLOAD TO STDIN : " << q_datas; child_process->write(q_datas); child_process->write("\n"); //child_process->waitForBytesWritten(100000); } void Service::readyReadStandardOutput() { QByteArray service_stdout = child_process->readAllStandardOutput(); QString json = service_stdout; json = json.simplified(); std::cout << "STDOUT : " << json.toStdString() << std::endl; std::cout << "m_session_uuid : " << m_session_uuid.toStdString() << std::endl; BSONObjBuilder b_datas; BSONObj b_out; QDateTime timestamp = QDateTime::currentDateTime(); try { b_out = mongo::fromjson(json.toAscii()); std::cout << "b_out : " << b_out << std::endl; if (b_out.hasField("action") && (b_out.getField("action").str().compare("create") == 0 || b_out.getField("action").str().compare("publish") == 0 || b_out.getField("action").str().compare("replay") == 0)) { qDebug() << "WORKER SERVICE BEFORE CREATE PAYLOAD EMIT"; emit push_payload(b_out); qDebug() << "WORKER SERVICE AFTER CREATE PAYLOAD EMIT"; return; } else if (!m_session_uuid.isEmpty() && b_out.hasField("action") && b_out.getField("action").str().compare("get_file") == 0) { qDebug() << "WORKER SERVICE BEFORE GET FILE PAYLOAD EMIT"; b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "node_uuid" << m_node_uuid.toStdString(); b_datas << "node_password" << m_node_password.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "get_file" << "timestamp" << timestamp.toTime_t(); BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; qDebug() << "WORKER SERVICE AFTER GET FILE PAYLOAD BEFORE EMIT"; emit get_stream(s_datas); qDebug() << "WORKER SERVICE AFTER GET FILE PAYLOAD EMIT"; return; } else if (!m_session_uuid.isEmpty()) { b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "terminate" << "timestamp" << timestamp.toTime_t() << "datas" << b_out; } } catch (mongo::MsgAssertionException &e) { std::cout << "m_session_uuid : " << m_session_uuid.toStdString() << std::endl; std::cout << "m_service_name : " << m_service_name.toStdString() << std::endl; std::cout << "error on parsing JSON : " << e.what() << std::endl; if (!m_session_uuid.isEmpty()) { b_datas << "type" << "service"; b_datas << "session_uuid" << m_session_uuid.toStdString(); b_datas << "name" << m_service_name.toStdString() << "action" << "terminate" << "timestamp" << timestamp.toTime_t() << "datas" << json.toStdString(); } } BSONObj s_datas = b_datas.obj(); std::cout << "s_datas : " << s_datas << std::endl; if (s_datas.isValid() && s_datas.objsize() > 0) { qDebug() << "WORKER PROCESS BEFORE EMIT"; emit push_payload(s_datas); qDebug() << "WORKER PROCESS AFTER EMIT"; } //m_mutex->unlock(); } <|endoftext|>
<commit_before>#include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <memory> #include <syslog.h> #include <zmq.hpp> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <Magick++.h> #include "thumq.pb.h" namespace protobuf = google::protobuf; using thumq::Request; using thumq::Response; namespace { static bool receive_message_part(zmq::socket_t &socket, zmq::message_t &message) { while (true) { try { socket.recv(&message); break; } catch (const zmq::error_t &e) { if (e.num() != EINTR) throw e; } } while (true) { try { int value; size_t length = sizeof value; socket.getsockopt(ZMQ_RCVMORE, &value, &length); return value; } catch (const zmq::error_t &e) { if (e.num() != EINTR) throw e; } } } static void send_message_part(zmq::socket_t &socket, zmq::message_t &message, bool more) { int flags = 0; if (more) flags |= ZMQ_SNDMORE; while (true) { try { socket.send(message, flags); break; } catch (const zmq::error_t &e) { if (e.num() != EINTR) throw e; } } } static bool decode_request(const zmq::message_t &message, Request &request) { protobuf::io::ArrayInputStream array(message.data(), message.size()); protobuf::io::CodedInputStream coded(&array); return request.MergePartialFromCodedStream(&coded); } static void encode_response(const Response &response, zmq::message_t &message) { message.rebuild(response.ByteSize()); protobuf::io::ArrayOutputStream array(message.data(), message.size()); protobuf::io::CodedOutputStream coded(&array); response.SerializeWithCachedSizes(&coded); } static void convert_image(Magick::Image &image, int scale, Request::Crop crop) { switch (atoi(image.attribute("EXIF:Orientation").c_str())) { case Magick::TopLeftOrientation: break; case Magick::TopRightOrientation: image.flop(); break; case Magick::BottomRightOrientation: image.rotate(180); break; case Magick::BottomLeftOrientation: image.flip(); break; case Magick::LeftTopOrientation: image.rotate(90); image.flop(); break; case Magick::RightTopOrientation: image.rotate(90); break; case Magick::RightBottomOrientation: image.rotate(270); image.flop(); break; case Magick::LeftBottomOrientation: image.rotate(270); break; } Magick::Geometry size = image.size(); int width = size.width(); int height = size.height(); switch (crop) { case Request::NO_CROP: break; case Request::TOP_SQUARE: if (width < height) { image.crop(Magick::Geometry(width, width)); height = width; } else { image.crop(Magick::Geometry(height, height, (width - height) / 2, 0)); width = height; } break; } if (width > scale || height > scale) image.scale(Magick::Geometry(scale, scale)); image.strip(); } static void free_blob_data(void *, void *hint) { Magick::Blob *blob = reinterpret_cast<Magick::Blob *> (hint); delete blob; } static void write_jpeg(Magick::Image &image, zmq::message_t &data) { std::auto_ptr<Magick::Blob> blob(new Magick::Blob); image.write(blob.get(), "JPEG"); data.rebuild(const_cast<void *> (blob->data()), blob->length(), free_blob_data, blob.get()); blob.release(); } } // namespace int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s ADDRESS...\n", argv[0]); return 2; } const char *progname = strrchr(argv[0], '/'); if (progname) progname++; else progname = argv[0]; openlog(progname, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER); Magick::InitializeMagick(argv[0]); zmq::context_t context; zmq::socket_t socket(context, ZMQ_REP); for (int i = 1; i < argc; i++) socket.bind(argv[i]); while (true) { zmq::message_t request_data; zmq::message_t input_image_data; Response response; zmq::message_t output_image_data; if (receive_message_part(socket, request_data)) { if (receive_message_part(socket, input_image_data)) { zmq::message_t extraneous; while (receive_message_part(socket, extraneous)) { } } Request request; if (decode_request(request_data, request)) { try { Magick::Blob blob(input_image_data.data(), input_image_data.size()); Magick::Image image(blob); response.set_original_format(image.magick()); convert_image(image, request.scale(), request.crop()); write_jpeg(image, output_image_data); } catch (const Magick::Exception &e) { syslog(LOG_ERR, "%s", e.what()); } } else { syslog(LOG_ERR, "could not decode request header"); } } else { syslog(LOG_ERR, "request message was too short"); } zmq::message_t response_data; encode_response(response, response_data); if (output_image_data.size() > 0) { send_message_part(socket, response_data, true); send_message_part(socket, output_image_data, false); } else { send_message_part(socket, response_data, false); } } } <commit_msg>robust I/O error handling<commit_after>#include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <memory> #include <syslog.h> #include <zmq.hpp> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <Magick++.h> #include "thumq.pb.h" namespace protobuf = google::protobuf; using thumq::Request; using thumq::Response; namespace { class IO { IO(IO &); void operator=(const IO &); public: /** * @param socket for use in a single receive-send cycle. */ explicit IO(zmq::socket_t &socket) throw (): handled(false), m_socket(socket), m_received(false) { } /** * Does nothing if a complete message hasn't been received. Sends a * complete message (response_header and response_image) if handled, or an * incomplete message if not. */ ~IO() throw (zmq::error_t) { if (!m_received) return; send_part(response_header, handled); if (handled) send_part(response_image, false); } /** * @return true if a complete message was received (request_header and * response_image), or false if an incomplete message was received. */ bool receive() { if (receive_part(request_header)) { if (receive_part(request_image)) { zmq::message_t extraneous; while (receive_part(extraneous)) { } } return true; } return false; } zmq::message_t request_header; zmq::message_t request_image; zmq::message_t response_header; zmq::message_t response_image; bool handled; private: bool receive_part(zmq::message_t &message) { m_socket.recv(&message); int more; size_t length = sizeof more; m_socket.getsockopt(ZMQ_RCVMORE, &more, &length); if (!more) m_received = true; return more; } void send_part(zmq::message_t &message, bool more) { int flags = 0; if (more) flags |= ZMQ_SNDMORE; m_socket.send(message, flags); } zmq::socket_t &m_socket; bool m_received; }; static bool decode_request(const zmq::message_t &message, Request &request) { protobuf::io::ArrayInputStream array(message.data(), message.size()); protobuf::io::CodedInputStream coded(&array); return request.MergePartialFromCodedStream(&coded); } static void encode_response(const Response &response, zmq::message_t &message) { message.rebuild(response.ByteSize()); protobuf::io::ArrayOutputStream array(message.data(), message.size()); protobuf::io::CodedOutputStream coded(&array); response.SerializeWithCachedSizes(&coded); } static void convert_image(Magick::Image &image, int scale, Request::Crop crop) { switch (atoi(image.attribute("EXIF:Orientation").c_str())) { case Magick::TopLeftOrientation: break; case Magick::TopRightOrientation: image.flop(); break; case Magick::BottomRightOrientation: image.rotate(180); break; case Magick::BottomLeftOrientation: image.flip(); break; case Magick::LeftTopOrientation: image.rotate(90); image.flop(); break; case Magick::RightTopOrientation: image.rotate(90); break; case Magick::RightBottomOrientation: image.rotate(270); image.flop(); break; case Magick::LeftBottomOrientation: image.rotate(270); break; } Magick::Geometry size = image.size(); int width = size.width(); int height = size.height(); switch (crop) { case Request::NO_CROP: break; case Request::TOP_SQUARE: if (width < height) { image.crop(Magick::Geometry(width, width)); height = width; } else { image.crop(Magick::Geometry(height, height, (width - height) / 2, 0)); width = height; } break; } if (width > scale || height > scale) image.scale(Magick::Geometry(scale, scale)); image.strip(); } static void free_blob_data(void *, void *hint) { Magick::Blob *blob = reinterpret_cast<Magick::Blob *> (hint); delete blob; } static void write_jpeg(Magick::Image &image, zmq::message_t &data) { std::auto_ptr<Magick::Blob> blob(new Magick::Blob); image.write(blob.get(), "JPEG"); data.rebuild(const_cast<void *> (blob->data()), blob->length(), free_blob_data, blob.get()); blob.release(); } } // namespace int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s ADDRESS...\n", argv[0]); return 2; } const char *progname = strrchr(argv[0], '/'); if (progname) progname++; else progname = argv[0]; openlog(progname, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER); Magick::InitializeMagick(argv[0]); zmq::context_t context; zmq::socket_t socket(context, ZMQ_REP); try { for (int i = 1; i < argc; i++) socket.bind(argv[i]); while (true) { IO io(socket); if (!io.receive()) { syslog(LOG_ERR, "request message was too short"); continue; } Request request; Response response; if (!decode_request(io.request_header, request)) { syslog(LOG_ERR, "could not decode request header"); continue; } try { Magick::Blob blob(io.request_image.data(), io.request_image.size()); Magick::Image image(blob); response.set_original_format(image.magick()); convert_image(image, request.scale(), request.crop()); write_jpeg(image, io.response_image); } catch (const Magick::Exception &e) { syslog(LOG_ERR, "magick: %s", e.what()); continue; } encode_response(response, io.response_header); io.handled = true; } } catch (const zmq::error_t &e) { syslog(LOG_CRIT, "zmq: %s", e.what()); } return 1; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pickerhelper.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2005-04-13 10:24:48 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _PICKERHELPER_HXX #define _PICKERHELPER_HXX #ifndef INCLUDED_SVLDLLAPI_H #include "svtools/svldllapi.h" #endif #ifndef _SAL_TYPES_H_ #include "sal/types.h" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include "com/sun/star/uno/Reference.hxx" #endif namespace com { namespace sun { namespace star { namespace ui { namespace dialogs { class XFilePicker; class XFolderPicker; } } } } } namespace svt { SVL_DLLPUBLIC void SetDialogHelpId( ::com::sun::star::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > _mxFileDlg, sal_Int32 _nHelpId ); SVL_DLLPUBLIC void SetDialogHelpId( ::com::sun::star::uno::Reference < ::com::sun::star::ui::dialogs::XFolderPicker > _mxFileDlg, sal_Int32 _nHelpId ); } //----------------------------------------------------------------------------- #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.140); FILE MERGED 2005/09/05 14:50:56 rt 1.2.140.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pickerhelper.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 10:03:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PICKERHELPER_HXX #define _PICKERHELPER_HXX #ifndef INCLUDED_SVLDLLAPI_H #include "svtools/svldllapi.h" #endif #ifndef _SAL_TYPES_H_ #include "sal/types.h" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include "com/sun/star/uno/Reference.hxx" #endif namespace com { namespace sun { namespace star { namespace ui { namespace dialogs { class XFilePicker; class XFolderPicker; } } } } } namespace svt { SVL_DLLPUBLIC void SetDialogHelpId( ::com::sun::star::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > _mxFileDlg, sal_Int32 _nHelpId ); SVL_DLLPUBLIC void SetDialogHelpId( ::com::sun::star::uno::Reference < ::com::sun::star::ui::dialogs::XFolderPicker > _mxFileDlg, sal_Int32 _nHelpId ); } //----------------------------------------------------------------------------- #endif <|endoftext|>
<commit_before>/*********************************************************************** * Module: APlayer.h * Author: Fiahil * Modified: Monday, May 07, 2012 6:23:17 PM * Purpose: Declaration of the class APlayer ***********************************************************************/ #if !defined(__Bomberman_APlayer_h) #define __Bomberman_APlayer_h #include <map> #include <string> #include <Model.hpp> #include "enum.hpp" #include "AObj.hpp" class APlayer : public AObj { public: APlayer(); virtual ~APlayer(); virtual void play(gdl::GameClock const&, gdl::Input&)=0; // void takeDamage(Point origin, Pattern pattern); virtual void initialize(void); virtual void draw(void); virtual void update(gdl::GameClock const& clock, gdl::Input& input); void setPv(int); int getPv() const; void setWeapon(Bomb::eBomb); Bomb::eBomb getWeapon() const; void setSkin(Skin::eSkin); Skin::eSkin getSkin() const; void setTeam(size_t); size_t getTeam() const; void setId(size_t); size_t getId() const; void setState(State::eState); State::eState getState() const; void setDir(Dir::eDir); Dir::eDir getDir() const; void setName(std::string const&); std::string const& getName() const; private: typedef void (*fBomb)(); typedef void (*fBonus)(); protected: int _pv; Bomb::eBomb _weapon; Skin::eSkin _skin; size_t _team; size_t _id; State::eState _state; Dir::eDir _dir; std::map<Bomb::eBomb, fBomb> _bombEffect; std::map<Bonus::eBonus, fBonus> _bonusEffect; gdl::Model _model; std::string _name; std::vector<size_t> * _achivement; // modified : implement const std::vector<size_t> _skill; // modified : implement private: APlayer(const APlayer& oldAPlayer); }; #endif <commit_msg>Magerisation APlayer<commit_after>/*********************************************************************** * Module: APlayer.h * Author: Fiahil * Modified: Monday, May 07, 2012 6:23:17 PM * Purpose: Declaration of the class APlayer ***********************************************************************/ #if !defined(__Bomberman_APlayer_h) #define __Bomberman_APlayer_h #include <map> #include <string> #include <Model.hpp> #include "enum.hpp" #include "AObj.hpp" class APlayer : public AObj { public: APlayer(); virtual ~APlayer(); virtual void play(gdl::GameClock const&, gdl::Input&)=0; // void takeDamage(Point origin, Pattern pattern); virtual void initialize(void); virtual void draw(void); virtual void update(gdl::GameClock const& clock, gdl::Input& input); void setPv(int); int getPv() const; void setWeapon(Bomb::eBomb); Bomb::eBomb getWeapon() const; void setSkin(Skin::eSkin); Skin::eSkin getSkin() const; void setTeam(size_t); size_t getTeam() const; void setId(size_t); size_t getId() const; void setState(State::eState); State::eState getState() const; void setDir(Dir::eDir); Dir::eDir getDir() const; void setName(std::string const&); std::string const& getName() const; private: typedef void (*fBomb)(); typedef void (*fBonus)(); protected: int _pv; size_t _team; size_t _id; std::string _name; std::string _teamName; // modified : implement Bomb::eBomb _weapon; Skin::eSkin _skin; State::eState _state; Dir::eDir _dir; std::vector<size_t> * _achivement; // modified : implement const std::vector<size_t> _skill; // modified : implement std::map<Bomb::eBomb, fBomb> _bombEffect; std::map<Bonus::eBonus, fBonus> _bonusEffect; gdl::Model _model; private: APlayer(const APlayer& oldAPlayer); }; #endif <|endoftext|>
<commit_before>// Sh: A GPU metaprogramming language. // // Copyright 2003-2005 Serious Hack Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA ////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <cassert> #include "ShSyntax.hpp" #include "ShContext.hpp" #include "ShTokenizer.hpp" #include "ShToken.hpp" #include "ShInfo.hpp" #include "ShStatement.hpp" #include "ShProgram.hpp" #include "ShBackend.hpp" #include "ShTransformer.hpp" #include "ShOptimizations.hpp" namespace SH { ShProgram shBeginShader(const std::string& target) { ShProgram prg(target); ShContext::current()->enter(prg.node()); return prg; } void shEndShader() { ShContext* context = ShContext::current(); ShProgramNodePtr parsing = context->parsing(); assert(parsing); parsing->ctrlGraph = new ShCtrlGraph(parsing->tokenizer.blockList()); optimize(parsing); context->exit(); parsing->finish(); } void shCompile(ShProgram& prg) { shCompile(prg, prg.target()); } void shCompile(ShProgram& prg, const std::string& target) { ShBackendPtr backend = ShBackend::get_backend(target); if (!backend) return; prg.compile(target, backend); } void shCompileShader(ShProgram& prg) { shCompile(prg); } void shCompileShader(const std::string& target, ShProgram& prg) { shCompile(prg, target); } void shBind(ShProgram& prg) { ShBackendPtr backend = ShBackend::get_backend(prg.target()); if (!backend) return; prg.code(backend)->bind(); } void shBind(const ShProgramSet& s) { ShBackendPtr backend = ShBackend::get_backend((*(s.begin()))->target()); if (!backend) return; s.backend_set(backend)->bind(); } void shBind(const std::string& target, ShProgram& prg) { ShBackendPtr backend = ShBackend::get_backend(target); if (!backend) return; prg.code(target, backend)->bind(); } void shUnbind() { ShBackend::unbind_all_backends(); } void shUnbind(ShProgram& prg) { ShBackendPtr backend = ShBackend::get_backend(prg.target()); if (!backend) return; prg.code(backend)->unbind(); } void shUnbind(const ShProgramSet& s) { ShBackendPtr backend = ShBackend::get_backend((*(s.begin()))->target()); if (!backend) return; s.backend_set(backend)->unbind(); } void shUnbind(const std::string& target, ShProgram& prg) { ShBackendPtr backend = ShBackend::get_backend(target); if (!backend) return; prg.code(target, backend)->unbind(); } void shLink(const ShProgramSet& s) { ShBackendPtr backend = ShBackend::get_backend((*(s.begin()))->target()); if (!backend) return; s.backend_set(backend)->link(); } typedef std::map<std::string, ShProgram> BoundProgramMap; void shUpdate() { for (BoundProgramMap::iterator i = ShContext::current()->begin_bound(); i != ShContext::current()->end_bound(); i++) { ShBackendPtr backend = ShBackend::get_backend(i->second.target()); if (backend) { i->second.code(backend)->update(); } } } void shBindShader(ShProgram& shader) { shBind(shader); } void shBindShader(const std::string& target, ShProgram& shader) { shBind(target, shader); } bool shSetBackend(const std::string& name) { SH::ShBackend::clear_backends(); if (name.empty()) return false; return SH::ShBackend::use_backend(name); } bool shUseBackend(const std::string& name) { if (name.empty()) return false; return SH::ShBackend::use_backend(name); } bool shHaveBackend(const std::string& name) { if (name.empty()) return false; return SH::ShBackend::have_backend(name); } void shClearBackends() { return SH::ShBackend::clear_backends(); } std::string shFindBackend(const std::string& target) { if (target.empty()) return ""; return SH::ShBackend::target_handler(target, false); } bool shEvaluateCondition(const ShVariable& arg) { bool cond = false; for (int i = 0; i < arg.size(); i++) { cond = cond || arg.getVariant(i)->isTrue(); } return cond; } bool shProcessArg(const ShVariable& arg, bool* internal_cond) { if (ShContext::current()->parsing()) { ShContext::current()->parsing()->tokenizer.processArg(arg); } else { if (internal_cond) *internal_cond = shEvaluateCondition(arg); } return true; } bool shPushArgQueue() { if (ShContext::current()->parsing()) ShContext::current()->parsing()->tokenizer.pushArgQueue(); return true; } bool shPushArg() { if (ShContext::current()->parsing()) ShContext::current()->parsing()->tokenizer.pushArg(); return true; } void shInit() { ShContext::current(); // TODO: Initialize backends } void shIf(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_IF); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shEndIf() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDIF)); } void shElse() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ELSE)); } void shWhile(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_WHILE); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shEndWhile() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDWHILE)); } void shDo() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_DO)); } void shUntil(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_UNTIL); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shFor(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_FOR); for (int i = 0; i < 3; i++) { token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); } ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shEndFor() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDFOR)); } void shBreak(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_BREAK); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shContinue(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_CONTINUE); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shBeginSection() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_STARTSEC)); } void shEndSection() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDSEC)); } void shComment(const std::string& comment) { if (!ShContext::current()->parsing()) return; ShStatement stmt(SH_OP_COMMENT); stmt.add_info(new ShInfoComment(comment)); ShContext::current()->parsing()->tokenizer.blockList()->addStatement(stmt); } } <commit_msg>shSetBackend() now makes use of shUseBackend()<commit_after>// Sh: A GPU metaprogramming language. // // Copyright 2003-2005 Serious Hack Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA ////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <cassert> #include "ShSyntax.hpp" #include "ShContext.hpp" #include "ShTokenizer.hpp" #include "ShToken.hpp" #include "ShInfo.hpp" #include "ShStatement.hpp" #include "ShProgram.hpp" #include "ShBackend.hpp" #include "ShTransformer.hpp" #include "ShOptimizations.hpp" namespace SH { ShProgram shBeginShader(const std::string& target) { ShProgram prg(target); ShContext::current()->enter(prg.node()); return prg; } void shEndShader() { ShContext* context = ShContext::current(); ShProgramNodePtr parsing = context->parsing(); assert(parsing); parsing->ctrlGraph = new ShCtrlGraph(parsing->tokenizer.blockList()); optimize(parsing); context->exit(); parsing->finish(); } void shCompile(ShProgram& prg) { shCompile(prg, prg.target()); } void shCompile(ShProgram& prg, const std::string& target) { ShBackendPtr backend = ShBackend::get_backend(target); if (!backend) return; prg.compile(target, backend); } void shCompileShader(ShProgram& prg) { shCompile(prg); } void shCompileShader(const std::string& target, ShProgram& prg) { shCompile(prg, target); } void shBind(ShProgram& prg) { ShBackendPtr backend = ShBackend::get_backend(prg.target()); if (!backend) return; prg.code(backend)->bind(); } void shBind(const ShProgramSet& s) { ShBackendPtr backend = ShBackend::get_backend((*(s.begin()))->target()); if (!backend) return; s.backend_set(backend)->bind(); } void shBind(const std::string& target, ShProgram& prg) { ShBackendPtr backend = ShBackend::get_backend(target); if (!backend) return; prg.code(target, backend)->bind(); } void shUnbind() { ShBackend::unbind_all_backends(); } void shUnbind(ShProgram& prg) { ShBackendPtr backend = ShBackend::get_backend(prg.target()); if (!backend) return; prg.code(backend)->unbind(); } void shUnbind(const ShProgramSet& s) { ShBackendPtr backend = ShBackend::get_backend((*(s.begin()))->target()); if (!backend) return; s.backend_set(backend)->unbind(); } void shUnbind(const std::string& target, ShProgram& prg) { ShBackendPtr backend = ShBackend::get_backend(target); if (!backend) return; prg.code(target, backend)->unbind(); } void shLink(const ShProgramSet& s) { ShBackendPtr backend = ShBackend::get_backend((*(s.begin()))->target()); if (!backend) return; s.backend_set(backend)->link(); } typedef std::map<std::string, ShProgram> BoundProgramMap; void shUpdate() { for (BoundProgramMap::iterator i = ShContext::current()->begin_bound(); i != ShContext::current()->end_bound(); i++) { ShBackendPtr backend = ShBackend::get_backend(i->second.target()); if (backend) { i->second.code(backend)->update(); } } } void shBindShader(ShProgram& shader) { shBind(shader); } void shBindShader(const std::string& target, ShProgram& shader) { shBind(target, shader); } bool shSetBackend(const std::string& name) { SH::ShBackend::clear_backends(); return shUseBackend(name); } bool shUseBackend(const std::string& name) { if (name.empty()) return false; return SH::ShBackend::use_backend(name); } bool shHaveBackend(const std::string& name) { if (name.empty()) return false; return SH::ShBackend::have_backend(name); } void shClearBackends() { return SH::ShBackend::clear_backends(); } std::string shFindBackend(const std::string& target) { if (target.empty()) return ""; return SH::ShBackend::target_handler(target, false); } bool shEvaluateCondition(const ShVariable& arg) { bool cond = false; for (int i = 0; i < arg.size(); i++) { cond = cond || arg.getVariant(i)->isTrue(); } return cond; } bool shProcessArg(const ShVariable& arg, bool* internal_cond) { if (ShContext::current()->parsing()) { ShContext::current()->parsing()->tokenizer.processArg(arg); } else { if (internal_cond) *internal_cond = shEvaluateCondition(arg); } return true; } bool shPushArgQueue() { if (ShContext::current()->parsing()) ShContext::current()->parsing()->tokenizer.pushArgQueue(); return true; } bool shPushArg() { if (ShContext::current()->parsing()) ShContext::current()->parsing()->tokenizer.pushArg(); return true; } void shInit() { ShContext::current(); // TODO: Initialize backends } void shIf(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_IF); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shEndIf() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDIF)); } void shElse() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ELSE)); } void shWhile(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_WHILE); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shEndWhile() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDWHILE)); } void shDo() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_DO)); } void shUntil(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_UNTIL); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shFor(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_FOR); for (int i = 0; i < 3; i++) { token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); } ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shEndFor() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDFOR)); } void shBreak(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_BREAK); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shContinue(bool) { if (!ShContext::current()->parsing()) return; ShPointer<ShToken> token = new ShToken(SH_TOKEN_CONTINUE); token->arguments.push_back(ShContext::current()->parsing()->tokenizer.getArgument()); ShContext::current()->parsing()->tokenizer.popArgQueue(); ShContext::current()->parsing()->tokenizer.blockList()->addBlock(token); } void shBeginSection() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_STARTSEC)); } void shEndSection() { if (!ShContext::current()->parsing()) return; ShContext::current()->parsing()->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDSEC)); } void shComment(const std::string& comment) { if (!ShContext::current()->parsing()) return; ShStatement stmt(SH_OP_COMMENT); stmt.add_info(new ShInfoComment(comment)); ShContext::current()->parsing()->tokenizer.blockList()->addStatement(stmt); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dview.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-07-12 15:48:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DVIEW_HXX #define _DVIEW_HXX #ifndef _SVX_FMVIEW_HXX //autogen #include <svx/fmview.hxx> #endif class OutputDevice; class SwViewImp; class SwDrawView : public FmFormView { //Fuer den Anker Point aAnchorPoint; //Ankerposition SwViewImp &rImp; //Die View gehoert immer zu einer Shell const SwFrm *CalcAnchor(); protected: // add custom handles (used by other apps, e.g. AnchorPos) virtual void AddCustomHdl(); public: SwDrawView( SwViewImp &rI, SdrModel *pMd, OutputDevice* pOutDev=NULL ); //aus der Basisklasse virtual SdrObject* GetMaxToTopObj(SdrObject* pObj) const; virtual SdrObject* GetMaxToBtmObj(SdrObject* pObj) const; virtual void MarkListHasChanged(); // #i7672# // Overload to resue edit background color in active text edit view (OutlinerView) virtual void ModelHasChanged(); virtual void ObjOrderChanged( SdrObject* pObj, ULONG nOldPos, ULONG nNewPos ); virtual BOOL TakeDragLimit(SdrDragMode eMode, Rectangle& rRect) const; virtual void MakeVisible( const Rectangle&, Window &rWin ); virtual void CheckPossibilities(); const SwViewImp &Imp() const { return rImp; } SwViewImp &Imp() { return rImp; } // Innerhalb eines des sichtbaren Ankers? Rectangle *IsAnchorAtPos( const Point &rPt ) const; //Anker und Xor fuer das Draggen. void ShowDragAnchor(); virtual void DeleteMarked(); //JP 06.10.98: 2. Versuch inline void ValidateMarkList() { FlushComeBackTimer(); } // OD 18.06.2003 #108784# - method to replace marked/selected <SwDrawVirtObj> // by its reference object for delete of selection and group selection static void ReplaceMarkedDrawVirtObjs( SdrMarkView& _rMarkView ); }; #endif <commit_msg>INTEGRATION: CWS tune05 (1.3.484); FILE MERGED 2004/07/23 16:02:59 mhu 1.3.484.2: RESYNC: (1.3-1.4); FILE MERGED 2004/07/22 09:33:13 cmc 1.3.484.1: #i30554# unused SwDrawView::IsAnchorAtPos<commit_after>/************************************************************************* * * $RCSfile: dview.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-08-12 12:27:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DVIEW_HXX #define _DVIEW_HXX #ifndef _SVX_FMVIEW_HXX //autogen #include <svx/fmview.hxx> #endif class OutputDevice; class SwViewImp; class SwDrawView : public FmFormView { //Fuer den Anker Point aAnchorPoint; //Ankerposition SwViewImp &rImp; //Die View gehoert immer zu einer Shell const SwFrm *CalcAnchor(); protected: // add custom handles (used by other apps, e.g. AnchorPos) virtual void AddCustomHdl(); public: SwDrawView( SwViewImp &rI, SdrModel *pMd, OutputDevice* pOutDev=NULL ); //aus der Basisklasse virtual SdrObject* GetMaxToTopObj(SdrObject* pObj) const; virtual SdrObject* GetMaxToBtmObj(SdrObject* pObj) const; virtual void MarkListHasChanged(); // #i7672# // Overload to resue edit background color in active text edit view (OutlinerView) virtual void ModelHasChanged(); virtual void ObjOrderChanged( SdrObject* pObj, ULONG nOldPos, ULONG nNewPos ); virtual BOOL TakeDragLimit(SdrDragMode eMode, Rectangle& rRect) const; virtual void MakeVisible( const Rectangle&, Window &rWin ); virtual void CheckPossibilities(); const SwViewImp &Imp() const { return rImp; } SwViewImp &Imp() { return rImp; } //Anker und Xor fuer das Draggen. void ShowDragAnchor(); virtual void DeleteMarked(); //JP 06.10.98: 2. Versuch inline void ValidateMarkList() { FlushComeBackTimer(); } // OD 18.06.2003 #108784# - method to replace marked/selected <SwDrawVirtObj> // by its reference object for delete of selection and group selection static void ReplaceMarkedDrawVirtObjs( SdrMarkView& _rMarkView ); }; #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2004-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * leon.sha@sun.com * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "MMgc.h" #include "GCDebug.h" #include "GC.h" #include <sys/mman.h> #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #define MAP_ANONYMOUS MAP_ANON #endif // !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #if defined(MEMORY_INFO) && defined(AVMPLUS_UNIX) #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <dlfcn.h> #endif // avmplus standalone uses UNIX #ifdef _MAC #define MAP_ANONYMOUS MAP_ANON #endif #ifdef SOLARIS #include <ucontext.h> #include <dlfcn.h> extern "C" caddr_t _getfp(void); typedef caddr_t maddr_ptr; #else typedef void *maddr_ptr; #endif namespace MMgc { #ifndef USE_MMAP void *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc) { char *ptr, *ptr2, *aligned_ptr; int align_mask = align_size - 1; int alloc_size = size + align_size + sizeof(int); ptr=(char *)m_malloc(alloc_size); if(ptr==NULL) return(NULL); ptr2 = ptr + sizeof(int); aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask)); ptr2 = aligned_ptr - sizeof(int); *((int *)ptr2)=(int)(aligned_ptr - ptr); return(aligned_ptr); } void aligned_free(void *ptr, GCFreeFuncPtr m_free) { int *ptr2=(int *)ptr - 1; char *unaligned_ptr = (char*) ptr - *ptr2; m_free(unaligned_ptr); } #endif /* !USE_MMAP */ #ifdef USE_MMAP int GCHeap::vmPageSize() { long v = sysconf(_SC_PAGESIZE); return v; } void* GCHeap::ReserveCodeMemory(void* address, size_t size) { return (char*) mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); } void GCHeap::ReleaseCodeMemory(void* address, size_t size) { if (munmap((maddr_ptr)address, size) != 0) GCAssert(false); } bool GCHeap::SetGuardPage(void *address) { return false; } #endif /* USE_MMAP */ #ifdef AVMPLUS_JIT_READONLY /** * SetExecuteBit changes the page access protections on a block of pages, * to make JIT-ted code executable or not. * * If executableFlag is true, the memory is made executable and read-only. * * If executableFlag is false, the memory is made non-executable and * read-write. */ void GCHeap::SetExecuteBit(void *address, size_t size, bool executableFlag) { // Should use vmPageSize() or kNativePageSize here. // But this value is hard coded to 4096 if we don't use mmap. int bitmask = sysconf(_SC_PAGESIZE) - 1; // mprotect requires that the addresses be aligned on page boundaries void *endAddress = (void*) ((char*)address + size); void *beginPage = (void*) ((size_t)address & ~bitmask); void *endPage = (void*) (((size_t)endAddress + bitmask) & ~bitmask); size_t sizePaged = (size_t)endPage - (size_t)beginPage; #ifdef DEBUG int retval = #endif mprotect((maddr_ptr)beginPage, sizePaged, executableFlag ? (PROT_READ|PROT_WRITE|PROT_EXEC) : (PROT_READ|PROT_WRITE)); GCAssert(retval == 0); } #endif /* AVMPLUS_JIT_READONLY */ #ifdef USE_MMAP void* GCHeap::CommitCodeMemory(void* address, size_t size) { void* res; if (size == 0) size = GCHeap::kNativePageSize; // default of one page #ifdef AVMPLUS_JIT_READONLY mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); #else mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); #endif /* AVMPLUS_JIT_READONLY */ res = address; if (res == address) address = (void*)( (uintptr)address + size ); else address = 0; return address; } void* GCHeap::DecommitCodeMemory(void* address, size_t size) { if (size == 0) size = GCHeap::kNativePageSize; // default of one page // release and re-reserve it ReleaseCodeMemory(address, size); address = ReserveCodeMemory(address, size); return address; } #else int GCHeap::vmPageSize() { return 4096; } void* GCHeap::ReserveCodeMemory(void* address, size_t size) { return aligned_malloc(size, 4096, m_malloc); } void GCHeap::ReleaseCodeMemory(void* address, size_t size) { aligned_free(address, m_free); } bool GCHeap::SetGuardPage(void *address) { return false; } void* GCHeap::CommitCodeMemory(void* address, size_t size) { return address; } void* GCHeap::DecommitCodeMemory(void* address, size_t size) { return address; } #endif /* USE_MMAP */ #ifdef USE_MMAP char* GCHeap::ReserveMemory(char *address, size_t size) { char *addr = (char*)mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (addr == MAP_FAILED) { return NULL; } if(address && address != addr) { // behave like windows and fail if we didn't get the right address ReleaseMemory(addr, size); return NULL; } return addr; } bool GCHeap::CommitMemory(char *address, size_t size) { char *addr = (char*)mmap(address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); GCAssert(addr == address); return addr == address; } bool GCHeap::DecommitMemory(char *address, size_t size) { ReleaseMemory(address, size); // re-reserve it char *addr = (char*)mmap((maddr_ptr)address, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); GCAssert(addr == address); return addr == address; } bool GCHeap::CommitMemoryThatMaySpanRegions(char *address, size_t size) { return CommitMemory(address, size); } bool GCHeap::DecommitMemoryThatMaySpanRegions(char *address, size_t size) { return DecommitMemory(address, size); } void GCHeap::ReleaseMemory(char *address, size_t size) { #ifdef DEBUG int result = #endif munmap((maddr_ptr)address, size); GCAssert(result == 0); } #else char* GCHeap::AllocateMemory(size_t size) { return (char *) aligned_malloc(size, 4096, m_malloc); } void GCHeap::ReleaseMemory(char *address) { aligned_free(address, m_free); } #endif #ifdef MEMORY_INFO void GetInfoFromPC(int pc, char *buff, int buffSize) { #ifdef AVMPLUS_UNIX Dl_info dlip; dladdr((void *const)pc, &dlip); sprintf(buff, "0x%08x:%s", pc, dlip.dli_sname); #else sprintf(buff, "0x%x", pc); #endif } #ifdef MMGC_SPARC void GetStackTrace(int *trace, int len, int skip) { // TODO for sparc. GCAssert(false); } #endif #ifdef MMGC_PPC void GetStackTrace(int *trace, int len, int skip) { register int stackp; int pc; asm("mr %0,r1" : "=r" (stackp)); while(skip--) { stackp = *(int*)stackp; } int i=0; // save space for 0 terminator len--; while(i<len && stackp) { pc = *((int*)stackp+2); trace[i++]=pc; stackp = *(int*)stackp; } trace[i] = 0; } #endif #ifdef MMGC_IA32 void GetStackTrace(int *trace, int len, int skip) { void **ebp; #ifdef SOLARIS ebp = (void **)_getfp(); #else asm("mov %%ebp, %0" : "=r" (ebp)); #endif while(skip-- && *ebp) { ebp = (void**)(*ebp); } /* save space for 0 terminator */ len--; int i = 0; while (i < len && *ebp) { /* store the current frame pointer */ trace[i++] = *((int*) ebp + 1); /* get the next frame pointer */ ebp = (void**)(*ebp); } trace[i] = 0; } #endif #ifdef MMGC_ARM void GetStackTrace(int *trace, int len, int skip) {} #endif #endif } <commit_msg>Bug 426733 [Regression] test/acceptance/ecma3/Statements/eforin_001.abc crash avmshell debugger build on solaris. stejohns: review+<commit_after>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2004-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * leon.sha@sun.com * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "MMgc.h" #include "GCDebug.h" #include "GC.h" #include <sys/mman.h> #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #define MAP_ANONYMOUS MAP_ANON #endif // !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #if defined(MEMORY_INFO) && defined(AVMPLUS_UNIX) #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <dlfcn.h> #endif // avmplus standalone uses UNIX #ifdef _MAC #define MAP_ANONYMOUS MAP_ANON #endif #ifdef SOLARIS #include <ucontext.h> #include <dlfcn.h> extern "C" caddr_t _getfp(void); typedef caddr_t maddr_ptr; #else typedef void *maddr_ptr; #endif namespace MMgc { #ifndef USE_MMAP void *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc) { char *ptr, *ptr2, *aligned_ptr; int align_mask = align_size - 1; int alloc_size = size + align_size + sizeof(int); ptr=(char *)m_malloc(alloc_size); if(ptr==NULL) return(NULL); ptr2 = ptr + sizeof(int); aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask)); ptr2 = aligned_ptr - sizeof(int); *((int *)ptr2)=(int)(aligned_ptr - ptr); return(aligned_ptr); } void aligned_free(void *ptr, GCFreeFuncPtr m_free) { int *ptr2=(int *)ptr - 1; char *unaligned_ptr = (char*) ptr - *ptr2; m_free(unaligned_ptr); } #endif /* !USE_MMAP */ #ifdef USE_MMAP int GCHeap::vmPageSize() { long v = sysconf(_SC_PAGESIZE); return v; } void* GCHeap::ReserveCodeMemory(void* address, size_t size) { return (char*) mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); } void GCHeap::ReleaseCodeMemory(void* address, size_t size) { if (munmap((maddr_ptr)address, size) != 0) GCAssert(false); } bool GCHeap::SetGuardPage(void *address) { return false; } #endif /* USE_MMAP */ #ifdef AVMPLUS_JIT_READONLY /** * SetExecuteBit changes the page access protections on a block of pages, * to make JIT-ted code executable or not. * * If executableFlag is true, the memory is made executable and read-only. * * If executableFlag is false, the memory is made non-executable and * read-write. * * [rickr] bug #182323 The codegen can bail in the middle of generating * code for any number of reasons. When this occurs we need to ensure * that any code that was previously on the page still executes, so we * leave the page as PAGE_EXECUTE_READWRITE rather than PAGE_READWRITE. * Ideally we'd use PAGE_READWRITE and then on failure revert it back to * read/execute but this is a little tricker and doesn't add too much * protection since only a single page is 'exposed' with this technique. * * [leon.sha] from above discription, if you want to change the excuatable * status of one pice of memory, you changed the whole page's status. So * just ignore the executableFlag. */ void GCHeap::SetExecuteBit(void *address, size_t size, bool executableFlag) { // Should use vmPageSize() or kNativePageSize here. // But this value is hard coded to 4096 if we don't use mmap. int bitmask = sysconf(_SC_PAGESIZE) - 1; // mprotect requires that the addresses be aligned on page boundaries void *endAddress = (void*) ((char*)address + size); void *beginPage = (void*) ((size_t)address & ~bitmask); void *endPage = (void*) (((size_t)endAddress + bitmask) & ~bitmask); size_t sizePaged = (size_t)endPage - (size_t)beginPage; #ifdef DEBUG int retval = #endif mprotect((maddr_ptr)beginPage, sizePaged, (PROT_READ|PROT_WRITE|PROT_EXEC)); GCAssert(retval == 0); } #endif /* AVMPLUS_JIT_READONLY */ #ifdef USE_MMAP void* GCHeap::CommitCodeMemory(void* address, size_t size) { void* res; if (size == 0) size = GCHeap::kNativePageSize; // default of one page #ifdef AVMPLUS_JIT_READONLY mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); #else mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); #endif /* AVMPLUS_JIT_READONLY */ res = address; if (res == address) address = (void*)( (uintptr)address + size ); else address = 0; return address; } void* GCHeap::DecommitCodeMemory(void* address, size_t size) { if (size == 0) size = GCHeap::kNativePageSize; // default of one page // release and re-reserve it ReleaseCodeMemory(address, size); address = ReserveCodeMemory(address, size); return address; } #else int GCHeap::vmPageSize() { return 4096; } void* GCHeap::ReserveCodeMemory(void* address, size_t size) { return aligned_malloc(size, 4096, m_malloc); } void GCHeap::ReleaseCodeMemory(void* address, size_t size) { aligned_free(address, m_free); } bool GCHeap::SetGuardPage(void *address) { return false; } void* GCHeap::CommitCodeMemory(void* address, size_t size) { return address; } void* GCHeap::DecommitCodeMemory(void* address, size_t size) { return address; } #endif /* USE_MMAP */ #ifdef USE_MMAP char* GCHeap::ReserveMemory(char *address, size_t size) { char *addr = (char*)mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (addr == MAP_FAILED) { return NULL; } if(address && address != addr) { // behave like windows and fail if we didn't get the right address ReleaseMemory(addr, size); return NULL; } return addr; } bool GCHeap::CommitMemory(char *address, size_t size) { char *addr = (char*)mmap(address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); GCAssert(addr == address); return addr == address; } bool GCHeap::DecommitMemory(char *address, size_t size) { ReleaseMemory(address, size); // re-reserve it char *addr = (char*)mmap((maddr_ptr)address, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); GCAssert(addr == address); return addr == address; } bool GCHeap::CommitMemoryThatMaySpanRegions(char *address, size_t size) { return CommitMemory(address, size); } bool GCHeap::DecommitMemoryThatMaySpanRegions(char *address, size_t size) { return DecommitMemory(address, size); } void GCHeap::ReleaseMemory(char *address, size_t size) { #ifdef DEBUG int result = #endif munmap((maddr_ptr)address, size); GCAssert(result == 0); } #else char* GCHeap::AllocateMemory(size_t size) { return (char *) aligned_malloc(size, 4096, m_malloc); } void GCHeap::ReleaseMemory(char *address) { aligned_free(address, m_free); } #endif #ifdef MEMORY_INFO void GetInfoFromPC(int pc, char *buff, int buffSize) { #ifdef AVMPLUS_UNIX Dl_info dlip; dladdr((void *const)pc, &dlip); sprintf(buff, "0x%08x:%s", pc, dlip.dli_sname); #else sprintf(buff, "0x%x", pc); #endif } #ifdef MMGC_SPARC void GetStackTrace(int *trace, int len, int skip) { // TODO for sparc. GCAssert(false); } #endif #ifdef MMGC_PPC void GetStackTrace(int *trace, int len, int skip) { register int stackp; int pc; asm("mr %0,r1" : "=r" (stackp)); while(skip--) { stackp = *(int*)stackp; } int i=0; // save space for 0 terminator len--; while(i<len && stackp) { pc = *((int*)stackp+2); trace[i++]=pc; stackp = *(int*)stackp; } trace[i] = 0; } #endif #ifdef MMGC_IA32 void GetStackTrace(int *trace, int len, int skip) { void **ebp; #ifdef SOLARIS ebp = (void **)_getfp(); #else asm("mov %%ebp, %0" : "=r" (ebp)); #endif while(skip-- && *ebp) { ebp = (void**)(*ebp); } /* save space for 0 terminator */ len--; int i = 0; while (i < len && *ebp) { /* store the current frame pointer */ trace[i++] = *((int*) ebp + 1); /* get the next frame pointer */ ebp = (void**)(*ebp); } trace[i] = 0; } #endif #ifdef MMGC_ARM void GetStackTrace(int *trace, int len, int skip) {} #endif #endif } <|endoftext|>
<commit_before>/* Empath - Mailer for KDE Copyright (C) 1998 Rik Hemsley rik@kde.org 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ // Qt includes #include <qstring.h> // Local includes #include <RMM_BodyPart.h> #include <RMM_Body.h> #include <RMM_Message.h> #include <RMM_MimeType.h> #include <RMM_Envelope.h> #include <RMM_Utility.h> #include <RMM_Enum.h> RBody::RBody() : RMessageComponent() { rmmDebug("ctor"); partList_.setAutoDelete(true); } RBody::RBody(const RBody & body) : RMessageComponent(body) { rmmDebug("ctor"); partList_.setAutoDelete(true); partList_ = body.partList_; assembled_ = false; } RBody::~RBody() { rmmDebug("dtor"); } RBody & RBody::operator = (const RBody & body) { rmmDebug("operator ="); partList_.clear(); RBodyPartListIterator it(partList_); for (;it.current(); ++it) partList_.append(it.current()); RMessageComponent::operator = (body); return *this; } void RBody::parse() { rmmDebug("parse() called"); if (parsed_) return; partList_.clear(); // We need to know what type of encoding we're looking at. RMM::CteType t(RMM::RCteStr2Enum(cte_.mechanism())); QCString decoded; switch (t) { case RMM::CteTypeQuotedPrintable: decoded = RDecodeQuotedPrintable(strRep_); break; case RMM::CteTypeBase64: decoded = RDecodeBase64(strRep_); break; case RMM::CteType7bit: case RMM::CteType8bit: case RMM::CteTypeBinary: default: decoded = strRep_; break; } if (!isMultiPart_) { RBodyPart * newPart = new RBodyPart(strRep_); CHECK_PTR(newPart); newPart->parse(); return; } // So, dear message, you are of multiple parts. Let's see what you're made // of. // Start by looking for the first boundary. If there's data before it, then // that's the preamble. int i(strRep_.find(boundary_)); if (i == -1) { // Argh ! This is supposed to be a multipart message, but there's not // even one boundary ! // Let's just call it a plain text message. // return; } preamble_ = strRep_.left(i); int oldi(i + boundary_.length()); // Now do the rest of the parts. i = strRep_.find(boundary_, i + boundary_.length()); while (i != -1) { // Looks like there's only one body part. RBodyPart * newPart = new RBodyPart(strRep_.mid(oldi, i)); CHECK_PTR(newPart); oldi = i + boundary_.length(); i = strRep_.find(boundary_, i + boundary_.length()); } // No more body parts. Anything that's left is the epilogue. epilogue_ = strRep_.right(strRep_.length() - i + boundary_.length()); parsed_ = true; assembled_ = false; } void RBody::assemble() { parse(); rmmDebug("assemble() called"); assembled_ = true; } int RBody::numberOfParts() { parse(); return partList_.count(); } void RBody::addPart(RBodyPart * bp) { partList_.append(bp); assembled_ = false; } void RBody::removePart(RBodyPart * part) { partList_.remove(part); assembled_ = false; } RBodyPart RBody::part(int index) { return *(partList_.at(index)); } void RBody::createDefault() { rmmDebug("createDefault() called"); strRep_ = "Empty message"; parsed_ = true; assembled_ = true; } void RBody::setBoundary(const QCString & s) { boundary_ = s; assembled_ = false; } void RBody::setContentType(RContentType & t) { contentType_ = t; assembled_ = false; } void RBody::setCTE(RCte & t) { cte_ = t; assembled_ = false; } void RBody::setMultiPart(bool b) { isMultiPart_ = b; assembled_ = false; } <commit_msg>Now unnecessary<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wtextsh.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-05-22 16:40:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include "hintids.hxx" #ifndef _SFXOBJFACE_HXX //autogen #include <sfx2/objface.hxx> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SVX_SRCHITEM_HXX #include <svx/srchitem.hxx> //*** #endif #ifndef __SBX_SBXVARIABLE_HXX //autogen #include <basic/sbxvar.hxx> #endif #ifndef _SVX_SVXIDS_HRC //autogen #include <svx/svxids.hrc> #endif #include "swtypes.hxx" #include "cmdid.h" #include "view.hxx" #include "wtextsh.hxx" #include "basesh.hxx" #include "globals.hrc" #include "popup.hrc" #include "shells.hrc" #include "web.hrc" #define C2S(cChar) UniString::CreateFromAscii(cChar) // STATIC DATA ----------------------------------------------------------- #define SwWebTextShell #define Paragraph #define HyphenZone #define TextFont #define DropCap #include "itemdef.hxx" #include "swslots.hxx" /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SFX_IMPL_INTERFACE(SwWebTextShell, SwBaseShell, SW_RES(STR_SHELLNAME_WEBTEXT)) { SFX_POPUPMENU_REGISTRATION(SW_RES(MN_WEB_TEXT_POPUPMENU)); SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_WEBTEXT_TOOLBOX)); SFX_CHILDWINDOW_REGISTRATION(FN_EDIT_FORMULA); SFX_CHILDWINDOW_REGISTRATION(FN_INSERT_FIELD); } TYPEINIT1(SwWebTextShell, SwTextShell) /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwWebTextShell::SwWebTextShell(SwView &rView) : SwTextShell(rView) { SetHelpId(SW_WEBTEXTSHELL); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwWebTextShell::~SwWebTextShell() { } <commit_msg>INTEGRATION: CWS swwarnings (1.8.222); FILE MERGED 2007/06/01 07:17:48 tl 1.8.222.3: #i69287# warning-free code 2007/05/29 15:09:09 os 1.8.222.2: RESYNC: (1.8-1.9); FILE MERGED 2007/03/26 12:09:39 tl 1.8.222.1: #i69287# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wtextsh.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2007-09-27 12:52:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include "hintids.hxx" #ifndef _SFXOBJFACE_HXX //autogen #include <sfx2/objface.hxx> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SVX_SRCHITEM_HXX #include <svx/srchitem.hxx> //*** #endif #ifndef __SBX_SBXVARIABLE_HXX //autogen #include <basic/sbxvar.hxx> #endif #ifndef _SVX_SVXIDS_HRC //autogen #include <svx/svxids.hrc> #endif #include "swtypes.hxx" #include "cmdid.h" #include "view.hxx" #include "wtextsh.hxx" #include "basesh.hxx" #include "globals.hrc" #include "popup.hrc" #include "shells.hrc" #include "web.hrc" #include <unomid.h> // STATIC DATA ----------------------------------------------------------- #define SwWebTextShell #define Paragraph #define HyphenZone #define TextFont #define DropCap #include "itemdef.hxx" #include "swslots.hxx" /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SFX_IMPL_INTERFACE(SwWebTextShell, SwBaseShell, SW_RES(STR_SHELLNAME_WEBTEXT)) { SFX_POPUPMENU_REGISTRATION(SW_RES(MN_WEB_TEXT_POPUPMENU)); SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_WEBTEXT_TOOLBOX)); SFX_CHILDWINDOW_REGISTRATION(FN_EDIT_FORMULA); SFX_CHILDWINDOW_REGISTRATION(FN_INSERT_FIELD); } TYPEINIT1(SwWebTextShell, SwTextShell) /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwWebTextShell::SwWebTextShell(SwView &_rView) : SwTextShell(_rView) { SetHelpId(SW_WEBTEXTSHELL); } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ SwWebTextShell::~SwWebTextShell() { } <|endoftext|>
<commit_before>#ifndef MBGL_UTIL_MATH #define MBGL_UTIL_MATH #include <cmath> #include <array> #include "vec.hpp" namespace MonkVG { namespace util { template <typename T> inline T perp(const T& a) { return T(-a.y, a.x); } template <typename T, typename S1, typename S2> inline T dist(const S1& a, const S2& b) { T dx = b.x - a.x; T dy = b.y - a.y; T c = std::sqrt(dx * dx + dy * dy); return c; } // Take the magnitude of vector a. template <typename T = double, typename S> inline T mag(const S& a) { return std::sqrt(a.x * a.x + a.y * a.y); } template <typename S> inline S unit(const S& a) { auto magnitude = mag(a); if (magnitude == 0) { return a; } return a * (1 / magnitude); } } } #endif <commit_msg>Added mapbox copyright<commit_after>/* mapbox-gl-native copyright (c) 2014-2016 Mapbox. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef MBGL_UTIL_MATH #define MBGL_UTIL_MATH #include <cmath> #include <array> #include "vec.hpp" namespace MonkVG { namespace util { template <typename T> inline T perp(const T& a) { return T(-a.y, a.x); } template <typename T, typename S1, typename S2> inline T dist(const S1& a, const S2& b) { T dx = b.x - a.x; T dy = b.y - a.y; T c = std::sqrt(dx * dx + dy * dy); return c; } // Take the magnitude of vector a. template <typename T = double, typename S> inline T mag(const S& a) { return std::sqrt(a.x * a.x + a.y * a.y); } template <typename S> inline S unit(const S& a) { auto magnitude = mag(a); if (magnitude == 0) { return a; } return a * (1 / magnitude); } } } #endif <|endoftext|>
<commit_before>#include "fast_lexical_cast.hpp" #include "viterbi.h" #include <sstream> #include <vector> #include "hg.h" //#define DEBUG_VITERBI_SORT using namespace std; std::string viterbi_stats(Hypergraph const& hg, std::string const& name, bool estring, bool etree,bool show_derivation) { ostringstream o; o << hg.stats(name); if (estring) { vector<WordID> trans; const prob_t vs = ViterbiESentence(hg, &trans); o<<name<<" Viterbi logp: "<<log(vs)<< " (norm=" << log(vs)/trans.size() << ")" << endl; o<<name<<" Viterbi: "<<TD::GetString(trans)<<endl; } if (etree) { o<<name<<" tree: "<<ViterbiETree(hg)<<endl; } if (show_derivation) { o<<name<<" derivation: "; o << hg.show_viterbi_tree(false); // last item should be goal (or at least depend on prev items). TODO: this doesn't actually reorder the nodes in hg. o<<endl; } #ifdef DEBUG_VITERBI_SORT const_cast<Hypergraph&>(hg).ViterbiSortInEdges(); o<<name<<"sorted #1 derivation: "; o<<hg.show_first_tree(false); o<<endl; #endif return o.str(); } string ViterbiETree(const Hypergraph& hg) { vector<WordID> tmp; Viterbi<ETreeTraversal>(hg, &tmp); return TD::GetString(tmp); } string ViterbiFTree(const Hypergraph& hg) { vector<WordID> tmp; Viterbi<FTreeTraversal>(hg, &tmp); return TD::GetString(tmp); } prob_t ViterbiESentence(const Hypergraph& hg, vector<WordID>* result) { return Viterbi<ESentenceTraversal>(hg, result); } prob_t ViterbiFSentence(const Hypergraph& hg, vector<WordID>* result) { return Viterbi<FSentenceTraversal>(hg, result); } int ViterbiELength(const Hypergraph& hg) { int len = -1; Viterbi<ELengthTraversal>(hg, &len); return len; } int ViterbiPathLength(const Hypergraph& hg) { int len = -1; Viterbi<PathLengthTraversal>(hg, &len); return len; } // create a strings of the form (S (X the man) (X said (X he (X would (X go))))) struct JoshuaVisTraversal { JoshuaVisTraversal() : left("("), space(" "), right(")") {} const std::string left; const std::string space; const std::string right; typedef std::vector<WordID> Result; void operator()(const Hypergraph::Edge& edge, const std::vector<const Result*>& ants, Result* result) const { Result tmp; edge.rule_->ESubstitute(ants, &tmp); const std::string cat = TD::Convert(edge.rule_->GetLHS() * -1); if (cat == "Goal") result->swap(tmp); else { ostringstream os; os << left << cat << '{' << edge.i_ << '-' << edge.j_ << '}' << space << TD::GetString(tmp) << right; TD::ConvertSentence(os.str(), result); } } }; string JoshuaVisualizationString(const Hypergraph& hg) { vector<WordID> tmp; Viterbi<JoshuaVisTraversal>(hg, &tmp); return TD::GetString(tmp); } //TODO: move to appropriate header if useful elsewhere /* The simple solution like abs(f1-f2) <= e does not work for very small or very big values. This floating-point comparison algorithm is based on the more confident solution presented by Knuth in [1]. For a given floating point values u and v and a tolerance e: | u - v | <= e * |u| and | u - v | <= e * |v| defines a "very close with tolerance e" relationship between u and v (1) | u - v | <= e * |u| or | u - v | <= e * |v| defines a "close enough with tolerance e" relationship between u and v (2) Both relationships are commutative but are not transitive. The relationship defined by inequations (1) is stronger that the relationship defined by inequations (2) (i.e. (1) => (2) ). Because of the multiplication in the right side of inequations, that could cause an unwanted underflow condition, the implementation is using modified version of the inequations (1) and (2) where all underflow, overflow conditions could be guarded safely: | u - v | / |u| <= e and | u - v | / |v| <= e | u - v | / |u| <= e or | u - v | / |v| <= e (1`) (2`) */ #include <cmath> #include <stdexcept> inline bool close_enough(double a,double b,double epsilon) { using std::fabs; double diff=fabs(a-b); return diff<=epsilon*fabs(a) || diff<=epsilon*fabs(b); } FeatureVector ViterbiFeatures(Hypergraph const& hg,WeightVector const* weights,bool fatal_dotprod_disagreement) { FeatureVector r; const prob_t p = Viterbi<FeatureVectorTraversal>(hg, &r); if (weights) { double logp=log(p); double fv=r.dot(*weights); const double EPSILON=1e-5; if (!close_enough(logp,fv,EPSILON)) { string complaint="ViterbiFeatures log prob disagrees with features.dot(weights)"+boost::lexical_cast<string>(logp)+"!="+boost::lexical_cast<string>(fv); if (fatal_dotprod_disagreement) throw std::runtime_error(complaint); else cerr<<complaint<<endl; } } return r; } <commit_msg>remove meaningless stat<commit_after>#include "fast_lexical_cast.hpp" #include "viterbi.h" #include <sstream> #include <vector> #include "hg.h" //#define DEBUG_VITERBI_SORT using namespace std; std::string viterbi_stats(Hypergraph const& hg, std::string const& name, bool estring, bool etree,bool show_derivation) { ostringstream o; o << hg.stats(name); if (estring) { vector<WordID> trans; const prob_t vs = ViterbiESentence(hg, &trans); o<<name<<" Viterbi logp: "<<log(vs)<< endl; o<<name<<" Viterbi: "<<TD::GetString(trans)<<endl; } if (etree) { o<<name<<" tree: "<<ViterbiETree(hg)<<endl; } if (show_derivation) { o<<name<<" derivation: "; o << hg.show_viterbi_tree(false); // last item should be goal (or at least depend on prev items). TODO: this doesn't actually reorder the nodes in hg. o<<endl; } #ifdef DEBUG_VITERBI_SORT const_cast<Hypergraph&>(hg).ViterbiSortInEdges(); o<<name<<"sorted #1 derivation: "; o<<hg.show_first_tree(false); o<<endl; #endif return o.str(); } string ViterbiETree(const Hypergraph& hg) { vector<WordID> tmp; Viterbi<ETreeTraversal>(hg, &tmp); return TD::GetString(tmp); } string ViterbiFTree(const Hypergraph& hg) { vector<WordID> tmp; Viterbi<FTreeTraversal>(hg, &tmp); return TD::GetString(tmp); } prob_t ViterbiESentence(const Hypergraph& hg, vector<WordID>* result) { return Viterbi<ESentenceTraversal>(hg, result); } prob_t ViterbiFSentence(const Hypergraph& hg, vector<WordID>* result) { return Viterbi<FSentenceTraversal>(hg, result); } int ViterbiELength(const Hypergraph& hg) { int len = -1; Viterbi<ELengthTraversal>(hg, &len); return len; } int ViterbiPathLength(const Hypergraph& hg) { int len = -1; Viterbi<PathLengthTraversal>(hg, &len); return len; } // create a strings of the form (S (X the man) (X said (X he (X would (X go))))) struct JoshuaVisTraversal { JoshuaVisTraversal() : left("("), space(" "), right(")") {} const std::string left; const std::string space; const std::string right; typedef std::vector<WordID> Result; void operator()(const Hypergraph::Edge& edge, const std::vector<const Result*>& ants, Result* result) const { Result tmp; edge.rule_->ESubstitute(ants, &tmp); const std::string cat = TD::Convert(edge.rule_->GetLHS() * -1); if (cat == "Goal") result->swap(tmp); else { ostringstream os; os << left << cat << '{' << edge.i_ << '-' << edge.j_ << '}' << space << TD::GetString(tmp) << right; TD::ConvertSentence(os.str(), result); } } }; string JoshuaVisualizationString(const Hypergraph& hg) { vector<WordID> tmp; Viterbi<JoshuaVisTraversal>(hg, &tmp); return TD::GetString(tmp); } //TODO: move to appropriate header if useful elsewhere /* The simple solution like abs(f1-f2) <= e does not work for very small or very big values. This floating-point comparison algorithm is based on the more confident solution presented by Knuth in [1]. For a given floating point values u and v and a tolerance e: | u - v | <= e * |u| and | u - v | <= e * |v| defines a "very close with tolerance e" relationship between u and v (1) | u - v | <= e * |u| or | u - v | <= e * |v| defines a "close enough with tolerance e" relationship between u and v (2) Both relationships are commutative but are not transitive. The relationship defined by inequations (1) is stronger that the relationship defined by inequations (2) (i.e. (1) => (2) ). Because of the multiplication in the right side of inequations, that could cause an unwanted underflow condition, the implementation is using modified version of the inequations (1) and (2) where all underflow, overflow conditions could be guarded safely: | u - v | / |u| <= e and | u - v | / |v| <= e | u - v | / |u| <= e or | u - v | / |v| <= e (1`) (2`) */ #include <cmath> #include <stdexcept> inline bool close_enough(double a,double b,double epsilon) { using std::fabs; double diff=fabs(a-b); return diff<=epsilon*fabs(a) || diff<=epsilon*fabs(b); } FeatureVector ViterbiFeatures(Hypergraph const& hg,WeightVector const* weights,bool fatal_dotprod_disagreement) { FeatureVector r; const prob_t p = Viterbi<FeatureVectorTraversal>(hg, &r); if (weights) { double logp=log(p); double fv=r.dot(*weights); const double EPSILON=1e-5; if (!close_enough(logp,fv,EPSILON)) { string complaint="ViterbiFeatures log prob disagrees with features.dot(weights)"+boost::lexical_cast<string>(logp)+"!="+boost::lexical_cast<string>(fv); if (fatal_dotprod_disagreement) throw std::runtime_error(complaint); else cerr<<complaint<<endl; } } return r; } <|endoftext|>
<commit_before>#include "config.hpp" #include "MidiPlayer.hpp" #include <iostream> #include <stdexcept> #include "filesystem.hpp" namespace MidiPlayer { MidiDisplayManager::MidiDisplayManager() :m_width(800), m_height(600), m_fullscreen(false), m_title("MidiPlayer"), m_context(3, 2, 0), m_window(m_width, m_height, m_fullscreen, m_title), m_eventManager(), m_eventPump(&m_eventManager), m_boardSpeed(0.001), m_maxNotes(127) { m_running = true; m_logger = spdlog::get("default"); m_window.make_current(&m_context); m_window.disable_sync(); m_song.load(); if(!gladLoadGL()) { throw std::runtime_error(_("Error: GLAD failed to load.")); } m_lis.handler = std::bind(&MidiDisplayManager::event_handler, this, std::placeholders::_1); m_lis.mask = ORCore::EventType::EventAll; m_eventManager.add_listener(m_lis); m_fpsTime = 0.0; m_ss = std::cout.precision(); m_renderer.init_gl(); ORCore::ShaderInfo vertInfo {GL_VERTEX_SHADER, "./data/shaders/main.vs"}; ORCore::ShaderInfo fragInfo {GL_FRAGMENT_SHADER, "./data/shaders/main.fs"}; m_program = m_renderer.add_program(ORCore::Shader(vertInfo), ORCore::Shader(fragInfo)); resize(m_width, m_height); m_logger->info(_("Preping notes for render")); //m_renderer->mesh_clear(); prep_render_notes(m_songTime-1000, 1000.0); m_logger->info(_("Notes prep'd")); m_logger->info(_("Committing geometry.")); m_renderer.commit(); m_logger->info(_("Starting rendering.")); glClearColor(0.5, 0.5, 0.5, 1.0); std::cout << "Done INIT " << std::endl; } MidiDisplayManager::~MidiDisplayManager() { m_window.make_current(nullptr); } // multithread this k! void MidiDisplayManager::prep_render_notes(double time, double length) { int trackColorIndex = 0; ORCore::RenderObject obj; obj.set_program(m_program); obj.set_primitive_type(ORCore::Primitive::triangle); for (auto track: *m_song.get_tracks()) { glm::vec4 color = m_colorArray[trackColorIndex]; m_colorArray[trackColorIndex] += m_colorMutator[trackColorIndex]; trackColorIndex++; auto noteInfo = track.get_notes();//get_notes_in_frame(time, time+length); for(int i = noteInfo.start; i < noteInfo.end; i++) { auto &note = (*noteInfo.notes)[i]; float z = note.time; float noteLength = note.length*m_boardSpeed; obj.set_scale(glm::vec3{0.005f, noteLength, 0.0f}); obj.set_translation(glm::vec3{(static_cast<int>(note.noteValue)/(m_maxNotes*1.0)), -(z*m_boardSpeed), 0.0f}); // center the line on the screen obj.set_geometry(ORCore::create_rect_mesh(color)); m_renderer.add_object(obj); } } } void MidiDisplayManager::start() { GLenum error; while (m_running) { m_fpsTime += m_clock.tick(); m_eventPump.process(); update(); render(); do { error = glGetError(); if (error != GL_NO_ERROR) { m_logger->info(_("GL error: {}"), error); } } while(error != GL_NO_ERROR); m_window.flip(); if (m_fpsTime >= 2000.0) { std::cout.precision (5); std::cout << "FPS: " << m_clock.get_fps() << std::endl; std::cout << "Song Time: " << m_songTime << std::endl; std::cout.precision (m_ss); m_fpsTime = 0; } } } void MidiDisplayManager::resize(int width, int height) { m_width = width; m_height = height; glViewport(0, 0, m_width, m_height); m_ortho = glm::ortho(0.0f, static_cast<float>(1.0), static_cast<float>(1.0), 0.0f, -1.0f, 1.0f); } bool MidiDisplayManager::event_handler(const ORCore::Event &event) { switch(event.type) { case ORCore::Quit: { m_running = false; break; } case ORCore::WindowSize: { auto ev = ORCore::event_cast<ORCore::WindowSizeEvent>(event); resize(ev.width, ev.height); break; } default: break; } return true; } void MidiDisplayManager::handle_song() { } void MidiDisplayManager::update() { m_songTime = m_clock.get_current_time(); m_renderer.set_camera_transform("ortho", glm::translate(m_ortho, glm::vec3(0.0f, m_songTime*m_boardSpeed, 0.0f))); // translate projection with song // m_renderer->mesh_clear(); // prep_render_notes(m_songTime-1000, 1000.0); // m_renderer->mesh_commit(); } void MidiDisplayManager::render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_renderer.render(); } }<commit_msg>Comment out color code, as there seems to be some sort of bug?<commit_after>#include "config.hpp" #include "MidiPlayer.hpp" #include <iostream> #include <stdexcept> #include "filesystem.hpp" namespace MidiPlayer { MidiDisplayManager::MidiDisplayManager() :m_width(800), m_height(600), m_fullscreen(false), m_title("MidiPlayer"), m_context(3, 2, 0), m_window(m_width, m_height, m_fullscreen, m_title), m_eventManager(), m_eventPump(&m_eventManager), m_boardSpeed(0.5), m_maxNotes(127) { m_running = true; m_logger = spdlog::get("default"); m_window.make_current(&m_context); m_window.disable_sync(); m_song.load(); if(!gladLoadGL()) { throw std::runtime_error(_("Error: GLAD failed to load.")); } m_lis.handler = std::bind(&MidiDisplayManager::event_handler, this, std::placeholders::_1); m_lis.mask = ORCore::EventType::EventAll; m_eventManager.add_listener(m_lis); m_fpsTime = 0.0; m_ss = std::cout.precision(); m_renderer.init_gl(); ORCore::ShaderInfo vertInfo {GL_VERTEX_SHADER, "./data/shaders/main.vs"}; ORCore::ShaderInfo fragInfo {GL_FRAGMENT_SHADER, "./data/shaders/main.fs"}; m_program = m_renderer.add_program(ORCore::Shader(vertInfo), ORCore::Shader(fragInfo)); resize(m_width, m_height); m_logger->info(_("Preping notes for render")); //m_renderer->mesh_clear(); prep_render_notes(m_songTime-1000, 1000.0); m_logger->info(_("Notes prep'd")); m_logger->info(_("Committing geometry.")); m_renderer.commit(); m_logger->info(_("Starting rendering.")); glClearColor(0.5, 0.5, 0.5, 1.0); std::cout << "Done INIT " << std::endl; } MidiDisplayManager::~MidiDisplayManager() { m_window.make_current(nullptr); } // multithread this k! void MidiDisplayManager::prep_render_notes(double time, double length) { int trackColorIndex = 0; ORCore::RenderObject obj; obj.set_program(m_program); obj.set_primitive_type(ORCore::Primitive::triangle); for (auto track: *m_song.get_tracks()) { // glm::vec4 color = m_colorArray[trackColorIndex]; // m_colorArray[trackColorIndex] += m_colorMutator[trackColorIndex]; // trackColorIndex++; obj.set_geometry(ORCore::create_rect_mesh(glm::vec4{1.0f,1.0f,1.0f,1.0f})); auto noteInfo = track.get_notes();//get_notes_in_frame(time, time+length); for(int i = noteInfo.start; i < noteInfo.end; i++) { auto &note = (*noteInfo.notes)[i]; float z = note.time; float noteLength = note.length*m_boardSpeed; obj.set_scale(glm::vec3{0.005f, noteLength, 0.0f}); obj.set_translation(glm::vec3{(static_cast<int>(note.noteValue)/(m_maxNotes*1.0)), -(z*m_boardSpeed), 0.0f}); // center the line on the screen m_renderer.add_object(obj); } } } void MidiDisplayManager::start() { GLenum error; while (m_running) { m_fpsTime += m_clock.tick(); m_eventPump.process(); update(); render(); do { error = glGetError(); if (error != GL_NO_ERROR) { m_logger->info(_("GL error: {}"), error); } } while(error != GL_NO_ERROR); m_window.flip(); if (m_fpsTime >= 2000.0) { std::cout.precision (5); std::cout << "FPS: " << m_clock.get_fps() << std::endl; std::cout << "Song Time: " << m_songTime << std::endl; std::cout.precision (m_ss); m_fpsTime = 0; } } } void MidiDisplayManager::resize(int width, int height) { m_width = width; m_height = height; glViewport(0, 0, m_width, m_height); m_ortho = glm::ortho(0.0f, static_cast<float>(1.0), static_cast<float>(1.0), 0.0f, -1.0f, 1.0f); } bool MidiDisplayManager::event_handler(const ORCore::Event &event) { switch(event.type) { case ORCore::Quit: { m_running = false; break; } case ORCore::WindowSize: { auto ev = ORCore::event_cast<ORCore::WindowSizeEvent>(event); resize(ev.width, ev.height); break; } default: break; } return true; } void MidiDisplayManager::handle_song() { } void MidiDisplayManager::update() { m_songTime = m_clock.get_current_time()/1000.0; m_renderer.set_camera_transform("ortho", glm::translate(m_ortho, glm::vec3(0.0f, m_songTime*m_boardSpeed, 0.0f))); // translate projection with song // m_renderer->mesh_clear(); // prep_render_notes(m_songTime-1000, 1000.0); // m_renderer->mesh_commit(); } void MidiDisplayManager::render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_renderer.render(); } }<|endoftext|>
<commit_before>/*************************************************************************** CGTFile.cpp - Encapsulates the Compiled Grammar Table File read operations and structures. ------------------- begin : Fri May 31 00:53:11 CEST 2002 copyright : (C) 2002 by Manuel Astudillo email : d00mas@efd.lth.se ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include "CGTFile.h" #include "GrammarInfo.h" CGTFile::CGTFile () { gInfo = NULL; errorString = NULL; header = NULL; ruleTable = NULL; symbolTable = NULL; stateTable = NULL; LALRTable = NULL; characterSetTable = NULL; theDFA = NULL; theLALR = NULL; } CGTFile::~CGTFile () { delete gInfo; delete [] errorString; delete [] header; // Delete tables delete symbolTable; delete stateTable; delete LALRTable; delete ruleTable; delete characterSetTable; delete theDFA; delete theLALR; } bool CGTFile::load (char *filename) { ifstream cgtStream; cgtStream.open (filename, ifstream::in | ifstream::binary); if (cgtStream.bad()) { return false; } bool result = load (&cgtStream); cgtStream.close(); return result; } bool CGTFile::load (ifstream *myStream) { int i; EntryStruct entry; theStream = myStream; // Read Header ////////////// header = readUnicodeString(); // Read Records //////////////// unsigned char recordType; integer nbrEntries; integer index; while (!theStream->eof()) { // Read record type & number of entries theStream->read ((char*)&recordType, 1); if (theStream->fail()) { if (theStream->eof()) { break; } else { return false; } } theStream->read ((char*) &nbrEntries, 2); // wprintf (L"Record Type: %d\n", recordType); // wprintf (L"Entries: %d\n", nbrEntries); if (recordType != 77) { errorString = "Record type is not supported\n"; return false; } // Read the type of content byte contentType; readEntry (&entry); contentType = entry.vByte; // wprintf (L"Content Type: %d\n", contentType); switch (contentType) { // Parameters Record case 'P': delete gInfo; gInfo = new GrammarInfo (); // read name readEntry (&entry); gInfo->name = entry.vString; // read version readEntry (&entry); gInfo->version = entry.vString; // read Author readEntry (&entry); gInfo->author = entry.vString; // read About readEntry (&entry); gInfo->about = entry.vString; // Case readEntry (&entry); caseSensitive = entry.vBool; // start symbol readEntry (&entry); startSymbol = entry.vInteger; break; // Table Counts case 'T' : readEntry (&entry); nbrSymbolTable = entry.vInteger; // Delete & Create a Symbol Table delete symbolTable; symbolTable = new SymbolTable (nbrSymbolTable); readEntry (&entry); nbrCharacterSets = entry.vInteger; // Delete & Create a Character Sets Table delete characterSetTable; characterSetTable = new CharacterSetTable (nbrCharacterSets); // Delete & Create a Rule Table readEntry (&entry); nbrRuleTable = entry.vInteger; delete ruleTable; ruleTable = new RuleTable (nbrRuleTable); // Delete & Create a DFAStateTable readEntry (&entry); nbrDFATable = entry.vInteger; delete stateTable; stateTable = new DFAStateTable (nbrDFATable); // Delete & Create a LALR Table readEntry (&entry); nbrLALRTable = entry.vInteger; delete LALRTable; LALRTable = new LALRStateTable (nbrLALRTable); break; // Character Set Table Entry case 'C' : readEntry (&entry); index = entry.vInteger; readEntry (&entry); characterSetTable->characters[index] = entry.vString; break; // Symbol Table Entry case 'S' : readEntry (&entry); index = entry.vInteger; readEntry (&entry); symbolTable->symbols[index].name = entry.vString; readEntry (&entry); symbolTable->symbols[index].kind = (SymbolType) entry.vInteger; break; // Rule case 'R' : readEntry (&entry); index = entry.vInteger; readEntry (&entry); ruleTable->rules[index].nonTerminal = entry.vInteger; // Read empty field readEntry (&entry); // Read symbols for this rule (nonTerminal -> symbol0 symbol1 ... symboln) for (i=0; i < nbrEntries-4; i++) { readEntry (&entry); // ruleTable->rules[index].symbols.push_back (entry.vInteger); RuleStruct *rst = &ruleTable->rules[index]; vector <integer> *s = &rst->symbols; s->push_back (entry.vInteger); } break; // Initial States case 'I' : readEntry(&entry); DFAInit = entry.vInteger; readEntry (&entry); LALRInit = entry.vInteger; break; // DFA State Entry case 'D': readEntry (&entry); index = entry.vInteger; // create a new State an insert it in the table readEntry (&entry); stateTable->states[index].accept = entry.vBool; readEntry(&entry); stateTable->states[index].acceptIndex = entry.vInteger; readEntry(&entry); Edge edge; for (i=0; i < nbrEntries-5; i+=3) { readEntry(&entry); edge.characterSetIndex = entry.vInteger; readEntry(&entry); edge.targetIndex = entry.vInteger; readEntry(&entry); stateTable->states[index].edges.push_back(edge); } break; // LALR State entry case 'L': readEntry(&entry); index = entry.vInteger; readEntry(&entry); Action action; for (i=0; i < nbrEntries-3; i+=4) { readEntry(&entry); action.symbolIndex = entry.vInteger; readEntry(&entry); action.action = entry.vInteger; readEntry(&entry); action.target = entry.vInteger; readEntry(&entry); LALRTable->states[index].actions.push_back(action); } break; } } return true; } /* Reads an entry in a record */ void CGTFile::readEntry (EntryStruct *entry) { char tmpChar; char dataType; theStream->get (dataType); if (theStream->fail()) { wprintf (L"Error reading entry\n"); } else { switch (dataType) { case 'E': break; case 'B': theStream->get (tmpChar); if (tmpChar) { entry->vBool = true; } else { entry->vBool = false; } break; case 'b': theStream->read ((char*) &entry->vByte, 1); break; case 'I': theStream->read ((char*) &entry->vInteger, 2); break; case 'S': entry->vString = readUnicodeString(); break; } } } /* Reads a Unicode String */ wchar_t *CGTFile::readUnicodeString () { int i = 0; wchar_t readChar; wchar_t tmpString[512]; wchar_t *retString; char tmpChar1, tmpChar2; theStream->get (tmpChar1); theStream->get (tmpChar2); while ((tmpChar1 != 0) || (tmpChar2 != 0)) { readChar = (wchar_t) tmpChar2; readChar <<= 8; readChar |= tmpChar1; tmpString[i] = readChar; theStream->get (tmpChar1); theStream->get (tmpChar2); i++; } tmpString[i] = 0; retString = new wchar_t [wcslen (tmpString) + 1]; wcscpy (retString, tmpString); return retString; } GrammarInfo *CGTFile::getInfo () { return gInfo; } DFA *CGTFile::getScanner () { delete theDFA; theDFA = new DFA (stateTable, symbolTable, characterSetTable, DFAInit, caseSensitive); return theDFA; } LALR *CGTFile::getParser () { delete theLALR; theLALR = new LALR (LALRTable, symbolTable, ruleTable, LALRInit); return theLALR; } void CGTFile::printInfo () { // Prints the info of this grammar wprintf (L"Grammar Information\n"); wprintf (L"Name: %s, ", gInfo->name); wprintf (L"%s\n", gInfo->version); wprintf (L"Author: %s\n", gInfo->author); wprintf (L"About: %s\n", gInfo->about); } <commit_msg>* Added Endian Conversion support. * Change some stream.gets to stream.reads.<commit_after>/*************************************************************************** CGTFile.cpp - Encapsulates the Compiled Grammar Table File read operations and structures. ------------------- begin : Fri May 31 00:53:11 CEST 2002 copyright : (C) 2002 by Manuel Astudillo email : d00mas@efd.lth.se ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include "CGTFile.h" #include "GrammarInfo.h" CGTFile::CGTFile () { gInfo = NULL; errorString = NULL; header = NULL; ruleTable = NULL; symbolTable = NULL; stateTable = NULL; LALRTable = NULL; characterSetTable = NULL; theDFA = NULL; theLALR = NULL; } CGTFile::~CGTFile () { delete gInfo; delete [] errorString; delete [] header; // Delete tables delete symbolTable; delete stateTable; delete LALRTable; delete ruleTable; delete characterSetTable; delete theDFA; delete theLALR; } bool CGTFile::load (char *filename) { ifstream cgtStream; cgtStream.open (filename, ifstream::in | ifstream::binary); if (cgtStream.bad()) { return false; } bool result = load (&cgtStream); cgtStream.close(); return result; } bool CGTFile::load (ifstream *myStream) { int i; EntryStruct entry; theStream = myStream; // Read Header ////////////// header = readUnicodeString(); // Read Records //////////////// unsigned char recordType; integer nbrEntries; integer index; while (!theStream->eof()) { // Read record type & number of entries theStream->read ((char*)&recordType, 1); if (theStream->fail()) { if (theStream->eof()) { break; } else { return false; } } theStream->read ((char*) &nbrEntries, 2); //Convert to little endian if needed. nbrEntries = EndianConversion(nbrEntries); //wprintf (L"Record Type: %i\n", recordType); //wprintf (L"Entries: %i\n", nbrEntries); if (recordType != 77) { errorString = "Record type is not supported\n"; return false; } // Read the type of content byte contentType; readEntry (&entry); contentType = entry.vByte; //wprintf (L"Content Type: %d\n", contentType); switch (contentType) { // Parameters Record case 'P': delete gInfo; gInfo = new GrammarInfo (); // read name readEntry (&entry); gInfo->name = entry.vString; // read version readEntry (&entry); gInfo->version = entry.vString; // read Author readEntry (&entry); gInfo->author = entry.vString; // read About readEntry (&entry); gInfo->about = entry.vString; // Case readEntry (&entry); caseSensitive = entry.vBool; // start symbol readEntry (&entry); startSymbol = entry.vInteger; break; // Table Counts case 'T' : readEntry (&entry); nbrSymbolTable = entry.vInteger; // Delete & Create a Symbol Table delete symbolTable; symbolTable = new SymbolTable (nbrSymbolTable); readEntry (&entry); nbrCharacterSets = entry.vInteger; // Delete & Create a Character Sets Table delete characterSetTable; characterSetTable = new CharacterSetTable (nbrCharacterSets); // Delete & Create a Rule Table readEntry (&entry); nbrRuleTable = entry.vInteger; delete ruleTable; ruleTable = new RuleTable (nbrRuleTable); // Delete & Create a DFAStateTable readEntry (&entry); nbrDFATable = entry.vInteger; delete stateTable; stateTable = new DFAStateTable (nbrDFATable); // Delete & Create a LALR Table readEntry (&entry); nbrLALRTable = entry.vInteger; delete LALRTable; LALRTable = new LALRStateTable (nbrLALRTable); break; // Character Set Table Entry case 'C' : readEntry (&entry); index = entry.vInteger; readEntry (&entry); characterSetTable->characters[index] = entry.vString; break; // Symbol Table Entry case 'S' : readEntry (&entry); index = entry.vInteger; readEntry (&entry); symbolTable->symbols[index].name = entry.vString; readEntry (&entry); symbolTable->symbols[index].kind = (SymbolType) entry.vInteger; break; // Rule case 'R' : readEntry (&entry); index = entry.vInteger; readEntry (&entry); ruleTable->rules[index].nonTerminal = entry.vInteger; // Read empty field readEntry (&entry); // Read symbols for this rule (nonTerminal -> symbol0 symbol1 ... symboln) for (i=0; i < nbrEntries-4; i++) { readEntry (&entry); // ruleTable->rules[index].symbols.push_back (entry.vInteger); RuleStruct *rst = &ruleTable->rules[index]; vector <integer> *s = &rst->symbols; s->push_back (entry.vInteger); } break; // Initial States case 'I' : readEntry(&entry); DFAInit = entry.vInteger; readEntry (&entry); LALRInit = entry.vInteger; break; // DFA State Entry case 'D': readEntry (&entry); index = entry.vInteger; // create a new State an insert it in the table readEntry (&entry); stateTable->states[index].accept = entry.vBool; readEntry(&entry); stateTable->states[index].acceptIndex = entry.vInteger; readEntry(&entry); Edge edge; for (i=0; i < nbrEntries-5; i+=3) { readEntry(&entry); edge.characterSetIndex = entry.vInteger; readEntry(&entry); edge.targetIndex = entry.vInteger; readEntry(&entry); stateTable->states[index].edges.push_back(edge); } break; // LALR State entry case 'L': readEntry(&entry); index = entry.vInteger; readEntry(&entry); Action action; for (i=0; i < nbrEntries-3; i+=4) { readEntry(&entry); action.symbolIndex = entry.vInteger; readEntry(&entry); action.action = entry.vInteger; readEntry(&entry); action.target = entry.vInteger; readEntry(&entry); LALRTable->states[index].actions.push_back(action); } break; } } return true; } /* Reads an entry in a record */ void CGTFile::readEntry (EntryStruct *entry) { char tmpChar; char dataType; theStream->get (dataType); if (theStream->fail()) { wprintf (L"Error reading entry\n"); } else { switch (dataType) { case 'E': break; case 'B': theStream->get (tmpChar); if (tmpChar) { entry->vBool = true; } else { entry->vBool = false; } break; case 'b': theStream->read ((char*) &entry->vByte, 1); break; case 'I': theStream->read ((char*) &entry->vInteger, 2); entry->vInteger = EndianConversion(entry->vInteger); break; case 'S': entry->vString = readUnicodeString(); break; } } } /* Reads a Unicode String */ wchar_t *CGTFile::readUnicodeString () { int i = 0; wchar_t readChar; wchar_t tmpString[512]; wchar_t *retString; char tmpChar1, tmpChar2; //theStream->get (tmpChar1); //theStream->get (tmpChar2); theStream->read(&tmpChar1, 1); theStream->read(&tmpChar2, 1); while ((tmpChar1 != 0) || (tmpChar2 != 0)) { readChar = (wchar_t) tmpChar2; readChar <<= 8; readChar |= tmpChar1; tmpString[i] = readChar; //theStream->get (tmpChar1); //theStream->get (tmpChar2); theStream->read(&tmpChar1,1); theStream->read(&tmpChar2,1); i++; } tmpString[i] = 0; retString = new wchar_t [wcslen (tmpString) + 1]; wcscpy (retString, tmpString); //wprintf(L"Header: %s", retString); return retString; } GrammarInfo *CGTFile::getInfo () { return gInfo; } DFA *CGTFile::getScanner () { delete theDFA; theDFA = new DFA (stateTable, symbolTable, characterSetTable, DFAInit, caseSensitive); return theDFA; } LALR *CGTFile::getParser () { delete theLALR; theLALR = new LALR (LALRTable, symbolTable, ruleTable, LALRInit); return theLALR; } void CGTFile::printInfo () { // Prints the info of this grammar wprintf (L"Grammar Information\n"); wprintf (L"Name: %s\n, ", gInfo->name); wprintf (L"%s\n", gInfo->version); wprintf (L"Author: %s\n", gInfo->author); wprintf (L"About: %s\n", gInfo->about); } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include <fstream> #include <signal.h> #include <cstdlib> #include <getopt.h> #include <string> #include "util/stackinfo.h" #include "util/debug.h" #include "util/interrupt.h" #include "util/script_state.h" #include "util/thread.h" #include "kernel/printer.h" #include "library/io_state.h" #include "library/kernel_bindings.h" #include "frontends/lean/parser.h" #include "frontends/lean/frontend.h" #include "frontends/lua/register_modules.h" #include "shell/lua_repl.h" #include "version.h" #include "githash.h" // NOLINT using lean::shell; using lean::frontend; using lean::parser; using lean::script_state; using lean::unreachable_reached; using lean::invoke_debugger; using lean::notify_assertion_violation; enum class input_kind { Unspecified, Lean, Lua }; static void on_ctrl_c(int ) { lean::request_interrupt(); } static void display_header(std::ostream & out) { out << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ", commit " << std::string(g_githash).substr(0, 12) << ")\n"; } static void display_help(std::ostream & out) { display_header(out); std::cout << "Input format:\n"; std::cout << " --lean use parser for Lean default input format for files,\n"; std::cout << " with unknown extension (default)\n"; std::cout << " --lua use Lua parser for files with unknown extension\n"; std::cout << "Miscellaneous:\n"; std::cout << " --help -h display this message\n"; std::cout << " --version -v display version number\n"; std::cout << " --githash display the git commit hash number used to build this binary\n"; std::cout << " --luahook=num -c how often the Lua interpreter checks the interrupted flag,\n"; std::cout << " it is useful for interrupting non-terminating user scripts,\n"; std::cout << " 0 means 'do not check'.\n"; #if defined(LEAN_USE_BOOST) std::cout << " --tstack=num -s thread stack size in Kb\n"; #endif } static char const * get_file_extension(char const * fname) { if (fname == 0) return 0; char const * last_dot = 0; while (true) { char const * tmp = strchr(fname, '.'); if (tmp == 0) { return last_dot; } last_dot = tmp + 1; fname = last_dot; } } static struct option g_long_options[] = { {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {"lean", no_argument, 0, 'l'}, {"lua", no_argument, 0, 'u'}, {"luahook", required_argument, 0, 'c'}, {"githash", no_argument, 0, 'g'}, #if defined(LEAN_USE_BOOST) {"tstack", required_argument, 0, 's'}, #endif {0, 0, 0, 0} }; int main(int argc, char ** argv) { lean::save_stack_info(); lean::register_modules(); input_kind default_k = input_kind::Lean; // default while (true) { int c = getopt_long(argc, argv, "lugvhc:012s:012", g_long_options, &optind); if (c == -1) break; // end of command line switch (c) { case 'v': display_header(std::cout); return 0; case 'g': std::cout << g_githash << "\n"; return 0; case 'h': display_help(std::cout); return 0; case 'l': default_k = input_kind::Lean; break; case 'u': default_k = input_kind::Lua; break; case 'c': script_state::set_check_interrupt_freq(atoi(optarg)); break; case 's': lean::set_thread_stack_size(atoi(optarg)*1024); break; default: std::cerr << "Unknown command line option\n"; display_help(std::cerr); return 1; } } if (optind >= argc) { display_header(std::cout); signal(SIGINT, on_ctrl_c); if (default_k == input_kind::Lean) { #if defined(LEAN_WINDOWS) std::cout << "Type 'Exit.' to exit or 'Help.' for help."<< std::endl; #else std::cout << "Type Ctrl-D or 'Exit.' to exit or 'Help.' for help."<< std::endl; #endif frontend f; script_state S; shell sh(f, &S); return sh() ? 0 : 1; } else { lean_assert(default_k == input_kind::Lua); script_state S; S.dostring(g_lua_repl); } } else { frontend f; script_state S; bool ok = true; for (int i = optind; i < argc; i++) { char const * ext = get_file_extension(argv[i]); input_kind k = default_k; if (ext) { if (strcmp(ext, "lean") == 0) { k = input_kind::Lean; } else if (strcmp(ext, "lua") == 0) { k = input_kind::Lua; } } if (k == input_kind::Lean) { std::ifstream in(argv[i]); if (in.bad() || in.fail()) { std::cerr << "Failed to open file '" << argv[i] << "'\n"; return 1; } parser p(f, in, &S, false, false); if (!p()) ok = false; } else if (k == input_kind::Lua) { try { S.dofile(argv[i]); } catch (lean::exception & ex) { std::cerr << ex.what() << std::endl; ok = false; } } else { lean_unreachable(); // LCOV_EXCL_LINE } } return ok ? 0 : 1; } } <commit_msg>fix(shell/lean.cpp): fix not to overwrite optind by getopt_long<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include <fstream> #include <signal.h> #include <cstdlib> #include <getopt.h> #include <string> #include "util/stackinfo.h" #include "util/debug.h" #include "util/interrupt.h" #include "util/script_state.h" #include "util/thread.h" #include "kernel/printer.h" #include "library/io_state.h" #include "library/kernel_bindings.h" #include "frontends/lean/parser.h" #include "frontends/lean/frontend.h" #include "frontends/lua/register_modules.h" #include "shell/lua_repl.h" #include "version.h" #include "githash.h" // NOLINT using lean::shell; using lean::frontend; using lean::parser; using lean::script_state; using lean::unreachable_reached; using lean::invoke_debugger; using lean::notify_assertion_violation; enum class input_kind { Unspecified, Lean, Lua }; static void on_ctrl_c(int ) { lean::request_interrupt(); } static void display_header(std::ostream & out) { out << "Lean (version " << LEAN_VERSION_MAJOR << "." << LEAN_VERSION_MINOR << ", commit " << std::string(g_githash).substr(0, 12) << ")\n"; } static void display_help(std::ostream & out) { display_header(out); std::cout << "Input format:\n"; std::cout << " --lean use parser for Lean default input format for files,\n"; std::cout << " with unknown extension (default)\n"; std::cout << " --lua use Lua parser for files with unknown extension\n"; std::cout << "Miscellaneous:\n"; std::cout << " --help -h display this message\n"; std::cout << " --version -v display version number\n"; std::cout << " --githash display the git commit hash number used to build this binary\n"; std::cout << " --luahook=num -c how often the Lua interpreter checks the interrupted flag,\n"; std::cout << " it is useful for interrupting non-terminating user scripts,\n"; std::cout << " 0 means 'do not check'.\n"; #if defined(LEAN_USE_BOOST) std::cout << " --tstack=num -s thread stack size in Kb\n"; #endif } static char const * get_file_extension(char const * fname) { if (fname == 0) return 0; char const * last_dot = 0; while (true) { char const * tmp = strchr(fname, '.'); if (tmp == 0) { return last_dot; } last_dot = tmp + 1; fname = last_dot; } } static struct option g_long_options[] = { {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {"lean", no_argument, 0, 'l'}, {"lua", no_argument, 0, 'u'}, {"luahook", required_argument, 0, 'c'}, {"githash", no_argument, 0, 'g'}, #if defined(LEAN_USE_BOOST) {"tstack", required_argument, 0, 's'}, #endif {0, 0, 0, 0} }; int main(int argc, char ** argv) { lean::save_stack_info(); lean::register_modules(); input_kind default_k = input_kind::Lean; // default while (true) { int c = getopt_long(argc, argv, "lugvhc:012s:012", g_long_options, NULL); if (c == -1) break; // end of command line switch (c) { case 'v': display_header(std::cout); return 0; case 'g': std::cout << g_githash << "\n"; return 0; case 'h': display_help(std::cout); return 0; case 'l': default_k = input_kind::Lean; break; case 'u': default_k = input_kind::Lua; break; case 'c': script_state::set_check_interrupt_freq(atoi(optarg)); break; case 's': lean::set_thread_stack_size(atoi(optarg)*1024); break; default: std::cerr << "Unknown command line option\n"; display_help(std::cerr); return 1; } } if (optind >= argc) { display_header(std::cout); signal(SIGINT, on_ctrl_c); if (default_k == input_kind::Lean) { #if defined(LEAN_WINDOWS) std::cout << "Type 'Exit.' to exit or 'Help.' for help."<< std::endl; #else std::cout << "Type Ctrl-D or 'Exit.' to exit or 'Help.' for help."<< std::endl; #endif frontend f; script_state S; shell sh(f, &S); return sh() ? 0 : 1; } else { lean_assert(default_k == input_kind::Lua); script_state S; S.dostring(g_lua_repl); } } else { frontend f; script_state S; bool ok = true; for (int i = optind; i < argc; i++) { char const * ext = get_file_extension(argv[i]); input_kind k = default_k; if (ext) { if (strcmp(ext, "lean") == 0) { k = input_kind::Lean; } else if (strcmp(ext, "lua") == 0) { k = input_kind::Lua; } } if (k == input_kind::Lean) { std::ifstream in(argv[i]); if (in.bad() || in.fail()) { std::cerr << "Failed to open file '" << argv[i] << "'\n"; return 1; } parser p(f, in, &S, false, false); if (!p()) ok = false; } else if (k == input_kind::Lua) { try { S.dofile(argv[i]); } catch (lean::exception & ex) { std::cerr << ex.what() << std::endl; ok = false; } } else { lean_unreachable(); // LCOV_EXCL_LINE } } return ok ? 0 : 1; } } <|endoftext|>
<commit_before>// Copyright 2017 The Johns Hopkins University Applied Physics Laboratory. // Licensed under the MIT License. See LICENSE.txt in the project root for full license information. #include <cstdio> #include <ctime> #include "orthoimage.h" #include "shr3d.h" // Print command line arguments. void printArguments() { printf("Command line arguments: <Input File (LAS|TIF)> <Options>\n"); printf("Required Options:\n"); printf(" DH= horizontal uncertainty (meters)\n"); printf(" DZ= vertical uncertainty (meters)\n"); printf(" AGL= minimum building height above ground level (meters)\n"); printf("Options:\n"); printf(" AREA= minimum building area (meters)\n"); printf(" EGM96 set this flag to write vertical datum = EGM96\n"); printf(" FOPEN set this flag for ground detection under dense foliage\n"); printf("Examples:\n"); printf(" For EO DSM: shr3d dsm.tif DH=5.0 DZ=1.0 AGL=2 AREA=50.0 EGM96\n"); printf(" For lidar DSM: shr3d dsm.tif DH=1.0 DZ=1.0 AGL=2.0 AREA=50.0\n"); printf(" For lidar LAS: shr3d pts.las DH=1.0 DZ=1.0 AGL=2.0 AREA=50.0\n"); } // Main program for bare earth classification. int main(int argc, char **argv) { // If no parameters, then print command line arguments. if (argc < 4) { printf("Number of arguments = %d\n", argc); for (int i = 0; i < argc; i++) { printf("ARG[%d] = %s\n", i, argv[i]); } printArguments(); return -1; } // Get command line arguments and confirm they are valid. double gsd_meters = 0.0; double dh_meters = 0.0; double dz_meters = 0.0; double agl_meters = 0.0; double min_area_meters = 50.0; bool egm96 = false; bool convert = false; char inputFileName[1024]; sprintf(inputFileName, argv[1]); for (int i = 2; i < argc; i++) { if (strstr(argv[i], "DH=")) { dh_meters = atof(&(argv[i][3])); } if (strstr(argv[i], "DZ=")) { dz_meters = atof(&(argv[i][3])); } if (strstr(argv[i], "AGL=")) { agl_meters = atof(&(argv[i][4])); } if (strstr(argv[i], "AREA=")) { min_area_meters = atof(&(argv[i][5])); } if (strstr(argv[i], "EGM96")) { egm96 = true; } if (strstr(argv[i], "CONVERT")) { convert = true; } } if ((dh_meters == 0.0) || (dz_meters == 0.0) || (agl_meters == 0.0)) { printf("DH_METERS = %f\n", dh_meters); printf("DZ_METERS = %f\n", dz_meters); printf("AGL_METERS = %f\n", agl_meters); printf("Error: All three values must be nonzero.\n"); printArguments(); return -1; } // Initialize the timer. time_t t0; time(&t0); // If specified, then convert to GDAL TIFF. char readFileName[1024]; strcpy(readFileName, inputFileName); if (convert) { char cmd[4096]; sprintf(readFileName, "temp.tif\0"); sprintf(cmd, ".\\gdal\\gdal_translate %s temp.tif\n", inputFileName); system(cmd); } // Read DSM as SHORT. // Input can be GeoTIFF or LAS. shr3d::OrthoImage<unsigned short> dsmImage; shr3d::OrthoImage<unsigned short> minImage; printf("Reading DSM as SHORT.\n"); int len = (int) strlen(inputFileName); char *ext = &inputFileName[len - 3]; printf("File Type = .%s\n", ext); if (strcmp(ext, "tif") == 0) { bool ok = dsmImage.read(readFileName); if (!ok) return -1; } else if ((strcmp(ext, "las") == 0) || (strcmp(ext, "bpf") == 0)) { // First get the max Z values for the DSM. bool ok = dsmImage.readFromPointCloud(inputFileName, (float) dh_meters, shr3d::MAX_VALUE); if (!ok) return -1; // Median filter, replacing only points differing by more than the AGL threshold. dsmImage.medianFilter(1, (unsigned int) (agl_meters / dsmImage.scale)); // Fill small voids in the DSM. dsmImage.fillVoidsPyramid(true, 2); // Write the DSM image as FLOAT. char dsmOutFileName[1024]; sprintf(dsmOutFileName, "%s_DSM.tif\0", inputFileName); dsmImage.write(dsmOutFileName, true); // Now get the minimum Z values for the DTM. ok = minImage.readFromPointCloud(inputFileName, (float) dh_meters, shr3d::MIN_VALUE); if (!ok) return -1; // Median filter, replacing only points differing by more than the AGL threshold. minImage.medianFilter(1, (unsigned int) (agl_meters / minImage.scale)); // Fill small voids in the DSM. minImage.fillVoidsPyramid(true, 2); #ifdef DEBUG // Write the MIN image as FLOAT. char minOutFileName[1024]; sprintf(minOutFileName, "%s_MIN.tif\0", inputFileName); minImage.write(minOutFileName, true); #endif // Find many of the trees by comparing MIN and MAX. Set their values to void. for (int j = 0; j < dsmImage.height; j++) { for (int i = 0; i < dsmImage.width; i++) { float minValue = (float) minImage.data[j][i]; // This check is to avoid penalizing spurious returns under very tall buildings. // CAUTION: This is a hack to address an observed lidar sensor issue and may not generalize well. if (((float) dsmImage.data[j][i] - minValue) < (40.0 / minImage.scale)) { // If this is in the trees, then set to void. bool found = false; double threshold = dz_meters / dsmImage.scale; int i1 = MAX(0, i - 1); int i2 = MIN(i + 1, dsmImage.width - 1); int j1 = MAX(0, j - 1); int j2 = MIN(j + 1, dsmImage.height - 1); for (int jj = j1; jj <= j2; jj++) { for (int ii = i1; ii <= i2; ii++) { float diff = (float) dsmImage.data[jj][ii] - minValue; if (diff < threshold) found = true; } } if (!found) dsmImage.data[j][i] = 0; } } } // Write the DSM2 image as FLOAT. #ifdef DEBUG char dsm2OutFileName[1024]; sprintf(dsm2OutFileName, "%s_DSM2.tif\0", inputFileName); dsmImage.write(dsm2OutFileName, true); #endif } else { printf("Error: Unrecognized file type."); return -1; } // Convert horizontal and vertical uncertainty values to bin units. int dh_bins = MAX(1, (int) floor(dh_meters / dsmImage.gsd)); printf("DZ_METERS = %f\n", dz_meters); printf("DH_METERS = %f\n", dh_meters); printf("DH_BINS = %d\n", dh_bins); unsigned int dz_short = (unsigned int) (dz_meters / dsmImage.scale); printf("DZ_SHORT = %d\n", dz_short); printf("AGL_METERS = %f\n", agl_meters); unsigned int agl_short = (unsigned int) (agl_meters / dsmImage.scale); printf("AGL_SHORT = %d\n", agl_short); printf("AREA_METERS = %f\n", min_area_meters); // Generate label image. shr3d::OrthoImage<unsigned long> labelImage; labelImage.Allocate(dsmImage.width, dsmImage.height); labelImage.easting = dsmImage.easting; labelImage.northing = dsmImage.northing; labelImage.zone = dsmImage.zone; labelImage.gsd = dsmImage.gsd; // Allocate a DTM image as SHORT and copy in the DSM values. shr3d::OrthoImage<unsigned short> dtmImage; dtmImage.Allocate(dsmImage.width, dsmImage.height); dtmImage.easting = dsmImage.easting; dtmImage.northing = dsmImage.northing; dtmImage.zone = dsmImage.zone; dtmImage.gsd = dsmImage.gsd; dtmImage.scale = dsmImage.scale; dtmImage.offset = dsmImage.offset; dtmImage.bands = dsmImage.bands; for (int j = 0; j < dsmImage.height; j++) { for (int i = 0; i < dsmImage.width; i++) { dtmImage.data[j][i] = minImage.data[j][i]; } } // Classify ground points. shr3d::Shr3dder::classifyGround(labelImage, dsmImage, dtmImage, dh_bins, dz_short); // For DSM voids, also set DTM value to void. printf("Setting DTM values to VOID where DSM is VOID...\n"); for (int j = 0; j < dsmImage.height; j++) { for (int i = 0; i < dsmImage.width; i++) { if (dsmImage.data[j][i] == 0) dtmImage.data[j][i] = 0; } } // Median filter, replacing only points differing by more than the DZ threshold. dtmImage.medianFilter(1, (unsigned int) (dz_meters / dsmImage.scale)); // Refine the object label image and export building outlines. shr3d::Shr3dder::classifyNonGround(dsmImage, dtmImage, labelImage, dz_short, agl_short, (float) min_area_meters); // Fill small voids in the DTM after all processing is complete. dtmImage.fillVoidsPyramid(true, 2); // Write the DTM image as FLOAT. char dtmOutFileName[1024]; sprintf(dtmOutFileName, "%s_DTM.tif\0", inputFileName); dtmImage.write(dtmOutFileName, true, egm96); // Produce a classification raster image with LAS standard point classes. shr3d::OrthoImage<unsigned char> classImage; classImage.Allocate(labelImage.width, labelImage.height); classImage.easting = dsmImage.easting; classImage.northing = dsmImage.northing; classImage.zone = dsmImage.zone; classImage.gsd = dsmImage.gsd; for (int j = 0; j < classImage.height; j++) { for (int i = 0; i < classImage.width; i++) { // Set default as unlabeled. classImage.data[j][i] = LAS_UNCLASSIFIED; // Label trees. if ((dsmImage.data[j][i] == 0) || (fabs((float) dsmImage.data[j][i] - (float) dtmImage.data[j][i]) > agl_short)) classImage.data[j][i] = LAS_TREE; // Label buildings. if (labelImage.data[j][i] == 1) classImage.data[j][i] = LAS_BUILDING; // Label ground. if (fabs((float) dsmImage.data[j][i] - (float) dtmImage.data[j][i]) < dz_short) classImage.data[j][i] = LAS_GROUND; } } // Fill missing labels inside building regions. shr3d::Shr3dder::fillInsideBuildings(classImage); // Write the classification image. char classOutFileName[1024]; sprintf(classOutFileName, "%s_class.tif\0", inputFileName); classImage.write(classOutFileName, false, egm96); for (int j = 0; j < classImage.height; j++) { for (int i = 0; i < classImage.width; i++) { if (classImage.data[j][i] != LAS_BUILDING) classImage.data[j][i] = 0; } } sprintf(classOutFileName, "%s_buildings.tif\0", inputFileName); classImage.write(classOutFileName, false, egm96); // Report total elapsed time. time_t t1; time(&t1); printf("Total time elapsed = %f seconds\n", double(t1 - t0)); } <commit_msg>FOPEN is not used anywhere in the code and can be removed<commit_after>// Copyright 2017 The Johns Hopkins University Applied Physics Laboratory. // Licensed under the MIT License. See LICENSE.txt in the project root for full license information. #include <cstdio> #include <ctime> #include "orthoimage.h" #include "shr3d.h" // Print command line arguments. void printArguments() { printf("Command line arguments: <Input File (LAS|TIF)> <Options>\n"); printf("Required Options:\n"); printf(" DH= horizontal uncertainty (meters)\n"); printf(" DZ= vertical uncertainty (meters)\n"); printf(" AGL= minimum building height above ground level (meters)\n"); printf("Options:\n"); printf(" AREA= minimum building area (meters)\n"); printf(" EGM96 set this flag to write vertical datum = EGM96\n"); printf("Examples:\n"); printf(" For EO DSM: shr3d dsm.tif DH=5.0 DZ=1.0 AGL=2 AREA=50.0 EGM96\n"); printf(" For lidar DSM: shr3d dsm.tif DH=1.0 DZ=1.0 AGL=2.0 AREA=50.0\n"); printf(" For lidar LAS: shr3d pts.las DH=1.0 DZ=1.0 AGL=2.0 AREA=50.0\n"); } // Main program for bare earth classification. int main(int argc, char **argv) { // If no parameters, then print command line arguments. if (argc < 4) { printf("Number of arguments = %d\n", argc); for (int i = 0; i < argc; i++) { printf("ARG[%d] = %s\n", i, argv[i]); } printArguments(); return -1; } // Get command line arguments and confirm they are valid. double gsd_meters = 0.0; double dh_meters = 0.0; double dz_meters = 0.0; double agl_meters = 0.0; double min_area_meters = 50.0; bool egm96 = false; bool convert = false; char inputFileName[1024]; sprintf(inputFileName, argv[1]); for (int i = 2; i < argc; i++) { if (strstr(argv[i], "DH=")) { dh_meters = atof(&(argv[i][3])); } if (strstr(argv[i], "DZ=")) { dz_meters = atof(&(argv[i][3])); } if (strstr(argv[i], "AGL=")) { agl_meters = atof(&(argv[i][4])); } if (strstr(argv[i], "AREA=")) { min_area_meters = atof(&(argv[i][5])); } if (strstr(argv[i], "EGM96")) { egm96 = true; } if (strstr(argv[i], "CONVERT")) { convert = true; } } if ((dh_meters == 0.0) || (dz_meters == 0.0) || (agl_meters == 0.0)) { printf("DH_METERS = %f\n", dh_meters); printf("DZ_METERS = %f\n", dz_meters); printf("AGL_METERS = %f\n", agl_meters); printf("Error: All three values must be nonzero.\n"); printArguments(); return -1; } // Initialize the timer. time_t t0; time(&t0); // If specified, then convert to GDAL TIFF. char readFileName[1024]; strcpy(readFileName, inputFileName); if (convert) { char cmd[4096]; sprintf(readFileName, "temp.tif\0"); sprintf(cmd, ".\\gdal\\gdal_translate %s temp.tif\n", inputFileName); system(cmd); } // Read DSM as SHORT. // Input can be GeoTIFF or LAS. shr3d::OrthoImage<unsigned short> dsmImage; shr3d::OrthoImage<unsigned short> minImage; printf("Reading DSM as SHORT.\n"); int len = (int) strlen(inputFileName); char *ext = &inputFileName[len - 3]; printf("File Type = .%s\n", ext); if (strcmp(ext, "tif") == 0) { bool ok = dsmImage.read(readFileName); if (!ok) return -1; } else if ((strcmp(ext, "las") == 0) || (strcmp(ext, "bpf") == 0)) { // First get the max Z values for the DSM. bool ok = dsmImage.readFromPointCloud(inputFileName, (float) dh_meters, shr3d::MAX_VALUE); if (!ok) return -1; // Median filter, replacing only points differing by more than the AGL threshold. dsmImage.medianFilter(1, (unsigned int) (agl_meters / dsmImage.scale)); // Fill small voids in the DSM. dsmImage.fillVoidsPyramid(true, 2); // Write the DSM image as FLOAT. char dsmOutFileName[1024]; sprintf(dsmOutFileName, "%s_DSM.tif\0", inputFileName); dsmImage.write(dsmOutFileName, true); // Now get the minimum Z values for the DTM. ok = minImage.readFromPointCloud(inputFileName, (float) dh_meters, shr3d::MIN_VALUE); if (!ok) return -1; // Median filter, replacing only points differing by more than the AGL threshold. minImage.medianFilter(1, (unsigned int) (agl_meters / minImage.scale)); // Fill small voids in the DSM. minImage.fillVoidsPyramid(true, 2); #ifdef DEBUG // Write the MIN image as FLOAT. char minOutFileName[1024]; sprintf(minOutFileName, "%s_MIN.tif\0", inputFileName); minImage.write(minOutFileName, true); #endif // Find many of the trees by comparing MIN and MAX. Set their values to void. for (int j = 0; j < dsmImage.height; j++) { for (int i = 0; i < dsmImage.width; i++) { float minValue = (float) minImage.data[j][i]; // This check is to avoid penalizing spurious returns under very tall buildings. // CAUTION: This is a hack to address an observed lidar sensor issue and may not generalize well. if (((float) dsmImage.data[j][i] - minValue) < (40.0 / minImage.scale)) { // If this is in the trees, then set to void. bool found = false; double threshold = dz_meters / dsmImage.scale; int i1 = MAX(0, i - 1); int i2 = MIN(i + 1, dsmImage.width - 1); int j1 = MAX(0, j - 1); int j2 = MIN(j + 1, dsmImage.height - 1); for (int jj = j1; jj <= j2; jj++) { for (int ii = i1; ii <= i2; ii++) { float diff = (float) dsmImage.data[jj][ii] - minValue; if (diff < threshold) found = true; } } if (!found) dsmImage.data[j][i] = 0; } } } // Write the DSM2 image as FLOAT. #ifdef DEBUG char dsm2OutFileName[1024]; sprintf(dsm2OutFileName, "%s_DSM2.tif\0", inputFileName); dsmImage.write(dsm2OutFileName, true); #endif } else { printf("Error: Unrecognized file type."); return -1; } // Convert horizontal and vertical uncertainty values to bin units. int dh_bins = MAX(1, (int) floor(dh_meters / dsmImage.gsd)); printf("DZ_METERS = %f\n", dz_meters); printf("DH_METERS = %f\n", dh_meters); printf("DH_BINS = %d\n", dh_bins); unsigned int dz_short = (unsigned int) (dz_meters / dsmImage.scale); printf("DZ_SHORT = %d\n", dz_short); printf("AGL_METERS = %f\n", agl_meters); unsigned int agl_short = (unsigned int) (agl_meters / dsmImage.scale); printf("AGL_SHORT = %d\n", agl_short); printf("AREA_METERS = %f\n", min_area_meters); // Generate label image. shr3d::OrthoImage<unsigned long> labelImage; labelImage.Allocate(dsmImage.width, dsmImage.height); labelImage.easting = dsmImage.easting; labelImage.northing = dsmImage.northing; labelImage.zone = dsmImage.zone; labelImage.gsd = dsmImage.gsd; // Allocate a DTM image as SHORT and copy in the DSM values. shr3d::OrthoImage<unsigned short> dtmImage; dtmImage.Allocate(dsmImage.width, dsmImage.height); dtmImage.easting = dsmImage.easting; dtmImage.northing = dsmImage.northing; dtmImage.zone = dsmImage.zone; dtmImage.gsd = dsmImage.gsd; dtmImage.scale = dsmImage.scale; dtmImage.offset = dsmImage.offset; dtmImage.bands = dsmImage.bands; for (int j = 0; j < dsmImage.height; j++) { for (int i = 0; i < dsmImage.width; i++) { dtmImage.data[j][i] = minImage.data[j][i]; } } // Classify ground points. shr3d::Shr3dder::classifyGround(labelImage, dsmImage, dtmImage, dh_bins, dz_short); // For DSM voids, also set DTM value to void. printf("Setting DTM values to VOID where DSM is VOID...\n"); for (int j = 0; j < dsmImage.height; j++) { for (int i = 0; i < dsmImage.width; i++) { if (dsmImage.data[j][i] == 0) dtmImage.data[j][i] = 0; } } // Median filter, replacing only points differing by more than the DZ threshold. dtmImage.medianFilter(1, (unsigned int) (dz_meters / dsmImage.scale)); // Refine the object label image and export building outlines. shr3d::Shr3dder::classifyNonGround(dsmImage, dtmImage, labelImage, dz_short, agl_short, (float) min_area_meters); // Fill small voids in the DTM after all processing is complete. dtmImage.fillVoidsPyramid(true, 2); // Write the DTM image as FLOAT. char dtmOutFileName[1024]; sprintf(dtmOutFileName, "%s_DTM.tif\0", inputFileName); dtmImage.write(dtmOutFileName, true, egm96); // Produce a classification raster image with LAS standard point classes. shr3d::OrthoImage<unsigned char> classImage; classImage.Allocate(labelImage.width, labelImage.height); classImage.easting = dsmImage.easting; classImage.northing = dsmImage.northing; classImage.zone = dsmImage.zone; classImage.gsd = dsmImage.gsd; for (int j = 0; j < classImage.height; j++) { for (int i = 0; i < classImage.width; i++) { // Set default as unlabeled. classImage.data[j][i] = LAS_UNCLASSIFIED; // Label trees. if ((dsmImage.data[j][i] == 0) || (fabs((float) dsmImage.data[j][i] - (float) dtmImage.data[j][i]) > agl_short)) classImage.data[j][i] = LAS_TREE; // Label buildings. if (labelImage.data[j][i] == 1) classImage.data[j][i] = LAS_BUILDING; // Label ground. if (fabs((float) dsmImage.data[j][i] - (float) dtmImage.data[j][i]) < dz_short) classImage.data[j][i] = LAS_GROUND; } } // Fill missing labels inside building regions. shr3d::Shr3dder::fillInsideBuildings(classImage); // Write the classification image. char classOutFileName[1024]; sprintf(classOutFileName, "%s_class.tif\0", inputFileName); classImage.write(classOutFileName, false, egm96); for (int j = 0; j < classImage.height; j++) { for (int i = 0; i < classImage.width; i++) { if (classImage.data[j][i] != LAS_BUILDING) classImage.data[j][i] = 0; } } sprintf(classOutFileName, "%s_buildings.tif\0", inputFileName); classImage.write(classOutFileName, false, egm96); // Report total elapsed time. time_t t1; time(&t1); printf("Total time elapsed = %f seconds\n", double(t1 - t0)); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "AVT.hpp" #include <algorithm> #include <Include/STLHelper.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <PlatformSupport/StringTokenizer.hpp> #include <PlatformSupport/XalanUnicode.hpp> #include <DOMSupport/DOMServices.hpp> #include "AVTPartSimple.hpp" #include "AVTPartXPath.hpp" #include "StylesheetConstructionContext.hpp" static const XalanDOMChar theTokenDelimiterCharacters[] = { XalanUnicode::charLeftCurlyBracket, XalanUnicode::charRightCurlyBracket, XalanUnicode::charApostrophe, XalanUnicode::charQuoteMark, 0 }; static const XalanDOMChar theLeftCurlyBracketString[] = { XalanUnicode::charLeftCurlyBracket, 0 }; static const XalanDOMChar theRightCurlyBracketString[] = { XalanUnicode::charRightCurlyBracket, 0 }; /** * Construct an AVT by parsing the string, and either * constructing a vector of AVTParts, or simply hold * on to the string if the AVT is simple. */ AVT::AVT( const XalanDOMChar* name, const XalanDOMChar* type, const XalanDOMChar* stringedValue, const PrefixResolver& resolver, StylesheetConstructionContext& constructionContext) : m_parts(), m_simpleString(), // $$$ ToDo: Explicit XalanDOMString constructor m_name(XalanDOMString(name)), m_prefix(getPrefix(name)), m_pcType(type) { StringTokenizer tokenizer(stringedValue, theTokenDelimiterCharacters, true); const unsigned int nTokens = tokenizer.countTokens(); if(nTokens < 2) { m_simpleString = stringedValue; // then do the simple thing } else { m_parts.reserve(nTokens + 1); XalanDOMString buffer; XalanDOMString exprBuffer; XalanDOMString t; // base token XalanDOMString lookahead; // next token XalanDOMString error; // if non-null, break from loop while(tokenizer.hasMoreTokens()) { if(length(lookahead)) { t = lookahead; clear(lookahead); } else { t = tokenizer.nextToken(); } if(length(t) == 1) { const XalanDOMChar theChar = charAt(t, 0); switch(theChar) { case(XalanUnicode::charLeftCurlyBracket): { // Attribute Value Template start lookahead = tokenizer.nextToken(); if(equals(lookahead, theLeftCurlyBracketString)) { // Double curlys mean escape to show curly append(buffer, lookahead); clear(lookahead); break; // from switch } else { if(length(buffer) > 0) { m_parts.push_back(new AVTPartSimple(buffer)); clear(buffer); } clear(exprBuffer); while(length(lookahead) > 0 && !equals(lookahead, theRightCurlyBracketString)) { if(length(lookahead) == 1) { switch(charAt(lookahead, 0)) { case XalanUnicode::charApostrophe: case XalanUnicode::charQuoteMark: { // String start append(exprBuffer, lookahead); const XalanDOMString quote = lookahead; // Consume stuff 'till next quote lookahead = tokenizer.nextToken(); while(!equals(lookahead, quote)) { append(exprBuffer, lookahead); lookahead = tokenizer.nextToken(); } append(exprBuffer,lookahead); break; } case XalanUnicode::charLeftCurlyBracket: { // What's another curly doing here? error = TranscodeFromLocalCodePage("Error: Can not have \"{\" within expression."); break; } default: { // part of the template stuff, just add it. append(exprBuffer, lookahead); } } // end inner switch } // end if lookahead length == 1 else { // part of the template stuff, just add it. append(exprBuffer,lookahead); } lookahead = tokenizer.nextToken(); } // end while(!equals(lookahead, "}")) assert(equals(lookahead, theRightCurlyBracketString)); // Proper close of attribute template. Evaluate the // expression. clear(buffer); const XPath* const xpath = constructionContext.createXPath(exprBuffer, resolver); assert(xpath != 0); m_parts.push_back(new AVTPartXPath(xpath)); clear(lookahead); // breaks out of inner while loop if(length(error) > 0) { break; // from inner while loop } } break; } case(XalanUnicode::charRightCurlyBracket): { lookahead = tokenizer.nextToken(); if(equals(lookahead, theRightCurlyBracketString)) { // Double curlys mean escape to show curly append(buffer, lookahead); clear(lookahead); // swallow } else { // Illegal, I think... constructionContext.warn("Found \"}\" but no attribute template open!"); append(buffer, theRightCurlyBracketString); // leave the lookahead to be processed by the next round. } break; } default: { const XalanDOMString s(&theChar, 1); // Anything else just add to string. append(buffer, s); } } // end switch t } // end if length == 1 else { // Anything else just add to string. append(buffer,t); } if(length(error) > 0) { constructionContext.warn("Attr Template, " + error); break; } } // end while(tokenizer.hasMoreTokens()) if(length(buffer) > 0) { m_parts.push_back(new AVTPartSimple(buffer)); clear(buffer); } } // end else nTokens > 1 if(m_parts.empty() && length(m_simpleString) == 0) { // Error? clear(m_simpleString); } else if (m_parts.size() < m_parts.capacity()) { AVTPartPtrVectorType(m_parts).swap(m_parts); } } AVT::~AVT() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Clean up all entries in the vector. for_each(m_parts.begin(), m_parts.end(), DeleteFunctor<AVTPart>()); } void AVT::evaluate( XalanDOMString& buf, XalanNode* contextNode, const PrefixResolver& prefixResolver, XPathExecutionContext& executionContext) const { if(length(m_simpleString) > 0) { buf = m_simpleString; } else { clear(buf); if(m_parts.empty() == false) { const AVTPartPtrVectorType::size_type n = m_parts.size(); for(AVTPartPtrVectorType::size_type i = 0; i < n; i++) { assert(m_parts[i] != 0); m_parts[i]->evaluate(buf, contextNode, prefixResolver, executionContext); } } } } XalanDOMString AVT::getPrefix(const XalanDOMChar* theName) { if (startsWith(theName, DOMServices::s_XMLNamespaceWithSeparator) == true) { return substring(theName, DOMServices::s_XMLNamespaceWithSeparatorLength); } else { return XalanDOMString(); } } <commit_msg>Use new StringTokenizer overload.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "AVT.hpp" #include <algorithm> #include <Include/STLHelper.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <PlatformSupport/StringTokenizer.hpp> #include <PlatformSupport/XalanUnicode.hpp> #include <DOMSupport/DOMServices.hpp> #include "AVTPartSimple.hpp" #include "AVTPartXPath.hpp" #include "StylesheetConstructionContext.hpp" static const XalanDOMChar theTokenDelimiterCharacters[] = { XalanUnicode::charLeftCurlyBracket, XalanUnicode::charRightCurlyBracket, XalanUnicode::charApostrophe, XalanUnicode::charQuoteMark, 0 }; static const XalanDOMChar theLeftCurlyBracketString[] = { XalanUnicode::charLeftCurlyBracket, 0 }; static const XalanDOMChar theRightCurlyBracketString[] = { XalanUnicode::charRightCurlyBracket, 0 }; /** * Construct an AVT by parsing the string, and either * constructing a vector of AVTParts, or simply hold * on to the string if the AVT is simple. */ AVT::AVT( const XalanDOMChar* name, const XalanDOMChar* type, const XalanDOMChar* stringedValue, const PrefixResolver& resolver, StylesheetConstructionContext& constructionContext) : m_parts(), m_simpleString(), // $$$ ToDo: Explicit XalanDOMString constructor m_name(XalanDOMString(name)), m_prefix(getPrefix(name)), m_pcType(type) { StringTokenizer tokenizer(stringedValue, theTokenDelimiterCharacters, true); const unsigned int nTokens = tokenizer.countTokens(); if(nTokens < 2) { m_simpleString = stringedValue; // then do the simple thing } else { m_parts.reserve(nTokens + 1); XalanDOMString buffer; XalanDOMString exprBuffer; XalanDOMString t; // base token XalanDOMString lookahead; // next token XalanDOMString error; // if non-null, break from loop while(tokenizer.hasMoreTokens()) { if(length(lookahead)) { t = lookahead; clear(lookahead); } else { tokenizer.nextToken(t); } if(length(t) == 1) { const XalanDOMChar theChar = charAt(t, 0); switch(theChar) { case(XalanUnicode::charLeftCurlyBracket): { // Attribute Value Template start tokenizer.nextToken(lookahead); if(equals(lookahead, theLeftCurlyBracketString)) { // Double curlys mean escape to show curly append(buffer, lookahead); clear(lookahead); break; // from switch } else { if(length(buffer) > 0) { m_parts.push_back(new AVTPartSimple(buffer)); clear(buffer); } clear(exprBuffer); while(length(lookahead) > 0 && !equals(lookahead, theRightCurlyBracketString)) { if(length(lookahead) == 1) { switch(charAt(lookahead, 0)) { case XalanUnicode::charApostrophe: case XalanUnicode::charQuoteMark: { // String start append(exprBuffer, lookahead); const XalanDOMString quote = lookahead; // Consume stuff 'till next quote tokenizer.nextToken(lookahead); while(!equals(lookahead, quote)) { append(exprBuffer, lookahead); tokenizer.nextToken(lookahead); } append(exprBuffer,lookahead); break; } case XalanUnicode::charLeftCurlyBracket: { // What's another curly doing here? error = TranscodeFromLocalCodePage("Error: Can not have \"{\" within expression."); break; } default: { // part of the template stuff, just add it. append(exprBuffer, lookahead); } } // end inner switch } // end if lookahead length == 1 else { // part of the template stuff, just add it. append(exprBuffer,lookahead); } tokenizer.nextToken(lookahead); } // end while(!equals(lookahead, "}")) assert(equals(lookahead, theRightCurlyBracketString)); // Proper close of attribute template. Evaluate the // expression. clear(buffer); const XPath* const xpath = constructionContext.createXPath(exprBuffer, resolver); assert(xpath != 0); m_parts.push_back(new AVTPartXPath(xpath)); clear(lookahead); // breaks out of inner while loop if(length(error) > 0) { break; // from inner while loop } } break; } case(XalanUnicode::charRightCurlyBracket): { tokenizer.nextToken(lookahead); if(equals(lookahead, theRightCurlyBracketString)) { // Double curlys mean escape to show curly append(buffer, lookahead); clear(lookahead); // swallow } else { // Illegal, I think... constructionContext.warn("Found \"}\" but no attribute template open!"); append(buffer, theRightCurlyBracketString); // leave the lookahead to be processed by the next round. } break; } default: { const XalanDOMString s(&theChar, 1); // Anything else just add to string. append(buffer, s); } } // end switch t } // end if length == 1 else { // Anything else just add to string. append(buffer,t); } if(length(error) > 0) { constructionContext.warn("Attr Template, " + error); break; } } // end while(tokenizer.hasMoreTokens()) if(length(buffer) > 0) { m_parts.push_back(new AVTPartSimple(buffer)); clear(buffer); } } // end else nTokens > 1 if(m_parts.empty() && length(m_simpleString) == 0) { // Error? clear(m_simpleString); } else if (m_parts.size() < m_parts.capacity()) { AVTPartPtrVectorType(m_parts).swap(m_parts); } } AVT::~AVT() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Clean up all entries in the vector. for_each(m_parts.begin(), m_parts.end(), DeleteFunctor<AVTPart>()); } void AVT::evaluate( XalanDOMString& buf, XalanNode* contextNode, const PrefixResolver& prefixResolver, XPathExecutionContext& executionContext) const { if(length(m_simpleString) > 0) { buf = m_simpleString; } else { clear(buf); if(m_parts.empty() == false) { const AVTPartPtrVectorType::size_type n = m_parts.size(); for(AVTPartPtrVectorType::size_type i = 0; i < n; i++) { assert(m_parts[i] != 0); m_parts[i]->evaluate(buf, contextNode, prefixResolver, executionContext); } } } } XalanDOMString AVT::getPrefix(const XalanDOMChar* theName) { if (startsWith(theName, DOMServices::s_XMLNamespaceWithSeparator) == true) { return substring(theName, DOMServices::s_XMLNamespaceWithSeparatorLength); } else { return XalanDOMString(); } } <|endoftext|>
<commit_before>/*! @file simulation.cpp @brief Implementation of Simulation class @defgroup params Parameters */ #include "simulation.hpp" #include "tissue.hpp" #include "cell.hpp" #include "random.hpp" #include "version.hpp" #include <wtl/iostr.hpp> #include <wtl/chrono.hpp> #include <wtl/exception.hpp> #include <clippson/clippson.hpp> namespace tumopp { //! Global variables mapper of commane-line arguments nlohmann::json VM; //! Options description for general purpose inline clipp::group general_options(nlohmann::json* vm) { return ( wtl::option(vm, {"h", "help"}, false, "Print this help"), wtl::option(vm, {"version"}, false, "Print version") ).doc("General:"); } //! Parameters of Simulation class /*! @ingroup params Command line option | Symbol | Variable | ------------------- | -------------- | ------------------------- | `-D,--dimensions` | - | - `-C,--coord` | - | - `-L,--local` | \f$E_2\f$ | - `-P,--path` | - | - `-O,--origin` | \f$N_0\f$ | - `-N,--max` | \f$N_\max\f$ | - `-T,--plateau` | - | - `-U,--mutate` | \f$N_\mu\f$ | - `-o,--outdir` | - | - `-I,--interval` | - | - `-R,--record` | - | - `--seed` | - | - */ inline clipp::group simulation_options(nlohmann::json* vm) { const std::string OUT_DIR = wtl::strftime("tumopp_%Y%m%d_%H%M%S"); const int seed = static_cast<int>(std::random_device{}()); // 32-bit signed integer for R return ( wtl::option(vm, {"D", "dimensions"}, 3u), wtl::option(vm, {"C", "coord"}, "moore", "Neighborhood {neumann, moore, hex}"), wtl::option(vm, {"L", "local"}, "const", "E2: resource competition {const, step, linear}"), wtl::option(vm, {"P", "path"}, "random", "Push method {1: random, 2: roulette, 3: mindrag, 4: minstraight, 5: stroll}"), wtl::option(vm, {"O", "origin"}, 1u), wtl::option(vm, {"N", "max"}, 16384u, "Maximum number of cells to simulate"), wtl::option(vm, {"max_time"}, 0.0, "Maximum time to simulate"), wtl::option(vm, {"T", "plateau"}, 0.0, "Duration of turn-over phase after population growth"), wtl::option(vm, {"U", "mutate"}, 0u, "Introduce a driver mutation to U-th cell"), wtl::option(vm, {"treatment"}, 0.0), wtl::option(vm, {"resistant"}, 3u), wtl::option(vm, {"o", "outdir"}, OUT_DIR), wtl::option(vm, {"I", "interval"}, 0.0, "Time interval to take snapshots"), wtl::option(vm, {"R", "record"}, 0u, "Tumor size to stop taking snapshots"), wtl::option(vm, {"extinction"}, 100u, "Maximum number of trials in case of extinction"), wtl::option(vm, {"benchmark"}, false), wtl::option(vm, {"seed"}, seed), wtl::option(vm, {"v", "verbose"}, false, "Verbose output") ).doc("Simulation:"); } //! Parameters of Cell class /*! @ingroup params Command line option | Symbol | Variable | ------------------- | ------------------- | ------------------------- | `-b,--beta0` | \f$\beta_0\f$ | EventRates::birth_rate `-d,--delta0` | \f$\delta_0\f$ | EventRates::death_rate `-a,--alpha0` | \f$\alpha_0\f$ | EventRates::death_prob `-m,--rho0` | \f$\rho_0\f$ | EventRates::migra_rate `-k,--shape` | \f$k\f$ | CellParams::GAMMA_SHAPE `-p,--symmetric` | \f$p_s\f$ | CellParams::PROB_SYMMETRIC_DIVISION `-r,--prolif` | \f$\omega_{\max}\f$ | CellParams::MAX_PROLIFERATION_CAPACITY `--ub` | \f$\mu_\beta\f$ | CellParams::RATE_BIRTH `--ud` | \f$\mu_\delta\f$ | CellParams::RATE_DEATH `--um` | \f$\mu_\rho\f$ | CellParams::RATE_MIGRA `--mb` | \f$\bar s_\beta\f$ | CellParams::MEAN_BIRTH `--md` | \f$\bar s_\delta\f$ | CellParams::MEAN_DEATH `--mm` | \f$\bar s_\rho\f$ | CellParams::MEAN_MIGRA `--sb` | \f$\sigma_\beta\f$ | CellParams::SD_BIRTH `--sd` | \f$\sigma_\delta\f$ | CellParams::SD_DEATH `--sm` | \f$\sigma_\rho\f$ | CellParams::SD_MIGRA */ inline clipp::group cell_options(nlohmann::json* vm, EventRates* init_event_rates, CellParams* cell_params) { return ( wtl::option(vm, {"b", "beta0"}, &init_event_rates->birth_rate, "Basic birth rate"), wtl::option(vm, {"d", "delta0"}, &init_event_rates->death_rate, "Basic death rate"), wtl::option(vm, {"a", "alpha0"}, &init_event_rates->death_prob, "Basic death rate on cell division attempt"), wtl::option(vm, {"m", "rho0"}, &init_event_rates->migra_rate, "Basic migration rate"), wtl::option(vm, {"k", "shape"}, &cell_params->GAMMA_SHAPE, "Shape parameter of waiting time distribution for cell division"), wtl::option(vm, {"p", "symmetric"}, &cell_params->PROB_SYMMETRIC_DIVISION, "$p_s$: Probability of symmetric division"), wtl::option(vm, {"r", "prolif"}, &cell_params->MAX_PROLIFERATION_CAPACITY, "$\\omega$: Maximum number of division for a TAC"), ( wtl::option(vm, {"ub"}, &cell_params->RATE_BIRTH, "$\\mu_\\beta$"), wtl::option(vm, {"ud"}, &cell_params->RATE_DEATH, "$\\mu_\\delta$"), wtl::option(vm, {"ua"}, &cell_params->RATE_ALPHA, "$\\mu_\\alpha$"), wtl::option(vm, {"um"}, &cell_params->RATE_MIGRA, "$\\mu_\\rho$") ).doc("Rate of driver mutations:"), ( wtl::option(vm, {"mb"}, &cell_params->MEAN_BIRTH, "$\\bar s_\\beta$"), wtl::option(vm, {"md"}, &cell_params->MEAN_DEATH, "$\\bar s_\\delta$"), wtl::option(vm, {"ma"}, &cell_params->MEAN_ALPHA, "$\\bar s_\\alpha$"), wtl::option(vm, {"mm"}, &cell_params->MEAN_MIGRA, "$\\bar s_\\rho$") ).doc("Mean effect of driver mutations:"), ( wtl::option(vm, {"sb"}, &cell_params->SD_BIRTH, "$\\sigma_\\beta$"), wtl::option(vm, {"sd"}, &cell_params->SD_DEATH, "$\\sigma_\\delta$"), wtl::option(vm, {"sa"}, &cell_params->SD_ALPHA, "$\\sigma_\\alpha$"), wtl::option(vm, {"sm"}, &cell_params->SD_MIGRA, "$\\sigma_\\rho$") ).doc("SD of driver mutations:") ).doc("Cell:"); } Simulation::Simulation(const std::vector<std::string>& arguments) : init_event_rates_(std::make_unique<EventRates>()), cell_params_(std::make_unique<CellParams>()) { std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.precision(9); std::cerr.precision(6); VM.clear(); nlohmann::json vm_local; auto cli = ( general_options(&vm_local), simulation_options(&VM), cell_options(&VM, init_event_rates_.get(), cell_params_.get()) ); wtl::parse(cli, arguments); if (vm_local["help"]) { auto fmt = wtl::doc_format().paragraph_spacing(0); std::cout << "Usage: " << PROJECT_NAME << " [options]\n\n"; std::cout << clipp::documentation(cli, fmt) << "\n"; throw wtl::ExitSuccess(); } if (vm_local["version"]) { std::cout << PROJECT_VERSION << "\n"; throw wtl::ExitSuccess(); } Cell::param(*cell_params_); config_ = VM.dump(2) + "\n"; } Simulation::~Simulation() = default; void Simulation::run() { const auto max_size = VM.at("max").get<size_t>(); const double max_time = VM.at("max_time").get<double>(); const auto plateau_time = VM.at("plateau").get<double>(); const auto treatment = VM.at("treatment").get<double>(); const auto resistant = VM.at("resistant").get<size_t>(); const auto allowed_extinction = VM.at("extinction").get<unsigned>(); urbg_t seeder(VM.at("seed").get<uint_fast32_t>()); for (size_t i=0; i<allowed_extinction; ++i) { tissue_ = std::make_unique<Tissue>( VM.at("origin").get<size_t>(), VM.at("dimensions").get<unsigned>(), VM.at("coord").get<std::string>(), VM.at("local").get<std::string>(), VM.at("path").get<std::string>(), *init_event_rates_, seeder(), VM.at("benchmark").get<bool>() ); bool success = tissue_->grow( max_size, max_time > 0.0 ? max_time : std::log2(max_size) * 100.0, VM.at("interval").get<double>(), VM.at("record").get<size_t>(), VM.at("mutate").get<size_t>(), VM.at("verbose").get<bool>() ); if (success) break; std::cerr << "Trial " << i << ": size = " << tissue_->size() << std::endl; } if (max_time == 0.0 && tissue_->size() != max_size) { std::cerr << "Warning: size = " << tissue_->size() << std::endl; } if (max_time == 0.0 && plateau_time > 0.0) { tissue_->plateau(plateau_time); } if (max_time == 0.0 && treatment > 0.0) { tissue_->treatment(treatment, resistant); } } std::string Simulation::outdir() const { return VM.at("outdir").get<std::string>(); } std::string Simulation::history() const { std::ostringstream oss; tissue_->write_history(oss); return oss.str(); } std::string Simulation::snapshots() const { if (!tissue_->has_snapshots()) return std::string{}; std::ostringstream oss; tissue_->write_snapshots(oss); return oss.str(); } std::string Simulation::drivers() const { if (!tissue_->has_drivers()) return std::string{}; std::ostringstream oss; tissue_->write_drivers(oss); return oss.str(); } std::string Simulation::benchmark() const { if (!tissue_->has_benchmark()) return std::string{}; std::ostringstream oss; tissue_->write_benchmark(oss); return oss.str(); } std::streambuf* std_cout_rdbuf(std::streambuf* buf) { return std::cout.rdbuf(buf); } std::streambuf* std_cerr_rdbuf(std::streambuf* buf) { return std::cerr.rdbuf(buf); } } // namespace tumopp <commit_msg>:memo: Use unicode Greek letters in -h/--help<commit_after>/*! @file simulation.cpp @brief Implementation of Simulation class @defgroup params Parameters */ #include "simulation.hpp" #include "tissue.hpp" #include "cell.hpp" #include "random.hpp" #include "version.hpp" #include <wtl/iostr.hpp> #include <wtl/chrono.hpp> #include <wtl/exception.hpp> #include <clippson/clippson.hpp> namespace tumopp { //! Global variables mapper of commane-line arguments nlohmann::json VM; //! Options description for general purpose inline clipp::group general_options(nlohmann::json* vm) { return ( wtl::option(vm, {"h", "help"}, false, "Print this help"), wtl::option(vm, {"version"}, false, "Print version") ).doc("General:"); } //! Parameters of Simulation class /*! @ingroup params Command line option | Symbol | Variable | ------------------- | -------------- | ------------------------- | `-D,--dimensions` | - | - `-C,--coord` | - | - `-L,--local` | \f$E_2\f$ | - `-P,--path` | - | - `-O,--origin` | \f$N_0\f$ | - `-N,--max` | \f$N_\max\f$ | - `-T,--plateau` | - | - `-U,--mutate` | \f$N_\mu\f$ | - `-o,--outdir` | - | - `-I,--interval` | - | - `-R,--record` | - | - `--seed` | - | - */ inline clipp::group simulation_options(nlohmann::json* vm) { const std::string OUT_DIR = wtl::strftime("tumopp_%Y%m%d_%H%M%S"); const int seed = static_cast<int>(std::random_device{}()); // 32-bit signed integer for R return ( wtl::option(vm, {"D", "dimensions"}, 3u), wtl::option(vm, {"C", "coord"}, "moore", "Neighborhood {neumann, moore, hex}"), wtl::option(vm, {"L", "local"}, "const", "E2: resource competition {const, step, linear}"), wtl::option(vm, {"P", "path"}, "random", "Push method {random, roulette, mindrag, minstraight, stroll}"), wtl::option(vm, {"O", "origin"}, 1u), wtl::option(vm, {"N", "max"}, 16384u, "Maximum number of cells to simulate"), wtl::option(vm, {"max_time"}, 0.0, "Maximum time to simulate"), wtl::option(vm, {"T", "plateau"}, 0.0, "Duration of turn-over phase after population growth"), wtl::option(vm, {"U", "mutate"}, 0u, "Introduce a driver mutation to U-th cell"), wtl::option(vm, {"treatment"}, 0.0), wtl::option(vm, {"resistant"}, 3u), wtl::option(vm, {"o", "outdir"}, OUT_DIR), wtl::option(vm, {"I", "interval"}, 0.0, "Time interval to take snapshots"), wtl::option(vm, {"R", "record"}, 0u, "Tumor size to stop taking snapshots"), wtl::option(vm, {"extinction"}, 100u, "Maximum number of trials in case of extinction"), wtl::option(vm, {"benchmark"}, false), wtl::option(vm, {"seed"}, seed), wtl::option(vm, {"v", "verbose"}, false, "Verbose output") ).doc("Simulation:"); } //! Parameters of Cell class /*! @ingroup params Command line option | Symbol | Variable | ------------------- | ------------------- | ------------------------- | `-b,--beta0` | \f$\beta_0\f$ | EventRates::birth_rate `-d,--delta0` | \f$\delta_0\f$ | EventRates::death_rate `-a,--alpha0` | \f$\alpha_0\f$ | EventRates::death_prob `-m,--rho0` | \f$\rho_0\f$ | EventRates::migra_rate `-k,--shape` | \f$k\f$ | CellParams::GAMMA_SHAPE `-p,--symmetric` | \f$p_s\f$ | CellParams::PROB_SYMMETRIC_DIVISION `-r,--prolif` | \f$\omega_{\max}\f$ | CellParams::MAX_PROLIFERATION_CAPACITY `--ub` | \f$\mu_\beta\f$ | CellParams::RATE_BIRTH `--ud` | \f$\mu_\delta\f$ | CellParams::RATE_DEATH `--um` | \f$\mu_\rho\f$ | CellParams::RATE_MIGRA `--mb` | \f$\bar s_\beta\f$ | CellParams::MEAN_BIRTH `--md` | \f$\bar s_\delta\f$ | CellParams::MEAN_DEATH `--mm` | \f$\bar s_\rho\f$ | CellParams::MEAN_MIGRA `--sb` | \f$\sigma_\beta\f$ | CellParams::SD_BIRTH `--sd` | \f$\sigma_\delta\f$ | CellParams::SD_DEATH `--sm` | \f$\sigma_\rho\f$ | CellParams::SD_MIGRA */ inline clipp::group cell_options(nlohmann::json* vm, EventRates* init_event_rates, CellParams* cell_params) { return ( wtl::option(vm, {"b", "beta0"}, &init_event_rates->birth_rate, "Basic birth rate"), wtl::option(vm, {"d", "delta0"}, &init_event_rates->death_rate, "Basic death rate"), wtl::option(vm, {"a", "alpha0"}, &init_event_rates->death_prob, "Basic death rate on cell division attempt"), wtl::option(vm, {"m", "rho0"}, &init_event_rates->migra_rate, "Basic migration rate"), wtl::option(vm, {"k", "shape"}, &cell_params->GAMMA_SHAPE, "Shape parameter of waiting time distribution for cell division"), wtl::option(vm, {"p", "symmetric"}, &cell_params->PROB_SYMMETRIC_DIVISION, "p_s: Probability of symmetric division"), wtl::option(vm, {"r", "prolif"}, &cell_params->MAX_PROLIFERATION_CAPACITY, u8"ω: Maximum number of division for a TAC"), ( wtl::option(vm, {"ub"}, &cell_params->RATE_BIRTH, u8"μ_β"), wtl::option(vm, {"ud"}, &cell_params->RATE_DEATH, u8"μ_δ"), wtl::option(vm, {"ua"}, &cell_params->RATE_ALPHA, u8"μ_α"), wtl::option(vm, {"um"}, &cell_params->RATE_MIGRA, u8"μ_ρ") ).doc("Rate of driver mutations:"), ( wtl::option(vm, {"mb"}, &cell_params->MEAN_BIRTH, u8"E[s_β]"), wtl::option(vm, {"md"}, &cell_params->MEAN_DEATH, u8"E[s_δ]"), wtl::option(vm, {"ma"}, &cell_params->MEAN_ALPHA, u8"E[s_α]"), wtl::option(vm, {"mm"}, &cell_params->MEAN_MIGRA, u8"E[s_ρ]") ).doc("Mean effect of driver mutations:"), ( wtl::option(vm, {"sb"}, &cell_params->SD_BIRTH, u8"σ_β"), wtl::option(vm, {"sd"}, &cell_params->SD_DEATH, u8"σ_δ"), wtl::option(vm, {"sa"}, &cell_params->SD_ALPHA, u8"σ_α"), wtl::option(vm, {"sm"}, &cell_params->SD_MIGRA, u8"σ_ρ") ).doc("SD of driver mutations:") ).doc("Cell:"); } Simulation::Simulation(const std::vector<std::string>& arguments) : init_event_rates_(std::make_unique<EventRates>()), cell_params_(std::make_unique<CellParams>()) { std::ios::sync_with_stdio(false); std::cin.tie(0); std::cout.precision(9); std::cerr.precision(6); VM.clear(); nlohmann::json vm_local; auto cli = ( general_options(&vm_local), simulation_options(&VM), cell_options(&VM, init_event_rates_.get(), cell_params_.get()) ); wtl::parse(cli, arguments); if (vm_local["help"]) { auto fmt = wtl::doc_format().paragraph_spacing(0); std::cout << "Usage: " << PROJECT_NAME << " [options]\n\n"; std::cout << clipp::documentation(cli, fmt) << "\n"; throw wtl::ExitSuccess(); } if (vm_local["version"]) { std::cout << PROJECT_VERSION << "\n"; throw wtl::ExitSuccess(); } Cell::param(*cell_params_); config_ = VM.dump(2) + "\n"; } Simulation::~Simulation() = default; void Simulation::run() { const auto max_size = VM.at("max").get<size_t>(); const double max_time = VM.at("max_time").get<double>(); const auto plateau_time = VM.at("plateau").get<double>(); const auto treatment = VM.at("treatment").get<double>(); const auto resistant = VM.at("resistant").get<size_t>(); const auto allowed_extinction = VM.at("extinction").get<unsigned>(); urbg_t seeder(VM.at("seed").get<uint_fast32_t>()); for (size_t i=0; i<allowed_extinction; ++i) { tissue_ = std::make_unique<Tissue>( VM.at("origin").get<size_t>(), VM.at("dimensions").get<unsigned>(), VM.at("coord").get<std::string>(), VM.at("local").get<std::string>(), VM.at("path").get<std::string>(), *init_event_rates_, seeder(), VM.at("benchmark").get<bool>() ); bool success = tissue_->grow( max_size, max_time > 0.0 ? max_time : std::log2(max_size) * 100.0, VM.at("interval").get<double>(), VM.at("record").get<size_t>(), VM.at("mutate").get<size_t>(), VM.at("verbose").get<bool>() ); if (success) break; std::cerr << "Trial " << i << ": size = " << tissue_->size() << std::endl; } if (max_time == 0.0 && tissue_->size() != max_size) { std::cerr << "Warning: size = " << tissue_->size() << std::endl; } if (max_time == 0.0 && plateau_time > 0.0) { tissue_->plateau(plateau_time); } if (max_time == 0.0 && treatment > 0.0) { tissue_->treatment(treatment, resistant); } } std::string Simulation::outdir() const { return VM.at("outdir").get<std::string>(); } std::string Simulation::history() const { std::ostringstream oss; tissue_->write_history(oss); return oss.str(); } std::string Simulation::snapshots() const { if (!tissue_->has_snapshots()) return std::string{}; std::ostringstream oss; tissue_->write_snapshots(oss); return oss.str(); } std::string Simulation::drivers() const { if (!tissue_->has_drivers()) return std::string{}; std::ostringstream oss; tissue_->write_drivers(oss); return oss.str(); } std::string Simulation::benchmark() const { if (!tissue_->has_benchmark()) return std::string{}; std::ostringstream oss; tissue_->write_benchmark(oss); return oss.str(); } std::streambuf* std_cout_rdbuf(std::streambuf* buf) { return std::cout.rdbuf(buf); } std::streambuf* std_cerr_rdbuf(std::streambuf* buf) { return std::cerr.rdbuf(buf); } } // namespace tumopp <|endoftext|>
<commit_before>#include <cstdlib> #include <ctime> #include <sys/wait.h> #include <fstream> #include <set> #include <string> #include <iostream> #include <deque> #include <vector> #include "Crawler.h" #include "Downloader.h" #include "HTMLContent.h" #include "HTMLTag.h" #include "WikiPage.h" std::string Crawler::GenerateFileName() { return data_directory_ + std::to_string(time(NULL)) + " " + std::to_string(rand()); } // Return value: // 0 - success // 1 - failed to download // 2 - received interruption signal // 3 - download queue is empty int Crawler::FetchNextPage() { if (download_queue_.container.empty()) { return 3; } std::string link = download_queue_.container.front(); std::string original_link = link; if (link.compare(0, root_path_.length(), root_path_) != 0) { link = root_path_ + link; } std::string filename = GenerateFileName(); std::cout << "Downloading " << link << std::endl; int result = Downloader::DownloadPage(link, filename); // check if program got signal to quit if (WIFSIGNALED(result) && (WTERMSIG(result) == SIGINT || WTERMSIG(result) == SIGQUIT)) { return 2; } // decode value that was returned by system() call result = WEXITSTATUS(result); if (result != 0) { std::cerr << "\033[1;31mFailed to fetch page " << link << "\033[0m" << std::endl; } if (result != 0 && result != 8) // 8 means server issued an error response (like 404) and we should // probably just ignore it { return 1; } download_queue_.container.pop_front(); ParsePage(original_link, filename); return 0; } void Crawler::ParsePage(const std::string& link, const std::string& filename) { std::ifstream file(filename); std::string html, temp; while (std::getline(file, temp)) { html += temp + '\n'; } WikiPage page = WikiPage(*HTMLContent(html, 0).tags()[1]); std::ofstream article_text_file(filename + ".text"); article_text_file << link << std::endl << page.text(); std::ofstream found_links_file(filename + ".links"); found_links_file << link << std::endl << std::endl; for (const std::string& found_link : page.links()) { found_links_file << found_link << std::endl; AddLink(found_link); } if (article_text_file.good() && found_links_file.good()) { file.close(); std::remove(filename.c_str()); } } bool Crawler::AddLink(const std::string& link) { if (visited_links_.container.count(link) != 0) { return false; } visited_links_.container.insert(link); download_queue_.container.push_back(link); return true; } Crawler::Crawler(const std::string& data_directory, const std::string& root_path, const std::string& required_link_prefix, const std::vector<char>& banned_symbols) : data_directory_(data_directory), root_path_(root_path), required_link_prefix_(required_link_prefix), banned_symbols_(banned_symbols) { download_queue_ = SaveableStringContainer<std::deque<std::string>> (data_directory_ + queue_filename_); visited_links_ = SaveableStringContainer<std::unordered_set<std::string>> (data_directory_ + visited_filename_); } void Crawler::Crawl(const std::string& start_page) { if (download_queue_.container.empty()) { download_queue_.container.push_back(start_page); visited_links_.container.insert(start_page); } while (FetchNextPage() <= 1) { } } <commit_msg>Fix bug with 404 pages.<commit_after>#include <cstdlib> #include <ctime> #include <sys/wait.h> #include <fstream> #include <set> #include <string> #include <iostream> #include <deque> #include <vector> #include "Crawler.h" #include "Downloader.h" #include "HTMLContent.h" #include "HTMLTag.h" #include "WikiPage.h" std::string Crawler::GenerateFileName() { return data_directory_ + std::to_string(time(NULL)) + " " + std::to_string(rand()); } // Return value: // 0 - success // 1 - failed to download // 2 - received interruption signal // 3 - download queue is empty int Crawler::FetchNextPage() { if (download_queue_.container.empty()) { return 3; } std::string link = download_queue_.container.front(); std::string original_link = link; if (link.compare(0, root_path_.length(), root_path_) != 0) { link = root_path_ + link; } std::string filename = GenerateFileName(); std::cout << "Downloading " << link << std::endl; int result = Downloader::DownloadPage(link, filename); // check if program got signal to quit if (WIFSIGNALED(result) && (WTERMSIG(result) == SIGINT || WTERMSIG(result) == SIGQUIT)) { return 2; } // decode value that was returned by system() call result = WEXITSTATUS(result); if (result != 0) { std::cerr << "\033[1;31mFailed to fetch page " << link << "\033[0m" << std::endl; } if (result != 0 && result != 8) // 8 means server issued an error response (like 404) and we should // probably just ignore it { return 1; } download_queue_.container.pop_front(); if (result == 0) { ParsePage(original_link, filename); } return 0; } void Crawler::ParsePage(const std::string& link, const std::string& filename) { std::ifstream file(filename); std::string html, temp; while (std::getline(file, temp)) { html += temp + '\n'; } WikiPage page = WikiPage(*HTMLContent(html, 0).tags()[1]); std::ofstream article_text_file(filename + ".text"); article_text_file << link << std::endl << page.text(); std::ofstream found_links_file(filename + ".links"); found_links_file << link << std::endl << std::endl; for (const std::string& found_link : page.links()) { found_links_file << found_link << std::endl; AddLink(found_link); } if (article_text_file.good() && found_links_file.good()) { file.close(); std::remove(filename.c_str()); } } bool Crawler::AddLink(const std::string& link) { if (visited_links_.container.count(link) != 0) { return false; } visited_links_.container.insert(link); download_queue_.container.push_back(link); return true; } Crawler::Crawler(const std::string& data_directory, const std::string& root_path, const std::string& required_link_prefix, const std::vector<char>& banned_symbols) : data_directory_(data_directory), root_path_(root_path), required_link_prefix_(required_link_prefix), banned_symbols_(banned_symbols) { download_queue_ = SaveableStringContainer<std::deque<std::string>> (data_directory_ + queue_filename_); visited_links_ = SaveableStringContainer<std::unordered_set<std::string>> (data_directory_ + visited_filename_); } void Crawler::Crawl(const std::string& start_page) { if (download_queue_.container.empty()) { download_queue_.container.push_back(start_page); visited_links_.container.insert(start_page); } while (FetchNextPage() <= 1) { } } <|endoftext|>
<commit_before>/* * File: Factory.cpp * Author: iMer * * Created on 19. August 2014, 18:40 */ #include "Factory.hpp" #include "ParticleSystem.hpp" namespace engine { std::map<std::string, std::function<Node*(Json::Value& root, Node* parent) >> Factory::m_types = { std::make_pair(std::string("node"), std::function < Node * (Json::Value& root, Node * parent) >(Factory::CreateChildNode<Node>)), std::make_pair(std::string("sprite"), std::function < Node * (Json::Value& root, Node * parent) >(Factory::CreateChildNode<SpriteNode>)), std::make_pair(std::string("light"), std::function < Node * (Json::Value& root, Node * parent) >(Factory::CreateChildNode<Light>)), std::make_pair(std::string("particlesystem"), std::function < Node * (Json::Value& root, Node * parent) >(Factory::CreateChildNode<ParticleSystem>)) }; void Factory::RegisterType(std::string name, std::function<Node*(Json::Value& root, Node* parent) > callback) { m_types.insert(std::make_pair(name, callback)); } void Factory::RemoveType(std::string name) { m_types.erase(name); } bool Factory::LoadJson(std::string filename, Json::Value & root) { Json::Reader reader; std::ifstream jconfig; jconfig.open(filename); if (!jconfig.good()) { std::cerr << "Could not open config file: " << strerror(errno) << std::endl; return false; } if (!reader.parse(jconfig, root)) { std::cerr << "Couldn't parse config" << std::endl << reader.getFormattedErrorMessages() << std::endl; jconfig.seekg(0); std::cerr << jconfig.rdbuf() << std::endl; return false; } return true; } Node * Factory::CreateChild(Json::Value root, Node * parent) { Json::Value childData; if (root["childData"].isString()) { if (!LoadJson(root["childData"].asString(), childData)) { std::cerr << "Couldn't load childData from file" << std::endl; return nullptr; } } else { childData = root["childData"]; } MergeJson(childData, root); std::string type = childData.get("type", "node").asString(); auto it = m_types.find(type); if (it == m_types.end()) { std::cerr << "Type '" << type << "' was not registered. Cant load child." << std::endl; return nullptr; } Node* c = it->second(childData, parent); if (!c) { return nullptr; } return c; } Node * Factory::CreateChildFromFile(std::string file, Node * parent) { Json::Value root; if (!Factory::LoadJson(file, root)) { return nullptr; } std::string type = root.get("type", "node").asString(); auto it = m_types.find(type); if (it == m_types.end()) { std::cerr << "Type '" << type << "' was not registered. Cant load child." << std::endl; return nullptr; } Node* c = it->second(root, parent); if (!c) { return nullptr; } return c; } void Factory::MergeJson(Json::Value& a, Json::Value& b) { // http://stackoverflow.com/a/23860017/1318435 if (!b.isObject()) return; for (const auto& key : b.getMemberNames()) { if (a[key].isObject()) { MergeJson(a[key], b[key]); } else { a[key] = b[key]; } } } } <commit_msg>Fixed CreateChildFromFile<commit_after>/* * File: Factory.cpp * Author: iMer * * Created on 19. August 2014, 18:40 */ #include "Factory.hpp" #include "ParticleSystem.hpp" namespace engine { std::map<std::string, std::function<Node*(Json::Value& root, Node* parent) >> Factory::m_types = { std::make_pair(std::string("node"), std::function < Node * (Json::Value& root, Node * parent) >(Factory::CreateChildNode<Node>)), std::make_pair(std::string("sprite"), std::function < Node * (Json::Value& root, Node * parent) >(Factory::CreateChildNode<SpriteNode>)), std::make_pair(std::string("light"), std::function < Node * (Json::Value& root, Node * parent) >(Factory::CreateChildNode<Light>)), std::make_pair(std::string("particlesystem"), std::function < Node * (Json::Value& root, Node * parent) >(Factory::CreateChildNode<ParticleSystem>)) }; void Factory::RegisterType(std::string name, std::function<Node*(Json::Value& root, Node* parent) > callback) { m_types.insert(std::make_pair(name, callback)); } void Factory::RemoveType(std::string name) { m_types.erase(name); } bool Factory::LoadJson(std::string filename, Json::Value & root) { Json::Reader reader; std::ifstream jconfig; jconfig.open(filename); if (!jconfig.good()) { std::cerr << "Could not open config file: " << strerror(errno) << std::endl; return false; } if (!reader.parse(jconfig, root)) { std::cerr << "Couldn't parse config" << std::endl << reader.getFormattedErrorMessages() << std::endl; jconfig.seekg(0); std::cerr << jconfig.rdbuf() << std::endl; return false; } return true; } Node * Factory::CreateChild(Json::Value root, Node * parent) { Json::Value childData; if (root["childData"].isString()) { if (!LoadJson(root["childData"].asString(), childData)) { std::cerr << "Couldn't load childData from file" << std::endl; return nullptr; } } else { childData = root["childData"]; } MergeJson(childData, root); std::string type = childData.get("type", "node").asString(); auto it = m_types.find(type); if (it == m_types.end()) { std::cerr << "Type '" << type << "' was not registered. Cant load child." << std::endl; return nullptr; } Node* c = it->second(childData, parent); if (!c) { return nullptr; } return c; } Node * Factory::CreateChildFromFile(std::string file, Node * parent) { Json::Value root; if (!Factory::LoadJson(file, root)) { return nullptr; } std::string type = root.get("type", "node").asString(); auto it = m_types.find(type); if (it == m_types.end()) { std::cerr << "Type '" << type << "' was not registered. Cant load child." << std::endl; return nullptr; } Node* c = it->second(root, parent); if (!c) { return nullptr; } parent->AddNode(c); return c; } void Factory::MergeJson(Json::Value& a, Json::Value& b) { // http://stackoverflow.com/a/23860017/1318435 if (!b.isObject()) return; for (const auto& key : b.getMemberNames()) { if (a[key].isObject()) { MergeJson(a[key], b[key]); } else { a[key] = b[key]; } } } } <|endoftext|>
<commit_before>/* GG is a GUI for SDL and OpenGL. Copyright (C) 2003 T. Zachary Laine This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you do not wish to comply with the terms of the LGPL please contact the author as other terms are available for a fee. Zach Laine whatwasthataddress@hotmail.com */ /* $Header$ */ #include "GGZList.h" #include "GGWnd.h" namespace GG { namespace { const int DESIRED_GAP_SIZE = 10; // leaves room for 10-deep nested child windows (and that should be plenty) const int DESIRED_LOWEST_Z = 1 << 30; // start z-values at 1/4 of 32-bit int's positive range (2^32 / 4 = 2^30) const int MIN_Z = 1 << 29; // set low end of z-value range at 1/8 of 32-bit int's range (2^32 / 8 = 2^29) const int MAX_Z = 7 * MIN_Z; // set high end of z-value range at 7/8 of 32-bit int's range (7 * 2^32 / 8 = 7 * 2^29) const int MAX_AVG_GAP_SIZE = 15; // if things get too spread out.. const int MIN_AVG_GAP_SIZE = 5; // ..or too packed, compresion may be needed const int MAX_SPAN = 1 << 31; // windows should be laid out over no more than 1/2 of possible z-value range (2^32 / 2 = 2^31) }; /////////////////////////////////////// // class GG::ZList /////////////////////////////////////// Wnd* ZList::Pick(const Pt& pt, Wnd* modal) const { Wnd* retval = 0; if (modal) { // if a modal window is active, only look there retval = modal->InWindow(pt) ? PickWithinWindow(pt, modal) : 0; } else { // otherwise, look in the z-list const_iterator end_it = end(); for (const_iterator it = begin(); it != end_it; ++it) { Wnd* temp = 0; if ((*it)->InWindow(pt) && (temp = PickWithinWindow(pt, *it))) { retval = temp; break; } } } return retval; } void ZList::Add(Wnd* wnd) { if (m_contents.find(wnd) == m_contents.end()) { // add wnd to the end of the list... if (empty()) { // list empty wnd->m_zorder = DESIRED_LOWEST_Z; // by default, add first element at DESIRED_LOWEST_Z insert(begin(), wnd); } else { // list not empty wnd->m_zorder = back()->m_zorder - (DESIRED_GAP_SIZE + 1); insert(end(), wnd); } m_contents.insert(wnd); // then move it up to its proper place MoveUp(wnd); if (NeedsRealignment()) Realign(); } } bool ZList::Remove(Wnd* wnd) { bool retval = false; if (m_contents.find(wnd) != m_contents.end()) { iterator it = std::find(begin(), end(), wnd); if (it != end()) erase(it); if (NeedsRealignment()) Realign(); m_contents.erase(wnd); retval = true; } return retval; } bool ZList::MoveUp(Wnd* wnd) { bool retval = false; iterator it = std::find(begin(), end(), wnd); if (it != end()) { // note that this also implies !empty().. int top_z = front()->m_zorder; // ..so this is okay to do without checking if (!front()->OnTop() || wnd->OnTop()) { // if there are no on-top windows, or wnd is an on-top window.. (*it)->m_zorder = top_z + DESIRED_GAP_SIZE + 1; // ..just slap wnd on top of the topmost element splice(begin(), *this, it); } else { // front()->OnTop() && !wnd->OnTop(), so only move wnd up to just below the bottom of the on-top range iterator first_non_ontop_it = FirstNonOnTop(); int prev_z = (*--first_non_ontop_it)->m_zorder; int curr_z = (*++first_non_ontop_it)->m_zorder; if (prev_z - curr_z - 1 >= 3) { // if there's at least 3 positions in between.. (*it)->m_zorder = (*first_non_ontop_it)->m_zorder + (prev_z - curr_z - 1) / 2; // ..just stick wnd in the middle splice(first_non_ontop_it, *this, it); } else { // make room by bumping up all the on-top windows iterator it2 = first_non_ontop_it; (*--it2)->m_zorder += 2 * (DESIRED_GAP_SIZE + 1); // double the gap before first_non_ontop_it, to leave the right gap on either side of wnd while (it2 != begin()) { --it2; (*it2)->m_zorder += DESIRED_GAP_SIZE + 1; } (*it)->m_zorder = (*first_non_ontop_it)->m_zorder + DESIRED_GAP_SIZE + 1; splice(first_non_ontop_it, *this, it); } } retval = true; } if (NeedsRealignment()) Realign(); return retval; } bool ZList::MoveDown(Wnd* wnd) { bool retval = false; iterator it = std::find(begin(), end(), wnd); if (it != end()) { int bottom_z = back()->m_zorder; if (back()->OnTop() || !wnd->OnTop()) { // if there are only on-top windows, or wnd is not an on-top window.. (*it)->m_zorder = bottom_z - (DESIRED_GAP_SIZE + 1); // ..just put wnd below the bottom element splice(end(), *this, it); } else { // !back()->OnTop() && wnd->OnTop(), so only move wnd up to just below the bottom of the on-top range iterator first_non_ontop_it = FirstNonOnTop(); int prev_z = (*--first_non_ontop_it)->m_zorder; int curr_z = (*++first_non_ontop_it)->m_zorder; if (prev_z - curr_z - 1 >= 3) { // if there's at least 3 positions in between.. (*it)->m_zorder = (*first_non_ontop_it)->m_zorder + (prev_z - curr_z - 1) / 2; // ..just stick wnd in the middle splice(first_non_ontop_it, *this, it); } else { // make room by bumping up all the on-top windows iterator it2 = first_non_ontop_it; (*--it2)->m_zorder += 2 * (DESIRED_GAP_SIZE + 1); // double the gap before first_non_ontop_it, to leave the right gap on either side of wnd while (it2 != begin()) { --it2; (*it2)->m_zorder += DESIRED_GAP_SIZE + 1; } (*it)->m_zorder = (*first_non_ontop_it)->m_zorder + DESIRED_GAP_SIZE + 1; splice(first_non_ontop_it, *this, it); } } retval = true; } if (NeedsRealignment()) Realign(); return retval; } Wnd* ZList::PickWithinWindow(const Pt& pt, Wnd* wnd) const { // if wnd is visible and clickable, return it if no child windows also catch pt Wnd* retval = (wnd->Visible() && wnd->Clickable()) ? wnd : 0; // look through all the children of wnd, and determine whether pt lies in any of them (or their children) std::list<Wnd*>::iterator end_it = wnd->m_children.end(); for (std::list<Wnd*>::iterator it = wnd->m_children.begin(); it != end_it; ++it) { Wnd* temp = 0; if ((*it)->InWindow(pt) && (temp = PickWithinWindow(pt, *it))) { retval = temp; break; } } return retval; } bool ZList::NeedsRealignment() const { bool retval = false; if (unsigned int sz = size()) { int front_z = front()->m_zorder; int back_z = back()->m_zorder; int range = front_z - back_z + 1; int empty_slots = range - sz; double avg_gap = empty_slots / static_cast<double>(sz - 1); // empty slots over the number of spaces in between the elements bool max_span_impossible = DESIRED_GAP_SIZE * static_cast<double>(sz) > MAX_SPAN; // done with doubles to avoid integer overflow retval = ((range > MAX_SPAN && !max_span_impossible) || avg_gap > MAX_AVG_GAP_SIZE || avg_gap < MIN_AVG_GAP_SIZE || front_z > MAX_Z || back_z < MIN_Z); } return retval; } void ZList::Realign() { int z = DESIRED_LOWEST_Z; // z-value to place next element at for (reverse_iterator it = rbegin(); it != rend(); ++it) { (*it)->m_zorder = z; z += DESIRED_GAP_SIZE + 1; } } ZList::iterator ZList::FirstNonOnTop() { iterator retval = begin(); for (; retval != end(); ++retval) if (!(*retval)->OnTop()) break; return retval; } } // namespace GG <commit_msg>Adjusted PickWithinWindow() to account for the new ordering of child windows in Wnd.<commit_after>/* GG is a GUI for SDL and OpenGL. Copyright (C) 2003 T. Zachary Laine This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you do not wish to comply with the terms of the LGPL please contact the author as other terms are available for a fee. Zach Laine whatwasthataddress@hotmail.com */ /* $Header$ */ #include "GGZList.h" #include "GGWnd.h" namespace GG { namespace { const int DESIRED_GAP_SIZE = 10; // leaves room for 10-deep nested child windows (and that should be plenty) const int DESIRED_LOWEST_Z = 1 << 30; // start z-values at 1/4 of 32-bit int's positive range (2^32 / 4 = 2^30) const int MIN_Z = 1 << 29; // set low end of z-value range at 1/8 of 32-bit int's range (2^32 / 8 = 2^29) const int MAX_Z = 7 * MIN_Z; // set high end of z-value range at 7/8 of 32-bit int's range (7 * 2^32 / 8 = 7 * 2^29) const int MAX_AVG_GAP_SIZE = 15; // if things get too spread out.. const int MIN_AVG_GAP_SIZE = 5; // ..or too packed, compresion may be needed const int MAX_SPAN = 1 << 31; // windows should be laid out over no more than 1/2 of possible z-value range (2^32 / 2 = 2^31) }; /////////////////////////////////////// // class GG::ZList /////////////////////////////////////// Wnd* ZList::Pick(const Pt& pt, Wnd* modal) const { Wnd* retval = 0; if (modal) { // if a modal window is active, only look there retval = modal->InWindow(pt) ? PickWithinWindow(pt, modal) : 0; } else { // otherwise, look in the z-list const_iterator end_it = end(); for (const_iterator it = begin(); it != end_it; ++it) { Wnd* temp = 0; if ((*it)->InWindow(pt) && (temp = PickWithinWindow(pt, *it))) { retval = temp; break; } } } return retval; } void ZList::Add(Wnd* wnd) { if (m_contents.find(wnd) == m_contents.end()) { // add wnd to the end of the list... if (empty()) { // list empty wnd->m_zorder = DESIRED_LOWEST_Z; // by default, add first element at DESIRED_LOWEST_Z insert(begin(), wnd); } else { // list not empty wnd->m_zorder = back()->m_zorder - (DESIRED_GAP_SIZE + 1); insert(end(), wnd); } m_contents.insert(wnd); // then move it up to its proper place MoveUp(wnd); if (NeedsRealignment()) Realign(); } } bool ZList::Remove(Wnd* wnd) { bool retval = false; if (m_contents.find(wnd) != m_contents.end()) { iterator it = std::find(begin(), end(), wnd); if (it != end()) erase(it); if (NeedsRealignment()) Realign(); m_contents.erase(wnd); retval = true; } return retval; } bool ZList::MoveUp(Wnd* wnd) { bool retval = false; iterator it = std::find(begin(), end(), wnd); if (it != end()) { // note that this also implies !empty().. int top_z = front()->m_zorder; // ..so this is okay to do without checking if (!front()->OnTop() || wnd->OnTop()) { // if there are no on-top windows, or wnd is an on-top window.. (*it)->m_zorder = top_z + DESIRED_GAP_SIZE + 1; // ..just slap wnd on top of the topmost element splice(begin(), *this, it); } else { // front()->OnTop() && !wnd->OnTop(), so only move wnd up to just below the bottom of the on-top range iterator first_non_ontop_it = FirstNonOnTop(); int prev_z = (*--first_non_ontop_it)->m_zorder; int curr_z = (*++first_non_ontop_it)->m_zorder; if (prev_z - curr_z - 1 >= 3) { // if there's at least 3 positions in between.. (*it)->m_zorder = (*first_non_ontop_it)->m_zorder + (prev_z - curr_z - 1) / 2; // ..just stick wnd in the middle splice(first_non_ontop_it, *this, it); } else { // make room by bumping up all the on-top windows iterator it2 = first_non_ontop_it; (*--it2)->m_zorder += 2 * (DESIRED_GAP_SIZE + 1); // double the gap before first_non_ontop_it, to leave the right gap on either side of wnd while (it2 != begin()) { --it2; (*it2)->m_zorder += DESIRED_GAP_SIZE + 1; } (*it)->m_zorder = (*first_non_ontop_it)->m_zorder + DESIRED_GAP_SIZE + 1; splice(first_non_ontop_it, *this, it); } } retval = true; } if (NeedsRealignment()) Realign(); return retval; } bool ZList::MoveDown(Wnd* wnd) { bool retval = false; iterator it = std::find(begin(), end(), wnd); if (it != end()) { int bottom_z = back()->m_zorder; if (back()->OnTop() || !wnd->OnTop()) { // if there are only on-top windows, or wnd is not an on-top window.. (*it)->m_zorder = bottom_z - (DESIRED_GAP_SIZE + 1); // ..just put wnd below the bottom element splice(end(), *this, it); } else { // !back()->OnTop() && wnd->OnTop(), so only move wnd up to just below the bottom of the on-top range iterator first_non_ontop_it = FirstNonOnTop(); int prev_z = (*--first_non_ontop_it)->m_zorder; int curr_z = (*++first_non_ontop_it)->m_zorder; if (prev_z - curr_z - 1 >= 3) { // if there's at least 3 positions in between.. (*it)->m_zorder = (*first_non_ontop_it)->m_zorder + (prev_z - curr_z - 1) / 2; // ..just stick wnd in the middle splice(first_non_ontop_it, *this, it); } else { // make room by bumping up all the on-top windows iterator it2 = first_non_ontop_it; (*--it2)->m_zorder += 2 * (DESIRED_GAP_SIZE + 1); // double the gap before first_non_ontop_it, to leave the right gap on either side of wnd while (it2 != begin()) { --it2; (*it2)->m_zorder += DESIRED_GAP_SIZE + 1; } (*it)->m_zorder = (*first_non_ontop_it)->m_zorder + DESIRED_GAP_SIZE + 1; splice(first_non_ontop_it, *this, it); } } retval = true; } if (NeedsRealignment()) Realign(); return retval; } Wnd* ZList::PickWithinWindow(const Pt& pt, Wnd* wnd) const { // if wnd is visible and clickable, return it if no child windows also catch pt Wnd* retval = (wnd->Visible() && wnd->Clickable()) ? wnd : 0; // look through all the children of wnd, and determine whether pt lies in any of them (or their children) std::list<Wnd*>::reverse_iterator end_it = wnd->m_children.rend(); for (std::list<Wnd*>::reverse_iterator it = wnd->m_children.rbegin(); it != end_it; ++it) { Wnd* temp = 0; if ((*it)->InWindow(pt) && (temp = PickWithinWindow(pt, *it))) { retval = temp; break; } } return retval; } bool ZList::NeedsRealignment() const { bool retval = false; if (unsigned int sz = size()) { int front_z = front()->m_zorder; int back_z = back()->m_zorder; int range = front_z - back_z + 1; int empty_slots = range - sz; double avg_gap = empty_slots / static_cast<double>(sz - 1); // empty slots over the number of spaces in between the elements bool max_span_impossible = DESIRED_GAP_SIZE * static_cast<double>(sz) > MAX_SPAN; // done with doubles to avoid integer overflow retval = ((range > MAX_SPAN && !max_span_impossible) || avg_gap > MAX_AVG_GAP_SIZE || avg_gap < MIN_AVG_GAP_SIZE || front_z > MAX_Z || back_z < MIN_Z); } return retval; } void ZList::Realign() { int z = DESIRED_LOWEST_Z; // z-value to place next element at for (reverse_iterator it = rbegin(); it != rend(); ++it) { (*it)->m_zorder = z; z += DESIRED_GAP_SIZE + 1; } } ZList::iterator ZList::FirstNonOnTop() { iterator retval = begin(); for (; retval != end(); ++retval) if (!(*retval)->OnTop()) break; return retval; } } // namespace GG <|endoftext|>
<commit_before>#ifndef WF_UTIL_HPP #define WF_UTIL_HPP #include <functional> #include <pixman.h> extern "C" { #include <wlr/types/wlr_box.h> } /* ------------------ point and geometry utility functions ------------------ */ /* Format for log_* to use when printing wf_point/wf_geometry/wlr_box */ #define Prwp "(%d,%d)" #define Ewp(v) v.x, v.y /* Format for log_* to use when printing wf_geometry/wlr_box */ #define Prwg "(%d,%d %dx%d)" #define Ewg(v) v.x, v.y, v.width, v.height struct wf_point { int x, y; }; using wf_geometry = wlr_box; bool operator == (const wf_geometry& a, const wf_geometry& b); bool operator != (const wf_geometry& a, const wf_geometry& b); wf_point operator + (const wf_point& a, const wf_point& b); wf_point operator + (const wf_point& a, const wf_geometry& b); wf_geometry operator + (const wf_geometry &a, const wf_point& b); wf_point operator - (const wf_point& a); /* Returns true if point is inside rect */ bool operator & (const wf_geometry& rect, const wf_point& point); /* Returns true if the two geometries have a common point */ bool operator & (const wf_geometry& r1, const wf_geometry& r2); /* Returns the intersection of the two boxes, if the boxes don't intersect, * the resulting geometry has undefined (x,y) and width == height == 0 */ wf_geometry wf_geometry_intersection(const wf_geometry& r1, const wf_geometry& r2); /* ---------------------- pixman utility functions -------------------------- */ struct wf_region { wf_region(); /* Makes a copy of the given region */ wf_region(pixman_region32_t *damage); wf_region(const wlr_box& box); ~wf_region(); wf_region(const wf_region& other); wf_region(wf_region&& other); wf_region& operator = (const wf_region& other); wf_region& operator = (wf_region&& other); bool empty() const; void clear(); void expand_edges(int amount); pixman_box32_t get_extents() const; /* Translate the region */ wf_region operator + (const wf_point& vector) const; wf_region& operator += (const wf_point& vector); wf_region operator * (float scale) const; wf_region& operator *= (float scale); /* Region intersection */ wf_region operator & (const wlr_box& box) const; wf_region operator & (const wf_region& other) const; wf_region& operator &= (const wlr_box& box); wf_region& operator &= (const wf_region& other); /* Region union */ wf_region operator | (const wlr_box& other) const; wf_region operator | (const wf_region& other) const; wf_region& operator |= (const wlr_box& other); wf_region& operator |= (const wf_region& other); /* Subtract the box/region from the current region */ wf_region operator ^ (const wlr_box& box) const; wf_region operator ^ (const wf_region& other) const; wf_region& operator ^= (const wlr_box& box); wf_region& operator ^= (const wf_region& other); pixman_region32_t *to_pixman(); const pixman_box32_t* begin() const; const pixman_box32_t* end() const; private: pixman_region32_t _region; /* Returns a const-casted pixman_region32_t*, useful in const operators * where we use this->_region as only source for calculations, but pixman * won't let us pass a const pixman_region32_t* */ pixman_region32_t* unconst() const; }; wlr_box wlr_box_from_pixman_box(const pixman_box32_t& box); pixman_box32_t pixman_box_from_wlr_box(const wlr_box& box); /* ------------------------- misc helper functions ------------------------- */ int64_t timespec_to_msec(const timespec& ts); /* Returns current time in msec, using CLOCK_MONOTONIC as a base */ uint32_t get_current_time(); /* Ensure that value is in the interval [min, max] */ template<class T> T clamp(T value, T min, T max) { return std::min(std::max(value, min), max); } #endif /* end of include guard: WF_UTIL_HPP */ <commit_msg>api: add missing include <algorithm> for std::min/max<commit_after>#ifndef WF_UTIL_HPP #define WF_UTIL_HPP #include <algorithm> #include <functional> #include <pixman.h> extern "C" { #include <wlr/types/wlr_box.h> } /* ------------------ point and geometry utility functions ------------------ */ /* Format for log_* to use when printing wf_point/wf_geometry/wlr_box */ #define Prwp "(%d,%d)" #define Ewp(v) v.x, v.y /* Format for log_* to use when printing wf_geometry/wlr_box */ #define Prwg "(%d,%d %dx%d)" #define Ewg(v) v.x, v.y, v.width, v.height struct wf_point { int x, y; }; using wf_geometry = wlr_box; bool operator == (const wf_geometry& a, const wf_geometry& b); bool operator != (const wf_geometry& a, const wf_geometry& b); wf_point operator + (const wf_point& a, const wf_point& b); wf_point operator + (const wf_point& a, const wf_geometry& b); wf_geometry operator + (const wf_geometry &a, const wf_point& b); wf_point operator - (const wf_point& a); /* Returns true if point is inside rect */ bool operator & (const wf_geometry& rect, const wf_point& point); /* Returns true if the two geometries have a common point */ bool operator & (const wf_geometry& r1, const wf_geometry& r2); /* Returns the intersection of the two boxes, if the boxes don't intersect, * the resulting geometry has undefined (x,y) and width == height == 0 */ wf_geometry wf_geometry_intersection(const wf_geometry& r1, const wf_geometry& r2); /* ---------------------- pixman utility functions -------------------------- */ struct wf_region { wf_region(); /* Makes a copy of the given region */ wf_region(pixman_region32_t *damage); wf_region(const wlr_box& box); ~wf_region(); wf_region(const wf_region& other); wf_region(wf_region&& other); wf_region& operator = (const wf_region& other); wf_region& operator = (wf_region&& other); bool empty() const; void clear(); void expand_edges(int amount); pixman_box32_t get_extents() const; /* Translate the region */ wf_region operator + (const wf_point& vector) const; wf_region& operator += (const wf_point& vector); wf_region operator * (float scale) const; wf_region& operator *= (float scale); /* Region intersection */ wf_region operator & (const wlr_box& box) const; wf_region operator & (const wf_region& other) const; wf_region& operator &= (const wlr_box& box); wf_region& operator &= (const wf_region& other); /* Region union */ wf_region operator | (const wlr_box& other) const; wf_region operator | (const wf_region& other) const; wf_region& operator |= (const wlr_box& other); wf_region& operator |= (const wf_region& other); /* Subtract the box/region from the current region */ wf_region operator ^ (const wlr_box& box) const; wf_region operator ^ (const wf_region& other) const; wf_region& operator ^= (const wlr_box& box); wf_region& operator ^= (const wf_region& other); pixman_region32_t *to_pixman(); const pixman_box32_t* begin() const; const pixman_box32_t* end() const; private: pixman_region32_t _region; /* Returns a const-casted pixman_region32_t*, useful in const operators * where we use this->_region as only source for calculations, but pixman * won't let us pass a const pixman_region32_t* */ pixman_region32_t* unconst() const; }; wlr_box wlr_box_from_pixman_box(const pixman_box32_t& box); pixman_box32_t pixman_box_from_wlr_box(const wlr_box& box); /* ------------------------- misc helper functions ------------------------- */ int64_t timespec_to_msec(const timespec& ts); /* Returns current time in msec, using CLOCK_MONOTONIC as a base */ uint32_t get_current_time(); /* Ensure that value is in the interval [min, max] */ template<class T> T clamp(T value, T min, T max) { return std::min(std::max(value, min), max); } #endif /* end of include guard: WF_UTIL_HPP */ <|endoftext|>
<commit_before>/// /// @file help.cpp /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <iostream> #include <cstdlib> #include <string> using namespace std; namespace { const string helpMenu( "Usage: primecount x [OPTION]...\n" "Count the primes below x <= 10^27 using the prime counting function,\n" "by default the Deleglise-Rivat algorithm (-d) is used.\n" "\n" "Options:\n" " -a<N>, --alpha=<N> Tuning factor for LMO and Deleglise-Rivat\n" " -d, --deleglise_rivat Count primes using Deleglise-Rivat algorithm\n" " --legendre Count primes using Legendre's formula\n" " --lehmer Count primes using Lehmer's formula\n" " -l, --lmo Count primes using Lagarias-Miller-Odlyzko\n" " -m, --meissel Count primes using Meissel's formula\n" " --Li Approximate pi(x) using the logarithmic integral\n" " --Li_inverse Approximate the nth prime using Li^-1(x)\n" " -n, --nthprime Calculate the nth prime\n" " -p, --primesieve Count primes using the sieve of Eratosthenes\n" " -s, --status Print status info during computation\n" " --test Run various correctness tests and exit\n" " --time Print the time elapsed in seconds\n" " -t<N>, --threads=<N> Set the number of threads, 1 <= N <= CPU cores\n" " -v, --version Print version and license information\n" " -h, --help Print this help menu\n" "\n" "Examples:\n" " primecount 10**13\n" " primecount 10**13 --nthprime --threads=4" ); const string versionInfo( "primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n" "Copyright (C) 2015 Kim Walisch\n" "BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>" ); } // end namespace namespace primecount { void help() { cout << helpMenu << endl; exit(1); } void version() { cout << versionInfo << endl; exit(1); } } // namespace primecount <commit_msg>Update tuning factor documentation<commit_after>/// /// @file help.cpp /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <iostream> #include <cstdlib> #include <string> using namespace std; namespace { const string helpMenu( "Usage: primecount x [OPTION]...\n" "Count the primes below x <= 10^27 using the prime counting function,\n" "by default the Deleglise-Rivat algorithm (-d) is used.\n" "\n" "Options:\n" " -a<N>, --alpha=<N> Tuning factor, 1 <= alpha <= x^(1/6)\n" " -d, --deleglise_rivat Count primes using Deleglise-Rivat algorithm\n" " --legendre Count primes using Legendre's formula\n" " --lehmer Count primes using Lehmer's formula\n" " -l, --lmo Count primes using Lagarias-Miller-Odlyzko\n" " -m, --meissel Count primes using Meissel's formula\n" " --Li Approximate pi(x) using the logarithmic integral\n" " --Li_inverse Approximate the nth prime using Li^-1(x)\n" " -n, --nthprime Calculate the nth prime\n" " -p, --primesieve Count primes using the sieve of Eratosthenes\n" " -s, --status Print status info during computation\n" " --test Run various correctness tests and exit\n" " --time Print the time elapsed in seconds\n" " -t<N>, --threads=<N> Set the number of threads, 1 <= N <= CPU cores\n" " -v, --version Print version and license information\n" " -h, --help Print this help menu\n" "\n" "Examples:\n" " primecount 10**13\n" " primecount 10**13 --nthprime --threads=4" ); const string versionInfo( "primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n" "Copyright (C) 2015 Kim Walisch\n" "BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>" ); } // end namespace namespace primecount { void help() { cout << helpMenu << endl; exit(1); } void version() { cout << versionInfo << endl; exit(1); } } // namespace primecount <|endoftext|>
<commit_before>#include "html.h" #include "stylesheet.h" #include <algorithm> #include "document.h" void litehtml::css::parse_stylesheet(const tchar_t* str, const tchar_t* baseurl, const std::shared_ptr<document>& doc, const media_query_list::ptr& media) { tstring text = str; // remove comments tstring::size_type c_start = text.find(_t("/*")); while(c_start != tstring::npos) { tstring::size_type c_end = text.find(_t("*/"), c_start + 2); text.erase(c_start, c_end - c_start + 2); c_start = text.find(_t("/*")); } tstring::size_type pos = text.find_first_not_of(_t(" \n\r\t")); while(pos != tstring::npos) { while(pos != tstring::npos && text[pos] == _t('@')) { tstring::size_type sPos = pos; pos = text.find_first_of(_t("{"), pos); if(pos != tstring::npos && text[pos] == _t('{')) { pos = find_close_bracket(text, pos, _t('{'), _t('}')); } if(pos != tstring::npos) { parse_atrule(text.substr(sPos, pos - sPos + 1), baseurl, doc, media); } else { parse_atrule(text.substr(sPos), baseurl, doc, media); } if(pos != tstring::npos) { pos = text.find_first_not_of(_t(" \n\r\t"), pos + 1); } } if(pos == tstring::npos) { break; } tstring::size_type style_start = text.find(_t("{"), pos); tstring::size_type style_end = text.find(_t("}"), pos); if(style_start != tstring::npos && style_end != tstring::npos) { style::ptr st = std::make_shared<style>(); st->add(text.substr(style_start + 1, style_end - style_start - 1).c_str(), baseurl); parse_selectors(text.substr(pos, style_start - pos), st, media); if(media && doc) { doc->add_media_list(media); } pos = style_end + 1; } else { pos = tstring::npos; } if(pos != tstring::npos) { pos = text.find_first_not_of(_t(" \n\r\t"), pos); } } } void litehtml::css::parse_css_url( const tstring& str, tstring& url ) { url = _t(""); size_t pos1 = str.find(_t('(')); size_t pos2 = str.find(_t(')')); if(pos1 != tstring::npos && pos2 != tstring::npos) { url = str.substr(pos1 + 1, pos2 - pos1 - 1); if(url.length()) { if(url[0] == _t('\'') || url[0] == _t('"')) { url.erase(0, 1); } } if(url.length()) { if(url[url.length() - 1] == _t('\'') || url[url.length() - 1] == _t('"')) { url.erase(url.length() - 1, 1); } } } } bool litehtml::css::parse_selectors( const tstring& txt, const litehtml::style::ptr& styles, const media_query_list::ptr& media ) { tstring selector = txt; trim(selector); string_vector tokens; split_string(selector, tokens, _t(",")); bool added_something = false; for(string_vector::iterator tok = tokens.begin(); tok != tokens.end(); tok++) { css_selector::ptr selector = std::make_shared<css_selector>(media); selector->m_style = styles; trim(*tok); if(selector->parse(*tok)) { selector->calc_specificity(); add_selector(selector); added_something = true; } } return added_something; } void litehtml::css::sort_selectors() { sort(m_selectors.begin(), m_selectors.end(), std::less<css_selector::ptr>( )); } void litehtml::css::parse_atrule(const tstring& text, const tchar_t* baseurl, const std::shared_ptr<document>& doc, const media_query_list::ptr& media) { if(text.substr(0, 7) == _t("@import")) { int sPos = 7; tstring iStr; iStr = text.substr(sPos); if(iStr[iStr.length() - 1] == _t(';')) { iStr.erase(iStr.length() - 1); } trim(iStr); string_vector tokens; split_string(iStr, tokens, _t(" "), _t(""), _t("(\"")); if(!tokens.empty()) { tstring url; parse_css_url(tokens.front(), url); if(url.empty()) { url = tokens.front(); } tokens.erase(tokens.begin()); if(doc) { document_container* doc_cont = doc->container(); if(doc_cont) { tstring css_text; tstring css_baseurl; if(baseurl) { css_baseurl = baseurl; } doc_cont->import_css(css_text, url, css_baseurl); if(!css_text.empty()) { media_query_list::ptr new_media = media; if(!tokens.empty()) { tstring media_str; for(string_vector::iterator iter = tokens.begin(); iter != tokens.end(); iter++) { if(iter != tokens.begin()) { media_str += _t(" "); } media_str += (*iter); } new_media = media_query_list::create_from_string(media_str, doc); if(!new_media) { new_media = media; } } parse_stylesheet(css_text.c_str(), css_baseurl.c_str(), doc, new_media); } } } } } else if(text.substr(0, 6) == _t("@media")) { tstring::size_type b1 = text.find_first_of(_t('{')); tstring::size_type b2 = text.find_last_of(_t('}')); if(b1 != tstring::npos) { tstring media_type = text.substr(6, b1 - 6); trim(media_type); media_query_list::ptr new_media = media_query_list::create_from_string(media_type, doc); tstring media_style; if(b2 != tstring::npos) { media_style = text.substr(b1 + 1, b2 - b1 - 1); } else { media_style = text.substr(b1 + 1); } parse_stylesheet(media_style.c_str(), baseurl, doc, new_media); } } } <commit_msg>Removed std::less from a call to std::sort.<commit_after>#include "html.h" #include "stylesheet.h" #include <algorithm> #include "document.h" void litehtml::css::parse_stylesheet(const tchar_t* str, const tchar_t* baseurl, const std::shared_ptr<document>& doc, const media_query_list::ptr& media) { tstring text = str; // remove comments tstring::size_type c_start = text.find(_t("/*")); while(c_start != tstring::npos) { tstring::size_type c_end = text.find(_t("*/"), c_start + 2); text.erase(c_start, c_end - c_start + 2); c_start = text.find(_t("/*")); } tstring::size_type pos = text.find_first_not_of(_t(" \n\r\t")); while(pos != tstring::npos) { while(pos != tstring::npos && text[pos] == _t('@')) { tstring::size_type sPos = pos; pos = text.find_first_of(_t("{"), pos); if(pos != tstring::npos && text[pos] == _t('{')) { pos = find_close_bracket(text, pos, _t('{'), _t('}')); } if(pos != tstring::npos) { parse_atrule(text.substr(sPos, pos - sPos + 1), baseurl, doc, media); } else { parse_atrule(text.substr(sPos), baseurl, doc, media); } if(pos != tstring::npos) { pos = text.find_first_not_of(_t(" \n\r\t"), pos + 1); } } if(pos == tstring::npos) { break; } tstring::size_type style_start = text.find(_t("{"), pos); tstring::size_type style_end = text.find(_t("}"), pos); if(style_start != tstring::npos && style_end != tstring::npos) { style::ptr st = std::make_shared<style>(); st->add(text.substr(style_start + 1, style_end - style_start - 1).c_str(), baseurl); parse_selectors(text.substr(pos, style_start - pos), st, media); if(media && doc) { doc->add_media_list(media); } pos = style_end + 1; } else { pos = tstring::npos; } if(pos != tstring::npos) { pos = text.find_first_not_of(_t(" \n\r\t"), pos); } } } void litehtml::css::parse_css_url( const tstring& str, tstring& url ) { url = _t(""); size_t pos1 = str.find(_t('(')); size_t pos2 = str.find(_t(')')); if(pos1 != tstring::npos && pos2 != tstring::npos) { url = str.substr(pos1 + 1, pos2 - pos1 - 1); if(url.length()) { if(url[0] == _t('\'') || url[0] == _t('"')) { url.erase(0, 1); } } if(url.length()) { if(url[url.length() - 1] == _t('\'') || url[url.length() - 1] == _t('"')) { url.erase(url.length() - 1, 1); } } } } bool litehtml::css::parse_selectors( const tstring& txt, const litehtml::style::ptr& styles, const media_query_list::ptr& media ) { tstring selector = txt; trim(selector); string_vector tokens; split_string(selector, tokens, _t(",")); bool added_something = false; for(string_vector::iterator tok = tokens.begin(); tok != tokens.end(); tok++) { css_selector::ptr selector = std::make_shared<css_selector>(media); selector->m_style = styles; trim(*tok); if(selector->parse(*tok)) { selector->calc_specificity(); add_selector(selector); added_something = true; } } return added_something; } void litehtml::css::sort_selectors() { sort(m_selectors.begin(), m_selectors.end()); } void litehtml::css::parse_atrule(const tstring& text, const tchar_t* baseurl, const std::shared_ptr<document>& doc, const media_query_list::ptr& media) { if(text.substr(0, 7) == _t("@import")) { int sPos = 7; tstring iStr; iStr = text.substr(sPos); if(iStr[iStr.length() - 1] == _t(';')) { iStr.erase(iStr.length() - 1); } trim(iStr); string_vector tokens; split_string(iStr, tokens, _t(" "), _t(""), _t("(\"")); if(!tokens.empty()) { tstring url; parse_css_url(tokens.front(), url); if(url.empty()) { url = tokens.front(); } tokens.erase(tokens.begin()); if(doc) { document_container* doc_cont = doc->container(); if(doc_cont) { tstring css_text; tstring css_baseurl; if(baseurl) { css_baseurl = baseurl; } doc_cont->import_css(css_text, url, css_baseurl); if(!css_text.empty()) { media_query_list::ptr new_media = media; if(!tokens.empty()) { tstring media_str; for(string_vector::iterator iter = tokens.begin(); iter != tokens.end(); iter++) { if(iter != tokens.begin()) { media_str += _t(" "); } media_str += (*iter); } new_media = media_query_list::create_from_string(media_str, doc); if(!new_media) { new_media = media; } } parse_stylesheet(css_text.c_str(), css_baseurl.c_str(), doc, new_media); } } } } } else if(text.substr(0, 6) == _t("@media")) { tstring::size_type b1 = text.find_first_of(_t('{')); tstring::size_type b2 = text.find_last_of(_t('}')); if(b1 != tstring::npos) { tstring media_type = text.substr(6, b1 - 6); trim(media_type); media_query_list::ptr new_media = media_query_list::create_from_string(media_type, doc); tstring media_style; if(b2 != tstring::npos) { media_style = text.substr(b1 + 1, b2 - b1 - 1); } else { media_style = text.substr(b1 + 1); } parse_stylesheet(media_style.c_str(), baseurl, doc, new_media); } } } <|endoftext|>
<commit_before>#ifndef __ETERNAL_TCP_HEADERS__ #define __ETERNAL_TCP_HEADERS__ #include <arpa/inet.h> #include <errno.h> #include <pthread.h> /* POSIX Threads */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <algorithm> #include <array> #include <deque> #include <exception> #include <fstream> #include <iostream> #include <memory> #include <mutex> #include <set> #include <sstream> #include <streambuf> #include <string> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> #include <gflags/gflags.h> #include <glog/logging.h> #include <google/protobuf/message.h> #include "ET.pb.h" using namespace std; // The ET protocol version supported by this binary static const int PROTOCOL_VERSION = 3; // Nonces for CryptoHandler static const unsigned char CLIENT_SERVER_NONCE_MSB = 0; static const unsigned char SERVER_CLIENT_NONCE_MSB = 1; #define FATAL_FAIL(X) \ if (((X) == -1)) \ LOG(FATAL) << "Error: (" << errno << "): " << strerror(errno); template <typename Out> inline void split(const std::string &s, char delim, Out result) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } inline std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } #endif <commit_msg>rev protocol version<commit_after>#ifndef __ETERNAL_TCP_HEADERS__ #define __ETERNAL_TCP_HEADERS__ #include <arpa/inet.h> #include <errno.h> #include <pthread.h> /* POSIX Threads */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <algorithm> #include <array> #include <deque> #include <exception> #include <fstream> #include <iostream> #include <memory> #include <mutex> #include <set> #include <sstream> #include <streambuf> #include <string> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> #include <gflags/gflags.h> #include <glog/logging.h> #include <google/protobuf/message.h> #include "ET.pb.h" using namespace std; // The ET protocol version supported by this binary static const int PROTOCOL_VERSION = 4; // Nonces for CryptoHandler static const unsigned char CLIENT_SERVER_NONCE_MSB = 0; static const unsigned char SERVER_CLIENT_NONCE_MSB = 1; #define FATAL_FAIL(X) \ if (((X) == -1)) \ LOG(FATAL) << "Error: (" << errno << "): " << strerror(errno); template <typename Out> inline void split(const std::string &s, char delim, Out result) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } inline std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } #endif <|endoftext|>
<commit_before>// Module: Log4CPLUS // File: timehelper.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2013 Tad E. Smith // // 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 <log4cplus/helpers/timehelper.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/streams.h> #include <log4cplus/helpers/stringhelper.h> #include <log4cplus/internal/internal.h> #include <algorithm> #include <vector> #include <iomanip> #include <cassert> #include <cerrno> #if defined (UNICODE) #include <cwchar> #endif #if defined (LOG4CPLUS_HAVE_SYS_TYPES_H) #include <sys/types.h> #endif #if defined(LOG4CPLUS_HAVE_SYS_TIME_H) #include <sys/time.h> #endif #if defined (LOG4CPLUS_HAVE_SYS_TIMEB_H) #include <sys/timeb.h> #endif #if defined(LOG4CPLUS_HAVE_GMTIME_R) && !defined(LOG4CPLUS_SINGLE_THREADED) #define LOG4CPLUS_NEED_GMTIME_R #endif #if defined(LOG4CPLUS_HAVE_LOCALTIME_R) && !defined(LOG4CPLUS_SINGLE_THREADED) #define LOG4CPLUS_NEED_LOCALTIME_R #endif namespace log4cplus { namespace helpers { const int ONE_SEC_IN_USEC = 1000000; using std::mktime; using std::gmtime; using std::localtime; #if defined (UNICODE) using std::wcsftime; #else using std::strftime; #endif ////////////////////////////////////////////////////////////////////////////// // Time ctors ////////////////////////////////////////////////////////////////////////////// Time::Time() : tv_sec(0) , tv_usec(0) { } Time::Time(time_t tv_sec_, long tv_usec_) : tv_sec(tv_sec_) , tv_usec(tv_usec_) { assert (tv_usec < ONE_SEC_IN_USEC); } Time::Time(time_t time) : tv_sec(time) , tv_usec(0) { } Time Time::gettimeofday() { #if defined (LOG4CPLUS_HAVE_CLOCK_GETTIME) struct timespec ts; int res = clock_gettime (CLOCK_REALTIME, &ts); assert (res == 0); if (res != 0) LogLog::getLogLog ()->error ( LOG4CPLUS_TEXT("clock_gettime() has failed"), true); return Time (ts.tv_sec, ts.tv_nsec / 1000); #elif defined(LOG4CPLUS_HAVE_GETTIMEOFDAY) struct timeval tp; ::gettimeofday(&tp, 0); return Time(tp.tv_sec, tp.tv_usec); #elif defined (_WIN32) FILETIME ft; #if _WIN32_WINNT >= 0x602 GetSystemTimePreciseAsFileTime (&ft); #else GetSystemTimeAsFileTime (&ft); #endif typedef unsigned __int64 uint64_type; uint64_type st100ns = uint64_type (ft.dwHighDateTime) << 32 | ft.dwLowDateTime; // Number of 100-ns intervals between UNIX epoch and Windows system time // is 116444736000000000. uint64_type const offset = uint64_type (116444736) * 1000 * 1000 * 1000; uint64_type fixed_time = st100ns - offset; return Time (fixed_time / (10 * 1000 * 1000), fixed_time % (10 * 1000 * 1000) / 10); #elif defined(LOG4CPLUS_HAVE_FTIME) struct timeb tp; ftime(&tp); return Time(tp.time, tp.millitm * 1000); #else #warning "Time::gettimeofday()- low resolution timer: gettimeofday and ftime unavailable" return Time(::time(0), 0); #endif } ////////////////////////////////////////////////////////////////////////////// // Time methods ////////////////////////////////////////////////////////////////////////////// time_t Time::setTime(tm* t) { time_t time = helpers::mktime(t); if (time != -1) tv_sec = time; return time; } time_t Time::getTime() const { return tv_sec; } void Time::gmtime(tm* t) const { time_t clock = tv_sec; #if defined (LOG4CPLUS_HAVE_GMTIME_S) && defined (_MSC_VER) gmtime_s (t, &clock); #elif defined (LOG4CPLUS_HAVE_GMTIME_S) && defined (__BORLANDC__) gmtime_s (&clock, t); #elif defined (LOG4CPLUS_NEED_GMTIME_R) gmtime_r (&clock, t); #else tm* tmp = helpers::gmtime(&clock); *t = *tmp; #endif } void Time::localtime(tm* t) const { time_t clock = tv_sec; #ifdef LOG4CPLUS_NEED_LOCALTIME_R ::localtime_r(&clock, t); #else tm* tmp = helpers::localtime(&clock); *t = *tmp; #endif } namespace { static log4cplus::tstring const padding_zeros[4] = { log4cplus::tstring (LOG4CPLUS_TEXT("000")), log4cplus::tstring (LOG4CPLUS_TEXT("00")), log4cplus::tstring (LOG4CPLUS_TEXT("0")), log4cplus::tstring (LOG4CPLUS_TEXT("")) }; static log4cplus::tstring const uc_q_padding_zeros[4] = { log4cplus::tstring (LOG4CPLUS_TEXT(".000")), log4cplus::tstring (LOG4CPLUS_TEXT(".00")), log4cplus::tstring (LOG4CPLUS_TEXT(".0")), log4cplus::tstring (LOG4CPLUS_TEXT(".")) }; static void build_q_value (log4cplus::tstring & q_str, long tv_usec) { convertIntegerToString(q_str, tv_usec / 1000); std::size_t const len = q_str.length(); if (len <= 2) q_str.insert (0, padding_zeros[q_str.length()]); } static void build_uc_q_value (log4cplus::tstring & uc_q_str, long tv_usec, log4cplus::tstring & tmp) { build_q_value (uc_q_str, tv_usec); convertIntegerToString(tmp, tv_usec % 1000); std::size_t const usecs_len = tmp.length(); tmp.insert (0, usecs_len <= 3 ? uc_q_padding_zeros[usecs_len] : uc_q_padding_zeros[3]); uc_q_str.append (tmp); } } // namespace log4cplus::tstring Time::getFormattedTime(const log4cplus::tstring& fmt_orig, bool use_gmtime) const { if (fmt_orig.empty () || fmt_orig[0] == 0) return log4cplus::tstring (); tm time; if (use_gmtime) gmtime(&time); else localtime(&time); enum State { TEXT, PERCENT_SIGN }; internal::gft_scratch_pad & gft_sp = internal::get_gft_scratch_pad (); gft_sp.reset (); std::size_t const fmt_orig_size = gft_sp.fmt.size (); gft_sp.ret.reserve (fmt_orig_size + fmt_orig_size / 3); State state = TEXT; // Walk the format string and process all occurences of %q, %Q and %s. for (log4cplus::tstring::const_iterator fmt_it = fmt_orig.begin (); fmt_it != fmt_orig.end (); ++fmt_it) { switch (state) { case TEXT: { if (*fmt_it == LOG4CPLUS_TEXT ('%')) state = PERCENT_SIGN; else gft_sp.ret.push_back (*fmt_it); } break; case PERCENT_SIGN: { switch (*fmt_it) { case LOG4CPLUS_TEXT ('q'): { if (! gft_sp.q_str_valid) { build_q_value (gft_sp.q_str, tv_usec); gft_sp.q_str_valid = true; } gft_sp.ret.append (gft_sp.q_str); state = TEXT; } break; case LOG4CPLUS_TEXT ('Q'): { if (! gft_sp.uc_q_str_valid) { build_uc_q_value (gft_sp.uc_q_str, tv_usec, gft_sp.tmp); gft_sp.uc_q_str_valid = true; } gft_sp.ret.append (gft_sp.uc_q_str); state = TEXT; } break; // Windows do not support %s format specifier // (seconds since epoch). case LOG4CPLUS_TEXT ('s'): { if (! gft_sp.s_str_valid) { convertIntegerToString (gft_sp.s_str, tv_sec); gft_sp.s_str_valid = true; } gft_sp.ret.append (gft_sp.s_str); state = TEXT; } break; default: { gft_sp.ret.push_back (LOG4CPLUS_TEXT ('%')); gft_sp.ret.push_back (*fmt_it); state = TEXT; } } } break; } } // Finally call strftime/wcsftime to format the rest of the string. gft_sp.fmt.swap (gft_sp.ret); std::size_t buffer_size = gft_sp.fmt.size () + 1; std::size_t len; // Limit how far can the buffer grow. This is necessary so that we // catch bad format string. Some implementations of strftime() signal // both too small buffer and invalid format string by returning 0 // without changing errno. std::size_t const buffer_size_max = (std::max) (static_cast<std::size_t>(1024), buffer_size * 16); do { gft_sp.buffer.resize (buffer_size); errno = 0; #ifdef UNICODE len = helpers::wcsftime(&gft_sp.buffer[0], buffer_size, gft_sp.fmt.c_str(), &time); #else len = helpers::strftime(&gft_sp.buffer[0], buffer_size, gft_sp.fmt.c_str(), &time); #endif if (len == 0) { int const eno = errno; buffer_size *= 2; if (buffer_size > buffer_size_max) { LogLog::getLogLog ()->error ( LOG4CPLUS_TEXT("Error in strftime(): ") + convertIntegerToString (eno), true); } } } while (len == 0); return tstring (gft_sp.buffer.begin (), gft_sp.buffer.begin () + len); } Time& Time::operator+=(const Time& rhs) { tv_sec += rhs.tv_sec; tv_usec += rhs.tv_usec; if(tv_usec > ONE_SEC_IN_USEC) { ++tv_sec; tv_usec -= ONE_SEC_IN_USEC; } return *this; } Time& Time::operator-=(const Time& rhs) { tv_sec -= rhs.tv_sec; tv_usec -= rhs.tv_usec; if(tv_usec < 0) { --tv_sec; tv_usec += ONE_SEC_IN_USEC; } return *this; } Time& Time::operator/=(long rhs) { long rem_secs = static_cast<long>(tv_sec % rhs); tv_sec /= rhs; tv_usec /= rhs; tv_usec += static_cast<long>((rem_secs * ONE_SEC_IN_USEC) / rhs); return *this; } Time& Time::operator*=(long rhs) { long new_usec = tv_usec * rhs; long overflow_sec = new_usec / ONE_SEC_IN_USEC; tv_usec = new_usec % ONE_SEC_IN_USEC; tv_sec *= rhs; tv_sec += overflow_sec; return *this; } ////////////////////////////////////////////////////////////////////////////// // Time globals ////////////////////////////////////////////////////////////////////////////// const Time operator+(const Time& lhs, const Time& rhs) { return Time(lhs) += rhs; } const Time operator-(const Time& lhs, const Time& rhs) { return Time(lhs) -= rhs; } const Time operator/(const Time& lhs, long rhs) { return Time(lhs) /= rhs; } const Time operator*(const Time& lhs, long rhs) { return Time(lhs) *= rhs; } bool operator<(const Time& lhs, const Time& rhs) { return ( (lhs.sec() < rhs.sec()) || ( (lhs.sec() == rhs.sec()) && (lhs.usec() < rhs.usec())) ); } bool operator<=(const Time& lhs, const Time& rhs) { return ((lhs < rhs) || (lhs == rhs)); } bool operator>(const Time& lhs, const Time& rhs) { return ( (lhs.sec() > rhs.sec()) || ( (lhs.sec() == rhs.sec()) && (lhs.usec() > rhs.usec())) ); } bool operator>=(const Time& lhs, const Time& rhs) { return ((lhs > rhs) || (lhs == rhs)); } bool operator==(const Time& lhs, const Time& rhs) { return ( lhs.sec() == rhs.sec() && lhs.usec() == rhs.usec()); } bool operator!=(const Time& lhs, const Time& rhs) { return !(lhs == rhs); } } } // namespace log4cplus { namespace helpers { <commit_msg>timehelper.cxx (Time::gettimeofday): Fall back to different method of getting time in the unlikely case where clock_gettime() fails.<commit_after>// Module: Log4CPLUS // File: timehelper.cxx // Created: 4/2003 // Author: Tad E. Smith // // // Copyright 2003-2013 Tad E. Smith // // 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 <log4cplus/helpers/timehelper.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/streams.h> #include <log4cplus/helpers/stringhelper.h> #include <log4cplus/internal/internal.h> #include <algorithm> #include <vector> #include <iomanip> #include <cassert> #include <cerrno> #if defined (UNICODE) #include <cwchar> #endif #if defined (LOG4CPLUS_HAVE_SYS_TYPES_H) #include <sys/types.h> #endif #if defined(LOG4CPLUS_HAVE_SYS_TIME_H) #include <sys/time.h> #endif #if defined (LOG4CPLUS_HAVE_SYS_TIMEB_H) #include <sys/timeb.h> #endif #if defined(LOG4CPLUS_HAVE_GMTIME_R) && !defined(LOG4CPLUS_SINGLE_THREADED) #define LOG4CPLUS_NEED_GMTIME_R #endif #if defined(LOG4CPLUS_HAVE_LOCALTIME_R) && !defined(LOG4CPLUS_SINGLE_THREADED) #define LOG4CPLUS_NEED_LOCALTIME_R #endif namespace log4cplus { namespace helpers { const int ONE_SEC_IN_USEC = 1000000; using std::mktime; using std::gmtime; using std::localtime; #if defined (UNICODE) using std::wcsftime; #else using std::strftime; #endif ////////////////////////////////////////////////////////////////////////////// // Time ctors ////////////////////////////////////////////////////////////////////////////// Time::Time() : tv_sec(0) , tv_usec(0) { } Time::Time(time_t tv_sec_, long tv_usec_) : tv_sec(tv_sec_) , tv_usec(tv_usec_) { assert (tv_usec < ONE_SEC_IN_USEC); } Time::Time(time_t time) : tv_sec(time) , tv_usec(0) { } Time Time::gettimeofday() { #if defined (LOG4CPLUS_HAVE_CLOCK_GETTIME) struct timespec ts; int res = clock_gettime (CLOCK_REALTIME, &ts); if (LOG4CPLUS_LIKELY (res == 0)) return Time (ts.tv_sec, ts.tv_nsec / 1000); // Fall through down to a different method of obtaining time. #endif #if defined(LOG4CPLUS_HAVE_GETTIMEOFDAY) struct timeval tp; ::gettimeofday(&tp, 0); return Time(tp.tv_sec, tp.tv_usec); #elif defined (_WIN32) FILETIME ft; #if _WIN32_WINNT >= 0x602 GetSystemTimePreciseAsFileTime (&ft); #else GetSystemTimeAsFileTime (&ft); #endif typedef unsigned __int64 uint64_type; uint64_type st100ns = uint64_type (ft.dwHighDateTime) << 32 | ft.dwLowDateTime; // Number of 100-ns intervals between UNIX epoch and Windows system time // is 116444736000000000. uint64_type const offset = uint64_type (116444736) * 1000 * 1000 * 1000; uint64_type fixed_time = st100ns - offset; return Time (fixed_time / (10 * 1000 * 1000), fixed_time % (10 * 1000 * 1000) / 10); #elif defined(LOG4CPLUS_HAVE_FTIME) struct timeb tp; ftime(&tp); return Time(tp.time, tp.millitm * 1000); #else #warning "Time::gettimeofday()- low resolution timer: gettimeofday and ftime unavailable" return Time(::time(0), 0); #endif } ////////////////////////////////////////////////////////////////////////////// // Time methods ////////////////////////////////////////////////////////////////////////////// time_t Time::setTime(tm* t) { time_t time = helpers::mktime(t); if (time != -1) tv_sec = time; return time; } time_t Time::getTime() const { return tv_sec; } void Time::gmtime(tm* t) const { time_t clock = tv_sec; #if defined (LOG4CPLUS_HAVE_GMTIME_S) && defined (_MSC_VER) gmtime_s (t, &clock); #elif defined (LOG4CPLUS_HAVE_GMTIME_S) && defined (__BORLANDC__) gmtime_s (&clock, t); #elif defined (LOG4CPLUS_NEED_GMTIME_R) gmtime_r (&clock, t); #else tm* tmp = helpers::gmtime(&clock); *t = *tmp; #endif } void Time::localtime(tm* t) const { time_t clock = tv_sec; #ifdef LOG4CPLUS_NEED_LOCALTIME_R ::localtime_r(&clock, t); #else tm* tmp = helpers::localtime(&clock); *t = *tmp; #endif } namespace { static log4cplus::tstring const padding_zeros[4] = { log4cplus::tstring (LOG4CPLUS_TEXT("000")), log4cplus::tstring (LOG4CPLUS_TEXT("00")), log4cplus::tstring (LOG4CPLUS_TEXT("0")), log4cplus::tstring (LOG4CPLUS_TEXT("")) }; static log4cplus::tstring const uc_q_padding_zeros[4] = { log4cplus::tstring (LOG4CPLUS_TEXT(".000")), log4cplus::tstring (LOG4CPLUS_TEXT(".00")), log4cplus::tstring (LOG4CPLUS_TEXT(".0")), log4cplus::tstring (LOG4CPLUS_TEXT(".")) }; static void build_q_value (log4cplus::tstring & q_str, long tv_usec) { convertIntegerToString(q_str, tv_usec / 1000); std::size_t const len = q_str.length(); if (len <= 2) q_str.insert (0, padding_zeros[q_str.length()]); } static void build_uc_q_value (log4cplus::tstring & uc_q_str, long tv_usec, log4cplus::tstring & tmp) { build_q_value (uc_q_str, tv_usec); convertIntegerToString(tmp, tv_usec % 1000); std::size_t const usecs_len = tmp.length(); tmp.insert (0, usecs_len <= 3 ? uc_q_padding_zeros[usecs_len] : uc_q_padding_zeros[3]); uc_q_str.append (tmp); } } // namespace log4cplus::tstring Time::getFormattedTime(const log4cplus::tstring& fmt_orig, bool use_gmtime) const { if (fmt_orig.empty () || fmt_orig[0] == 0) return log4cplus::tstring (); tm time; if (use_gmtime) gmtime(&time); else localtime(&time); enum State { TEXT, PERCENT_SIGN }; internal::gft_scratch_pad & gft_sp = internal::get_gft_scratch_pad (); gft_sp.reset (); std::size_t const fmt_orig_size = gft_sp.fmt.size (); gft_sp.ret.reserve (fmt_orig_size + fmt_orig_size / 3); State state = TEXT; // Walk the format string and process all occurences of %q, %Q and %s. for (log4cplus::tstring::const_iterator fmt_it = fmt_orig.begin (); fmt_it != fmt_orig.end (); ++fmt_it) { switch (state) { case TEXT: { if (*fmt_it == LOG4CPLUS_TEXT ('%')) state = PERCENT_SIGN; else gft_sp.ret.push_back (*fmt_it); } break; case PERCENT_SIGN: { switch (*fmt_it) { case LOG4CPLUS_TEXT ('q'): { if (! gft_sp.q_str_valid) { build_q_value (gft_sp.q_str, tv_usec); gft_sp.q_str_valid = true; } gft_sp.ret.append (gft_sp.q_str); state = TEXT; } break; case LOG4CPLUS_TEXT ('Q'): { if (! gft_sp.uc_q_str_valid) { build_uc_q_value (gft_sp.uc_q_str, tv_usec, gft_sp.tmp); gft_sp.uc_q_str_valid = true; } gft_sp.ret.append (gft_sp.uc_q_str); state = TEXT; } break; // Windows do not support %s format specifier // (seconds since epoch). case LOG4CPLUS_TEXT ('s'): { if (! gft_sp.s_str_valid) { convertIntegerToString (gft_sp.s_str, tv_sec); gft_sp.s_str_valid = true; } gft_sp.ret.append (gft_sp.s_str); state = TEXT; } break; default: { gft_sp.ret.push_back (LOG4CPLUS_TEXT ('%')); gft_sp.ret.push_back (*fmt_it); state = TEXT; } } } break; } } // Finally call strftime/wcsftime to format the rest of the string. gft_sp.fmt.swap (gft_sp.ret); std::size_t buffer_size = gft_sp.fmt.size () + 1; std::size_t len; // Limit how far can the buffer grow. This is necessary so that we // catch bad format string. Some implementations of strftime() signal // both too small buffer and invalid format string by returning 0 // without changing errno. std::size_t const buffer_size_max = (std::max) (static_cast<std::size_t>(1024), buffer_size * 16); do { gft_sp.buffer.resize (buffer_size); errno = 0; #ifdef UNICODE len = helpers::wcsftime(&gft_sp.buffer[0], buffer_size, gft_sp.fmt.c_str(), &time); #else len = helpers::strftime(&gft_sp.buffer[0], buffer_size, gft_sp.fmt.c_str(), &time); #endif if (len == 0) { int const eno = errno; buffer_size *= 2; if (buffer_size > buffer_size_max) { LogLog::getLogLog ()->error ( LOG4CPLUS_TEXT("Error in strftime(): ") + convertIntegerToString (eno), true); } } } while (len == 0); return tstring (gft_sp.buffer.begin (), gft_sp.buffer.begin () + len); } Time& Time::operator+=(const Time& rhs) { tv_sec += rhs.tv_sec; tv_usec += rhs.tv_usec; if(tv_usec > ONE_SEC_IN_USEC) { ++tv_sec; tv_usec -= ONE_SEC_IN_USEC; } return *this; } Time& Time::operator-=(const Time& rhs) { tv_sec -= rhs.tv_sec; tv_usec -= rhs.tv_usec; if(tv_usec < 0) { --tv_sec; tv_usec += ONE_SEC_IN_USEC; } return *this; } Time& Time::operator/=(long rhs) { long rem_secs = static_cast<long>(tv_sec % rhs); tv_sec /= rhs; tv_usec /= rhs; tv_usec += static_cast<long>((rem_secs * ONE_SEC_IN_USEC) / rhs); return *this; } Time& Time::operator*=(long rhs) { long new_usec = tv_usec * rhs; long overflow_sec = new_usec / ONE_SEC_IN_USEC; tv_usec = new_usec % ONE_SEC_IN_USEC; tv_sec *= rhs; tv_sec += overflow_sec; return *this; } ////////////////////////////////////////////////////////////////////////////// // Time globals ////////////////////////////////////////////////////////////////////////////// const Time operator+(const Time& lhs, const Time& rhs) { return Time(lhs) += rhs; } const Time operator-(const Time& lhs, const Time& rhs) { return Time(lhs) -= rhs; } const Time operator/(const Time& lhs, long rhs) { return Time(lhs) /= rhs; } const Time operator*(const Time& lhs, long rhs) { return Time(lhs) *= rhs; } bool operator<(const Time& lhs, const Time& rhs) { return ( (lhs.sec() < rhs.sec()) || ( (lhs.sec() == rhs.sec()) && (lhs.usec() < rhs.usec())) ); } bool operator<=(const Time& lhs, const Time& rhs) { return ((lhs < rhs) || (lhs == rhs)); } bool operator>(const Time& lhs, const Time& rhs) { return ( (lhs.sec() > rhs.sec()) || ( (lhs.sec() == rhs.sec()) && (lhs.usec() > rhs.usec())) ); } bool operator>=(const Time& lhs, const Time& rhs) { return ((lhs > rhs) || (lhs == rhs)); } bool operator==(const Time& lhs, const Time& rhs) { return ( lhs.sec() == rhs.sec() && lhs.usec() == rhs.usec()); } bool operator!=(const Time& lhs, const Time& rhs) { return !(lhs == rhs); } } } // namespace log4cplus { namespace helpers { <|endoftext|>
<commit_before>#include "Huffman.hpp" Node::Node(double probability, Node* left, Node* right) : probability(probability), left(left), right(right), is_leaf(false) {} Node::Node(double probability, int symbol) : probability(probability), symbol(symbol), is_leaf(true), left(nullptr), right(nullptr) {} Node::~Node() { delete left; delete right; } int Node::height() const { if (is_leaf) return 0; else if (left && right) return std::max(left->height(), right->height()) + 1; else if (left) return left->height() + 1; else return right->height() + 1; } SymbolCodeMap generateCodeMap(std::vector<int> text) { assert(text.size() > 0); unordered_map<int, int> symbol_counts; for (auto& symbol : text) { if (symbol_counts.count(symbol) == 0) { symbol_counts.emplace(symbol, 1); } else { ++symbol_counts[symbol]; } } Node* root = generateHuffTree(symbol_counts, text.size()); // list of symbols grouped by code length // symbols_per_length = symbols[code_length] vector<vector<int>> symbols(root->height() + 1); generateSymbolsPerCodelength(root, symbols); SymbolCodeMap code_map = generateCodes(symbols); delete root; return code_map; } // TODO: use frequencies instead of propabilities (int instead of doubles) Node* generateHuffTree(unordered_map<int, int> symbol_counts, size_t total) { auto comp = [](const Node* lhs, const Node* rhs) { return lhs->probability > rhs->probability; }; priority_queue<Node*, vector<Node*>, decltype(comp)> nodes; // create a leaf node for every symbol // also calculate it's probability from the given count and total for (const auto& pair : symbol_counts) { // pair.first: symbol // pair.second: count nodes.emplace(new Node((double)pair.second / (double)total, pair.first)); } // combine the two nodes with lowest probability into a new one till only one is left while (nodes.size() > 1) { // least probable symbol or node Node* first = nodes.top(); nodes.pop(); // second least probable symbol or node Node* second = nodes.top(); nodes.pop(); nodes.emplace(new Node(first->probability + second->probability, first, second)); } Node* root = nodes.top(); // handle the case where we only have a single symbol if (root->is_leaf) return new Node(root->probability, root, nullptr); else return root; } void generateSymbolsPerCodelength(Node* node, vector<vector<int>>& symbols, int depth /* = 0 */) { if (node->is_leaf) { symbols[depth].push_back(node->symbol); } else { if (node->left) { generateSymbolsPerCodelength(node->left, symbols, depth + 1); } if (node->right) { generateSymbolsPerCodelength(node->right, symbols, depth + 1); } } } SymbolCodeMap generateCodes(vector<vector<int>>& symbols) { // based on the algorithm in // Reza Hashemian: Memory Efficient and High-speed Search Huffman Coding, 1995 SymbolCodeMap code_map; uint32_t code = 0; for (int length = 1; length < symbols.size(); length++) { for (int symbol : symbols[length]) { // TODO: for speed: make a post-processing step instead of checking inside the loop if (code == (1 << length) - 1) { // the very last code, prevent a code consisting of only 1s code_map[symbol] = Code(code << 1, length+1); } else { code_map[symbol] = Code(code, length); } ++code; } code <<= 1; } return code_map; } Bitstream huffmanEncode(vector<int> text, SymbolCodeMap code_map) { Bitstream result; for (auto symbol : text) { const Code& code = code_map[symbol]; result.push_back(code.code, code.length); } return result; } // fill everything to the right of the code with 1s uint32_t fillRestWithOnes(uint32_t code, uint8_t code_length) { return code | ((1 << (32 - code_length)) - 1); } DecodeEntry::DecodeEntry(uint32_t code, uint8_t code_length, int symbol) { this->symbol = symbol; this->code_length = code_length; this->code = fillRestWithOnes(code, code_length); } vector<int> huffmanDecode(Bitstream bitstream, SymbolCodeMap code_map) { vector<DecodeEntry> code_table; code_table.reserve(code_map.size()); uint8_t max_code_length = 0; // prepare code_table and calc max_code_length for (const std::pair<int, Code>& pair : code_map) { uint8_t code_length = pair.second.length; if (code_length > max_code_length) max_code_length = code_length; code_table.emplace_back(pair.second.code, code_length, pair.first); } assert(max_code_length <= 32); // sort accoring to code std::sort(code_table.begin(), code_table.end()); vector<int> decoded_text; uint8_t to_extract = max_code_length; // current pos in bitstream unsigned int pos = 0; while (pos < bitstream.size()) { // when we are at the end, we have to extract less if (pos + max_code_length >= bitstream.size()) to_extract = bitstream.size() - pos; uint32_t bits = bitstream.extract(to_extract, pos); bits = fillRestWithOnes(bits, max_code_length); // find matching symbol for extracted code // todo: binary search // linear search for now... int index = -1; for (int i = 0; i < code_table.size(); i++) { // first entry that is greater than the extracted bits if (code_table[i].code >= bits) { index = i; break; } } // no entry found // some better error handling? assert(index != -1); decoded_text.push_back(code_table[index].symbol); // next position to extract from pos += code_table[index].code_length; } return decoded_text; }<commit_msg>removed unnecessary check if element was already present in container<commit_after>#include "Huffman.hpp" Node::Node(double probability, Node* left, Node* right) : probability(probability), left(left), right(right), is_leaf(false) {} Node::Node(double probability, int symbol) : probability(probability), symbol(symbol), is_leaf(true), left(nullptr), right(nullptr) {} Node::~Node() { delete left; delete right; } int Node::height() const { if (is_leaf) return 0; else if (left && right) return std::max(left->height(), right->height()) + 1; else if (left) return left->height() + 1; else return right->height() + 1; } SymbolCodeMap generateCodeMap(std::vector<int> text) { assert(text.size() > 0); unordered_map<int, int> symbol_counts; for (auto& symbol : text) { ++symbol_counts[symbol]; } Node* root = generateHuffTree(symbol_counts, text.size()); // list of symbols grouped by code length // symbols_per_length = symbols[code_length] vector<vector<int>> symbols(root->height() + 1); generateSymbolsPerCodelength(root, symbols); SymbolCodeMap code_map = generateCodes(symbols); delete root; return code_map; } // TODO: use frequencies instead of propabilities (int instead of doubles) Node* generateHuffTree(unordered_map<int, int> symbol_counts, size_t total) { auto comp = [](const Node* lhs, const Node* rhs) { return lhs->probability > rhs->probability; }; priority_queue<Node*, vector<Node*>, decltype(comp)> nodes; // create a leaf node for every symbol // also calculate it's probability from the given count and total for (const auto& pair : symbol_counts) { // pair.first: symbol // pair.second: count nodes.emplace(new Node((double)pair.second / (double)total, pair.first)); } // combine the two nodes with lowest probability into a new one till only one is left while (nodes.size() > 1) { // least probable symbol or node Node* first = nodes.top(); nodes.pop(); // second least probable symbol or node Node* second = nodes.top(); nodes.pop(); nodes.emplace(new Node(first->probability + second->probability, first, second)); } Node* root = nodes.top(); // handle the case where we only have a single symbol if (root->is_leaf) return new Node(root->probability, root, nullptr); else return root; } void generateSymbolsPerCodelength(Node* node, vector<vector<int>>& symbols, int depth /* = 0 */) { if (node->is_leaf) { symbols[depth].push_back(node->symbol); } else { if (node->left) { generateSymbolsPerCodelength(node->left, symbols, depth + 1); } if (node->right) { generateSymbolsPerCodelength(node->right, symbols, depth + 1); } } } SymbolCodeMap generateCodes(vector<vector<int>>& symbols) { // based on the algorithm in // Reza Hashemian: Memory Efficient and High-speed Search Huffman Coding, 1995 SymbolCodeMap code_map; uint32_t code = 0; for (int length = 1; length < symbols.size(); length++) { for (int symbol : symbols[length]) { // TODO: for speed: make a post-processing step instead of checking inside the loop if (code == (1 << length) - 1) { // the very last code, prevent a code consisting of only 1s code_map[symbol] = Code(code << 1, length+1); } else { code_map[symbol] = Code(code, length); } ++code; } code <<= 1; } return code_map; } Bitstream huffmanEncode(vector<int> text, SymbolCodeMap code_map) { Bitstream result; for (auto symbol : text) { const Code& code = code_map[symbol]; result.push_back(code.code, code.length); } return result; } // fill everything to the right of the code with 1s uint32_t fillRestWithOnes(uint32_t code, uint8_t code_length) { return code | ((1 << (32 - code_length)) - 1); } DecodeEntry::DecodeEntry(uint32_t code, uint8_t code_length, int symbol) { this->symbol = symbol; this->code_length = code_length; this->code = fillRestWithOnes(code, code_length); } vector<int> huffmanDecode(Bitstream bitstream, SymbolCodeMap code_map) { vector<DecodeEntry> code_table; code_table.reserve(code_map.size()); uint8_t max_code_length = 0; // prepare code_table and calc max_code_length for (const std::pair<int, Code>& pair : code_map) { uint8_t code_length = pair.second.length; if (code_length > max_code_length) max_code_length = code_length; code_table.emplace_back(pair.second.code, code_length, pair.first); } assert(max_code_length <= 32); // sort accoring to code std::sort(code_table.begin(), code_table.end()); vector<int> decoded_text; uint8_t to_extract = max_code_length; // current pos in bitstream unsigned int pos = 0; while (pos < bitstream.size()) { // when we are at the end, we have to extract less if (pos + max_code_length >= bitstream.size()) to_extract = bitstream.size() - pos; uint32_t bits = bitstream.extract(to_extract, pos); bits = fillRestWithOnes(bits, max_code_length); // find matching symbol for extracted code // todo: binary search // linear search for now... int index = -1; for (int i = 0; i < code_table.size(); i++) { // first entry that is greater than the extracted bits if (code_table[i].code >= bits) { index = i; break; } } // no entry found // some better error handling? assert(index != -1); decoded_text.push_back(code_table[index].symbol); // next position to extract from pos += code_table[index].code_length; } return decoded_text; }<|endoftext|>
<commit_before>#include <iostream> #include <map> #include "IRVisitor.h" #include "IRMatch.h" #include "IREquality.h" #include "IROperator.h" namespace Halide { namespace Internal { using std::vector; using std::map; using std::string; void expr_match_test() { vector<Expr> matches; Expr w = Variable::make(Int(32), "*"); Expr fw = Variable::make(Float(32), "*"); Expr x = Variable::make(Int(32), "x"); Expr y = Variable::make(Int(32), "y"); Expr fx = Variable::make(Float(32), "fx"); Expr fy = Variable::make(Float(32), "fy"); Expr vec_wild = Variable::make(Int(32, 4), "*"); internal_assert(expr_match(w, 3, matches) && equal(matches[0], 3)); internal_assert(expr_match(w + 3, (y*2) + 3, matches) && equal(matches[0], y*2)); internal_assert(expr_match(fw * 17 + cast<float>(w + cast<int>(fw)), (81.0f * fy) * 17 + cast<float>(x/2 + cast<int>(x + 4.5f)), matches) && equal(matches[0], 81.0f * fy) && equal(matches[1], x/2) && equal(matches[2], x + 4.5f)) << matches[0] << ", " << matches[1] << ", " << matches[2] << "\n"; internal_assert(!expr_match(fw + 17, fx + 18, matches) && matches.empty()); internal_assert(!expr_match((w*2) + 17, fx + 17, matches) && matches.empty()); internal_assert(!expr_match(w * 3, 3 * x, matches) && matches.empty()); internal_assert(expr_match(vec_wild * 3, Ramp::make(x, y, 4) * 3, matches)); std::cout << "expr_match test passed" << std::endl; } class IRMatch : public IRVisitor { public: bool result; vector<Expr> *matches; map<string, Expr> *var_matches; Expr expr; IRMatch(Expr e, vector<Expr> &m) : result(true), matches(&m), var_matches(NULL), expr(e) { } IRMatch(Expr e, map<string, Expr> &m) : result(true), matches(NULL), var_matches(&m), expr(e) { } using IRVisitor::visit; bool types_match(Type pattern_type, Type expr_type) { bool bits_matches = (pattern_type.bits == -1) || (pattern_type.bits == expr_type.bits); bool width_matches = (pattern_type.width == -1) || (pattern_type.width == expr_type.width); bool code_matches = (pattern_type.code == expr_type.code); return bits_matches && width_matches && code_matches; } void visit(const IntImm *op) { const IntImm *e = expr.as<IntImm>(); if (!e || e->value != op->value || !types_match(op->type, e->type)) { result = false; } } void visit(const UIntImm *op) { const UIntImm *e = expr.as<UIntImm>(); if (!e || e->value != op->value || !types_match(op->type, e->type)) { result = false; } } void visit(const FloatImm *op) { const FloatImm *e = expr.as<FloatImm>(); // Note we use uint64_t equality instead of double equality to // catch NaNs. We're checking for the same bits. if (!e || reinterpret_bits<uint64_t>(e->value) != reinterpret_bits<uint64_t>(op->value) || !types_match(op->type, e->type)) { result = false; } } void visit(const Cast *op) { const Cast *e = expr.as<Cast>(); if (result && e && types_match(op->type, e->type)) { expr = e->value; op->value.accept(this); } else { result = false; } } void visit(const Variable *op) { if (!result) { return; } if (!types_match(op->type, expr.type())) { result = false; } else if (matches) { if (op->name == "*") { matches->push_back(expr); } else { const Variable *e = expr.as<Variable>(); result = e && (e->name == op->name); } } else if (var_matches) { Expr &match = (*var_matches)[op->name]; if (match.defined()) { result = equal(match, expr); } else { match = expr; } } } template<typename T> void visit_binary_operator(const T *op) { const T *e = expr.as<T>(); if (result && e) { expr = e->a; op->a.accept(this); expr = e->b; op->b.accept(this); } else { result = false; } } void visit(const Add *op) {visit_binary_operator(op);} void visit(const Sub *op) {visit_binary_operator(op);} void visit(const Mul *op) {visit_binary_operator(op);} void visit(const Div *op) {visit_binary_operator(op);} void visit(const Mod *op) {visit_binary_operator(op);} void visit(const Min *op) {visit_binary_operator(op);} void visit(const Max *op) {visit_binary_operator(op);} void visit(const EQ *op) {visit_binary_operator(op);} void visit(const NE *op) {visit_binary_operator(op);} void visit(const LT *op) {visit_binary_operator(op);} void visit(const LE *op) {visit_binary_operator(op);} void visit(const GT *op) {visit_binary_operator(op);} void visit(const GE *op) {visit_binary_operator(op);} void visit(const And *op) {visit_binary_operator(op);} void visit(const Or *op) {visit_binary_operator(op);} void visit(const Not *op) { const Not *e = expr.as<Not>(); if (result && e) { expr = e->a; op->a.accept(this); } else { result = false; } } void visit(const Select *op) { const Select *e = expr.as<Select>(); if (result && e) { expr = e->condition; op->condition.accept(this); expr = e->true_value; op->true_value.accept(this); expr = e->false_value; op->false_value.accept(this); } else { result = false; } } void visit(const Load *op) { const Load *e = expr.as<Load>(); if (result && e && types_match(op->type, e->type) && e->name == op->name) { expr = e->index; op->index.accept(this); } else { result = false; } } void visit(const Ramp *op) { const Ramp *e = expr.as<Ramp>(); if (result && e && e->width == op->width) { expr = e->base; op->base.accept(this); expr = e->stride; op->stride.accept(this); } else { result = false; } } void visit(const Broadcast *op) { const Broadcast *e = expr.as<Broadcast>(); if (result && e && types_match(op->type, e->type)) { expr = e->value; op->value.accept(this); } else { result = false; } } void visit(const Call *op) { const Call *e = expr.as<Call>(); if (result && e && types_match(op->type, e->type) && e->name == op->name && e->value_index == op->value_index && e->call_type == op->call_type && e->args.size() == op->args.size()) { for (size_t i = 0; result && (i < e->args.size()); i++) { expr = e->args[i]; op->args[i].accept(this); } } else { result = false; } } void visit(const Let *op) { const Let *e = expr.as<Let>(); if (result && e && e->name == op->name) { expr = e->value; op->value.accept(this); expr = e->body; op->body.accept(this); } else { result = false; } } }; bool expr_match(Expr pattern, Expr expr, vector<Expr> &matches) { matches.clear(); if (!pattern.defined() && !expr.defined()) return true; if (!pattern.defined() || !expr.defined()) return false; IRMatch eq(expr, matches); pattern.accept(&eq); if (eq.result) { return true; } else { matches.clear(); return false; } } bool expr_match(Expr pattern, Expr expr, map<string, Expr> &matches) { // Explicitly don't clear matches. This allows usages to pre-match // some variables. if (!pattern.defined() && !expr.defined()) return true; if (!pattern.defined() || !expr.defined()) return false; IRMatch eq(expr, matches); pattern.accept(&eq); if (eq.result) { return true; } else { matches.clear(); return false; } } }} <commit_msg>Fix technical out-of-bounds read in IRMatch test<commit_after>#include <iostream> #include <map> #include "IRVisitor.h" #include "IRMatch.h" #include "IREquality.h" #include "IROperator.h" namespace Halide { namespace Internal { using std::vector; using std::map; using std::string; void expr_match_test() { vector<Expr> matches; Expr w = Variable::make(Int(32), "*"); Expr fw = Variable::make(Float(32), "*"); Expr x = Variable::make(Int(32), "x"); Expr y = Variable::make(Int(32), "y"); Expr fx = Variable::make(Float(32), "fx"); Expr fy = Variable::make(Float(32), "fy"); Expr vec_wild = Variable::make(Int(32, 4), "*"); internal_assert(expr_match(w, 3, matches) && equal(matches[0], 3)); internal_assert(expr_match(w + 3, (y*2) + 3, matches) && equal(matches[0], y*2)); internal_assert(expr_match(fw * 17 + cast<float>(w + cast<int>(fw)), (81.0f * fy) * 17 + cast<float>(x/2 + cast<int>(x + 4.5f)), matches) && matches.size() == 3 && equal(matches[0], 81.0f * fy) && equal(matches[1], x/2) && equal(matches[2], x + 4.5f)); internal_assert(!expr_match(fw + 17, fx + 18, matches) && matches.empty()); internal_assert(!expr_match((w*2) + 17, fx + 17, matches) && matches.empty()); internal_assert(!expr_match(w * 3, 3 * x, matches) && matches.empty()); internal_assert(expr_match(vec_wild * 3, Ramp::make(x, y, 4) * 3, matches)); std::cout << "expr_match test passed" << std::endl; } class IRMatch : public IRVisitor { public: bool result; vector<Expr> *matches; map<string, Expr> *var_matches; Expr expr; IRMatch(Expr e, vector<Expr> &m) : result(true), matches(&m), var_matches(NULL), expr(e) { } IRMatch(Expr e, map<string, Expr> &m) : result(true), matches(NULL), var_matches(&m), expr(e) { } using IRVisitor::visit; bool types_match(Type pattern_type, Type expr_type) { bool bits_matches = (pattern_type.bits == -1) || (pattern_type.bits == expr_type.bits); bool width_matches = (pattern_type.width == -1) || (pattern_type.width == expr_type.width); bool code_matches = (pattern_type.code == expr_type.code); return bits_matches && width_matches && code_matches; } void visit(const IntImm *op) { const IntImm *e = expr.as<IntImm>(); if (!e || e->value != op->value || !types_match(op->type, e->type)) { result = false; } } void visit(const UIntImm *op) { const UIntImm *e = expr.as<UIntImm>(); if (!e || e->value != op->value || !types_match(op->type, e->type)) { result = false; } } void visit(const FloatImm *op) { const FloatImm *e = expr.as<FloatImm>(); // Note we use uint64_t equality instead of double equality to // catch NaNs. We're checking for the same bits. if (!e || reinterpret_bits<uint64_t>(e->value) != reinterpret_bits<uint64_t>(op->value) || !types_match(op->type, e->type)) { result = false; } } void visit(const Cast *op) { const Cast *e = expr.as<Cast>(); if (result && e && types_match(op->type, e->type)) { expr = e->value; op->value.accept(this); } else { result = false; } } void visit(const Variable *op) { if (!result) { return; } if (!types_match(op->type, expr.type())) { result = false; } else if (matches) { if (op->name == "*") { matches->push_back(expr); } else { const Variable *e = expr.as<Variable>(); result = e && (e->name == op->name); } } else if (var_matches) { Expr &match = (*var_matches)[op->name]; if (match.defined()) { result = equal(match, expr); } else { match = expr; } } } template<typename T> void visit_binary_operator(const T *op) { const T *e = expr.as<T>(); if (result && e) { expr = e->a; op->a.accept(this); expr = e->b; op->b.accept(this); } else { result = false; } } void visit(const Add *op) {visit_binary_operator(op);} void visit(const Sub *op) {visit_binary_operator(op);} void visit(const Mul *op) {visit_binary_operator(op);} void visit(const Div *op) {visit_binary_operator(op);} void visit(const Mod *op) {visit_binary_operator(op);} void visit(const Min *op) {visit_binary_operator(op);} void visit(const Max *op) {visit_binary_operator(op);} void visit(const EQ *op) {visit_binary_operator(op);} void visit(const NE *op) {visit_binary_operator(op);} void visit(const LT *op) {visit_binary_operator(op);} void visit(const LE *op) {visit_binary_operator(op);} void visit(const GT *op) {visit_binary_operator(op);} void visit(const GE *op) {visit_binary_operator(op);} void visit(const And *op) {visit_binary_operator(op);} void visit(const Or *op) {visit_binary_operator(op);} void visit(const Not *op) { const Not *e = expr.as<Not>(); if (result && e) { expr = e->a; op->a.accept(this); } else { result = false; } } void visit(const Select *op) { const Select *e = expr.as<Select>(); if (result && e) { expr = e->condition; op->condition.accept(this); expr = e->true_value; op->true_value.accept(this); expr = e->false_value; op->false_value.accept(this); } else { result = false; } } void visit(const Load *op) { const Load *e = expr.as<Load>(); if (result && e && types_match(op->type, e->type) && e->name == op->name) { expr = e->index; op->index.accept(this); } else { result = false; } } void visit(const Ramp *op) { const Ramp *e = expr.as<Ramp>(); if (result && e && e->width == op->width) { expr = e->base; op->base.accept(this); expr = e->stride; op->stride.accept(this); } else { result = false; } } void visit(const Broadcast *op) { const Broadcast *e = expr.as<Broadcast>(); if (result && e && types_match(op->type, e->type)) { expr = e->value; op->value.accept(this); } else { result = false; } } void visit(const Call *op) { const Call *e = expr.as<Call>(); if (result && e && types_match(op->type, e->type) && e->name == op->name && e->value_index == op->value_index && e->call_type == op->call_type && e->args.size() == op->args.size()) { for (size_t i = 0; result && (i < e->args.size()); i++) { expr = e->args[i]; op->args[i].accept(this); } } else { result = false; } } void visit(const Let *op) { const Let *e = expr.as<Let>(); if (result && e && e->name == op->name) { expr = e->value; op->value.accept(this); expr = e->body; op->body.accept(this); } else { result = false; } } }; bool expr_match(Expr pattern, Expr expr, vector<Expr> &matches) { matches.clear(); if (!pattern.defined() && !expr.defined()) return true; if (!pattern.defined() || !expr.defined()) return false; IRMatch eq(expr, matches); pattern.accept(&eq); if (eq.result) { return true; } else { matches.clear(); return false; } } bool expr_match(Expr pattern, Expr expr, map<string, Expr> &matches) { // Explicitly don't clear matches. This allows usages to pre-match // some variables. if (!pattern.defined() && !expr.defined()) return true; if (!pattern.defined() || !expr.defined()) return false; IRMatch eq(expr, matches); pattern.accept(&eq); if (eq.result) { return true; } else { matches.clear(); return false; } } }} <|endoftext|>
<commit_before>/* * Verify URI parts. * * author: Max Kellermann <mk@cm4all.com> */ #include "uri_verify.hxx" #include "uri_chars.hxx" #include <string.h> bool uri_segment_verify(const char *src, const char *end) { for (; src < end; ++src) { /* XXX check for invalid escaped characters? */ if (!char_is_uri_pchar(*src)) return false; } return true; } bool uri_path_verify(const char *src, size_t length) { const char *end = src + length, *slash; if (length == 0 || src[0] != '/') /* path must begin with slash */ return false; ++src; while (src < end) { slash = (const char *)memchr(src, '/', end - src); if (slash == nullptr) slash = end; if (!uri_segment_verify(src, slash)) return false; src = slash + 1; } return true; } static bool is_encoded_dot(const char *p) { return p[0] == '%' && p[1] == '2' && (p[2] == 'e' || p[2] == 'E'); } bool uri_path_verify_paranoid(const char *uri) { if (uri[0] == '.' && (uri[1] == 0 || uri[1] == '/' || (uri[1] == '.' && (uri[2] == 0 || uri[2] == '/')) || is_encoded_dot(uri + 1))) /* no ".", "..", "./", "../" */ return false; if (is_encoded_dot(uri)) return false; while (*uri != 0 && *uri != '?') { if (*uri == '%') { ++uri; if (uri[0] == '0' && uri[1] == '0') /* don't allow an encoded NUL character */ return false; if (uri[0] == '2' && (uri[1] == 'f' || uri[1] == 'F')) /* don't allow an encoded slash (somebody trying to hide a hack?) */ return false; } else if (*uri == '/') { ++uri; if (is_encoded_dot(uri)) /* encoded dot after a slash - what's this client trying to hide? */ return false; if (*uri == '.') { ++uri; if (is_encoded_dot(uri)) /* encoded dot after a real dot - smells fishy */ return false; if (*uri == 0 || *uri == '/') return false; if (*uri == '.') /* disallow two dots after a slash, even if something else follows - this is the paranoid function after all! */ return false; } } else ++uri; } return true; } bool uri_path_verify_quick(const char *uri) { if (*uri != '/') /* must begin with a slash */ return false; for (++uri; *uri != 0; ++uri) if ((signed char)*uri <= 0x20) return false; return uri; } <commit_msg>uri_verify: rename is_encoded_dot()<commit_after>/* * Verify URI parts. * * author: Max Kellermann <mk@cm4all.com> */ #include "uri_verify.hxx" #include "uri_chars.hxx" #include <string.h> bool uri_segment_verify(const char *src, const char *end) { for (; src < end; ++src) { /* XXX check for invalid escaped characters? */ if (!char_is_uri_pchar(*src)) return false; } return true; } bool uri_path_verify(const char *src, size_t length) { const char *end = src + length, *slash; if (length == 0 || src[0] != '/') /* path must begin with slash */ return false; ++src; while (src < end) { slash = (const char *)memchr(src, '/', end - src); if (slash == nullptr) slash = end; if (!uri_segment_verify(src, slash)) return false; src = slash + 1; } return true; } static bool IsEncodedDot(const char *p) { return p[0] == '%' && p[1] == '2' && (p[2] == 'e' || p[2] == 'E'); } bool uri_path_verify_paranoid(const char *uri) { if (uri[0] == '.' && (uri[1] == 0 || uri[1] == '/' || (uri[1] == '.' && (uri[2] == 0 || uri[2] == '/')) || IsEncodedDot(uri + 1))) /* no ".", "..", "./", "../" */ return false; if (IsEncodedDot(uri)) return false; while (*uri != 0 && *uri != '?') { if (*uri == '%') { ++uri; if (uri[0] == '0' && uri[1] == '0') /* don't allow an encoded NUL character */ return false; if (uri[0] == '2' && (uri[1] == 'f' || uri[1] == 'F')) /* don't allow an encoded slash (somebody trying to hide a hack?) */ return false; } else if (*uri == '/') { ++uri; if (IsEncodedDot(uri)) /* encoded dot after a slash - what's this client trying to hide? */ return false; if (*uri == '.') { ++uri; if (IsEncodedDot(uri)) /* encoded dot after a real dot - smells fishy */ return false; if (*uri == 0 || *uri == '/') return false; if (*uri == '.') /* disallow two dots after a slash, even if something else follows - this is the paranoid function after all! */ return false; } } else ++uri; } return true; } bool uri_path_verify_quick(const char *uri) { if (*uri != '/') /* must begin with a slash */ return false; for (++uri; *uri != 0; ++uri) if ((signed char)*uri <= 0x20) return false; return uri; } <|endoftext|>
<commit_before>#include <sstream> #include <llvm/ADT/StringRef.h> #include <llvm/ADT/STLExtras.h> #include <llvm/Support/ErrorHandling.h> #include "type.h" #include "decl.h" #include "../support/utility.h" using namespace delta; #define DEFINE_BUILTIN_TYPE_GET_AND_IS(TYPE, NAME) \ Type Type::get##TYPE(bool isMutable) { \ static BasicType type(#NAME, /*genericArgs*/ {}); \ return Type(&type, isMutable); \ } \ bool Type::is##TYPE() const { \ return isBasicType() && getName() == #NAME; \ } DEFINE_BUILTIN_TYPE_GET_AND_IS(Void, void) DEFINE_BUILTIN_TYPE_GET_AND_IS(Bool, bool) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int, int) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int8, int8) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int16, int16) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int32, int32) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int64, int64) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt, uint) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt8, uint8) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt16, uint16) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt32, uint32) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt64, uint64) DEFINE_BUILTIN_TYPE_GET_AND_IS(Float, float) DEFINE_BUILTIN_TYPE_GET_AND_IS(Float32, float32) DEFINE_BUILTIN_TYPE_GET_AND_IS(Float64, float64) DEFINE_BUILTIN_TYPE_GET_AND_IS(Float80, float80) DEFINE_BUILTIN_TYPE_GET_AND_IS(String, String) DEFINE_BUILTIN_TYPE_GET_AND_IS(Char, char) DEFINE_BUILTIN_TYPE_GET_AND_IS(Null, null) #undef DEFINE_BUILTIN_TYPE_GET_AND_IS bool Type::isArrayWithConstantSize() const { return isArrayType() && getArraySize() >= 0; } bool Type::isArrayWithRuntimeSize() const { return isArrayType() && getArraySize() == ArrayType::runtimeSize; } bool Type::isArrayWithUnknownSize() const { return isArrayType() && getArraySize() == ArrayType::unknownSize; } bool Type::isBuiltinScalar(llvm::StringRef typeName) { static const char* const builtinTypeNames[] = { "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "float", "float32", "float64", "float80", "bool", "char", }; return std::find(std::begin(builtinTypeNames), std::end(builtinTypeNames), typeName) != std::end(builtinTypeNames); } Type Type::resolve(const llvm::StringMap<Type>& replacements) const { if (!typeBase) return Type(nullptr, isMutable()); switch (getKind()) { case TypeKind::BasicType: { auto it = replacements.find(getName()); if (it != replacements.end()) { // TODO: Handle generic arguments for type placeholders. return it->second.asMutable(isMutable()); } auto genericArgs = map(getGenericArgs(), [&](Type t) { return t.resolve(replacements); }); return BasicType::get(getName(), std::move(genericArgs), isMutable()); } case TypeKind::ArrayType: return ArrayType::get(getElementType().resolve(replacements), getArraySize(), isMutable()); case TypeKind::TupleType: { auto subtypes = map(getSubtypes(), [&](Type t) { return t.resolve(replacements); }); return TupleType::get(std::move(subtypes)); } case TypeKind::FunctionType: { auto paramTypes = map(getParamTypes(), [&](Type t) { return t.resolve(replacements); }); return FunctionType::get(getReturnType().resolve(replacements), std::move(paramTypes), isMutable()); } case TypeKind::PointerType: return PointerType::get(getPointee().resolve(replacements), isMutable()); case TypeKind::OptionalType: return OptionalType::get(getWrappedType().resolve(replacements), isMutable()); } llvm_unreachable("all cases handled"); } void Type::appendType(Type type) { std::vector<Type> subtypes; if (!isTupleType()) subtypes.push_back(*this); else subtypes = llvm::cast<TupleType>(*typeBase).getSubtypes(); subtypes.push_back(type); typeBase = TupleType::get(std::move(subtypes)).get(); } namespace { std::vector<std::unique_ptr<BasicType>> basicTypes; std::vector<std::unique_ptr<ArrayType>> arrayTypes; std::vector<std::unique_ptr<TupleType>> tupleTypes; std::vector<std::unique_ptr<FunctionType>> functionTypes; std::vector<std::unique_ptr<PointerType>> ptrTypes; std::vector<std::unique_ptr<OptionalType>> optionalTypes; } #define FETCH_AND_RETURN_TYPE(TYPE, CACHE, EQUALS, ...) \ auto it = llvm::find_if(CACHE, [&](const std::unique_ptr<TYPE>& t) { return EQUALS; }); \ if (it != CACHE.end()) return Type(it->get(), isMutable); \ CACHE.emplace_back(new TYPE(__VA_ARGS__)); \ return Type(CACHE.back().get(), isMutable); Type BasicType::get(llvm::StringRef name, llvm::ArrayRef<Type> genericArgs, bool isMutable) { FETCH_AND_RETURN_TYPE(BasicType, basicTypes, t->getName() == name && t->getGenericArgs() == genericArgs, name, genericArgs); } Type ArrayType::get(Type elementType, int64_t size, bool isMutable) { FETCH_AND_RETURN_TYPE(ArrayType, arrayTypes, t->getElementType() == elementType && t->getSize() == size, elementType, size); } Type TupleType::get(std::vector<Type>&& subtypes, bool isMutable) { FETCH_AND_RETURN_TYPE(TupleType, tupleTypes, t->getSubtypes() == llvm::makeArrayRef(subtypes), std::move(subtypes)); } Type FunctionType::get(Type returnType, std::vector<Type>&& paramTypes, bool isMutable) { FETCH_AND_RETURN_TYPE(FunctionType, functionTypes, t->getReturnType() == returnType && t->getParamTypes() == llvm::makeArrayRef(paramTypes), returnType, std::move(paramTypes)); } Type PointerType::get(Type pointeeType, bool isMutable) { FETCH_AND_RETURN_TYPE(PointerType, ptrTypes, t->getPointeeType() == pointeeType, pointeeType); } Type OptionalType::get(Type wrappedType, bool isMutable) { FETCH_AND_RETURN_TYPE(OptionalType, optionalTypes, t->getWrappedType() == wrappedType, wrappedType); } #undef FETCH_AND_RETURN_TYPE std::vector<ParamDecl> FunctionType::getParamDecls(SourceLocation location) const { std::vector<ParamDecl> paramDecls; paramDecls.reserve(paramTypes.size()); for (Type paramType : paramTypes) { paramDecls.push_back(ParamDecl(paramType, "", location)); } return paramDecls; } bool Type::isSigned() const { if (!isBasicType()) { return false; } llvm::StringRef name = getName(); return name == "int" || name == "int8" || name == "int16" || name == "int32" || name == "int64"; } bool Type::isUnsigned() const { ASSERT(isBasicType()); llvm::StringRef name = getName(); return name == "uint" || name == "uint8" || name == "uint16" || name == "uint32" || name == "uint64"; } void Type::setMutable(bool isMutable) { if (typeBase && isArrayType()) { auto& array = llvm::cast<ArrayType>(*typeBase); *this = ArrayType::get(array.getElementType().asMutable(isMutable), array.getSize(), isMutable); } else { mutableFlag = isMutable; } } llvm::StringRef Type::getName() const { return llvm::cast<BasicType>(typeBase)->getName(); } Type Type::getElementType() const { return llvm::cast<ArrayType>(typeBase)->getElementType().asMutable(isMutable()); } int64_t Type::getArraySize() const { return llvm::cast<ArrayType>(typeBase)->getSize(); } llvm::ArrayRef<Type> Type::getSubtypes() const { return llvm::cast<TupleType>(typeBase)->getSubtypes(); } llvm::ArrayRef<Type> Type::getGenericArgs() const { return llvm::cast<BasicType>(typeBase)->getGenericArgs(); } Type Type::getReturnType() const { return llvm::cast<FunctionType>(typeBase)->getReturnType(); } llvm::ArrayRef<Type> Type::getParamTypes() const { return llvm::cast<FunctionType>(typeBase)->getParamTypes(); } Type Type::getPointee() const { return llvm::cast<PointerType>(typeBase)->getPointeeType(); } Type Type::getWrappedType() const { return llvm::cast<OptionalType>(typeBase)->getWrappedType(); } bool delta::operator==(Type lhs, Type rhs) { if (lhs.isMutable() != rhs.isMutable()) return false; switch (lhs.getKind()) { case TypeKind::BasicType: return rhs.isBasicType() && lhs.getName() == rhs.getName() && lhs.getGenericArgs() == rhs.getGenericArgs(); case TypeKind::ArrayType: return rhs.isArrayType() && lhs.getElementType() == rhs.getElementType() && lhs.getArraySize() == rhs.getArraySize(); case TypeKind::TupleType: return rhs.isTupleType() && lhs.getSubtypes() == rhs.getSubtypes(); case TypeKind::FunctionType: return rhs.isFunctionType() && lhs.getReturnType() == rhs.getReturnType() && lhs.getParamTypes() == rhs.getParamTypes(); case TypeKind::PointerType: return rhs.isPointerType() && lhs.getPointee() == rhs.getPointee(); case TypeKind::OptionalType: return rhs.isOptionalType() && lhs.getWrappedType() == rhs.getWrappedType(); } llvm_unreachable("all cases handled"); } bool delta::operator!=(Type lhs, Type rhs) { return !(lhs == rhs); } void Type::printTo(std::ostream& stream, bool omitTopLevelMutable) const { switch (typeBase->getKind()) { case TypeKind::BasicType: { if (isMutable() && !omitTopLevelMutable) stream << "mutable "; stream << getName(); auto genericArgs = llvm::cast<BasicType>(typeBase)->getGenericArgs(); if (!genericArgs.empty()) { stream << "<"; for (auto& type : genericArgs) { type.printTo(stream, false); if (&type != &genericArgs.back()) stream << ", "; } stream << ">"; } break; } case TypeKind::ArrayType: getElementType().printTo(stream, omitTopLevelMutable); stream << "["; switch (getArraySize()) { case ArrayType::runtimeSize: break; case ArrayType::unknownSize: stream << "?"; break; default: stream << getArraySize(); break; } stream << "]"; break; case TypeKind::TupleType: stream << "("; for (const Type& subtype : getSubtypes()) { subtype.printTo(stream, omitTopLevelMutable); if (&subtype != &getSubtypes().back()) stream << ", "; } stream << ")"; break; case TypeKind::FunctionType: stream << "("; for (const Type& paramType : getParamTypes()) { stream << paramType; if (&paramType != &getParamTypes().back()) stream << ", "; } stream << ") -> "; getReturnType().printTo(stream, true); break; case TypeKind::PointerType: getPointee().printTo(stream, false); if (isMutable() && !omitTopLevelMutable) { stream << " mutable"; } stream << '*'; break; case TypeKind::OptionalType: getWrappedType().printTo(stream, false); if (isMutable() && !omitTopLevelMutable) { stream << " mutable"; } stream << '?'; break; } } std::string Type::toString(bool omitTopLevelMutable) const { std::ostringstream stream; printTo(stream, omitTopLevelMutable); return stream.str(); } std::ostream& delta::operator<<(std::ostream& stream, Type type) { type.printTo(stream, true); return stream; } llvm::raw_ostream& delta::operator<<(llvm::raw_ostream& stream, Type type) { std::ostringstream stringstream; type.printTo(stringstream, true); return stream << stringstream.str(); } <commit_msg>Wrap pointee/wrappee in parentheses if it's a function type<commit_after>#include <sstream> #include <llvm/ADT/StringRef.h> #include <llvm/ADT/STLExtras.h> #include <llvm/Support/ErrorHandling.h> #include "type.h" #include "decl.h" #include "../support/utility.h" using namespace delta; #define DEFINE_BUILTIN_TYPE_GET_AND_IS(TYPE, NAME) \ Type Type::get##TYPE(bool isMutable) { \ static BasicType type(#NAME, /*genericArgs*/ {}); \ return Type(&type, isMutable); \ } \ bool Type::is##TYPE() const { \ return isBasicType() && getName() == #NAME; \ } DEFINE_BUILTIN_TYPE_GET_AND_IS(Void, void) DEFINE_BUILTIN_TYPE_GET_AND_IS(Bool, bool) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int, int) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int8, int8) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int16, int16) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int32, int32) DEFINE_BUILTIN_TYPE_GET_AND_IS(Int64, int64) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt, uint) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt8, uint8) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt16, uint16) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt32, uint32) DEFINE_BUILTIN_TYPE_GET_AND_IS(UInt64, uint64) DEFINE_BUILTIN_TYPE_GET_AND_IS(Float, float) DEFINE_BUILTIN_TYPE_GET_AND_IS(Float32, float32) DEFINE_BUILTIN_TYPE_GET_AND_IS(Float64, float64) DEFINE_BUILTIN_TYPE_GET_AND_IS(Float80, float80) DEFINE_BUILTIN_TYPE_GET_AND_IS(String, String) DEFINE_BUILTIN_TYPE_GET_AND_IS(Char, char) DEFINE_BUILTIN_TYPE_GET_AND_IS(Null, null) #undef DEFINE_BUILTIN_TYPE_GET_AND_IS bool Type::isArrayWithConstantSize() const { return isArrayType() && getArraySize() >= 0; } bool Type::isArrayWithRuntimeSize() const { return isArrayType() && getArraySize() == ArrayType::runtimeSize; } bool Type::isArrayWithUnknownSize() const { return isArrayType() && getArraySize() == ArrayType::unknownSize; } bool Type::isBuiltinScalar(llvm::StringRef typeName) { static const char* const builtinTypeNames[] = { "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "float", "float32", "float64", "float80", "bool", "char", }; return std::find(std::begin(builtinTypeNames), std::end(builtinTypeNames), typeName) != std::end(builtinTypeNames); } Type Type::resolve(const llvm::StringMap<Type>& replacements) const { if (!typeBase) return Type(nullptr, isMutable()); switch (getKind()) { case TypeKind::BasicType: { auto it = replacements.find(getName()); if (it != replacements.end()) { // TODO: Handle generic arguments for type placeholders. return it->second.asMutable(isMutable()); } auto genericArgs = map(getGenericArgs(), [&](Type t) { return t.resolve(replacements); }); return BasicType::get(getName(), std::move(genericArgs), isMutable()); } case TypeKind::ArrayType: return ArrayType::get(getElementType().resolve(replacements), getArraySize(), isMutable()); case TypeKind::TupleType: { auto subtypes = map(getSubtypes(), [&](Type t) { return t.resolve(replacements); }); return TupleType::get(std::move(subtypes)); } case TypeKind::FunctionType: { auto paramTypes = map(getParamTypes(), [&](Type t) { return t.resolve(replacements); }); return FunctionType::get(getReturnType().resolve(replacements), std::move(paramTypes), isMutable()); } case TypeKind::PointerType: return PointerType::get(getPointee().resolve(replacements), isMutable()); case TypeKind::OptionalType: return OptionalType::get(getWrappedType().resolve(replacements), isMutable()); } llvm_unreachable("all cases handled"); } void Type::appendType(Type type) { std::vector<Type> subtypes; if (!isTupleType()) subtypes.push_back(*this); else subtypes = llvm::cast<TupleType>(*typeBase).getSubtypes(); subtypes.push_back(type); typeBase = TupleType::get(std::move(subtypes)).get(); } namespace { std::vector<std::unique_ptr<BasicType>> basicTypes; std::vector<std::unique_ptr<ArrayType>> arrayTypes; std::vector<std::unique_ptr<TupleType>> tupleTypes; std::vector<std::unique_ptr<FunctionType>> functionTypes; std::vector<std::unique_ptr<PointerType>> ptrTypes; std::vector<std::unique_ptr<OptionalType>> optionalTypes; } #define FETCH_AND_RETURN_TYPE(TYPE, CACHE, EQUALS, ...) \ auto it = llvm::find_if(CACHE, [&](const std::unique_ptr<TYPE>& t) { return EQUALS; }); \ if (it != CACHE.end()) return Type(it->get(), isMutable); \ CACHE.emplace_back(new TYPE(__VA_ARGS__)); \ return Type(CACHE.back().get(), isMutable); Type BasicType::get(llvm::StringRef name, llvm::ArrayRef<Type> genericArgs, bool isMutable) { FETCH_AND_RETURN_TYPE(BasicType, basicTypes, t->getName() == name && t->getGenericArgs() == genericArgs, name, genericArgs); } Type ArrayType::get(Type elementType, int64_t size, bool isMutable) { FETCH_AND_RETURN_TYPE(ArrayType, arrayTypes, t->getElementType() == elementType && t->getSize() == size, elementType, size); } Type TupleType::get(std::vector<Type>&& subtypes, bool isMutable) { FETCH_AND_RETURN_TYPE(TupleType, tupleTypes, t->getSubtypes() == llvm::makeArrayRef(subtypes), std::move(subtypes)); } Type FunctionType::get(Type returnType, std::vector<Type>&& paramTypes, bool isMutable) { FETCH_AND_RETURN_TYPE(FunctionType, functionTypes, t->getReturnType() == returnType && t->getParamTypes() == llvm::makeArrayRef(paramTypes), returnType, std::move(paramTypes)); } Type PointerType::get(Type pointeeType, bool isMutable) { FETCH_AND_RETURN_TYPE(PointerType, ptrTypes, t->getPointeeType() == pointeeType, pointeeType); } Type OptionalType::get(Type wrappedType, bool isMutable) { FETCH_AND_RETURN_TYPE(OptionalType, optionalTypes, t->getWrappedType() == wrappedType, wrappedType); } #undef FETCH_AND_RETURN_TYPE std::vector<ParamDecl> FunctionType::getParamDecls(SourceLocation location) const { std::vector<ParamDecl> paramDecls; paramDecls.reserve(paramTypes.size()); for (Type paramType : paramTypes) { paramDecls.push_back(ParamDecl(paramType, "", location)); } return paramDecls; } bool Type::isSigned() const { if (!isBasicType()) { return false; } llvm::StringRef name = getName(); return name == "int" || name == "int8" || name == "int16" || name == "int32" || name == "int64"; } bool Type::isUnsigned() const { ASSERT(isBasicType()); llvm::StringRef name = getName(); return name == "uint" || name == "uint8" || name == "uint16" || name == "uint32" || name == "uint64"; } void Type::setMutable(bool isMutable) { if (typeBase && isArrayType()) { auto& array = llvm::cast<ArrayType>(*typeBase); *this = ArrayType::get(array.getElementType().asMutable(isMutable), array.getSize(), isMutable); } else { mutableFlag = isMutable; } } llvm::StringRef Type::getName() const { return llvm::cast<BasicType>(typeBase)->getName(); } Type Type::getElementType() const { return llvm::cast<ArrayType>(typeBase)->getElementType().asMutable(isMutable()); } int64_t Type::getArraySize() const { return llvm::cast<ArrayType>(typeBase)->getSize(); } llvm::ArrayRef<Type> Type::getSubtypes() const { return llvm::cast<TupleType>(typeBase)->getSubtypes(); } llvm::ArrayRef<Type> Type::getGenericArgs() const { return llvm::cast<BasicType>(typeBase)->getGenericArgs(); } Type Type::getReturnType() const { return llvm::cast<FunctionType>(typeBase)->getReturnType(); } llvm::ArrayRef<Type> Type::getParamTypes() const { return llvm::cast<FunctionType>(typeBase)->getParamTypes(); } Type Type::getPointee() const { return llvm::cast<PointerType>(typeBase)->getPointeeType(); } Type Type::getWrappedType() const { return llvm::cast<OptionalType>(typeBase)->getWrappedType(); } bool delta::operator==(Type lhs, Type rhs) { if (lhs.isMutable() != rhs.isMutable()) return false; switch (lhs.getKind()) { case TypeKind::BasicType: return rhs.isBasicType() && lhs.getName() == rhs.getName() && lhs.getGenericArgs() == rhs.getGenericArgs(); case TypeKind::ArrayType: return rhs.isArrayType() && lhs.getElementType() == rhs.getElementType() && lhs.getArraySize() == rhs.getArraySize(); case TypeKind::TupleType: return rhs.isTupleType() && lhs.getSubtypes() == rhs.getSubtypes(); case TypeKind::FunctionType: return rhs.isFunctionType() && lhs.getReturnType() == rhs.getReturnType() && lhs.getParamTypes() == rhs.getParamTypes(); case TypeKind::PointerType: return rhs.isPointerType() && lhs.getPointee() == rhs.getPointee(); case TypeKind::OptionalType: return rhs.isOptionalType() && lhs.getWrappedType() == rhs.getWrappedType(); } llvm_unreachable("all cases handled"); } bool delta::operator!=(Type lhs, Type rhs) { return !(lhs == rhs); } void Type::printTo(std::ostream& stream, bool omitTopLevelMutable) const { switch (typeBase->getKind()) { case TypeKind::BasicType: { if (isMutable() && !omitTopLevelMutable) stream << "mutable "; stream << getName(); auto genericArgs = llvm::cast<BasicType>(typeBase)->getGenericArgs(); if (!genericArgs.empty()) { stream << "<"; for (auto& type : genericArgs) { type.printTo(stream, false); if (&type != &genericArgs.back()) stream << ", "; } stream << ">"; } break; } case TypeKind::ArrayType: getElementType().printTo(stream, omitTopLevelMutable); stream << "["; switch (getArraySize()) { case ArrayType::runtimeSize: break; case ArrayType::unknownSize: stream << "?"; break; default: stream << getArraySize(); break; } stream << "]"; break; case TypeKind::TupleType: stream << "("; for (const Type& subtype : getSubtypes()) { subtype.printTo(stream, omitTopLevelMutable); if (&subtype != &getSubtypes().back()) stream << ", "; } stream << ")"; break; case TypeKind::FunctionType: stream << "("; for (const Type& paramType : getParamTypes()) { stream << paramType; if (&paramType != &getParamTypes().back()) stream << ", "; } stream << ") -> "; getReturnType().printTo(stream, true); break; case TypeKind::PointerType: if (getPointee().isFunctionType()) { stream << '('; } getPointee().printTo(stream, false); if (isMutable() && !omitTopLevelMutable) { stream << " mutable"; } if (getPointee().isFunctionType()) { stream << ')'; } stream << '*'; break; case TypeKind::OptionalType: if (getWrappedType().isFunctionType()) { stream << '('; } getWrappedType().printTo(stream, false); if (isMutable() && !omitTopLevelMutable) { stream << " mutable"; } if (getWrappedType().isFunctionType()) { stream << ')'; } stream << '?'; break; } } std::string Type::toString(bool omitTopLevelMutable) const { std::ostringstream stream; printTo(stream, omitTopLevelMutable); return stream.str(); } std::ostream& delta::operator<<(std::ostream& stream, Type type) { type.printTo(stream, true); return stream; } llvm::raw_ostream& delta::operator<<(llvm::raw_ostream& stream, Type type) { std::ostringstream stringstream; type.printTo(stringstream, true); return stream << stringstream.str(); } <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "backtrace.hpp" #include <cxxabi.h> #include <execinfo.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> #include <string> #include "errors.hpp" #include <boost/ptr_container/ptr_map.hpp> #include "arch/runtime/coroutines.hpp" #include "containers/scoped.hpp" #include "logger.hpp" #include "rethinkdb_backtrace.hpp" #include "utils.hpp" static bool parse_backtrace_line(char *line, char **filename, char **function, char **offset, char **address) { /* backtrace() gives us lines in one of the following two forms: ./path/to/the/binary(function+offset) [address] ./path/to/the/binary [address] */ *filename = line; // Check if there is a function present if (char *paren1 = strchr(line, '(')) { char *paren2 = strchr(line, ')'); if (!paren2) return false; *paren1 = *paren2 = '\0'; // Null-terminate the offset and the filename *function = paren1 + 1; char *plus = strchr(*function, '+'); if (!plus) return false; *plus = '\0'; // Null-terminate the function name *offset = plus + 1; line = paren2 + 1; if (*line != ' ') return false; line += 1; } else { *function = NULL; *offset = NULL; char *bracket = strchr(line, '['); if (!bracket) return false; line = bracket - 1; if (*line != ' ') return false; *line = '\0'; // Null-terminate the file name line += 1; } // We are now at the opening bracket of the address if (*line != '[') return false; line += 1; *address = line; line = strchr(line, ']'); if (!line || line[1] != '\0') return false; *line = '\0'; // Null-terminate the address return true; } /* There has been some trouble with abi::__cxa_demangle. Originally, demangle_cpp_name() took a pointer to the mangled name, and returned a buffer that must be free()ed. It did this by calling __cxa_demangle() and passing NULL and 0 for the buffer and buffer-size arguments. There were complaints that print_backtrace() was smashing memory. Shachaf observed that pieces of the backtrace seemed to be ending up overwriting other structs, and filed issue #100. Daniel Mewes suspected that the memory smashing was related to calling malloc(). In December 2010, he changed demangle_cpp_name() to take a static buffer, and fill this static buffer with the demangled name. See 284246bd. abi::__cxa_demangle expects a malloc()ed buffer, and if the buffer is too small it will call realloc() on it. So the static-buffer approach worked except when the name to be demangled was too large. In March 2011, Tim and Ivan got tired of the memory allocator complaining that someone was trying to realloc() an unallocated buffer, and changed demangle_cpp_name() back to the way it was originally. Please don't change this function without talking to the people who have already been involved in this. */ std::string demangle_cpp_name(const char *mangled_name) { int res; char *name_as_c_str = abi::__cxa_demangle(mangled_name, NULL, 0, &res); if (res == 0) { std::string name_as_std_string(name_as_c_str); free(name_as_c_str); return name_as_std_string; } else { throw demangle_failed_exc_t(); } } int set_o_cloexec(int fd) { int flags = fcntl(fd, F_GETFD); if (flags < 0) { return flags; } return fcntl(fd, F_SETFD, flags | FD_CLOEXEC); } address_to_line_t::addr2line_t::addr2line_t(const char *executable) : input(NULL), output(NULL), bad(false), pid(-1) { if (pipe(child_in) || set_o_cloexec(child_in[0]) || set_o_cloexec(child_in[1]) || pipe(child_out) || set_o_cloexec(child_out[0]) || set_o_cloexec(child_out[1])) { bad = true; return; } if ((pid = fork())) { input = fdopen(child_in[1], "w"); output = fdopen(child_out[0], "r"); close(child_in[0]); close(child_out[1]); } else { dup2(child_in[0], 0); // stdin dup2(child_out[1], 1); // stdout const char *args[] = {"addr2line", "-s", "-e", executable, NULL}; execvp("addr2line", const_cast<char *const *>(args)); exit(EXIT_FAILURE); } } address_to_line_t::addr2line_t::~addr2line_t() { if (input) { fclose(input); } if (output) { fclose(output); } if (pid != -1) { waitpid(pid, NULL, 0); } } bool address_to_line_t::run_addr2line(const std::string &executable, const void *address, char *line, int line_size) { addr2line_t* proc; boost::ptr_map<const std::string, addr2line_t>::iterator iter = procs.find(executable); if (iter != procs.end()) { proc = iter->second; } else { proc = new addr2line_t(executable.c_str()); procs.insert(executable, proc); } if (proc->bad) { return false; } fprintf(proc->input, "%p\n", address); fflush(proc->input); char *result = fgets(line, line_size, proc->output); if (result == NULL) { proc->bad = true; return false; } line[line_size - 1] = '\0'; int len = strlen(line); if (line[len - 1] == '\n') { line[len - 1] = '\0'; } if (!strcmp(line, "??:0")) return false; return true; } std::string address_to_line_t::address_to_line(const std::string &executable, const void *address) { char line[255]; bool success = run_addr2line(executable, address, line, sizeof(line)); if (!success) { return ""; } else { return std::string(line); } } std::string format_backtrace(bool use_addr2line) { lazy_backtrace_formatter_t bt; return use_addr2line ? bt.lines() : bt.addrs(); } backtrace_t::backtrace_t() { scoped_array_t<void *> stack_frames(new void*[max_frames], max_frames); // Allocate on heap in case stack space is scarce int size = rethinkdb_backtrace(stack_frames.data(), max_frames); #ifdef CROSS_CORO_BACKTRACES if (coro_t::self() != NULL) { int space_remaining = max_frames - size; rassert(space_remaining >= 0); size += coro_t::self()->copy_spawn_backtrace(stack_frames.data() + size, space_remaining); } #endif frames.reserve(static_cast<size_t>(size)); for (int i = 0; i < size; ++i) { frames.push_back(backtrace_frame_t(stack_frames[i])); } } backtrace_frame_t::backtrace_frame_t(const void* _addr) : symbols_initialized(false), addr(_addr) { } void backtrace_frame_t::initialize_symbols() { void *addr_array[1] = {const_cast<void *>(addr)}; char **symbols = backtrace_symbols(addr_array, 1); if (symbols != NULL) { symbols_line = std::string(symbols[0]); char *c_filename; char *c_function; char *c_offset; char *c_address; if (parse_backtrace_line(symbols[0], &c_filename, &c_function, &c_offset, &c_address)) { if (c_filename != NULL) { filename = std::string(c_filename); } if (c_function != NULL) { function = std::string(c_function); } if (c_offset != NULL) { offset = std::string(c_offset); } } free(symbols); } symbols_initialized = true; } std::string backtrace_frame_t::get_name() const { rassert(symbols_initialized); return function; } std::string backtrace_frame_t::get_symbols_line() const { rassert(symbols_initialized); return symbols_line; } std::string backtrace_frame_t::get_demangled_name() const { rassert(symbols_initialized); return demangle_cpp_name(function.c_str()); } std::string backtrace_frame_t::get_filename() const { rassert(symbols_initialized); return filename; } std::string backtrace_frame_t::get_offset() const { rassert(symbols_initialized); return offset; } const void *backtrace_frame_t::get_addr() const { return addr; } lazy_backtrace_formatter_t::lazy_backtrace_formatter_t() : backtrace_t(), timestamp(time(0)), timestr(time2str(timestamp)) { } std::string lazy_backtrace_formatter_t::addrs() { if (cached_addrs == "") { cached_addrs = timestr + "\n" + print_frames(false); } return cached_addrs; } std::string lazy_backtrace_formatter_t::lines() { if (cached_lines == "") { cached_lines = timestr + "\n" + print_frames(true); } return cached_lines; } std::string lazy_backtrace_formatter_t::print_frames(bool use_addr2line) { address_to_line_t address_to_line; std::string output; for (size_t i = 0; i < get_num_frames(); i++) { backtrace_frame_t current_frame = get_frame(i); current_frame.initialize_symbols(); output.append(strprintf("%d: ", static_cast<int>(i+1))); try { output.append(current_frame.get_demangled_name()); } catch (const demangle_failed_exc_t &) { if (!current_frame.get_name().empty()) { output.append(current_frame.get_name() + "+" + current_frame.get_offset()); } else if (!current_frame.get_symbols_line().empty()) { output.append(current_frame.get_symbols_line()); } else { output.append("<unknown function>"); } } output.append(" at "); std::string some_other_line; if (use_addr2line) { if (!current_frame.get_filename().empty()) { some_other_line = address_to_line.address_to_line(current_frame.get_filename(), current_frame.get_addr()); } } if (!some_other_line.empty()) { output.append(some_other_line); } else { output.append(strprintf("%p", current_frame.get_addr()) + " (" + current_frame.get_filename() + ")"); } output.append("\n"); } return output; } <commit_msg>Added NOLINT in a comment in backtrace.cc.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "backtrace.hpp" #include <cxxabi.h> #include <execinfo.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> #include <string> #include "errors.hpp" #include <boost/ptr_container/ptr_map.hpp> #include "arch/runtime/coroutines.hpp" #include "containers/scoped.hpp" #include "logger.hpp" #include "rethinkdb_backtrace.hpp" #include "utils.hpp" static bool parse_backtrace_line(char *line, char **filename, char **function, char **offset, char **address) { /* backtrace() gives us lines in one of the following two forms: ./path/to/the/binary(function+offset) [address] ./path/to/the/binary [address] */ *filename = line; // Check if there is a function present if (char *paren1 = strchr(line, '(')) { char *paren2 = strchr(line, ')'); if (!paren2) return false; *paren1 = *paren2 = '\0'; // Null-terminate the offset and the filename *function = paren1 + 1; char *plus = strchr(*function, '+'); if (!plus) return false; *plus = '\0'; // Null-terminate the function name *offset = plus + 1; line = paren2 + 1; if (*line != ' ') return false; line += 1; } else { *function = NULL; *offset = NULL; char *bracket = strchr(line, '['); if (!bracket) return false; line = bracket - 1; if (*line != ' ') return false; *line = '\0'; // Null-terminate the file name line += 1; } // We are now at the opening bracket of the address if (*line != '[') return false; line += 1; *address = line; line = strchr(line, ']'); if (!line || line[1] != '\0') return false; *line = '\0'; // Null-terminate the address return true; } /* There has been some trouble with abi::__cxa_demangle. Originally, demangle_cpp_name() took a pointer to the mangled name, and returned a buffer that must be free()ed. It did this by calling __cxa_demangle() and passing NULL and 0 for the buffer and buffer-size arguments. There were complaints that print_backtrace() was smashing memory. Shachaf observed that pieces of the backtrace seemed to be ending up overwriting other structs, and filed issue #100. Daniel Mewes suspected that the memory smashing was related to calling malloc(). [NOLINT(rethinkdb/malloc)] In December 2010, he changed demangle_cpp_name() to take a static buffer, and fill this static buffer with the demangled name. See 284246bd. abi::__cxa_demangle expects a malloc()ed buffer, and if the buffer is too small it [NOLINT(rethinkdb/malloc)] will call realloc() on it. So the static-buffer approach worked except when the name [NOLINT(rethinkdb/malloc)] to be demangled was too large. In March 2011, Tim and Ivan got tired of the memory allocator complaining that someone was trying to realloc() an unallocated buffer, and changed demangle_cpp_name() back [NOLINT(rethinkdb/malloc)] to the way it was originally. Please don't change this function without talking to the people who have already been involved in this. */ std::string demangle_cpp_name(const char *mangled_name) { int res; char *name_as_c_str = abi::__cxa_demangle(mangled_name, NULL, 0, &res); if (res == 0) { std::string name_as_std_string(name_as_c_str); free(name_as_c_str); return name_as_std_string; } else { throw demangle_failed_exc_t(); } } int set_o_cloexec(int fd) { int flags = fcntl(fd, F_GETFD); if (flags < 0) { return flags; } return fcntl(fd, F_SETFD, flags | FD_CLOEXEC); } address_to_line_t::addr2line_t::addr2line_t(const char *executable) : input(NULL), output(NULL), bad(false), pid(-1) { if (pipe(child_in) || set_o_cloexec(child_in[0]) || set_o_cloexec(child_in[1]) || pipe(child_out) || set_o_cloexec(child_out[0]) || set_o_cloexec(child_out[1])) { bad = true; return; } if ((pid = fork())) { input = fdopen(child_in[1], "w"); output = fdopen(child_out[0], "r"); close(child_in[0]); close(child_out[1]); } else { dup2(child_in[0], 0); // stdin dup2(child_out[1], 1); // stdout const char *args[] = {"addr2line", "-s", "-e", executable, NULL}; execvp("addr2line", const_cast<char *const *>(args)); exit(EXIT_FAILURE); } } address_to_line_t::addr2line_t::~addr2line_t() { if (input) { fclose(input); } if (output) { fclose(output); } if (pid != -1) { waitpid(pid, NULL, 0); } } bool address_to_line_t::run_addr2line(const std::string &executable, const void *address, char *line, int line_size) { addr2line_t* proc; boost::ptr_map<const std::string, addr2line_t>::iterator iter = procs.find(executable); if (iter != procs.end()) { proc = iter->second; } else { proc = new addr2line_t(executable.c_str()); procs.insert(executable, proc); } if (proc->bad) { return false; } fprintf(proc->input, "%p\n", address); fflush(proc->input); char *result = fgets(line, line_size, proc->output); if (result == NULL) { proc->bad = true; return false; } line[line_size - 1] = '\0'; int len = strlen(line); if (line[len - 1] == '\n') { line[len - 1] = '\0'; } if (!strcmp(line, "??:0")) return false; return true; } std::string address_to_line_t::address_to_line(const std::string &executable, const void *address) { char line[255]; bool success = run_addr2line(executable, address, line, sizeof(line)); if (!success) { return ""; } else { return std::string(line); } } std::string format_backtrace(bool use_addr2line) { lazy_backtrace_formatter_t bt; return use_addr2line ? bt.lines() : bt.addrs(); } backtrace_t::backtrace_t() { scoped_array_t<void *> stack_frames(new void*[max_frames], max_frames); // Allocate on heap in case stack space is scarce int size = rethinkdb_backtrace(stack_frames.data(), max_frames); #ifdef CROSS_CORO_BACKTRACES if (coro_t::self() != NULL) { int space_remaining = max_frames - size; rassert(space_remaining >= 0); size += coro_t::self()->copy_spawn_backtrace(stack_frames.data() + size, space_remaining); } #endif frames.reserve(static_cast<size_t>(size)); for (int i = 0; i < size; ++i) { frames.push_back(backtrace_frame_t(stack_frames[i])); } } backtrace_frame_t::backtrace_frame_t(const void* _addr) : symbols_initialized(false), addr(_addr) { } void backtrace_frame_t::initialize_symbols() { void *addr_array[1] = {const_cast<void *>(addr)}; char **symbols = backtrace_symbols(addr_array, 1); if (symbols != NULL) { symbols_line = std::string(symbols[0]); char *c_filename; char *c_function; char *c_offset; char *c_address; if (parse_backtrace_line(symbols[0], &c_filename, &c_function, &c_offset, &c_address)) { if (c_filename != NULL) { filename = std::string(c_filename); } if (c_function != NULL) { function = std::string(c_function); } if (c_offset != NULL) { offset = std::string(c_offset); } } free(symbols); } symbols_initialized = true; } std::string backtrace_frame_t::get_name() const { rassert(symbols_initialized); return function; } std::string backtrace_frame_t::get_symbols_line() const { rassert(symbols_initialized); return symbols_line; } std::string backtrace_frame_t::get_demangled_name() const { rassert(symbols_initialized); return demangle_cpp_name(function.c_str()); } std::string backtrace_frame_t::get_filename() const { rassert(symbols_initialized); return filename; } std::string backtrace_frame_t::get_offset() const { rassert(symbols_initialized); return offset; } const void *backtrace_frame_t::get_addr() const { return addr; } lazy_backtrace_formatter_t::lazy_backtrace_formatter_t() : backtrace_t(), timestamp(time(0)), timestr(time2str(timestamp)) { } std::string lazy_backtrace_formatter_t::addrs() { if (cached_addrs == "") { cached_addrs = timestr + "\n" + print_frames(false); } return cached_addrs; } std::string lazy_backtrace_formatter_t::lines() { if (cached_lines == "") { cached_lines = timestr + "\n" + print_frames(true); } return cached_lines; } std::string lazy_backtrace_formatter_t::print_frames(bool use_addr2line) { address_to_line_t address_to_line; std::string output; for (size_t i = 0; i < get_num_frames(); i++) { backtrace_frame_t current_frame = get_frame(i); current_frame.initialize_symbols(); output.append(strprintf("%d: ", static_cast<int>(i+1))); try { output.append(current_frame.get_demangled_name()); } catch (const demangle_failed_exc_t &) { if (!current_frame.get_name().empty()) { output.append(current_frame.get_name() + "+" + current_frame.get_offset()); } else if (!current_frame.get_symbols_line().empty()) { output.append(current_frame.get_symbols_line()); } else { output.append("<unknown function>"); } } output.append(" at "); std::string some_other_line; if (use_addr2line) { if (!current_frame.get_filename().empty()) { some_other_line = address_to_line.address_to_line(current_frame.get_filename(), current_frame.get_addr()); } } if (!some_other_line.empty()) { output.append(some_other_line); } else { output.append(strprintf("%p", current_frame.get_addr()) + " (" + current_frame.get_filename() + ")"); } output.append("\n"); } return output; } <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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. * * Authors: Nathan Binkert * Dave Greene */ #ifndef __BASE_MISC_HH__ #define __BASE_MISC_HH__ #include "base/compiler.hh" #include "base/cprintf.hh" #include "base/varargs.hh" #if defined(__SUNPRO_CC) #define __FUNCTION__ "how to fix me?" #endif // General exit message, these functions will never return and will // either abort() if code is < 0 or exit with the code if >= 0 void __exit_message(const char *prefix, int code, const char *func, const char *file, int line, const char *format, CPRINTF_DECLARATION) M5_ATTR_NORETURN; void __exit_message(const char *prefix, int code, const char *func, const char *file, int line, const std::string &format, CPRINTF_DECLARATION) M5_ATTR_NORETURN; inline void __exit_message(const char *prefix, int code, const char *func, const char *file, int line, const std::string& format, CPRINTF_DEFINITION) { __exit_message(prefix, code, func, file, line, format.c_str(), VARARGS_ALLARGS); } M5_PRAGMA_NORETURN(__exit_message) #define exit_message(prefix, code, ...) \ __exit_message(prefix, code, __FUNCTION__, __FILE__, __LINE__, \ __VA_ARGS__) // // This implements a cprintf based panic() function. panic() should // be called when something happens that should never ever happen // regardless of what the user does (i.e., an acutal m5 bug). panic() // calls abort which can dump core or enter the debugger. // // #define panic(...) exit_message("panic", -1, __VA_ARGS__) // // This implements a cprintf based fatal() function. fatal() should // be called when the simulation cannot continue due to some condition // that is the user's fault (bad configuration, invalid arguments, // etc.) and not a simulator bug. fatal() calls exit(1), i.e., a // "normal" exit with an error code, as opposed to abort() like // panic() does. // #define fatal(...) exit_message("fatal", 1, __VA_ARGS__) void __base_message(std::ostream &stream, const char *prefix, bool verbose, const char *func, const char *file, int line, const char *format, CPRINTF_DECLARATION); inline void __base_message(std::ostream &stream, const char *prefix, bool verbose, const char *func, const char *file, int line, const std::string &format, CPRINTF_DECLARATION) { __base_message(stream, prefix, verbose, func, file, line, format.c_str(), VARARGS_ALLARGS); } #define base_message(stream, prefix, verbose, ...) \ __base_message(stream, prefix, verbose, __FUNCTION__, __FILE__, __LINE__, \ __VA_ARGS__) // Only print the message the first time this expression is // encountered. i.e. This doesn't check the string itself and // prevent duplicate strings, this prevents the statement from // happening more than once. So, even if the arguments change and that // would have resulted in a different message thoes messages would be // supressed. #define base_message_once(...) do { \ static bool once = false; \ if (!once) { \ base_message(__VA_ARGS__); \ once = true; \ } \ } while (0) #define cond_message(cond, ...) do { \ if (cond) \ base_message(__VA_ARGS__); \ } while (0) #define cond_message_once(cond, ...) do { \ static bool once = false; \ if (!once && cond) { \ base_message(__VA_ARGS__); \ once = true; \ } \ } while (0) extern bool want_warn, warn_verbose; extern bool want_info, info_verbose; extern bool want_hack, hack_verbose; #define warn(...) \ cond_message(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__) #define inform(...) \ cond_message(want_info, std::cout, "info", info_verbose, __VA_ARGS__) #define hack(...) \ cond_message(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__) #define warn_once(...) \ cond_message_once(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__) #define inform_once(...) \ cond_message_once(want_info, std::cout, "info", info_verbose, __VA_ARGS__) #define hack_once(...) \ cond_message_once(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__) #endif // __BASE_MISC_HH__ <commit_msg>base: calls abort() from fatal Currently fatal() ends the simulation in a normal fashion. This results in the call stack getting lost when using a debugger and it is not always possible to debug the simulation just from the information provided by the printed error message. Even though the error is likely due to a user's fault, the information available should not be thrown away. Hence, this patch to call abort() from fatal().<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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. * * Authors: Nathan Binkert * Dave Greene */ #ifndef __BASE_MISC_HH__ #define __BASE_MISC_HH__ #include "base/compiler.hh" #include "base/cprintf.hh" #include "base/varargs.hh" #if defined(__SUNPRO_CC) #define __FUNCTION__ "how to fix me?" #endif // General exit message, these functions will never return and will // either abort() if code is < 0 or exit with the code if >= 0 void __exit_message(const char *prefix, int code, const char *func, const char *file, int line, const char *format, CPRINTF_DECLARATION) M5_ATTR_NORETURN; void __exit_message(const char *prefix, int code, const char *func, const char *file, int line, const std::string &format, CPRINTF_DECLARATION) M5_ATTR_NORETURN; inline void __exit_message(const char *prefix, int code, const char *func, const char *file, int line, const std::string& format, CPRINTF_DEFINITION) { __exit_message(prefix, code, func, file, line, format.c_str(), VARARGS_ALLARGS); } M5_PRAGMA_NORETURN(__exit_message) #define exit_message(prefix, code, ...) \ __exit_message(prefix, code, __FUNCTION__, __FILE__, __LINE__, \ __VA_ARGS__) // // This implements a cprintf based panic() function. panic() should // be called when something happens that should never ever happen // regardless of what the user does (i.e., an acutal m5 bug). panic() // calls abort which can dump core or enter the debugger. // // #define panic(...) exit_message("panic", -1, __VA_ARGS__) // // This implements a cprintf based fatal() function. fatal() should // be called when the simulation cannot continue due to some condition // that is the user's fault (bad configuration, invalid arguments, // etc.) and not a simulator bug. fatal() calls abort() like // panic() does. // #define fatal(...) exit_message("fatal", -1, __VA_ARGS__) void __base_message(std::ostream &stream, const char *prefix, bool verbose, const char *func, const char *file, int line, const char *format, CPRINTF_DECLARATION); inline void __base_message(std::ostream &stream, const char *prefix, bool verbose, const char *func, const char *file, int line, const std::string &format, CPRINTF_DECLARATION) { __base_message(stream, prefix, verbose, func, file, line, format.c_str(), VARARGS_ALLARGS); } #define base_message(stream, prefix, verbose, ...) \ __base_message(stream, prefix, verbose, __FUNCTION__, __FILE__, __LINE__, \ __VA_ARGS__) // Only print the message the first time this expression is // encountered. i.e. This doesn't check the string itself and // prevent duplicate strings, this prevents the statement from // happening more than once. So, even if the arguments change and that // would have resulted in a different message thoes messages would be // supressed. #define base_message_once(...) do { \ static bool once = false; \ if (!once) { \ base_message(__VA_ARGS__); \ once = true; \ } \ } while (0) #define cond_message(cond, ...) do { \ if (cond) \ base_message(__VA_ARGS__); \ } while (0) #define cond_message_once(cond, ...) do { \ static bool once = false; \ if (!once && cond) { \ base_message(__VA_ARGS__); \ once = true; \ } \ } while (0) extern bool want_warn, warn_verbose; extern bool want_info, info_verbose; extern bool want_hack, hack_verbose; #define warn(...) \ cond_message(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__) #define inform(...) \ cond_message(want_info, std::cout, "info", info_verbose, __VA_ARGS__) #define hack(...) \ cond_message(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__) #define warn_once(...) \ cond_message_once(want_warn, std::cerr, "warn", warn_verbose, __VA_ARGS__) #define inform_once(...) \ cond_message_once(want_info, std::cout, "info", info_verbose, __VA_ARGS__) #define hack_once(...) \ cond_message_once(want_hack, std::cerr, "hack", hack_verbose, __VA_ARGS__) #endif // __BASE_MISC_HH__ <|endoftext|>
<commit_before>// Copyright 2017 Jose M. Arbos // // 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 <experimental/filesystem> #include <fstream> #include <iostream> #include "config.h" #include "yaml-cpp/yaml.h" using namespace std; using namespace std::experimental::filesystem::v1; static const char* nwn2_dirs[] = { "C:\\Program Files\\Atari\\Neverwinter Nights 2", "C:\\Program Files (x86)\\Atari\\Neverwinter Nights 2", "C:\\GOG Games\\Neverwinter Nights 2 Complete"}; static void create_config_file(const char *filename) { ofstream out(filename); out << "# (Optional) Directory where NWN2 is installed.\n"; out << "# nwn2_home: C:\\Program Files\\Atari\\Neverwinter Nights 2\n"; } static void find_nwn2_home(Config& config, YAML::Node& config_file) { if (config_file["nwn2_home"]) { auto nwn2_home = config_file["nwn2_home"].as<string>(""); if(exists(nwn2_home)) config.nwn2_home = nwn2_home; } else { for (unsigned i = 0; i < sizeof(nwn2_dirs) / sizeof(char*); ++i) if (exists(nwn2_dirs[i])) config.nwn2_home = nwn2_dirs[i]; } } Config::Config(const char *filename) { if (!exists(filename)) create_config_file(filename); auto config_file = YAML::LoadFile(filename); if(!config_file) { cout << "cannot open " << filename << endl; return; } find_nwn2_home(*this, config_file); if (nwn2_home.empty()) { cout << "Cannot find a NWN2 installation directory. Edit the " "config.yml file and put the directory where NWN2 is " "installed.\n"; } }<commit_msg>Catch YAML parser exceptions<commit_after>// Copyright 2017 Jose M. Arbos // // 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 <experimental/filesystem> #include <fstream> #include <iostream> #include "config.h" #include "yaml-cpp/yaml.h" using namespace std; using namespace std::experimental::filesystem::v1; static const char* nwn2_dirs[] = { "C:\\Program Files\\Atari\\Neverwinter Nights 2", "C:\\Program Files (x86)\\Atari\\Neverwinter Nights 2", "C:\\GOG Games\\Neverwinter Nights 2 Complete"}; static void create_config_file(const char *filename) { ofstream out(filename); out << "# (Optional) Directory where NWN2 is installed.\n"; out << "# nwn2_home: C:\\Program Files\\Atari\\Neverwinter Nights 2\n"; } static void find_nwn2_home(Config& config, YAML::Node& config_file) { if (config_file["nwn2_home"]) { auto nwn2_home = config_file["nwn2_home"].as<string>(""); if(exists(nwn2_home)) config.nwn2_home = nwn2_home; } else { for (unsigned i = 0; i < sizeof(nwn2_dirs) / sizeof(char*); ++i) if (exists(nwn2_dirs[i])) config.nwn2_home = nwn2_dirs[i]; } } Config::Config(const char *filename) { if (!exists(filename)) create_config_file(filename); try { auto config_file = YAML::LoadFile(filename); if (!config_file) { cout << "ERROR: Cannot open " << filename << endl; return; } find_nwn2_home(*this, config_file); } catch (...) { cout << "ERROR: Cannot open " << filename << ": It's ill-formed." << endl; return; } if (nwn2_home.empty()) { cout << "Cannot find a NWN2 installation directory. Edit the " "config.yml file and put the directory where NWN2 is " "installed.\n"; } }<|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "logger.h" #include <QtCore/QDebug> #include <QtCore/QVariant> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> class LoggerPrivate { public: QSqlDatabase m_database; LoggerPrivate(); void initializeDatabase(); }; LoggerPrivate::LoggerPrivate() { m_database = QSqlDatabase::addDatabase( "QSQLITE" ); } void LoggerPrivate::initializeDatabase() { QSqlQuery createJobsTable( "CREATE TABLE IF NOT EXISTS jobs (id VARCHAR(255) PRIMARY KEY, name TEXT, status TEXT, description TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP);" ); if ( createJobsTable.lastError().isValid() ) { qDebug() << "Error when executing query" << createJobsTable.lastQuery(); qDebug() << "Sql reports" << createJobsTable.lastError(); } } Logger::Logger(QObject *parent) : QObject(parent), d(new LoggerPrivate) { } Logger::~Logger() { delete d; } Logger &Logger::instance() { static Logger m_instance; return m_instance; } void Logger::setFilename(const QString &filename) { d->m_database.setDatabaseName( filename ); if ( !d->m_database.open() ) { qDebug() << "Failed to connect to database " << filename; } d->initializeDatabase(); } void Logger::setStatus(const QString &id, const QString &name, const QString &status, const QString &message) { QSqlQuery createJobsTable( QString("SELECT id FROM jobs WHERE id='%1';").arg(id) ); if ( createJobsTable.lastError().isValid() ) { qDebug() << "Error when executing query" << createJobsTable.lastQuery(); qDebug() << "Sql reports" << createJobsTable.lastError(); } else { if (!createJobsTable.next()) { QSqlQuery createStatus( QString("INSERT INTO jobs (id, name, status, description) VALUES ('%1', '%2', '%3', '%4');").arg(id).arg(name).arg(status).arg(message) ); if ( createStatus.lastError().isValid() ) { qDebug() << "Error when executing query" << createStatus.lastQuery(); qDebug() << "Sql reports" << createStatus.lastError(); } } else { QSqlQuery createStatus( QString("UPDATE jobs SET status='%2', description='%3', timestamp='CURRENT_TIMESTAMP' WHERE id='%1';").arg(id).arg(status).arg(message) ); if ( createStatus.lastError().isValid() ) { qDebug() << "Error when executing query" << createStatus.lastQuery(); qDebug() << "Sql reports" << createStatus.lastError(); } } } } <commit_msg>Simplify<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "logger.h" #include <QtCore/QDebug> #include <QtCore/QVariant> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> class LoggerPrivate { public: QSqlDatabase m_database; LoggerPrivate(); void initializeDatabase(); }; LoggerPrivate::LoggerPrivate() { m_database = QSqlDatabase::addDatabase( "QSQLITE" ); } void LoggerPrivate::initializeDatabase() { QSqlQuery createJobsTable( "CREATE TABLE IF NOT EXISTS jobs (id VARCHAR(255) PRIMARY KEY, name TEXT, status TEXT, description TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP);" ); if ( createJobsTable.lastError().isValid() ) { qDebug() << "Error when executing query" << createJobsTable.lastQuery(); qDebug() << "Sql reports" << createJobsTable.lastError(); } } Logger::Logger(QObject *parent) : QObject(parent), d(new LoggerPrivate) { } Logger::~Logger() { delete d; } Logger &Logger::instance() { static Logger m_instance; return m_instance; } void Logger::setFilename(const QString &filename) { d->m_database.setDatabaseName( filename ); if ( !d->m_database.open() ) { qDebug() << "Failed to connect to database " << filename; } d->initializeDatabase(); } void Logger::setStatus(const QString &id, const QString &name, const QString &status, const QString &message) { QSqlQuery deleteJob( QString("DELETE FROM jobs WHERE id='%1';").arg(id) ); if ( deleteJob.lastError().isValid() ) { qDebug() << "Error when executing query" << deleteJob.lastQuery(); qDebug() << "Sql reports" << deleteJob.lastError(); } else { QSqlQuery createStatus( QString("INSERT INTO jobs (id, name, status, description) VALUES ('%1', '%2', '%3', '%4');").arg(id).arg(name).arg(status).arg(message) ); if ( createStatus.lastError().isValid() ) { qDebug() << "Error when executing query" << createStatus.lastQuery(); qDebug() << "Sql reports" << createStatus.lastError(); } } } <|endoftext|>
<commit_before>// Rootmenu.cc for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net) // // 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. //Use GNU extensions #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif // _GNU_SOURCE #ifdef HAVE_CONFIG_H # include "../config.h" #endif // HAVE_CONFIG_H #include "fluxbox.hh" #include "Rootmenu.hh" #include "Screen.hh" #ifdef HAVE_STDIO_H # include <stdio.h> #endif // HAVE_STDIO_H #ifdef STDC_HEADERS # include <stdlib.h> # include <string.h> #endif // STDC_HEADERS #ifdef HAVE_SYS_PARAM_H # include <sys/param.h> #endif // HAVE_SYS_PARAM_H #ifndef MAXPATHLEN #define MAXPATHLEN 255 #endif // MAXPATHLEN Rootmenu::Rootmenu(BScreen *scrn) : Basemenu(scrn), auto_group_window(0) { screen = scrn; } void Rootmenu::itemSelected(int button, unsigned int index) { Fluxbox *fluxbox = Fluxbox::instance(); if (button == 1) { BasemenuItem *item = find(index); if (item->function()) { switch (item->function()) { case BScreen::EXECUTE: if (item->exec().size()) { #ifndef __EMX__ char displaystring[MAXPATHLEN]; sprintf(displaystring, "DISPLAY=%s", DisplayString(screen->getBaseDisplay()->getXDisplay())); sprintf(displaystring + strlen(displaystring) - 1, "%d", screen->getScreenNumber()); screen->setAutoGroupWindow(useAutoGroupWindow()); bexec(item->exec().c_str(), displaystring); #else // __EMX__ spawnlp(P_NOWAIT, "cmd.exe", "cmd.exe", "/c", item->exec().c_str(), NULL); #endif // !__EMX__ } break; case BScreen::RESTART: fluxbox->restart(); break; case BScreen::RESTARTOTHER: if (item->exec().size()) fluxbox->restart(item->exec().c_str()); break; case BScreen::EXIT: fluxbox->shutdown(); break; case BScreen::SETSTYLE: if (item->exec().size()) { fluxbox->saveStyleFilename(item->exec().c_str()); fluxbox->reconfigureTabs(); } fluxbox->reconfigure(); fluxbox->save_rc(); break; case BScreen::RECONFIGURE: fluxbox->reconfigure(); return; } if (! (screen->getRootmenu()->isTorn() || isTorn()) && item->function() != BScreen::RECONFIGURE && item->function() != BScreen::SETSTYLE) hide(); } } } void Rootmenu::setAutoGroupWindow(Window window) { auto_group_window = window; } Window Rootmenu::useAutoGroupWindow() { // Return and clear the auto-grouping state. Window w = auto_group_window; if (w) auto_group_window = 0; // clear it immediately // If not set check the parent and the parent's parent, ... else { // TODO: dynamic_cast throws std::bad_cast! Rootmenu *p = dynamic_cast<Rootmenu*>(parent()); if (p) w = p->useAutoGroupWindow(); } return w; } <commit_msg>cleaning and fixed menu always fully visible<commit_after>// Rootmenu.cc for fluxbox // Copyright (c) 2002 Henrik Kinnunen (fluxgen at linuxmail.org) // Rootmenu.cc for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net) // // 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. //Use GNU extensions #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif // _GNU_SOURCE #ifdef HAVE_CONFIG_H # include "../config.h" #endif // HAVE_CONFIG_H #include "fluxbox.hh" #include "Rootmenu.hh" #include "Screen.hh" #ifdef HAVE_STDIO_H # include <stdio.h> #endif // HAVE_STDIO_H #ifdef STDC_HEADERS # include <stdlib.h> # include <string.h> #endif // STDC_HEADERS #ifdef HAVE_SYS_PARAM_H # include <sys/param.h> #endif // HAVE_SYS_PARAM_H #ifndef MAXPATHLEN #define MAXPATHLEN 255 #endif // MAXPATHLEN Rootmenu::Rootmenu(BScreen *scrn) : Basemenu(scrn), auto_group_window(0) { } void Rootmenu::itemSelected(int button, unsigned int index) { Fluxbox *fluxbox = Fluxbox::instance(); if (button == 1) { BasemenuItem *item = find(index); if (item->function()) { switch (item->function()) { case BScreen::EXECUTE: if (item->exec().size()) { #ifndef __EMX__ char displaystring[MAXPATHLEN]; sprintf(displaystring, "DISPLAY=%s", DisplayString(screen()->getBaseDisplay()->getXDisplay())); sprintf(displaystring + strlen(displaystring) - 1, "%d", screen()->getScreenNumber()); screen()->setAutoGroupWindow(useAutoGroupWindow()); bexec(item->exec().c_str(), displaystring); #else // __EMX__ spawnlp(P_NOWAIT, "cmd.exe", "cmd.exe", "/c", item->exec().c_str(), NULL); #endif // !__EMX__ } break; case BScreen::RESTART: fluxbox->restart(); break; case BScreen::RESTARTOTHER: if (item->exec().size()) fluxbox->restart(item->exec().c_str()); break; case BScreen::EXIT: fluxbox->shutdown(); break; case BScreen::SETSTYLE: if (item->exec().size()) { fluxbox->saveStyleFilename(item->exec().c_str()); fluxbox->reconfigureTabs(); } fluxbox->reconfigure(); fluxbox->save_rc(); break; case BScreen::RECONFIGURE: fluxbox->reconfigure(); return; } if (! (screen()->getRootmenu()->isTorn() || isTorn()) && item->function() != BScreen::RECONFIGURE && item->function() != BScreen::SETSTYLE) hide(); } } } void Rootmenu::setAutoGroupWindow(Window window) { auto_group_window = window; } void Rootmenu::show() { Basemenu::show(); // make sure it's full visible int newx = x(), newy = y(); if (x() < 0) newx = 0; else if (x() + width() > screen()->getWidth()) newx = screen()->getWidth() - width(); if (y() < 0) newy = 0; else if (y() + height() > screen()->getHeight()) newy = screen()->getHeight() - height(); move(newx, newy); } Window Rootmenu::useAutoGroupWindow() { // Return and clear the auto-grouping state. Window w = auto_group_window; if (w) auto_group_window = 0; // clear it immediately // If not set check the parent and the parent's parent, ... else if (parent()) { // TODO: dynamic_cast throws std::bad_cast! Rootmenu *p = dynamic_cast<Rootmenu*>(parent()); w = p->useAutoGroupWindow(); } return w; } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "util.hpp" #include <arpa/inet.h> #ifdef __APPLE__ #include <libproc.h> #endif #include <net/if.h> #include <netinet/in.h> #include <pwd.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/stat.h> #include <unistd.h> #include <cerrno> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <csignal> #include <fstream> #include <sstream> #include <string> #include <utility> #include <vector> #include <glog/logging.h> #include <pficommon/lang/exception.h> #include <pficommon/text/json.h> #include <pficommon/concurrent/thread.h> #include "jubatus/core/common/exception.hpp" using std::string; using pfi::lang::lexical_cast; using pfi::lang::parse_error; namespace jubatus { namespace server { namespace common { namespace util { // TODO(kashihara): AF_INET does not specify IPv6 void get_ip(const char* nic, string& out) { int fd; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd == -1) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to create socket(AF_INET, SOCK_DGRAM)") << jubatus::core::common::exception::error_errno(errno)); } ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, nic, IFNAMSIZ - 1); if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to get IP address from interface") << jubatus::core::common::exception::error_errno(errno)); } close(fd); struct sockaddr_in* sin = (struct sockaddr_in*) (&(ifr.ifr_addr)); out = inet_ntoa((struct in_addr) (sin->sin_addr)); } string get_ip(const char* nic) { string ret; get_ip(nic, ret); return ret; } string base_name(const string& path) { size_t found = path.rfind('/'); return found != string::npos ? path.substr(found + 1) : path; } std::string get_program_name() { // WARNING: this code will only work on linux or OS X #ifdef __APPLE__ char path[PROC_PIDPATHINFO_MAXSIZE]; int ret = proc_pidpath(getpid(), path, PROC_PIDPATHINFO_MAXSIZE); #else const char* exe_sym_path = "/proc/self/exe"; // when BSD: /proc/curproc/file // when Solaris: /proc/self/path/a.out // Unix: getexecname(3) char path[PATH_MAX]; ssize_t ret = readlink(exe_sym_path, path, PATH_MAX); if (ret != -1) { if (ret == PATH_MAX) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to get program name. Path size overed PATH_MAX.") << jubatus::core::common::exception::error_errno(errno)); } path[ret] = '\0'; } #endif if (ret < 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("Failed to get program name") << core::common::exception::error_errno(errno)); } // get basename const string program_base_name = base_name(path); if (program_base_name == path) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( string("Failed to get program name from path: ") + path) << jubatus::core::common::exception::error_file_name(path)); } return program_base_name; } std::string get_user_name() { uid_t uid = getuid(); int64_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX); std::vector<char> buf(buflen); struct passwd pwd; struct passwd* result; int ret = getpwuid_r(uid, &pwd, &buf[0], buflen, &result); if (ret == 0) { if (result != NULL) { return result->pw_name; } throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("User not found") << core::common::exception::error_api_func("getpwuid_r")); } throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("Failed to get user name") << jubatus::core::common::exception::error_api_func("getpwuid_r") << jubatus::core::common::exception::error_errno(ret)); } bool is_writable(const char* dir_path) { struct stat st_buf; if (stat(dir_path, &st_buf) < 0) { return false; } if (!S_ISDIR(st_buf.st_mode)) { errno = ENOTDIR; return false; } if (access(dir_path, W_OK) < 0) { return false; } return true; } int daemonize() { return daemon(0, 0); } void append_env_path(const string& e, const string& argv0) { const char* env = getenv(e.c_str()); string new_path = string(env) + ":" + argv0; setenv(e.c_str(), new_path.c_str(), new_path.size()); } void append_server_path(const string& argv0) { const char* env = getenv("PATH"); char cwd[PATH_MAX]; if (!getcwd(cwd, PATH_MAX)) { throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("Failed to getcwd")) << jubatus::core::common::exception::error_errno(errno); } string p = argv0.substr(0, argv0.find_last_of('/')); string new_path = string(env) + ":" + cwd + "/" + p + "/../server"; setenv("PATH", new_path.c_str(), new_path.size()); } namespace { string get_statm_path() { // /proc/[pid]/statm shows using page size char path[64]; int pid = getpid(); // convert pid_t to int (for "%d") snprintf(path, sizeof(path), "/proc/%d/statm", pid); return path; } } // namespace void get_machine_status(machine_status_t& status) { // WARNING: this code will only work on linux uint64_t vm_virt = 0, vm_rss = 0, vm_shr = 0; { string path = get_statm_path(); std::ifstream statm(path.c_str()); if (statm) { const int64_t page_size = sysconf(_SC_PAGESIZE); statm >> vm_virt >> vm_rss >> vm_shr; vm_virt = vm_virt * page_size / 1024; vm_rss = vm_rss * page_size / 1024; vm_shr = vm_shr * page_size / 1024; } } // in KB status.vm_size = vm_virt; // total program size(virtual memory) status.vm_resident = vm_rss; // resident set size status.vm_share = vm_shr; // shared } namespace { // helper functions to handle sigset void clear_sigset(sigset_t* ss) { if (sigemptyset(ss) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigemptyset") << core::common::exception::error_api_func("clear_sigset") << core::common::exception::error_errno(errno)); } } void add_signal(sigset_t* ss, int signum) { if (sigaddset(ss, signum) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigaddset") << core::common::exception::error_api_func("add_signal") << core::common::exception::error_errno(errno)); } } void setup_sigset(sigset_t* ss) { clear_sigset(ss); add_signal(ss, SIGTERM); add_signal(ss, SIGINT); } void block_signals(const sigset_t* ss) { if (sigprocmask(SIG_BLOCK, ss, NULL) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigprocmask") << core::common::exception::error_api_func("block_signals") << core::common::exception::error_errno(errno)); } } void exit_on_term() { // internal function; do not call this function outside of set_exit_on_term try { sigset_t ss; setup_sigset(&ss); block_signals(&ss); int signo; if (sigwait(&ss, &signo) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigwait") << core::common::exception::error_api_func("exit_on_term") << core::common::exception::error_errno(errno)); } switch (signo) { case SIGINT: case SIGTERM: // intended signal; continue break; default: // unintended signal; raise error throw JUBATUS_EXCEPTION( core::common::exception::runtime_error( "unknown signal caught by sigwait (possibily logic error)") << core::common::exception::error_api_func("set_exit_on_term") << core::common::exception::error_errno(errno)); } LOG(INFO) << "stopping RPC server"; // TODO(SubaruG): PUT CODES TO STOP OTHER THREADS HERE; // or move sigwait to main thread // and use pthread_cancel exit(0); // never returns } catch (const jubatus::core::common::exception::jubatus_exception& e) { LOG(FATAL) << e.diagnostic_information(true); } catch (const std::exception& e) { LOG(FATAL) << e.what(); } abort(); } } // namespace void set_exit_on_term() { sigset_t ss; setup_sigset(&ss); block_signals(&ss); pfi::concurrent::thread(&exit_on_term).start(); } void ignore_sigpipe() { // portable code for socket write(2) MSG_NOSIGNAL if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("can't ignore SIGPIPE") << jubatus::core::common::exception::error_api_func("signal") << jubatus::core::common::exception::error_errno(errno)); } } } // namespace util } // namespace common } // namespace server } // namespace jubatus <commit_msg>Remove unnecessary errno<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "util.hpp" #include <arpa/inet.h> #ifdef __APPLE__ #include <libproc.h> #endif #include <net/if.h> #include <netinet/in.h> #include <pwd.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/stat.h> #include <unistd.h> #include <cerrno> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <csignal> #include <fstream> #include <sstream> #include <string> #include <utility> #include <vector> #include <glog/logging.h> #include <pficommon/lang/exception.h> #include <pficommon/text/json.h> #include <pficommon/concurrent/thread.h> #include "jubatus/core/common/exception.hpp" using std::string; using pfi::lang::lexical_cast; using pfi::lang::parse_error; namespace jubatus { namespace server { namespace common { namespace util { // TODO(kashihara): AF_INET does not specify IPv6 void get_ip(const char* nic, string& out) { int fd; struct ifreq ifr; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd == -1) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to create socket(AF_INET, SOCK_DGRAM)") << jubatus::core::common::exception::error_errno(errno)); } ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, nic, IFNAMSIZ - 1); if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to get IP address from interface") << jubatus::core::common::exception::error_errno(errno)); } close(fd); struct sockaddr_in* sin = (struct sockaddr_in*) (&(ifr.ifr_addr)); out = inet_ntoa((struct in_addr) (sin->sin_addr)); } string get_ip(const char* nic) { string ret; get_ip(nic, ret); return ret; } string base_name(const string& path) { size_t found = path.rfind('/'); return found != string::npos ? path.substr(found + 1) : path; } std::string get_program_name() { // WARNING: this code will only work on linux or OS X #ifdef __APPLE__ char path[PROC_PIDPATHINFO_MAXSIZE]; int ret = proc_pidpath(getpid(), path, PROC_PIDPATHINFO_MAXSIZE); #else const char* exe_sym_path = "/proc/self/exe"; // when BSD: /proc/curproc/file // when Solaris: /proc/self/path/a.out // Unix: getexecname(3) char path[PATH_MAX]; ssize_t ret = readlink(exe_sym_path, path, PATH_MAX); if (ret != -1) { if (ret == PATH_MAX) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( "Failed to get program name. Path size overed PATH_MAX.") << jubatus::core::common::exception::error_errno(errno)); } path[ret] = '\0'; } #endif if (ret < 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("Failed to get program name") << core::common::exception::error_errno(errno)); } // get basename const string program_base_name = base_name(path); if (program_base_name == path) { throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error( string("Failed to get program name from path: ") + path) << jubatus::core::common::exception::error_file_name(path)); } return program_base_name; } std::string get_user_name() { uid_t uid = getuid(); int64_t buflen = sysconf(_SC_GETPW_R_SIZE_MAX); std::vector<char> buf(buflen); struct passwd pwd; struct passwd* result; int ret = getpwuid_r(uid, &pwd, &buf[0], buflen, &result); if (ret == 0) { if (result != NULL) { return result->pw_name; } throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("User not found") << core::common::exception::error_api_func("getpwuid_r")); } throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("Failed to get user name") << jubatus::core::common::exception::error_api_func("getpwuid_r") << jubatus::core::common::exception::error_errno(ret)); } bool is_writable(const char* dir_path) { struct stat st_buf; if (stat(dir_path, &st_buf) < 0) { return false; } if (!S_ISDIR(st_buf.st_mode)) { errno = ENOTDIR; return false; } if (access(dir_path, W_OK) < 0) { return false; } return true; } int daemonize() { return daemon(0, 0); } void append_env_path(const string& e, const string& argv0) { const char* env = getenv(e.c_str()); string new_path = string(env) + ":" + argv0; setenv(e.c_str(), new_path.c_str(), new_path.size()); } void append_server_path(const string& argv0) { const char* env = getenv("PATH"); char cwd[PATH_MAX]; if (!getcwd(cwd, PATH_MAX)) { throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("Failed to getcwd")) << jubatus::core::common::exception::error_errno(errno); } string p = argv0.substr(0, argv0.find_last_of('/')); string new_path = string(env) + ":" + cwd + "/" + p + "/../server"; setenv("PATH", new_path.c_str(), new_path.size()); } namespace { string get_statm_path() { // /proc/[pid]/statm shows using page size char path[64]; int pid = getpid(); // convert pid_t to int (for "%d") snprintf(path, sizeof(path), "/proc/%d/statm", pid); return path; } } // namespace void get_machine_status(machine_status_t& status) { // WARNING: this code will only work on linux uint64_t vm_virt = 0, vm_rss = 0, vm_shr = 0; { string path = get_statm_path(); std::ifstream statm(path.c_str()); if (statm) { const int64_t page_size = sysconf(_SC_PAGESIZE); statm >> vm_virt >> vm_rss >> vm_shr; vm_virt = vm_virt * page_size / 1024; vm_rss = vm_rss * page_size / 1024; vm_shr = vm_shr * page_size / 1024; } } // in KB status.vm_size = vm_virt; // total program size(virtual memory) status.vm_resident = vm_rss; // resident set size status.vm_share = vm_shr; // shared } namespace { // helper functions to handle sigset void clear_sigset(sigset_t* ss) { if (sigemptyset(ss) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigemptyset") << core::common::exception::error_api_func("clear_sigset") << core::common::exception::error_errno(errno)); } } void add_signal(sigset_t* ss, int signum) { if (sigaddset(ss, signum) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigaddset") << core::common::exception::error_api_func("add_signal") << core::common::exception::error_errno(errno)); } } void setup_sigset(sigset_t* ss) { clear_sigset(ss); add_signal(ss, SIGTERM); add_signal(ss, SIGINT); } void block_signals(const sigset_t* ss) { if (sigprocmask(SIG_BLOCK, ss, NULL) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigprocmask") << core::common::exception::error_api_func("block_signals") << core::common::exception::error_errno(errno)); } } void exit_on_term() { // internal function; do not call this function outside of set_exit_on_term try { sigset_t ss; setup_sigset(&ss); block_signals(&ss); int signo; if (sigwait(&ss, &signo) != 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error("failed to call sigwait") << core::common::exception::error_api_func("exit_on_term")); } switch (signo) { case SIGINT: case SIGTERM: // intended signal; continue break; default: // unintended signal; raise error throw JUBATUS_EXCEPTION( core::common::exception::runtime_error( "unknown signal caught by sigwait (possibily logic error)") << core::common::exception::error_api_func("set_exit_on_term")); } LOG(INFO) << "stopping RPC server"; // TODO(SubaruG): PUT CODES TO STOP OTHER THREADS HERE; // or move sigwait to main thread // and use pthread_cancel exit(0); // never returns } catch (const jubatus::core::common::exception::jubatus_exception& e) { LOG(FATAL) << e.diagnostic_information(true); } catch (const std::exception& e) { LOG(FATAL) << e.what(); } abort(); } } // namespace void set_exit_on_term() { sigset_t ss; setup_sigset(&ss); block_signals(&ss); pfi::concurrent::thread(&exit_on_term).start(); } void ignore_sigpipe() { // portable code for socket write(2) MSG_NOSIGNAL if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { throw JUBATUS_EXCEPTION( jubatus::core::common::exception::runtime_error("can't ignore SIGPIPE") << jubatus::core::common::exception::error_api_func("signal") << jubatus::core::common::exception::error_errno(errno)); } } } // namespace util } // namespace common } // namespace server } // namespace jubatus <|endoftext|>
<commit_before>// Copyright (c) 2015 Yandex LLC. All rights reserved. // Author: Vasily Chekalkin <bacek@yandex-team.ru> #include "sdch_dictionary.h" #include <cassert> #include <cstring> #include <vector> #include <google/vcencoder.h> #include <openssl/sha.h> namespace sdch { namespace { #if nginx_version < 1006000 static void ngx_encode_base64url(ngx_str_t *dst, ngx_str_t *src) { ngx_encode_base64(dst, src); unsigned i; for (i = 0; i < dst->len; i++) { if (dst->data[i] == '+') dst->data[i] = '-'; if (dst->data[i] == '/') dst->data[i] = '_'; } } #endif void encode_id(u_char* sha, Dictionary::id_t& id) { ngx_str_t src = {6, sha}; ngx_str_t dst = {8, id.data()}; ngx_encode_base64url(&dst, &src); } void get_dict_ids(const char* buf, size_t buflen, Dictionary::id_t& client_id, Dictionary::id_t& server_id) { SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, buf, buflen); unsigned char sha[32]; SHA256_Final(sha, &ctx); encode_id(sha, client_id); encode_id(sha + 6, server_id); } } // namespace bool Dictionary::init_quasy(const char* buf, size_t len) { size_ = len; return init(buf, buf, buf + len); } bool Dictionary::init(const char* begin, const char* payload, const char* end) { hashed_dict_.reset(new open_vcdiff::HashedDictionary(payload, end - payload)); if (!hashed_dict_->Init()) return false; get_dict_ids(begin, end - begin, client_id_, server_id_); return true; } } // namespace sdch <commit_msg>Don't store dictionary blob. It's not nessesary<commit_after>// Copyright (c) 2015 Yandex LLC. All rights reserved. // Author: Vasily Chekalkin <bacek@yandex-team.ru> #include "sdch_dictionary.h" #include <cassert> #include <cstring> #include <vector> #include <google/vcencoder.h> #include <openssl/sha.h> namespace sdch { namespace { #if nginx_version < 1006000 static void ngx_encode_base64url(ngx_str_t *dst, ngx_str_t *src) { ngx_encode_base64(dst, src); unsigned i; for (i = 0; i < dst->len; i++) { if (dst->data[i] == '+') dst->data[i] = '-'; if (dst->data[i] == '/') dst->data[i] = '_'; } } #endif void encode_id(u_char* sha, Dictionary::id_t& id) { ngx_str_t src = {6, sha}; ngx_str_t dst = {8, id.data()}; ngx_encode_base64url(&dst, &src); } void get_dict_ids(const char* buf, size_t buflen, Dictionary::id_t& client_id, Dictionary::id_t& server_id) { SHA256_CTX ctx; SHA256_Init(&ctx); SHA256_Update(&ctx, buf, buflen); unsigned char sha[32]; SHA256_Final(sha, &ctx); encode_id(sha, client_id); encode_id(sha + 6, server_id); } } // namespace bool Dictionary::init_quasy(const char* buf, size_t len) { size_ = len; return init(buf, buf, buf + len); } bool Dictionary::init(const char* begin, const char* payload, const char* end) { hashed_dict_.reset(new open_vcdiff::HashedDictionary(payload, end - payload)); if (!hashed_dict_->Init()) return false; get_dict_ids(begin, end - begin, client_id_, server_id_); size_ = end - begin; return true; } } // namespace sdch <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <asm/param.h> #include <pthread.h> #include <fstream> #include <list> #include <string> #include "common/foreach.hpp" #include "common/try.hpp" #include "common/utils.hpp" #include "proc_utils.hpp" using std::ifstream; using std::string; using std::list; namespace mesos { namespace internal { namespace monitoring { // Code for initializing cached boot time. static pthread_once_t isBootTimeInitialized = PTHREAD_ONCE_INIT; static Try<double> cachedBootTime = Try<double>::error("not initialized"); void initCachedBootTime() { string line; ifstream statFile("/proc/stat"); if (statFile.is_open()) { while (statFile.good()) { getline (statFile, line); if (line.compare(0, 6, "btime ") == 0) { Try<double> bootTime = utils::numify<double>(line.substr(6)); if (bootTime.isSome()) { cachedBootTime = bootTime.get() * 1000.0; return; } } } } cachedBootTime = Try<double>::error("unable to read boot time from proc"); } // Converts time in jiffies to milliseconds. static inline double jiffiesToMillis(double jiffies) { return jiffies * 1000.0 / HZ; } // Converts time in system ticks (as defined by _SC_CLK_TCK, NOT CPU // clock ticks) to milliseconds. static inline double ticksToMillis(double ticks) { return ticks * 1000.0 / sysconf(_SC_CLK_TCK); } Try<ProcessStats> getProcessStats(const string& pid) { string procPath = "/proc/" + pid + "/stat"; ifstream pStatFile(procPath.c_str()); if (pStatFile.is_open()) { ProcessStats pinfo; // Dummy vars for leading entries in stat that we don't care about. string comm, state, tty_nr, tpgid, flags, minflt, cminflt, majflt, cmajflt; string cutime, cstime, priority, nice, num_threads, itrealvalue, vsize; // These are the fields we want. double rss, utime, stime, starttime; // Parse all fields from stat. pStatFile >> pinfo.pid >> comm >> state >> pinfo.ppid >> pinfo.pgrp >> pinfo.session >> tty_nr >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >> utime >> stime >> cutime >> cstime >> priority >> nice >> num_threads >> itrealvalue >> starttime >> vsize >> rss; Try<double> bootTime = getBootTime(); if (bootTime.isError()) { return Try<ProcessStats>::error(bootTime.error()); } pinfo.startTime = bootTime.get() + jiffiesToMillis(starttime); // TODO(adegtiar): consider doing something more sophisticated. pinfo.memUsage = rss * sysconf(_SC_PAGE_SIZE); pinfo.cpuTime = ticksToMillis(utime + stime); return pinfo; } else { return Try<ProcessStats>::error("Cannot open " + procPath + " for stats"); } } Try<double> getBootTime() { pthread_once(&isBootTimeInitialized, initCachedBootTime); return cachedBootTime; } Try<double> getStartTime(const string& pid) { Try<ProcessStats> pStats = getProcessStats(pid); if (pStats.isError()) { return Try<double>::error(pStats.error()); } else { return pStats.get().startTime; } } Try<list<string> > getAllPids() { list<string> pids = list<string>(); foreach (const string& filename, utils::os::listdir("/proc")) { if (utils::numify<uint64_t>(filename).isSome()) { pids.push_back(filename); } } if (pids.empty()) { return Try<list<string> >::error("Failed to retrieve pids from proc"); } else { return pids; } } } // namespace monitoring { } // namespace internal { } // namespace mesos { <commit_msg>Adding check for failed read from proc stats.<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <asm/param.h> #include <pthread.h> #include <fstream> #include <list> #include <string> #include "common/foreach.hpp" #include "common/try.hpp" #include "common/utils.hpp" #include "proc_utils.hpp" using std::ifstream; using std::string; using std::list; namespace mesos { namespace internal { namespace monitoring { // Code for initializing cached boot time. static pthread_once_t isBootTimeInitialized = PTHREAD_ONCE_INIT; static Try<double> cachedBootTime = Try<double>::error("not initialized"); void initCachedBootTime() { string line; ifstream statFile("/proc/stat"); if (statFile.is_open()) { while (statFile.good()) { getline (statFile, line); if (line.compare(0, 6, "btime ") == 0) { Try<double> bootTime = utils::numify<double>(line.substr(6)); if (bootTime.isSome()) { cachedBootTime = bootTime.get() * 1000.0; return; } } } } cachedBootTime = Try<double>::error("Failed to read boot time from proc"); } // Converts time in jiffies to milliseconds. static inline double jiffiesToMillis(double jiffies) { return jiffies * 1000.0 / HZ; } // Converts time in system ticks (as defined by _SC_CLK_TCK, NOT CPU // clock ticks) to milliseconds. static inline double ticksToMillis(double ticks) { return ticks * 1000.0 / sysconf(_SC_CLK_TCK); } Try<ProcessStats> getProcessStats(const string& pid) { string procPath = "/proc/" + pid + "/stat"; ifstream pStatFile(procPath.c_str()); if (pStatFile.is_open()) { ProcessStats pinfo; // Dummy vars for leading entries in stat that we don't care about. string comm, state, tty_nr, tpgid, flags, minflt, cminflt, majflt, cmajflt; string cutime, cstime, priority, nice, num_threads, itrealvalue, vsize; // These are the fields we want. double rss, utime, stime, starttime; // Parse all fields from stat. pStatFile >> pinfo.pid >> comm >> state >> pinfo.ppid >> pinfo.pgrp >> pinfo.session >> tty_nr >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >> utime >> stime >> cutime >> cstime >> priority >> nice >> num_threads >> itrealvalue >> starttime >> vsize >> rss; if (!pStatFile) { return Try<ProcessStats>::error("Failed to read ProcessStats from proc"); } Try<double> bootTime = getBootTime(); if (bootTime.isError()) { return Try<ProcessStats>::error(bootTime.error()); } pinfo.startTime = bootTime.get() + jiffiesToMillis(starttime); // TODO(adegtiar): consider doing something more sophisticated. pinfo.memUsage = rss * sysconf(_SC_PAGE_SIZE); pinfo.cpuTime = ticksToMillis(utime + stime); return pinfo; } else { return Try<ProcessStats>::error("Cannot open " + procPath + " for stats"); } } Try<double> getBootTime() { pthread_once(&isBootTimeInitialized, initCachedBootTime); return cachedBootTime; } Try<double> getStartTime(const string& pid) { Try<ProcessStats> pStats = getProcessStats(pid); if (pStats.isError()) { return Try<double>::error(pStats.error()); } else { return pStats.get().startTime; } } Try<list<string> > getAllPids() { list<string> pids = list<string>(); foreach (const string& filename, utils::os::listdir("/proc")) { if (utils::numify<uint64_t>(filename).isSome()) { pids.push_back(filename); } } if (pids.empty()) { return Try<list<string> >::error("Failed to retrieve pids from proc"); } else { return pids; } } } // namespace monitoring { } // namespace internal { } // namespace mesos { <|endoftext|>
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "build_log.h" #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "build.h" #include "graph.h" #include "util.h" // Implementation details: // Each run's log appends to the log file. // To load, we run through all log entries in series, throwing away // older runs. // Once the number of redundant entries exceeds a threshold, we write // out a new file and replace the existing one with it. namespace { const char kFileSignature[] = "# ninja log v%d\n"; const int kCurrentVersion = 4; } // namespace BuildLog::BuildLog() : log_file_(NULL), config_(NULL), needs_recompaction_(false) {} BuildLog::~BuildLog() { Close(); } bool BuildLog::OpenForWrite(const string& path, string* err) { if (config_ && config_->dry_run) return true; // Do nothing, report success. if (needs_recompaction_) { Close(); if (!Recompact(path, err)) return false; } log_file_ = fopen(path.c_str(), "ab"); if (!log_file_) { *err = strerror(errno); return false; } setvbuf(log_file_, NULL, _IOLBF, BUFSIZ); SetCloseOnExec(fileno(log_file_)); if (ftell(log_file_) == 0) { if (fprintf(log_file_, kFileSignature, kCurrentVersion) < 0) { *err = strerror(errno); return false; } } return true; } void BuildLog::RecordCommand(Edge* edge, int start_time, int end_time, TimeStamp restat_mtime) { const string command = edge->EvaluateCommand(); for (vector<Node*>::iterator out = edge->outputs_.begin(); out != edge->outputs_.end(); ++out) { const string& path = (*out)->path(); Log::iterator i = log_.find(path); LogEntry* log_entry; if (i != log_.end()) { log_entry = i->second; } else { log_entry = new LogEntry; log_entry->output = path; log_.insert(make_pair(log_entry->output.c_str(), log_entry)); } log_entry->command = command; log_entry->start_time = start_time; log_entry->end_time = end_time; log_entry->restat_mtime = restat_mtime; if (log_file_) WriteEntry(log_file_, *log_entry); } } void BuildLog::Close() { if (log_file_) fclose(log_file_); log_file_ = NULL; } bool BuildLog::Load(const string& path, string* err) { FILE* file = fopen(path.c_str(), "r"); if (!file) { if (errno == ENOENT) return true; *err = strerror(errno); return false; } int log_version = 0; int unique_entry_count = 0; int total_entry_count = 0; char buf[256 << 10]; while (fgets(buf, sizeof(buf), file)) { if (!log_version) { log_version = 1; // Assume by default. if (sscanf(buf, kFileSignature, &log_version) > 0) continue; } char field_separator = log_version >= 4 ? '\t' : ' '; char* start = buf; char* end = strchr(start, field_separator); if (!end) continue; *end = 0; int start_time = 0, end_time = 0; TimeStamp restat_mtime = 0; start_time = atoi(start); start = end + 1; end = strchr(start, field_separator); if (!end) continue; *end = 0; end_time = atoi(start); start = end + 1; end = strchr(start, field_separator); if (!end) continue; *end = 0; restat_mtime = atol(start); start = end + 1; end = strchr(start, field_separator); if (!end) continue; string output = string(start, end - start); start = end + 1; end = strchr(start, '\n'); if (!end) continue; LogEntry* entry; Log::iterator i = log_.find(output); if (i != log_.end()) { entry = i->second; } else { entry = new LogEntry; entry->output = output; log_.insert(make_pair(entry->output, entry)); ++unique_entry_count; } ++total_entry_count; entry->start_time = start_time; entry->end_time = end_time; entry->restat_mtime = restat_mtime; entry->command = string(start, end - start); } // Decide whether it's time to rebuild the log: // - if we're upgrading versions // - if it's getting large int kMinCompactionEntryCount = 100; int kCompactionRatio = 3; if (log_version < kCurrentVersion) { needs_recompaction_ = true; } else if (total_entry_count > kMinCompactionEntryCount && total_entry_count > unique_entry_count * kCompactionRatio) { needs_recompaction_ = true; } fclose(file); return true; } BuildLog::LogEntry* BuildLog::LookupByOutput(const string& path) { Log::iterator i = log_.find(path); if (i != log_.end()) return i->second; return NULL; } void BuildLog::WriteEntry(FILE* f, const LogEntry& entry) { fprintf(f, "%d\t%d\t%ld\t%s\t%s\n", entry.start_time, entry.end_time, (long) entry.restat_mtime, entry.output.c_str(), entry.command.c_str()); } bool BuildLog::Recompact(const string& path, string* err) { printf("Recompacting log...\n"); string temp_path = path + ".recompact"; FILE* f = fopen(temp_path.c_str(), "wb"); if (!f) { *err = strerror(errno); return false; } if (fprintf(f, kFileSignature, kCurrentVersion) < 0) { *err = strerror(errno); return false; } for (Log::iterator i = log_.begin(); i != log_.end(); ++i) { WriteEntry(f, *i->second); } fclose(f); if (unlink(path.c_str()) < 0) { *err = strerror(errno); return false; } if (rename(temp_path.c_str(), path.c_str()) < 0) { *err = strerror(errno); return false; } return true; } <commit_msg>BuildLog: Use Log::insert(Log::value_type()) to avoid invalid strings.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "build_log.h" #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "build.h" #include "graph.h" #include "util.h" // Implementation details: // Each run's log appends to the log file. // To load, we run through all log entries in series, throwing away // older runs. // Once the number of redundant entries exceeds a threshold, we write // out a new file and replace the existing one with it. namespace { const char kFileSignature[] = "# ninja log v%d\n"; const int kCurrentVersion = 4; } // namespace BuildLog::BuildLog() : log_file_(NULL), config_(NULL), needs_recompaction_(false) {} BuildLog::~BuildLog() { Close(); } bool BuildLog::OpenForWrite(const string& path, string* err) { if (config_ && config_->dry_run) return true; // Do nothing, report success. if (needs_recompaction_) { Close(); if (!Recompact(path, err)) return false; } log_file_ = fopen(path.c_str(), "ab"); if (!log_file_) { *err = strerror(errno); return false; } setvbuf(log_file_, NULL, _IOLBF, BUFSIZ); SetCloseOnExec(fileno(log_file_)); if (ftell(log_file_) == 0) { if (fprintf(log_file_, kFileSignature, kCurrentVersion) < 0) { *err = strerror(errno); return false; } } return true; } void BuildLog::RecordCommand(Edge* edge, int start_time, int end_time, TimeStamp restat_mtime) { const string command = edge->EvaluateCommand(); for (vector<Node*>::iterator out = edge->outputs_.begin(); out != edge->outputs_.end(); ++out) { const string& path = (*out)->path(); Log::iterator i = log_.find(path); LogEntry* log_entry; if (i != log_.end()) { log_entry = i->second; } else { log_entry = new LogEntry; log_entry->output = path; log_.insert(Log::value_type(log_entry->output, log_entry)); } log_entry->command = command; log_entry->start_time = start_time; log_entry->end_time = end_time; log_entry->restat_mtime = restat_mtime; if (log_file_) WriteEntry(log_file_, *log_entry); } } void BuildLog::Close() { if (log_file_) fclose(log_file_); log_file_ = NULL; } bool BuildLog::Load(const string& path, string* err) { FILE* file = fopen(path.c_str(), "r"); if (!file) { if (errno == ENOENT) return true; *err = strerror(errno); return false; } int log_version = 0; int unique_entry_count = 0; int total_entry_count = 0; char buf[256 << 10]; while (fgets(buf, sizeof(buf), file)) { if (!log_version) { log_version = 1; // Assume by default. if (sscanf(buf, kFileSignature, &log_version) > 0) continue; } char field_separator = log_version >= 4 ? '\t' : ' '; char* start = buf; char* end = strchr(start, field_separator); if (!end) continue; *end = 0; int start_time = 0, end_time = 0; TimeStamp restat_mtime = 0; start_time = atoi(start); start = end + 1; end = strchr(start, field_separator); if (!end) continue; *end = 0; end_time = atoi(start); start = end + 1; end = strchr(start, field_separator); if (!end) continue; *end = 0; restat_mtime = atol(start); start = end + 1; end = strchr(start, field_separator); if (!end) continue; string output = string(start, end - start); start = end + 1; end = strchr(start, '\n'); if (!end) continue; LogEntry* entry; Log::iterator i = log_.find(output); if (i != log_.end()) { entry = i->second; } else { entry = new LogEntry; entry->output = output; log_.insert(Log::value_type(entry->output, entry)); ++unique_entry_count; } ++total_entry_count; entry->start_time = start_time; entry->end_time = end_time; entry->restat_mtime = restat_mtime; entry->command = string(start, end - start); } // Decide whether it's time to rebuild the log: // - if we're upgrading versions // - if it's getting large int kMinCompactionEntryCount = 100; int kCompactionRatio = 3; if (log_version < kCurrentVersion) { needs_recompaction_ = true; } else if (total_entry_count > kMinCompactionEntryCount && total_entry_count > unique_entry_count * kCompactionRatio) { needs_recompaction_ = true; } fclose(file); return true; } BuildLog::LogEntry* BuildLog::LookupByOutput(const string& path) { Log::iterator i = log_.find(path); if (i != log_.end()) return i->second; return NULL; } void BuildLog::WriteEntry(FILE* f, const LogEntry& entry) { fprintf(f, "%d\t%d\t%ld\t%s\t%s\n", entry.start_time, entry.end_time, (long) entry.restat_mtime, entry.output.c_str(), entry.command.c_str()); } bool BuildLog::Recompact(const string& path, string* err) { printf("Recompacting log...\n"); string temp_path = path + ".recompact"; FILE* f = fopen(temp_path.c_str(), "wb"); if (!f) { *err = strerror(errno); return false; } if (fprintf(f, kFileSignature, kCurrentVersion) < 0) { *err = strerror(errno); return false; } for (Log::iterator i = log_.begin(); i != log_.end(); ++i) { WriteEntry(f, *i->second); } fclose(f); if (unlink(path.c_str()) < 0) { *err = strerror(errno); return false; } if (rename(temp_path.c_str(), path.c_str()) < 0) { *err = strerror(errno); return false; } return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2003-2011 Victor Semionov * 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 holder nor the names of the 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 HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <windows.h> #include <gl/gl.h> #include <gl/glu.h> #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include <math.h> #include <gl/glext.h> #include "Settings.h" #include "Loader.h" #include "VideoBase.h" #include "Window.h" #include "Error.h" #include "GamePlay.h" #include "StarMap.h" //resource stuff #define STARMAP_RESOURCE CSettings::DataFile #define STARMAP_FILE "STARS.TXT" //sphere radius #define STARMAP_RADIUS 100.0 //num random stars #define NUM_RANDOM_STARS_BASE 8192 #define NUM_RANDOM_STARS ((int)((float)NUM_RANDOM_STARS_BASE*CVideoBase::GetOptGeoDetail())) //random star size and color #define MIN_INTENSITY 0.6f //also affects colorfulness of stars, when generated randomly #define MIN_MAG 4.75 #define MAX_MAG 7.9 //real-star color levels #define COLOR_SCALE 0.75f //magnitude-size conversion #define STAR_SIZE(star_mag) (0.75+(7.0-star_mag)/2.5) //point size macros #define POINT_SIZE_AT_H600 1.25 #define SQRT_QUAD_ATTEN_INV (STARMAP_RADIUS) #define QUAD_ATTEN_INV (SQRT_QUAD_ATTEN_INV*SQRT_QUAD_ATTEN_INV) #define QUAD_ATTEN (1.0/QUAD_ATTEN_INV) #define STAR_DIST(star_size) (CVideoBase::GetExtPointParams()? \ (SQRT_QUAD_ATTEN_INV/star_size): \ STARMAP_RADIUS) #define AUTO_SIZE_COEF 0.625 CStarMap::CStarMap() { Init(); } CStarMap::~CStarMap() { Free(); } bool CStarMap::Load() { Free(); if (LoadStars()) { PrepColor(); } else { CError::LogError(WARNING_CODE,"Failed to load stars, trying to generate randomly."); Free(); if (CGamePlay::UserAbortedLoad()) { CError::LogError(ERROR_CODE,"Loading of star map aborted by user."); return false; } CGamePlay::UpdateSplash("generating... "); if (!GenStars()) { CError::LogError(WARNING_CODE,"Failed to generate random stars."); Free(); return false; } } PrepData(); point_size=(float)(POINT_SIZE_AT_H600*((double)CWindow::GetHeight()/600.0)); twinkle=CVideoBase::GetOptStarTwinkle(); twinkle=false; //no twinkle effect yet InitGL(); if (!twinkle) { object = glGenLists(1); if (object==0) { CError::LogError(WARNING_CODE,"Unable to record star map display list - internal OpenGL error."); Free(); return false; } glNewList(object,GL_COMPILE); { DrawStars(); } glEndList(); } return true; } void CStarMap::Free() { if (glIsList(object)) glDeleteLists(object,1); if (stars) { free(stars); } Init(); } void CStarMap::Draw() { if (!twinkle) { glCallList(object); } else { DrawStars(); } } void CStarMap::Init() { object=0; twinkle=false; stars=NULL; num_stars=0; point_size=1.0f; } bool CStarMap::LoadStars() { //////////////// #define FreeLines() \ { \ for (int l=0;l<numlines;l++)\ free(textlines[l]); \ free(textlines); \ textlines=NULL; \ numlines=0; \ } //////////////// #define AbortParse() \ { \ FreeLines(); \ return false; \ } //////////////// #define VA_NUM 6 #define VA_FMT "%lf %lf | %f | %f %f %f" #define VA_ARGS \ &stars[i].Dec, \ &stars[i].RA, \ &stars[i].mag, \ &stars[i].color[0], \ &stars[i].color[1], \ &stars[i].color[2] ///////////////////// const char *eof_msg="Unable to load star data - unexpected end of file."; char **textlines=NULL; int numlines=0; int lineindex; int i; CLoader loader; if (!loader.WithResource(STARMAP_RESOURCE)) { CError::LogError(WARNING_CODE,"Unable to load star map file - missing or invalid resource."); return false; } if (!loader.LoadText(STARMAP_FILE,&textlines,&numlines)) { CError::LogError(WARNING_CODE,"Unable to load star map data - file missing from resource or internal loader subsystem error."); return false; } if (textlines==NULL) { CError::LogError(WARNING_CODE,"Unable to load star map - internal loader subsystem error."); return false; } if (numlines==0) { CError::LogError(WARNING_CODE,"Unable to load star map - empty data file."); return false; } { lineindex=-1; do { lineindex++; if (lineindex>=numlines) { CError::LogError(WARNING_CODE,eof_msg); AbortParse(); } } while (sscanf(textlines[lineindex],"%d",&num_stars)!=1 || textlines[lineindex][0]=='/'); stars=(stardata_s*)malloc(num_stars*sizeof(stardata_s)); if (!stars) { CError::LogError(WARNING_CODE,"Unable to load stars - memory allocation failed."); AbortParse(); } ZeroMemory(stars,num_stars*sizeof(stardata_s)); for (i=0;i<num_stars;i++) { do { lineindex++; if (lineindex>=numlines) { CError::LogError(WARNING_CODE,eof_msg); AbortParse(); } } while (sscanf(textlines[lineindex],VA_FMT,VA_ARGS)!=VA_NUM || textlines[lineindex][0]=='/'); } } FreeLines(); return true; } bool CStarMap::GenStars() { int i; num_stars=NUM_RANDOM_STARS; stars=(stardata_s*)malloc(num_stars*sizeof(stardata_s)); if (!stars) { CError::LogError(WARNING_CODE,"Unable to generate star data - memory allocation failed."); return false; } const float mi=MIN_INTENSITY; const float ri=(1.0f-MIN_INTENSITY); for (i=0;i<num_stars;i++) { double Z=((double)(rand()%(2*8192+1))/8192.0)-1.0; stars[i].Dec=asin(Z)*(180.0/M_PI); stars[i].RA=(double)(rand()%(360*64))/64.0; stars[i].mag=(float)(MIN_MAG+(double)(rand()%(int)((MAX_MAG-MIN_MAG)*1000.0+1.0))/1000.0); stars[i].color[0]=mi+(float)(rand()%256)*ri/255.0f; stars[i].color[1]=mi+(float)(rand()%256)*ri/255.0f; stars[i].color[2]=mi+(float)(rand()%256)*ri/255.0f; } return true; } void CStarMap::PrepColor() { int i,j; for (i=0;i<num_stars;i++) { stardata_s *star=&stars[i]; for (j=0;j<3;j++) { star->color[j]*=COLOR_SCALE; } } } void CStarMap::PrepData() { int i; for (i=0;i<num_stars;i++) { double theta=(90.0-stars[i].Dec)*(M_PI/180.0); double phi=stars[i].RA*(M_PI/180.0); double Ctheta=cos(theta); double Stheta=sin(theta); double Cphi=cos(phi); double Sphi=sin(phi); double size=STAR_SIZE(stars[i].mag); // size correction size*=AUTO_SIZE_COEF; stars[i].size=(float)size; stars[i].pos[0]=(float)(STAR_DIST(size)*Cphi*Stheta); stars[i].pos[1]=(float)(STAR_DIST(size)*Sphi*Stheta); stars[i].pos[2]=(float)(STAR_DIST(size)*Ctheta); } } void CStarMap::InitGL() { glPointSize(point_size); bool autosize=CVideoBase::GetExtPointParams(); if (autosize) { PFNGLPOINTPARAMETERFARBPROC glPointParameterfARB = NULL; PFNGLPOINTPARAMETERFVARBPROC glPointParameterfvARB = NULL; glPointParameterfARB=(PFNGLPOINTPARAMETERFARBPROC)wglGetProcAddress("glPointParameterfARB"); glPointParameterfvARB=(PFNGLPOINTPARAMETERFVARBPROC)wglGetProcAddress("glPointParameterfvARB"); if (glPointParameterfvARB!=NULL) { GLfloat DistAttenFactors[3] = {0.0f, 0.0f, (float)QUAD_ATTEN}; glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB,DistAttenFactors); } } } void CStarMap::DrawStars() { int i; int lastsize10=(int)(point_size*10.0f); bool autosize=CVideoBase::GetExtPointParams(); glPushAttrib(GL_ENABLE_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE); { glBegin(GL_POINTS); { for (i=0;i<num_stars;i++) { if (!autosize) { int size10=(int)(stars[i].size*10.0f); if (size10!=lastsize10) { glEnd(); glPointSize(stars[i].size*point_size); glBegin(GL_POINTS); lastsize10=size10; } } glColor3fv((GLfloat*)&stars[i].color); glVertex3fv((GLfloat*)&stars[i].pos); } } glEnd(); } glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glPopAttrib(); } <commit_msg>Shortcut: do not prepare to draw stars if they have not been initialized.<commit_after>/* * Copyright (C) 2003-2011 Victor Semionov * 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 holder nor the names of the 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 HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <windows.h> #include <gl/gl.h> #include <gl/glu.h> #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif #include <math.h> #include <gl/glext.h> #include "Settings.h" #include "Loader.h" #include "VideoBase.h" #include "Window.h" #include "Error.h" #include "GamePlay.h" #include "StarMap.h" //resource stuff #define STARMAP_RESOURCE CSettings::DataFile #define STARMAP_FILE "STARS.TXT" //sphere radius #define STARMAP_RADIUS 100.0 //num random stars #define NUM_RANDOM_STARS_BASE 8192 #define NUM_RANDOM_STARS ((int)((float)NUM_RANDOM_STARS_BASE*CVideoBase::GetOptGeoDetail())) //random star size and color #define MIN_INTENSITY 0.6f //also affects colorfulness of stars, when generated randomly #define MIN_MAG 4.75 #define MAX_MAG 7.9 //real-star color levels #define COLOR_SCALE 0.75f //magnitude-size conversion #define STAR_SIZE(star_mag) (0.75+(7.0-star_mag)/2.5) //point size macros #define POINT_SIZE_AT_H600 1.25 #define SQRT_QUAD_ATTEN_INV (STARMAP_RADIUS) #define QUAD_ATTEN_INV (SQRT_QUAD_ATTEN_INV*SQRT_QUAD_ATTEN_INV) #define QUAD_ATTEN (1.0/QUAD_ATTEN_INV) #define STAR_DIST(star_size) (CVideoBase::GetExtPointParams()? \ (SQRT_QUAD_ATTEN_INV/star_size): \ STARMAP_RADIUS) #define AUTO_SIZE_COEF 0.625 CStarMap::CStarMap() { Init(); } CStarMap::~CStarMap() { Free(); } bool CStarMap::Load() { Free(); if (LoadStars()) { PrepColor(); } else { CError::LogError(WARNING_CODE,"Failed to load stars, trying to generate randomly."); Free(); if (CGamePlay::UserAbortedLoad()) { CError::LogError(ERROR_CODE,"Loading of star map aborted by user."); return false; } CGamePlay::UpdateSplash("generating... "); if (!GenStars()) { CError::LogError(WARNING_CODE,"Failed to generate random stars."); Free(); return false; } } PrepData(); point_size=(float)(POINT_SIZE_AT_H600*((double)CWindow::GetHeight()/600.0)); twinkle=CVideoBase::GetOptStarTwinkle(); twinkle=false; //no twinkle effect yet InitGL(); if (!twinkle) { object = glGenLists(1); if (object==0) { CError::LogError(WARNING_CODE,"Unable to record star map display list - internal OpenGL error."); Free(); return false; } glNewList(object,GL_COMPILE); { DrawStars(); } glEndList(); } return true; } void CStarMap::Free() { if (glIsList(object)) glDeleteLists(object,1); if (stars) { free(stars); } Init(); } void CStarMap::Draw() { if (!num_stars) return; if (!twinkle) { glCallList(object); } else { DrawStars(); } } void CStarMap::Init() { object=0; twinkle=false; stars=NULL; num_stars=0; point_size=1.0f; } bool CStarMap::LoadStars() { //////////////// #define FreeLines() \ { \ for (int l=0;l<numlines;l++)\ free(textlines[l]); \ free(textlines); \ textlines=NULL; \ numlines=0; \ } //////////////// #define AbortParse() \ { \ FreeLines(); \ return false; \ } //////////////// #define VA_NUM 6 #define VA_FMT "%lf %lf | %f | %f %f %f" #define VA_ARGS \ &stars[i].Dec, \ &stars[i].RA, \ &stars[i].mag, \ &stars[i].color[0], \ &stars[i].color[1], \ &stars[i].color[2] ///////////////////// const char *eof_msg="Unable to load star data - unexpected end of file."; char **textlines=NULL; int numlines=0; int lineindex; int i; CLoader loader; if (!loader.WithResource(STARMAP_RESOURCE)) { CError::LogError(WARNING_CODE,"Unable to load star map file - missing or invalid resource."); return false; } if (!loader.LoadText(STARMAP_FILE,&textlines,&numlines)) { CError::LogError(WARNING_CODE,"Unable to load star map data - file missing from resource or internal loader subsystem error."); return false; } if (textlines==NULL) { CError::LogError(WARNING_CODE,"Unable to load star map - internal loader subsystem error."); return false; } if (numlines==0) { CError::LogError(WARNING_CODE,"Unable to load star map - empty data file."); return false; } { lineindex=-1; do { lineindex++; if (lineindex>=numlines) { CError::LogError(WARNING_CODE,eof_msg); AbortParse(); } } while (sscanf(textlines[lineindex],"%d",&num_stars)!=1 || textlines[lineindex][0]=='/'); stars=(stardata_s*)malloc(num_stars*sizeof(stardata_s)); if (!stars) { CError::LogError(WARNING_CODE,"Unable to load stars - memory allocation failed."); AbortParse(); } ZeroMemory(stars,num_stars*sizeof(stardata_s)); for (i=0;i<num_stars;i++) { do { lineindex++; if (lineindex>=numlines) { CError::LogError(WARNING_CODE,eof_msg); AbortParse(); } } while (sscanf(textlines[lineindex],VA_FMT,VA_ARGS)!=VA_NUM || textlines[lineindex][0]=='/'); } } FreeLines(); return true; } bool CStarMap::GenStars() { int i; num_stars=NUM_RANDOM_STARS; stars=(stardata_s*)malloc(num_stars*sizeof(stardata_s)); if (!stars) { CError::LogError(WARNING_CODE,"Unable to generate star data - memory allocation failed."); return false; } const float mi=MIN_INTENSITY; const float ri=(1.0f-MIN_INTENSITY); for (i=0;i<num_stars;i++) { double Z=((double)(rand()%(2*8192+1))/8192.0)-1.0; stars[i].Dec=asin(Z)*(180.0/M_PI); stars[i].RA=(double)(rand()%(360*64))/64.0; stars[i].mag=(float)(MIN_MAG+(double)(rand()%(int)((MAX_MAG-MIN_MAG)*1000.0+1.0))/1000.0); stars[i].color[0]=mi+(float)(rand()%256)*ri/255.0f; stars[i].color[1]=mi+(float)(rand()%256)*ri/255.0f; stars[i].color[2]=mi+(float)(rand()%256)*ri/255.0f; } return true; } void CStarMap::PrepColor() { int i,j; for (i=0;i<num_stars;i++) { stardata_s *star=&stars[i]; for (j=0;j<3;j++) { star->color[j]*=COLOR_SCALE; } } } void CStarMap::PrepData() { int i; for (i=0;i<num_stars;i++) { double theta=(90.0-stars[i].Dec)*(M_PI/180.0); double phi=stars[i].RA*(M_PI/180.0); double Ctheta=cos(theta); double Stheta=sin(theta); double Cphi=cos(phi); double Sphi=sin(phi); double size=STAR_SIZE(stars[i].mag); // size correction size*=AUTO_SIZE_COEF; stars[i].size=(float)size; stars[i].pos[0]=(float)(STAR_DIST(size)*Cphi*Stheta); stars[i].pos[1]=(float)(STAR_DIST(size)*Sphi*Stheta); stars[i].pos[2]=(float)(STAR_DIST(size)*Ctheta); } } void CStarMap::InitGL() { glPointSize(point_size); bool autosize=CVideoBase::GetExtPointParams(); if (autosize) { PFNGLPOINTPARAMETERFARBPROC glPointParameterfARB = NULL; PFNGLPOINTPARAMETERFVARBPROC glPointParameterfvARB = NULL; glPointParameterfARB=(PFNGLPOINTPARAMETERFARBPROC)wglGetProcAddress("glPointParameterfARB"); glPointParameterfvARB=(PFNGLPOINTPARAMETERFVARBPROC)wglGetProcAddress("glPointParameterfvARB"); if (glPointParameterfvARB!=NULL) { GLfloat DistAttenFactors[3] = {0.0f, 0.0f, (float)QUAD_ATTEN}; glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB,DistAttenFactors); } } } void CStarMap::DrawStars() { int i; int lastsize10=(int)(point_size*10.0f); bool autosize=CVideoBase::GetExtPointParams(); glPushAttrib(GL_ENABLE_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE); { glBegin(GL_POINTS); { for (i=0;i<num_stars;i++) { if (!autosize) { int size10=(int)(stars[i].size*10.0f); if (size10!=lastsize10) { glEnd(); glPointSize(stars[i].size*point_size); glBegin(GL_POINTS); lastsize10=size10; } } glColor3fv((GLfloat*)&stars[i].color); glVertex3fv((GLfloat*)&stars[i].pos); } } glEnd(); } glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glPopAttrib(); } <|endoftext|>
<commit_before>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2015 Liviu Ionescu. * * µOS++ is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 3. * * µOS++ 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 program. If not, see <http://www.gnu.org/licenses/>. */ #if defined(__ARM_EABI__) #include "posix-io/types.h" // ---------------------------------------------------------------------------- extern "C" { // Many newlib functions call the reentrant versions right away, // and these call the _name() implementations. To avoid this, the // shortcut is to simply skip the reentrant code (ignore the pointer) // and directly call the posix implementation. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-declarations" #pragma GCC diagnostic ignored "-Wunused-parameter" int __attribute__((weak)) _close_r (void* ptr, int fildes) { return __posix_close (fildes); } int __attribute__((weak)) _execve_r (void* ptr, const char* path, char* const argv[], char* const envp[]) { return __posix_execve (path, argv, envp); } int __attribute__((weak)) _fcntl_r (void* ptr, int fildes, int cmd, int arg) { return __posix_fcntl (fildes, cmd, arg); } pid_t __attribute__((weak)) _fork_r (void* ptr) { return __posix_fork (); } int __attribute__((weak)) _fstat_r (void* ptr, int fildes, struct stat* buf) { return __posix_fstat (fildes, buf); } int __attribute__((weak)) _gettimeofday_r (void* ptr, struct timeval* ptimeval, void* ptimezone) { return __posix_gettimeofday (ptimeval, ptimezone); } int __attribute__((weak)) _isatty_r (void* ptr, int fildes) { return __posix_isatty (fildes); } int __attribute__((weak)) _kill_r (void* ptr, pid_t pid, int sig) { return __posix_kill (pid, sig); } int __attribute__((weak)) _link_r (void* ptr, const char* existing, const char* _new) { return __posix_link (existing, _new); } off_t __attribute__((weak)) _lseek_r (void* ptr, int fildes, off_t offset, int whence) { return __posix_lseek (fildes, offset, whence); } int __attribute__((weak)) _mkdir_r (void* ptr, const char* path, mode_t mode) { return __posix_mkdir (path, mode); } int __attribute__((weak)) _open_r (void* ptr, const char* path, int oflag, int mode) { return __posix_open (path, oflag, mode); } ssize_t __attribute__((weak)) _read_r (void* ptr, int fildes, void* buf, size_t nbyte) { return __posix_read (fildes, buf, nbyte); } int __attribute__((weak)) _rename_r (void* ptr, const char* oldfn, const char* newfn) { return __posix_rename (oldfn, newfn); } int __attribute__((weak)) _stat_r (void* ptr, const char* path, struct stat* buf) { return __posix_stat (path, buf); } clock_t __attribute__((weak)) _times_r (void* ptr, struct tms* buf) { return __posix_times (buf); } int __attribute__((weak)) _unlink_r (void* ptr, const char* name) { return __posix_unlink (name); } pid_t __attribute__((weak)) _wait_r (void* ptr, int* stat_loc) { return __posix_wait (stat_loc); } ssize_t __attribute__((weak)) _write_r (void* ptr, int fildes, const void* buf, size_t nbyte) { return __posix_write (fildes, buf, nbyte); } // -------------------------------------------------------------------------- void* _sbrk (ptrdiff_t incr); void* __attribute__((weak)) sbrk (ptrdiff_t incr) { return _sbrk (incr); } void* __attribute__((weak)) _sbrk_r (void* ptr, ptrdiff_t incr) { return _sbrk (incr); } #pragma GCC diagnostic pop } #endif /* defined(__ARM_EABI__) */ // ---------------------------------------------------------------------------- <commit_msg>newlib-reent.cpp: add _getpid_r()<commit_after>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2015 Liviu Ionescu. * * µOS++ is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 3. * * µOS++ 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 program. If not, see <http://www.gnu.org/licenses/>. */ #if defined(__ARM_EABI__) #include "posix-io/types.h" // ---------------------------------------------------------------------------- extern "C" { // Many newlib functions call the reentrant versions right away, // and these call the _name() implementations. To avoid this, the // shortcut is to simply skip the reentrant code (ignore the pointer) // and directly call the posix implementation. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmissing-declarations" #pragma GCC diagnostic ignored "-Wunused-parameter" int __attribute__((weak)) _close_r (void* ptr, int fildes) { return __posix_close (fildes); } int __attribute__((weak)) _execve_r (void* ptr, const char* path, char* const argv[], char* const envp[]) { return __posix_execve (path, argv, envp); } int __attribute__((weak)) _fcntl_r (void* ptr, int fildes, int cmd, int arg) { return __posix_fcntl (fildes, cmd, arg); } pid_t __attribute__((weak)) _fork_r (void* ptr) { return __posix_fork (); } int __attribute__((weak)) _fstat_r (void* ptr, int fildes, struct stat* buf) { return __posix_fstat (fildes, buf); } pid_t __attribute__((weak)) _getpid_r (void* ptr) { return __posix_getpid (); } int __attribute__((weak)) _gettimeofday_r (void* ptr, struct timeval* ptimeval, void* ptimezone) { return __posix_gettimeofday (ptimeval, ptimezone); } int __attribute__((weak)) _isatty_r (void* ptr, int fildes) { return __posix_isatty (fildes); } int __attribute__((weak)) _kill_r (void* ptr, pid_t pid, int sig) { return __posix_kill (pid, sig); } int __attribute__((weak)) _link_r (void* ptr, const char* existing, const char* _new) { return __posix_link (existing, _new); } off_t __attribute__((weak)) _lseek_r (void* ptr, int fildes, off_t offset, int whence) { return __posix_lseek (fildes, offset, whence); } int __attribute__((weak)) _mkdir_r (void* ptr, const char* path, mode_t mode) { return __posix_mkdir (path, mode); } int __attribute__((weak)) _open_r (void* ptr, const char* path, int oflag, int mode) { return __posix_open (path, oflag, mode); } ssize_t __attribute__((weak)) _read_r (void* ptr, int fildes, void* buf, size_t nbyte) { return __posix_read (fildes, buf, nbyte); } int __attribute__((weak)) _rename_r (void* ptr, const char* oldfn, const char* newfn) { return __posix_rename (oldfn, newfn); } int __attribute__((weak)) _stat_r (void* ptr, const char* path, struct stat* buf) { return __posix_stat (path, buf); } clock_t __attribute__((weak)) _times_r (void* ptr, struct tms* buf) { return __posix_times (buf); } int __attribute__((weak)) _unlink_r (void* ptr, const char* name) { return __posix_unlink (name); } pid_t __attribute__((weak)) _wait_r (void* ptr, int* stat_loc) { return __posix_wait (stat_loc); } ssize_t __attribute__((weak)) _write_r (void* ptr, int fildes, const void* buf, size_t nbyte) { return __posix_write (fildes, buf, nbyte); } // -------------------------------------------------------------------------- void* _sbrk (ptrdiff_t incr); void* __attribute__((weak)) sbrk (ptrdiff_t incr) { return _sbrk (incr); } void* __attribute__((weak)) _sbrk_r (void* ptr, ptrdiff_t incr) { return _sbrk (incr); } #pragma GCC diagnostic pop } #endif /* defined(__ARM_EABI__) */ // ---------------------------------------------------------------------------- <|endoftext|>
<commit_before>// Copyright 2014 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/net/http_transport.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <memory> #include <utility> #include <vector> #include "base/files/file_path.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "gtest/gtest.h" #include "test/multiprocess_exec.h" #include "test/test_paths.h" #include "util/file/file_io.h" #include "util/misc/random_string.h" #include "util/net/http_body.h" #include "util/net/http_headers.h" #include "util/net/http_multipart_builder.h" namespace crashpad { namespace test { namespace { #if defined(OS_WIN) std::string ToUTF8IfWin(const base::string16& x) { return base::UTF16ToUTF8(x); } #else std::string ToUTF8IfWin(const std::string& x) { return x; } #endif class HTTPTransportTestFixture : public MultiprocessExec { public: using RequestValidator = void(*)(HTTPTransportTestFixture*, const std::string&); HTTPTransportTestFixture(const base::FilePath::StringType& scheme, const HTTPHeaders& headers, std::unique_ptr<HTTPBodyStream> body_stream, uint16_t http_response_code, RequestValidator request_validator) : MultiprocessExec(), headers_(headers), body_stream_(std::move(body_stream)), response_code_(http_response_code), request_validator_(request_validator), cert_(), scheme_and_host_() { base::FilePath server_path = TestPaths::Executable().DirName().Append( FILE_PATH_LITERAL("http_transport_test_server") #if defined(OS_WIN) FILE_PATH_LITERAL(".exe") #endif ); if (ToUTF8IfWin(scheme) == "http") { scheme_and_host_ = "http://localhost"; SetChildCommand(server_path, nullptr); } else { std::vector<std::string> args; cert_ = TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("util/net/testdata/crashpad_util_test_cert.pem")); args.push_back(ToUTF8IfWin(cert_.value())); args.emplace_back( ToUTF8IfWin(TestPaths::TestDataRoot() .Append(FILE_PATH_LITERAL( "util/net/testdata/crashpad_util_test_key.pem")) .value())); SetChildCommand(server_path, &args); scheme_and_host_ = "https://localhost"; } } const HTTPHeaders& headers() { return headers_; } private: void MultiprocessParent() override { // Use Logging*File() instead of Checked*File() so that the test can fail // gracefully with a gtest assertion if the child does not execute properly. // The child will write the HTTP server port number as a packed unsigned // short to stdout. uint16_t port; ASSERT_TRUE(LoggingReadFileExactly(ReadPipeHandle(), &port, sizeof(port))); // Then the parent will tell the web server what response code to send // for the HTTP request. ASSERT_TRUE(LoggingWriteFile( WritePipeHandle(), &response_code_, sizeof(response_code_))); // The parent will also tell the web server what response body to send back. // The web server will only send the response body if the response code is // 200. const std::string random_string = RandomString(); ASSERT_TRUE(LoggingWriteFile(WritePipeHandle(), random_string.c_str(), random_string.size())); // Now execute the HTTP request. std::unique_ptr<HTTPTransport> transport(HTTPTransport::Create()); transport->SetMethod("POST"); if (!cert_.empty()) { transport->SetRootCACertificatePath(cert_); } transport->SetURL( base::StringPrintf("%s:%d/upload", scheme_and_host_.c_str(), port)); for (const auto& pair : headers_) { transport->SetHeader(pair.first, pair.second); } transport->SetBodyStream(std::move(body_stream_)); std::string response_body; bool success = transport->ExecuteSynchronously(&response_body); if (response_code_ >= 200 && response_code_ <= 203) { EXPECT_TRUE(success); std::string expect_response_body = random_string + "\r\n"; EXPECT_EQ(response_body, expect_response_body); } else { EXPECT_FALSE(success); EXPECT_TRUE(response_body.empty()); } // Read until the child's stdout closes. std::string request; char buf[32]; FileOperationResult bytes_read; while ((bytes_read = ReadFile(ReadPipeHandle(), buf, sizeof(buf))) != 0) { ASSERT_GE(bytes_read, 0); request.append(buf, bytes_read); } if (request_validator_) request_validator_(this, request); } HTTPHeaders headers_; std::unique_ptr<HTTPBodyStream> body_stream_; uint16_t response_code_; RequestValidator request_validator_; base::FilePath cert_; std::string scheme_and_host_; }; constexpr char kMultipartFormData[] = "multipart/form-data"; void GetHeaderField(const std::string& request, const std::string& header, std::string* value) { size_t index = request.find(header); ASSERT_NE(index, std::string::npos); // Since the header is never the first line of the request, it should always // be preceded by a CRLF. EXPECT_EQ(request[index - 1], '\n'); EXPECT_EQ(request[index - 2], '\r'); index += header.length(); EXPECT_EQ(request[index++], ':'); // Per RFC 7230 §3.2, there can be one or more spaces or horizontal tabs. // For testing purposes, just assume one space. EXPECT_EQ(request[index++], ' '); size_t header_end = request.find('\r', index); ASSERT_NE(header_end, std::string::npos); *value = request.substr(index, header_end - index); } void GetMultipartBoundary(const std::string& request, std::string* multipart_boundary) { std::string content_type; GetHeaderField(request, kContentType, &content_type); ASSERT_GE(content_type.length(), strlen(kMultipartFormData)); size_t index = strlen(kMultipartFormData); EXPECT_EQ(content_type.substr(0, index), kMultipartFormData); EXPECT_EQ(content_type[index++], ';'); size_t boundary_begin = content_type.find('=', index); ASSERT_NE(boundary_begin, std::string::npos); EXPECT_EQ(content_type[boundary_begin++], '='); if (multipart_boundary) { *multipart_boundary = content_type.substr(boundary_begin); } } constexpr char kBoundaryEq[] = "boundary="; void ValidFormData(HTTPTransportTestFixture* fixture, const std::string& request) { std::string actual_boundary; GetMultipartBoundary(request, &actual_boundary); const auto& content_type = fixture->headers().find(kContentType); ASSERT_NE(content_type, fixture->headers().end()); size_t boundary = content_type->second.find(kBoundaryEq); ASSERT_NE(boundary, std::string::npos); std::string expected_boundary = content_type->second.substr(boundary + strlen(kBoundaryEq)); EXPECT_EQ(actual_boundary, expected_boundary); size_t body_start = request.find("\r\n\r\n"); ASSERT_NE(body_start, std::string::npos); body_start += 4; std::string expected = "--" + expected_boundary + "\r\n"; expected += "Content-Disposition: form-data; name=\"key1\"\r\n\r\n"; expected += "test\r\n"; ASSERT_LT(body_start + expected.length(), request.length()); EXPECT_EQ(request.substr(body_start, expected.length()), expected); body_start += expected.length(); expected = "--" + expected_boundary + "\r\n"; expected += "Content-Disposition: form-data; name=\"key2\"\r\n\r\n"; expected += "--abcdefg123\r\n"; expected += "--" + expected_boundary + "--\r\n"; ASSERT_EQ(request.length(), body_start + expected.length()); EXPECT_EQ(request.substr(body_start), expected); } class HTTPTransport : public testing::TestWithParam<base::FilePath::StringType> {}; TEST_P(HTTPTransport, ValidFormData) { HTTPMultipartBuilder builder; builder.SetFormData("key1", "test"); builder.SetFormData("key2", "--abcdefg123"); HTTPHeaders headers; builder.PopulateContentHeaders(&headers); HTTPTransportTestFixture test(GetParam(), headers, builder.GetBodyStream(), 200, &ValidFormData); test.Run(); } TEST_P(HTTPTransport, ValidFormData_Gzip) { HTTPMultipartBuilder builder; builder.SetGzipEnabled(true); builder.SetFormData("key1", "test"); builder.SetFormData("key2", "--abcdefg123"); HTTPHeaders headers; builder.PopulateContentHeaders(&headers); HTTPTransportTestFixture test( GetParam(), headers, builder.GetBodyStream(), 200, &ValidFormData); test.Run(); } constexpr char kTextPlain[] = "text/plain"; void ErrorResponse(HTTPTransportTestFixture* fixture, const std::string& request) { std::string content_type; GetHeaderField(request, kContentType, &content_type); EXPECT_EQ(content_type, kTextPlain); } TEST_P(HTTPTransport, ErrorResponse) { HTTPMultipartBuilder builder; HTTPHeaders headers; headers[kContentType] = kTextPlain; HTTPTransportTestFixture test(GetParam(), headers, builder.GetBodyStream(), 404, &ErrorResponse); test.Run(); } constexpr char kTextBody[] = "hello world"; void UnchunkedPlainText(HTTPTransportTestFixture* fixture, const std::string& request) { std::string header_value; GetHeaderField(request, kContentType, &header_value); EXPECT_EQ(header_value, kTextPlain); GetHeaderField(request, kContentLength, &header_value); const auto& content_length = fixture->headers().find(kContentLength); ASSERT_NE(content_length, fixture->headers().end()); EXPECT_EQ(header_value, content_length->second); size_t body_start = request.rfind("\r\n"); ASSERT_NE(body_start, std::string::npos); EXPECT_EQ(request.substr(body_start + 2), kTextBody); } TEST_P(HTTPTransport, UnchunkedPlainText) { std::unique_ptr<HTTPBodyStream> body_stream( new StringHTTPBodyStream(kTextBody)); HTTPHeaders headers; headers[kContentType] = kTextPlain; headers[kContentLength] = base::StringPrintf("%" PRIuS, strlen(kTextBody)); HTTPTransportTestFixture test(GetParam(), headers, std::move(body_stream), 200, &UnchunkedPlainText); test.Run(); } void RunUpload33k(const base::FilePath::StringType& scheme, bool has_content_length) { // On macOS, NSMutableURLRequest winds up calling into a CFReadStream’s Read() // callback with a 32kB buffer. Make sure that it’s able to get everything // when enough is available to fill this buffer, requiring more than one // Read(). std::string request_string(33 * 1024, 'a'); std::unique_ptr<HTTPBodyStream> body_stream( new StringHTTPBodyStream(request_string)); HTTPHeaders headers; headers[kContentType] = "application/octet-stream"; if (has_content_length) { headers[kContentLength] = base::StringPrintf("%" PRIuS, request_string.size()); } HTTPTransportTestFixture test( scheme, headers, std::move(body_stream), 200, [](HTTPTransportTestFixture* fixture, const std::string& request) { size_t body_start = request.rfind("\r\n"); EXPECT_EQ(request.size() - body_start, 33 * 1024u + 2); }); test.Run(); } TEST_P(HTTPTransport, Upload33k) { RunUpload33k(GetParam(), true); } TEST_P(HTTPTransport, Upload33k_LengthUnknown) { // The same as Upload33k, but without declaring Content-Length ahead of time. RunUpload33k(GetParam(), false); } // This should be on for Fuchsia, but DX-382. Debug and re-enabled. #if defined(CRASHPAD_USE_BORINGSSL) && !defined(OS_FUCHSIA) // The test server requires BoringSSL or OpenSSL, so https in tests can only be // enabled where that's readily available. Additionally on Linux, the bots fail // lacking libcrypto.so.1.1, so disabled there for now. On Mac, they could also // likely be enabled relatively easily, if HTTPTransportMac learned to respect // the user-supplied cert. // // If tests with boringssl are failing because of expired certificates, try // re-running generate_test_server_key.py. INSTANTIATE_TEST_SUITE_P(HTTPTransport, HTTPTransport, testing::Values(FILE_PATH_LITERAL("http"), FILE_PATH_LITERAL("https"))); #else INSTANTIATE_TEST_SUITE_P(HTTPTransport, HTTPTransport, testing::Values(FILE_PATH_LITERAL("http"))); #endif } // namespace } // namespace test } // namespace crashpad <commit_msg>[net] specify parameter name in parameterized test suite<commit_after>// Copyright 2014 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/net/http_transport.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <memory> #include <utility> #include <vector> #include "base/files/file_path.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "gtest/gtest.h" #include "test/multiprocess_exec.h" #include "test/test_paths.h" #include "util/file/file_io.h" #include "util/misc/random_string.h" #include "util/net/http_body.h" #include "util/net/http_headers.h" #include "util/net/http_multipart_builder.h" namespace crashpad { namespace test { namespace { #if defined(OS_WIN) std::string ToUTF8IfWin(const base::string16& x) { return base::UTF16ToUTF8(x); } #else std::string ToUTF8IfWin(const std::string& x) { return x; } #endif class HTTPTransportTestFixture : public MultiprocessExec { public: using RequestValidator = void (*)(HTTPTransportTestFixture*, const std::string&); HTTPTransportTestFixture(const std::string& scheme, const HTTPHeaders& headers, std::unique_ptr<HTTPBodyStream> body_stream, uint16_t http_response_code, RequestValidator request_validator) : MultiprocessExec(), headers_(headers), body_stream_(std::move(body_stream)), response_code_(http_response_code), request_validator_(request_validator), cert_(), scheme_and_host_() { base::FilePath server_path = TestPaths::Executable().DirName().Append( FILE_PATH_LITERAL("http_transport_test_server") #if defined(OS_WIN) FILE_PATH_LITERAL(".exe") #endif ); if (scheme == "http") { scheme_and_host_ = "http://localhost"; SetChildCommand(server_path, nullptr); } else { std::vector<std::string> args; cert_ = TestPaths::TestDataRoot().Append( FILE_PATH_LITERAL("util/net/testdata/crashpad_util_test_cert.pem")); args.push_back(ToUTF8IfWin(cert_.value())); args.emplace_back( ToUTF8IfWin(TestPaths::TestDataRoot() .Append(FILE_PATH_LITERAL( "util/net/testdata/crashpad_util_test_key.pem")) .value())); SetChildCommand(server_path, &args); scheme_and_host_ = "https://localhost"; } } const HTTPHeaders& headers() { return headers_; } private: void MultiprocessParent() override { // Use Logging*File() instead of Checked*File() so that the test can fail // gracefully with a gtest assertion if the child does not execute properly. // The child will write the HTTP server port number as a packed unsigned // short to stdout. uint16_t port; ASSERT_TRUE(LoggingReadFileExactly(ReadPipeHandle(), &port, sizeof(port))); // Then the parent will tell the web server what response code to send // for the HTTP request. ASSERT_TRUE(LoggingWriteFile( WritePipeHandle(), &response_code_, sizeof(response_code_))); // The parent will also tell the web server what response body to send back. // The web server will only send the response body if the response code is // 200. const std::string random_string = RandomString(); ASSERT_TRUE(LoggingWriteFile( WritePipeHandle(), random_string.c_str(), random_string.size())); // Now execute the HTTP request. std::unique_ptr<HTTPTransport> transport(HTTPTransport::Create()); transport->SetMethod("POST"); if (!cert_.empty()) { transport->SetRootCACertificatePath(cert_); } transport->SetURL( base::StringPrintf("%s:%d/upload", scheme_and_host_.c_str(), port)); for (const auto& pair : headers_) { transport->SetHeader(pair.first, pair.second); } transport->SetBodyStream(std::move(body_stream_)); std::string response_body; bool success = transport->ExecuteSynchronously(&response_body); if (response_code_ >= 200 && response_code_ <= 203) { EXPECT_TRUE(success); std::string expect_response_body = random_string + "\r\n"; EXPECT_EQ(response_body, expect_response_body); } else { EXPECT_FALSE(success); EXPECT_TRUE(response_body.empty()); } // Read until the child's stdout closes. std::string request; char buf[32]; FileOperationResult bytes_read; while ((bytes_read = ReadFile(ReadPipeHandle(), buf, sizeof(buf))) != 0) { ASSERT_GE(bytes_read, 0); request.append(buf, bytes_read); } if (request_validator_) request_validator_(this, request); } HTTPHeaders headers_; std::unique_ptr<HTTPBodyStream> body_stream_; uint16_t response_code_; RequestValidator request_validator_; base::FilePath cert_; std::string scheme_and_host_; }; constexpr char kMultipartFormData[] = "multipart/form-data"; void GetHeaderField(const std::string& request, const std::string& header, std::string* value) { size_t index = request.find(header); ASSERT_NE(index, std::string::npos); // Since the header is never the first line of the request, it should always // be preceded by a CRLF. EXPECT_EQ(request[index - 1], '\n'); EXPECT_EQ(request[index - 2], '\r'); index += header.length(); EXPECT_EQ(request[index++], ':'); // Per RFC 7230 §3.2, there can be one or more spaces or horizontal tabs. // For testing purposes, just assume one space. EXPECT_EQ(request[index++], ' '); size_t header_end = request.find('\r', index); ASSERT_NE(header_end, std::string::npos); *value = request.substr(index, header_end - index); } void GetMultipartBoundary(const std::string& request, std::string* multipart_boundary) { std::string content_type; GetHeaderField(request, kContentType, &content_type); ASSERT_GE(content_type.length(), strlen(kMultipartFormData)); size_t index = strlen(kMultipartFormData); EXPECT_EQ(content_type.substr(0, index), kMultipartFormData); EXPECT_EQ(content_type[index++], ';'); size_t boundary_begin = content_type.find('=', index); ASSERT_NE(boundary_begin, std::string::npos); EXPECT_EQ(content_type[boundary_begin++], '='); if (multipart_boundary) { *multipart_boundary = content_type.substr(boundary_begin); } } constexpr char kBoundaryEq[] = "boundary="; void ValidFormData(HTTPTransportTestFixture* fixture, const std::string& request) { std::string actual_boundary; GetMultipartBoundary(request, &actual_boundary); const auto& content_type = fixture->headers().find(kContentType); ASSERT_NE(content_type, fixture->headers().end()); size_t boundary = content_type->second.find(kBoundaryEq); ASSERT_NE(boundary, std::string::npos); std::string expected_boundary = content_type->second.substr(boundary + strlen(kBoundaryEq)); EXPECT_EQ(actual_boundary, expected_boundary); size_t body_start = request.find("\r\n\r\n"); ASSERT_NE(body_start, std::string::npos); body_start += 4; std::string expected = "--" + expected_boundary + "\r\n"; expected += "Content-Disposition: form-data; name=\"key1\"\r\n\r\n"; expected += "test\r\n"; ASSERT_LT(body_start + expected.length(), request.length()); EXPECT_EQ(request.substr(body_start, expected.length()), expected); body_start += expected.length(); expected = "--" + expected_boundary + "\r\n"; expected += "Content-Disposition: form-data; name=\"key2\"\r\n\r\n"; expected += "--abcdefg123\r\n"; expected += "--" + expected_boundary + "--\r\n"; ASSERT_EQ(request.length(), body_start + expected.length()); EXPECT_EQ(request.substr(body_start), expected); } class HTTPTransport : public testing::TestWithParam<std::string> {}; TEST_P(HTTPTransport, ValidFormData) { HTTPMultipartBuilder builder; builder.SetFormData("key1", "test"); builder.SetFormData("key2", "--abcdefg123"); HTTPHeaders headers; builder.PopulateContentHeaders(&headers); HTTPTransportTestFixture test( GetParam(), headers, builder.GetBodyStream(), 200, &ValidFormData); test.Run(); } TEST_P(HTTPTransport, ValidFormData_Gzip) { HTTPMultipartBuilder builder; builder.SetGzipEnabled(true); builder.SetFormData("key1", "test"); builder.SetFormData("key2", "--abcdefg123"); HTTPHeaders headers; builder.PopulateContentHeaders(&headers); HTTPTransportTestFixture test( GetParam(), headers, builder.GetBodyStream(), 200, &ValidFormData); test.Run(); } constexpr char kTextPlain[] = "text/plain"; void ErrorResponse(HTTPTransportTestFixture* fixture, const std::string& request) { std::string content_type; GetHeaderField(request, kContentType, &content_type); EXPECT_EQ(content_type, kTextPlain); } TEST_P(HTTPTransport, ErrorResponse) { HTTPMultipartBuilder builder; HTTPHeaders headers; headers[kContentType] = kTextPlain; HTTPTransportTestFixture test( GetParam(), headers, builder.GetBodyStream(), 404, &ErrorResponse); test.Run(); } constexpr char kTextBody[] = "hello world"; void UnchunkedPlainText(HTTPTransportTestFixture* fixture, const std::string& request) { std::string header_value; GetHeaderField(request, kContentType, &header_value); EXPECT_EQ(header_value, kTextPlain); GetHeaderField(request, kContentLength, &header_value); const auto& content_length = fixture->headers().find(kContentLength); ASSERT_NE(content_length, fixture->headers().end()); EXPECT_EQ(header_value, content_length->second); size_t body_start = request.rfind("\r\n"); ASSERT_NE(body_start, std::string::npos); EXPECT_EQ(request.substr(body_start + 2), kTextBody); } TEST_P(HTTPTransport, UnchunkedPlainText) { std::unique_ptr<HTTPBodyStream> body_stream( new StringHTTPBodyStream(kTextBody)); HTTPHeaders headers; headers[kContentType] = kTextPlain; headers[kContentLength] = base::StringPrintf("%" PRIuS, strlen(kTextBody)); HTTPTransportTestFixture test( GetParam(), headers, std::move(body_stream), 200, &UnchunkedPlainText); test.Run(); } void RunUpload33k(const std::string& scheme, bool has_content_length) { // On macOS, NSMutableURLRequest winds up calling into a CFReadStream’s Read() // callback with a 32kB buffer. Make sure that it’s able to get everything // when enough is available to fill this buffer, requiring more than one // Read(). std::string request_string(33 * 1024, 'a'); std::unique_ptr<HTTPBodyStream> body_stream( new StringHTTPBodyStream(request_string)); HTTPHeaders headers; headers[kContentType] = "application/octet-stream"; if (has_content_length) { headers[kContentLength] = base::StringPrintf("%" PRIuS, request_string.size()); } HTTPTransportTestFixture test( scheme, headers, std::move(body_stream), 200, [](HTTPTransportTestFixture* fixture, const std::string& request) { size_t body_start = request.rfind("\r\n"); EXPECT_EQ(request.size() - body_start, 33 * 1024u + 2); }); test.Run(); } TEST_P(HTTPTransport, Upload33k) { RunUpload33k(GetParam(), true); } TEST_P(HTTPTransport, Upload33k_LengthUnknown) { // The same as Upload33k, but without declaring Content-Length ahead of time. RunUpload33k(GetParam(), false); } // This should be on for Fuchsia, but DX-382. Debug and re-enabled. #if defined(CRASHPAD_USE_BORINGSSL) && !defined(OS_FUCHSIA) // The test server requires BoringSSL or OpenSSL, so https in tests can only be // enabled where that's readily available. Additionally on Linux, the bots fail // lacking libcrypto.so.1.1, so disabled there for now. On Mac, they could also // likely be enabled relatively easily, if HTTPTransportMac learned to respect // the user-supplied cert. // // If tests with boringssl are failing because of expired certificates, try // re-running generate_test_server_key.py. INSTANTIATE_TEST_SUITE_P(HTTPTransport, HTTPTransport, testing::Values("http", "https"), [](const testing::TestParamInfo<std::string>& info) { return info.param; }); #else INSTANTIATE_TEST_SUITE_P(HTTPTransport, HTTPTransport, testing::Values("http"), [](const testing::TestParamInfo<std::string>& info) { return info.param; }); #endif } // namespace } // namespace test } // namespace crashpad <|endoftext|>
<commit_before>/* * TMC2130.cpp * * Created on: 03 nov 2019 * Author: Tim Evers */ #include "TMC2130.h" #if defined(FARMDUINO_EXP_V20) || defined(FARMDUINO_V30) || defined(FARMDUINO_V32) void loadTMC2130ParametersMotor(TMC2130_Basics *tb, int microsteps, int current, int sensitivity, bool stealth) { uint32_t data = 0; uint32_t value = 0; tb->init(); // Set the micro steps switch (microsteps) { case 1: data = 8; break; case 2: data = 7; break; case 4: data = 6; break; case 8: data = 5; break; case 16: data = 4; break; case 32: data = 3; break; case 64: data = 2; break; case 128: data = 1; break; } tb->set_CHOPCONF(FB_TMC_CHOPCONF_MRES, data); // Set the current uint16_t mA = current; float multiplier = 0.5; float RS = 0.11; uint8_t CS = 32.0*1.41421*mA / 1000.0*(RS + 0.02) / 0.325 - 1; if (CS < 16) { CS = 32.0*1.41421*mA / 1000.0*(RS + 0.02) / 0.180 - 1; } data = ((uint32_t(CS)&FB_TMC_IHOLD_MASK) << FB_TMC_IHOLD); data |= ((uint32_t(CS)&FB_TMC_IRUN_MASK) << FB_TMC_IRUN); data |= ((uint32_t(16)&FB_TMC_IHOLDDELAY_MASK) << FB_TMC_IHOLDDELAY); tb->write_REG(FB_TMC_REG_IHOLD_IRUN, data); // Chop and cool conf if (!stealth) { tb->set_GCONF(FB_TMC_GCONF_I_SCALE_ANALOG, 1); tb->set_CHOPCONF(FB_TMC_CHOPCONF_TOFF, 3); tb->set_CHOPCONF(FB_TMC_CHOPCONF_HSTRT, 4); tb->set_CHOPCONF(FB_TMC_CHOPCONF_HEND, 1); tb->set_CHOPCONF(FB_TMC_CHOPCONF_TBL, 2); tb->set_CHOPCONF(FB_TMC_CHOPCONF_CHM, 0); tb->set_CHOPCONF(FB_TMC_COOLCONF_SEMIN, 1); tb->set_CHOPCONF(FB_TMC_COOLCONF_SEMAX, 2); tb->set_CHOPCONF(FB_TMC_COOLCONF_SEDN, 0b01); tb->write_REG(FB_TMC_REG_TPWMTHRS, uint32_t(0xFFFFFFFF)); tb->write_REG(FB_TMC_REG_TCOOLTHRS, 0xFFFFF & FB_TMC_TCOOLTHRS_MASK); tb->write_REG(FB_TMC_REG_THIGH, 10000 & FB_TMC_THIGH_MASK); //dcStep settings tb->set_CHOPCONF(FB_TMC_CHOPCONF_VHIGHCHM, 0b01); tb->set_CHOPCONF(FB_TMC_CHOPCONF_VHIGHFS, 0b01); tb->set_CHOPCONF(FB_TMC_CHOPCONF_TOFF, 8); tb->alter_REG(FB_TMC_REG_DCCTRL, uint32_t(100) << FB_TMC_DCCTRL_DC_TIME, FB_TMC_DCCTRL_DC_TIME_MASK << FB_TMC_DCCTRL_DC_TIME); tb->alter_REG(FB_TMC_REG_DCCTRL, uint32_t(8) << FB_TMC_DCCTRL_DC_SG, FB_TMC_DCCTRL_DC_SG_MASK << FB_TMC_DCCTRL_DC_SG); tb->write_REG(FB_TMC_REG_THIGH, uint32_t(10000)); // Enable diagnostics tb->set_GCONF(FB_TMC_GCONF_DIAG0_ERROR, 1); tb->set_GCONF(FB_TMC_GCONF_DIAG1_STEPS_SKIPPED, 1); tb->set_CHOPCONF(FB_TMC_COOLCONF_SGT, sensitivity); } if (stealth) { tb->set_CHOPCONF(FB_TMC_CHOPCONF_TOFF, 3); tb->set_CHOPCONF(FB_TMC_CHOPCONF_TBL, 1); tb->set_CHOPCONF(FB_TMC_CHOPCONF_HSTRT, 0); tb->set_CHOPCONF(FB_TMC_CHOPCONF_HEND, 0); tb->set_CHOPCONF(FB_TMC_CHOPCONF_INTPOL, 1); tb->set_CHOPCONF(FB_TMC_CHOPCONF_CHM, 0); // Disable settings from non-stealth mode tb->set_GCONF(FB_TMC_GCONF_I_SCALE_ANALOG, 0); tb->set_CHOPCONF(FB_TMC_CHOPCONF_VHIGHCHM, 0b00); tb->set_CHOPCONF(FB_TMC_CHOPCONF_VHIGHFS, 0b00); // Enbable stealth tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(1) << FB_TMC_PWMCONF_PWM_AUTOSCALE, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_AUTOSCALE] << FB_TMC_PWMCONF_PWM_AUTOSCALE); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(0) << FB_TMC_PWMCONF_PWM_FREQ, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_FREQ] << FB_TMC_PWMCONF_PWM_FREQ); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(1) << FB_TMC_PWMCONF_PWM_GRAD, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_GRAD] << FB_TMC_PWMCONF_PWM_GRAD); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(128) << FB_TMC_PWMCONF_PWM_AMPL, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_AMPL] << FB_TMC_PWMCONF_PWM_AMPL); tb->set_GCONF(FB_TMC_GCONF_EN_PWM_MODE, uint32_t(1)); // Disable diagnostics tb->set_GCONF(FB_TMC_GCONF_DIAG0_ERROR, 0); tb->set_GCONF(FB_TMC_GCONF_DIAG1_STEPS_SKIPPED, 0); tb->set_CHOPCONF(FB_TMC_COOLCONF_SGT, 0); } delay(100); } #endif <commit_msg>improve diff<commit_after>/* * TMC2130.cpp * * Created on: 03 nov 2019 * Author: Tim Evers */ #include "TMC2130.h" #if defined(FARMDUINO_EXP_V20) || defined(FARMDUINO_V30) || defined(FARMDUINO_V32) void loadTMC2130ParametersMotor(TMC2130_Basics *tb, int microsteps, int current, int sensitivity, bool stealth) { uint32_t data = 0; uint32_t value = 0; tb->init(); // Set the micro steps switch (microsteps) { case 1: data = 8; break; case 2: data = 7; break; case 4: data = 6; break; case 8: data = 5; break; case 16: data = 4; break; case 32: data = 3; break; case 64: data = 2; break; case 128: data = 1; break; } tb->set_CHOPCONF(FB_TMC_CHOPCONF_MRES, data); // Set the current uint16_t mA = current; float multiplier = 0.5; float RS = 0.11; uint8_t CS = 32.0*1.41421*mA / 1000.0*(RS + 0.02) / 0.325 - 1; if (CS < 16) { CS = 32.0*1.41421*mA / 1000.0*(RS + 0.02) / 0.180 - 1; } data = ((uint32_t(CS)&FB_TMC_IHOLD_MASK) << FB_TMC_IHOLD); data |= ((uint32_t(CS)&FB_TMC_IRUN_MASK) << FB_TMC_IRUN); data |= ((uint32_t(16)&FB_TMC_IHOLDDELAY_MASK) << FB_TMC_IHOLDDELAY); tb->write_REG(FB_TMC_REG_IHOLD_IRUN, data); // Chop and cool conf if (!stealth) { tb->set_GCONF(FB_TMC_GCONF_I_SCALE_ANALOG, 1); tb->set_CHOPCONF(FB_TMC_CHOPCONF_TOFF, 3); tb->set_CHOPCONF(FB_TMC_CHOPCONF_HSTRT, 4); tb->set_CHOPCONF(FB_TMC_CHOPCONF_HEND, 1); tb->set_CHOPCONF(FB_TMC_CHOPCONF_TBL, 2); tb->set_CHOPCONF(FB_TMC_CHOPCONF_CHM, 0); tb->set_CHOPCONF(FB_TMC_COOLCONF_SEMIN, 1); tb->set_CHOPCONF(FB_TMC_COOLCONF_SEMAX, 2); tb->set_CHOPCONF(FB_TMC_COOLCONF_SEDN, 0b01); tb->write_REG(FB_TMC_REG_TPWMTHRS, uint32_t(0xFFFFFFFF)); tb->write_REG(FB_TMC_REG_TCOOLTHRS, 0xFFFFF & FB_TMC_TCOOLTHRS_MASK); tb->write_REG(FB_TMC_REG_THIGH, 10000 & FB_TMC_THIGH_MASK); //dcStep settings tb->set_CHOPCONF(FB_TMC_CHOPCONF_VHIGHCHM, 0b01); tb->set_CHOPCONF(FB_TMC_CHOPCONF_VHIGHFS, 0b01); tb->set_CHOPCONF(FB_TMC_CHOPCONF_TOFF, 8); tb->alter_REG(FB_TMC_REG_DCCTRL, uint32_t(100) << FB_TMC_DCCTRL_DC_TIME, FB_TMC_DCCTRL_DC_TIME_MASK << FB_TMC_DCCTRL_DC_TIME); tb->alter_REG(FB_TMC_REG_DCCTRL, uint32_t(8) << FB_TMC_DCCTRL_DC_SG, FB_TMC_DCCTRL_DC_SG_MASK << FB_TMC_DCCTRL_DC_SG); tb->write_REG(FB_TMC_REG_THIGH, uint32_t(10000)); // Enable diagnostics tb->set_GCONF(FB_TMC_GCONF_DIAG0_ERROR, 1); tb->set_GCONF(FB_TMC_GCONF_DIAG1_STEPS_SKIPPED, 1); tb->set_CHOPCONF(FB_TMC_COOLCONF_SGT, sensitivity); } if (stealth) { tb->set_CHOPCONF(FB_TMC_CHOPCONF_TOFF, 3); tb->set_CHOPCONF(FB_TMC_CHOPCONF_TBL, 1); tb->set_CHOPCONF(FB_TMC_CHOPCONF_HSTRT, 0); tb->set_CHOPCONF(FB_TMC_CHOPCONF_HEND, 0); tb->set_CHOPCONF(FB_TMC_CHOPCONF_INTPOL, 1); tb->set_CHOPCONF(FB_TMC_CHOPCONF_CHM, 0); // Disable settings from non-stealth mode tb->set_GCONF(FB_TMC_GCONF_I_SCALE_ANALOG, 0); tb->set_CHOPCONF(FB_TMC_CHOPCONF_VHIGHCHM, 0b00); tb->set_CHOPCONF(FB_TMC_CHOPCONF_VHIGHFS, 0b00); // Enbable stealth tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(1) << FB_TMC_PWMCONF_PWM_AUTOSCALE, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_AUTOSCALE] << FB_TMC_PWMCONF_PWM_AUTOSCALE); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(0) << FB_TMC_PWMCONF_PWM_FREQ, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_FREQ] << FB_TMC_PWMCONF_PWM_FREQ); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(1) << FB_TMC_PWMCONF_PWM_GRAD, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_GRAD] << FB_TMC_PWMCONF_PWM_GRAD); tb->alter_REG(FB_TMC_REG_PWMCONF, uint32_t(128) << FB_TMC_PWMCONF_PWM_AMPL, FB_TMC_PWMCONF_MASKS[FB_TMC_PWMCONF_PWM_AMPL] << FB_TMC_PWMCONF_PWM_AMPL); tb->set_GCONF(FB_TMC_GCONF_EN_PWM_MODE, uint32_t(1)); // Disable diagnostics tb->set_GCONF(FB_TMC_GCONF_DIAG0_ERROR, 0); tb->set_GCONF(FB_TMC_GCONF_DIAG1_STEPS_SKIPPED, 0); tb->set_CHOPCONF(FB_TMC_COOLCONF_SGT, 0); } delay(100); } #endif <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local Includes #include "libmesh/auto_ptr.h" #include "libmesh/preconditioner.h" #include "libmesh/eigen_preconditioner.h" #include "libmesh/petsc_preconditioner.h" #include "libmesh/trilinos_preconditioner.h" namespace libMesh { //------------------------------------------------------------------ // Preconditioner members template <typename T> Preconditioner<T> * Preconditioner<T>::build(const libMesh::Parallel::Communicator & comm, const SolverPackage solver_package) { // Build the appropriate solver switch (solver_package) { #ifdef LIBMESH_HAVE_PETSC case PETSC_SOLVERS: { return new PetscPreconditioner<T>(comm); } #endif #ifdef LIBMESH_TRILINOS_HAVE_EPETRA case TRILINOS_SOLVERS: return new TrilinosPreconditioner<T>(comm); #endif #ifdef LIBMESH_HAVE_EIGEN case EIGEN_SOLVERS: return new EigenPreconditioner<T>(comm); #endif default: libmesh_error_msg("ERROR: Unrecognized solver package: " << solver_package); } return libmesh_nullptr; } //------------------------------------------------------------------ // Explicit instantiations template class Preconditioner<Number>; } // namespace libMesh <commit_msg>Fix warnings when configured with --disable-optional.<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local Includes #include "libmesh/auto_ptr.h" #include "libmesh/preconditioner.h" #include "libmesh/eigen_preconditioner.h" #include "libmesh/petsc_preconditioner.h" #include "libmesh/trilinos_preconditioner.h" namespace libMesh { //------------------------------------------------------------------ // Preconditioner members template <typename T> Preconditioner<T> * Preconditioner<T>::build(const libMesh::Parallel::Communicator & comm, const SolverPackage solver_package) { // Avoid unused parameter warnings when no solver packages are enabled. libmesh_ignore(comm); // Build the appropriate solver switch (solver_package) { #ifdef LIBMESH_HAVE_PETSC case PETSC_SOLVERS: { return new PetscPreconditioner<T>(comm); } #endif #ifdef LIBMESH_TRILINOS_HAVE_EPETRA case TRILINOS_SOLVERS: return new TrilinosPreconditioner<T>(comm); #endif #ifdef LIBMESH_HAVE_EIGEN case EIGEN_SOLVERS: return new EigenPreconditioner<T>(comm); #endif default: libmesh_error_msg("ERROR: Unrecognized solver package: " << solver_package); } return libmesh_nullptr; } //------------------------------------------------------------------ // Explicit instantiations template class Preconditioner<Number>; } // namespace libMesh <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shapeindex.cc 27 2005-03-30 21:45:40Z pavlenko $ #include <iostream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #include "quadtree.hpp" #include "shapefile.hpp" #include "shape_io.hpp" const int MAXDEPTH = 64; const int DEFAULT_DEPTH = 8; const double MINRATIO=0.5; const double MAXRATIO=0.8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; using std::string; using std::vector; using std::clog; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; vector<string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<vector<string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { clog<<"version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { clog << desc << "\n"; return 1; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< vector<string> >(); } } catch (...) { clog << "Exception of unknown type!"<<std::endl; return -1; } std::clog<<"max tree depth:"<<depth<<std::endl; std::clog<<"split ratio:"<<ratio<<std::endl; vector<string>::const_iterator itr=shape_files.begin(); if (itr==shape_files.end()) { std::clog << "no shape files to index"<<std::endl; return 0; } while (itr != shape_files.end()) { std::clog<<"processing "<<*itr << std::endl; //shape_file shp; std::string shapename(*itr++); shape_file shp(shapename+".shp"); if (!shp.is_open()) { std::clog<<"error : cannot open "<< (shapename+".shp") <<"\n"; continue; } int code = shp.read_xdr_integer(); //file_code == 9994 std::clog << code << "\n"; shp.skip(5*4); int file_length=shp.read_xdr_integer(); int version=shp.read_ndr_integer(); int shape_type=shp.read_ndr_integer(); Envelope<double> extent; shp.read_envelope(extent); std::clog<<"length="<<file_length<<std::endl; std::clog<<"version="<<version<<std::endl; std::clog<<"type="<<shape_type<<std::endl; std::clog<<"extent:"<<extent<<std::endl; int pos=50; shp.seek(pos*2); quadtree<int> tree(extent,depth,ratio); int count=0; while (true) { long offset=shp.pos(); int record_number=shp.read_xdr_integer(); int content_length=shp.read_xdr_integer(); //std::clog << "rec number = "<< record_number << "\n"; //std::clog << "content length = "<< content_length << "\n"; shp.skip(4); //std::clog << "offset= "<< offset << std::endl; Envelope<double> item_ext; if (shape_type==shape_io::shape_point) { double x=shp.read_double(); double y=shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointm) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else { shp.read_envelope(item_ext); shp.skip(2*content_length-4*8-4); } tree.insert(offset,item_ext); if (verbose) { std::clog<<"record number "<<record_number<<" box="<<item_ext<<std::endl; } pos+=4+content_length; ++count; if (pos>=file_length) { break; } } shp.close(); std::clog<<" number shapes="<<count<<std::endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { std::clog << "cannot open index file for writing file \"" <<(shapename+".index")<<"\""<<std::endl; } else { tree.trim(); std::clog<<" number nodes="<<tree.count()<<std::endl; tree.write(file); file.close(); } } std::clog<<"done!"<<std::endl; return 0; } <commit_msg>patch from Martijn van Oosterhout <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shapeindex.cc 27 2005-03-30 21:45:40Z pavlenko $ #include <iostream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> #include "quadtree.hpp" #include "shapefile.hpp" #include "shape_io.hpp" const int MAXDEPTH = 64; const int DEFAULT_DEPTH = 8; const double MINRATIO=0.5; const double MAXRATIO=0.8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; using std::string; using std::vector; using std::clog; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; vector<string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<vector<string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { clog<<"version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { clog << desc << "\n"; return 1; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< vector<string> >(); } } catch (...) { clog << "Exception of unknown type!"<<std::endl; return -1; } std::clog<<"max tree depth:"<<depth<<std::endl; std::clog<<"split ratio:"<<ratio<<std::endl; vector<string>::const_iterator itr=shape_files.begin(); if (itr==shape_files.end()) { std::clog << "no shape files to index"<<std::endl; return 0; } while (itr != shape_files.end()) { std::clog<<"processing "<<*itr << std::endl; //shape_file shp; std::string shapename(*itr++); shape_file shp(shapename+".shp"); if (!shp.is_open()) { std::clog<<"error : cannot open "<< (shapename+".shp") <<"\n"; continue; } int code = shp.read_xdr_integer(); //file_code == 9994 std::clog << code << "\n"; shp.skip(5*4); int file_length=shp.read_xdr_integer(); int version=shp.read_ndr_integer(); int shape_type=shp.read_ndr_integer(); Envelope<double> extent; shp.read_envelope(extent); std::clog<<"length="<<file_length<<std::endl; std::clog<<"version="<<version<<std::endl; std::clog<<"type="<<shape_type<<std::endl; std::clog<<"extent:"<<extent<<std::endl; int pos=50; shp.seek(pos*2); quadtree<int> tree(extent,depth,ratio); int count=0; while (true) { long offset=shp.pos(); int record_number=shp.read_xdr_integer(); int content_length=shp.read_xdr_integer(); //std::clog << "rec number = "<< record_number << "\n"; //std::clog << "content length = "<< content_length << "\n"; shp.skip(4); //std::clog << "offset= "<< offset << std::endl; Envelope<double> item_ext; if (shape_type==shape_io::shape_point) { double x=shp.read_double(); double y=shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointm) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); shp.read_double(); item_ext=Envelope<double>(x,y,x,y); } else { shp.read_envelope(item_ext); shp.skip(2*content_length-4*8-4); } tree.insert(offset,item_ext); if (verbose) { std::clog<<"record number "<<record_number<<" box="<<item_ext<<std::endl; } pos+=4+content_length; ++count; if (pos>=file_length) { break; } } shp.close(); std::clog<<" number shapes="<<count<<std::endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { std::clog << "cannot open index file for writing file \"" <<(shapename+".index")<<"\""<<std::endl; } else { tree.trim(); std::clog<<" number nodes="<<tree.count()<<std::endl; file.exceptions(ios::failbit | ios::badbit); tree.write(file); file.flush(); file.close(); } } std::clog<<"done!"<<std::endl; return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shapeindex.cc 27 2005-03-30 21:45:40Z pavlenko $ #include <iostream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem/operations.hpp> #include <boost/program_options.hpp> #include "quadtree.hpp" #include "shapefile.hpp" #include "shape_io.hpp" const int MAXDEPTH = 64; const int DEFAULT_DEPTH = 8; const double MINRATIO=0.5; const double MAXRATIO=0.8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; using std::string; using std::vector; using std::clog; using std::endl; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; vector<string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<vector<string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { clog<<"version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { clog << desc << endl; return 1; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< vector<string> >(); } } catch (...) { clog << "Exception of unknown type!" << endl; return -1; } clog << "max tree depth:" << depth << endl; clog << "split ratio:" << ratio << endl; vector<string>::const_iterator itr = shape_files.begin(); if (itr == shape_files.end()) { clog << "no shape files to index" << endl; return 0; } while (itr != shape_files.end()) { clog << "processing " << *itr << endl; //shape_file shp; std::string shapename (*itr++); std::string shapename_full (shapename+".shp"); if (! boost::filesystem::exists (shapename_full)) { clog << "error : file " << shapename_full << " doesn't exists" << endl; continue; } shape_file shp (shapename_full); if (! shp.is_open()) { clog << "error : cannot open " << shapename_full << endl; continue; } int code = shp.read_xdr_integer(); //file_code == 9994 clog << code << endl; shp.skip(5*4); int file_length=shp.read_xdr_integer(); int version=shp.read_ndr_integer(); int shape_type=shp.read_ndr_integer(); box2d<double> extent; shp.read_envelope(extent); clog << "length=" << file_length << endl; clog << "version=" << version << endl; clog << "type=" << shape_type << endl; clog << "extent:" << extent << endl; int pos=50; shp.seek(pos*2); quadtree<int> tree(extent,depth,ratio); int count=0; while (true) { long offset=shp.pos(); int record_number=shp.read_xdr_integer(); int content_length=shp.read_xdr_integer(); //std::clog << "rec number = "<< record_number << "\n"; //std::clog << "content length = "<< content_length << "\n"; shp.skip(4); //std::clog << "offset= "<< offset << std::endl; box2d<double> item_ext; if (shape_type==shape_io::shape_point) { double x=shp.read_double(); double y=shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointm) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); shp.read_double(); shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else { shp.read_envelope(item_ext); shp.skip(2*content_length-4*8-4); } tree.insert(offset,item_ext); if (verbose) { clog << "record number " << record_number << " box=" << item_ext << endl; } pos+=4+content_length; ++count; if (pos>=file_length) { break; } } shp.close(); clog << " number shapes=" << count << endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { clog << "cannot open index file for writing file \"" << (shapename+".index") << "\"" << endl; } else { tree.trim(); std::clog<<" number nodes="<<tree.count()<<std::endl; file.exceptions(std::ios::failbit | std::ios::badbit); tree.write(file); file.flush(); file.close(); } } clog << "done!" << endl; return 0; } <commit_msg>improve shapeindex support for pointz<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shapeindex.cc 27 2005-03-30 21:45:40Z pavlenko $ #include <iostream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem/operations.hpp> #include <boost/program_options.hpp> #include "quadtree.hpp" #include "shapefile.hpp" #include "shape_io.hpp" const int MAXDEPTH = 64; const int DEFAULT_DEPTH = 8; const double MINRATIO=0.5; const double MAXRATIO=0.8; const double DEFAULT_RATIO=0.55; int main (int argc,char** argv) { using namespace mapnik; namespace po = boost::program_options; using std::string; using std::vector; using std::clog; using std::endl; bool verbose=false; unsigned int depth=DEFAULT_DEPTH; double ratio=DEFAULT_RATIO; vector<string> shape_files; try { po::options_description desc("shapeindex utility"); desc.add_options() ("help,h", "produce usage message") ("version,V","print version string") ("verbose,v","verbose output") ("depth,d", po::value<unsigned int>(), "max tree depth\n(default 8)") ("ratio,r",po::value<double>(),"split ratio (default 0.55)") ("shape_files",po::value<vector<string> >(),"shape files to index: file1 file2 ...fileN") ; po::positional_options_description p; p.add("shape_files",-1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (vm.count("version")) { clog<<"version 0.3.0" <<std::endl; return 1; } if (vm.count("help")) { clog << desc << endl; return 1; } if (vm.count("depth")) { depth = vm["depth"].as<unsigned int>(); } if (vm.count("ratio")) { ratio = vm["ratio"].as<double>(); } if (vm.count("shape_files")) { shape_files=vm["shape_files"].as< vector<string> >(); } } catch (...) { clog << "Exception of unknown type!" << endl; return -1; } clog << "max tree depth:" << depth << endl; clog << "split ratio:" << ratio << endl; vector<string>::const_iterator itr = shape_files.begin(); if (itr == shape_files.end()) { clog << "no shape files to index" << endl; return 0; } while (itr != shape_files.end()) { clog << "processing " << *itr << endl; //shape_file shp; std::string shapename (*itr++); std::string shapename_full (shapename+".shp"); if (! boost::filesystem::exists (shapename_full)) { clog << "error : file " << shapename_full << " doesn't exists" << endl; continue; } shape_file shp (shapename_full); if (! shp.is_open()) { clog << "error : cannot open " << shapename_full << endl; continue; } int code = shp.read_xdr_integer(); //file_code == 9994 clog << code << endl; shp.skip(5*4); int file_length=shp.read_xdr_integer(); int version=shp.read_ndr_integer(); int shape_type=shp.read_ndr_integer(); box2d<double> extent; shp.read_envelope(extent); clog << "length=" << file_length << endl; clog << "version=" << version << endl; clog << "type=" << shape_type << endl; clog << "extent:" << extent << endl; int pos=50; shp.seek(pos*2); quadtree<int> tree(extent,depth,ratio); int count=0; while (true) { long offset=shp.pos(); int record_number=shp.read_xdr_integer(); int content_length=shp.read_xdr_integer(); //std::clog << "rec number = "<< record_number << "\n"; //std::clog << "content length = "<< content_length << "\n"; shp.skip(4); //std::clog << "offset= "<< offset << std::endl; box2d<double> item_ext; if (shape_type==shape_io::shape_point) { double x=shp.read_double(); double y=shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointm) { double x=shp.read_double(); double y=shp.read_double(); // skip m shp.read_double(); item_ext=box2d<double>(x,y,x,y); } else if (shape_type==shape_io::shape_pointz) { double x=shp.read_double(); double y=shp.read_double(); // skip z shp.read_double(); //skip m if exists if ( content_length == 8 + 36) { shp.read_double(); } item_ext=box2d<double>(x,y,x,y); } else { shp.read_envelope(item_ext); shp.skip(2*content_length-4*8-4); } tree.insert(offset,item_ext); if (verbose) { clog << "record number " << record_number << " box=" << item_ext << endl; } pos+=4+content_length; ++count; if (pos>=file_length) { break; } } shp.close(); clog << " number shapes=" << count << endl; std::fstream file((shapename+".index").c_str(), std::ios::in | std::ios::out | std::ios::trunc | std::ios::binary); if (!file) { clog << "cannot open index file for writing file \"" << (shapename+".index") << "\"" << endl; } else { tree.trim(); std::clog<<" number nodes="<<tree.count()<<std::endl; file.exceptions(std::ios::failbit | std::ios::badbit); tree.write(file); file.flush(); file.close(); } } clog << "done!" << endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salpixmaputils.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-06-27 19:49:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_SALPIXMAPUTILS_HXX #define _SV_SALPIXMAPUTILS_HXX #include <premac.h> #include <ApplicationServices/ApplicationServices.h> #include <postmac.h> #ifndef _GEN_HXX #include <tools/gen.hxx> #endif #ifndef _SV_SALBTYPE_HXX #include <vcl/salbtype.hxx> #endif #ifndef _SV_SALGTYPE_HXX #include <vcl/salgtype.hxx> #endif #ifndef _SV_SALCONST_H #include <salconst.h> #endif #ifndef _SV_SALCOLORUTILS_HXX #include <salcolorutils.hxx> #endif // ------------------------------------------------------------------ PixMapHandle GetNewPixMap ( const Size &rPixMapSize, const USHORT nPixMapBits, const BitmapPalette &rBitmapPalette ); PixMapHandle CopyPixMap ( PixMapHandle hPixMap ); PixMapHandle GetCGrafPortPixMap ( const Size &rPixMapSize, const USHORT nPixMapBits, const BitmapPalette &rBitmapPalette, const CGrafPtr pCGraf ); // ------------------------------------------------------------------ #endif // _SV_SALPIXMAPUTILS_HXX <commit_msg>INTEGRATION: CWS aquavcl01 (1.5.112); FILE MERGED 2007/01/12 21:01:27 mox 1.5.112.1: aqua vcl cleanup. Get rid of obsolete QuickDraw functions, that are not used by the current Quartz 2D code. When Quartz functions are used this kind of color device management code is not needed at all (automatically handled by Quartz).<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salpixmaputils.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2007-07-05 08:15:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_SALPIXMAPUTILS_HXX #define _SV_SALPIXMAPUTILS_HXX #include <premac.h> #include <ApplicationServices/ApplicationServices.h> #include <postmac.h> #ifndef _GEN_HXX #include <tools/gen.hxx> #endif #ifndef _SV_SALBTYPE_HXX #include <vcl/salbtype.hxx> #endif #ifndef _SV_SALGTYPE_HXX #include <vcl/salgtype.hxx> #endif #ifndef _SV_SALCONST_H #include <salconst.h> #endif #ifndef _SV_SALCOLORUTILS_HXX #include <salcolorutils.hxx> #endif // ------------------------------------------------------------------ // Empty. Do we need this? // ------------------------------------------------------------------ #endif // _SV_SALPIXMAPUTILS_HXX <|endoftext|>
<commit_before>/* This file is part of KXForms. Copyright (c) 2005,2006 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "guihandlerflat.h" #include "manager.h" #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include <kdialog.h> #include <QLabel> #include <QVBoxLayout> #include <QGridLayout> #include <QFrame> #include <QStackedWidget> #include <QPushButton> #include <QDebug> using namespace KXForms; BreadCrumbLabel::BreadCrumbLabel( QWidget *parent ) : K3ActiveLabel( parent ) { } void BreadCrumbLabel::openLink( const QUrl &link ) { emit crumbClicked( link.toString().toInt() ); } BreadCrumbNavigator::BreadCrumbNavigator( QWidget *parent ) : QFrame( parent ) { QBoxLayout *topLayout = new QVBoxLayout( this ); #if 0 // Why doesn't this work? QPalette p = palette(); p.setColor( QPalette::Window, "#ffffa0" ); setPalette( p ); #endif #if 0 setFrameStyle( Plain | Panel ); setLineWidth( 1 ); #endif mLabel = new BreadCrumbLabel( this ); topLayout->addWidget( mLabel ); connect( mLabel, SIGNAL( crumbClicked( int ) ), SLOT( slotCrumbClicked( int ) ) ); } void BreadCrumbNavigator::push( FormGui *gui ) { mHistory.push( gui ); updateLabel(); } FormGui *BreadCrumbNavigator::pop() { FormGui *result; if ( mHistory.isEmpty() ) result = 0; else result = mHistory.pop(); updateLabel(); result->saveData(); return result; } FormGui *BreadCrumbNavigator::last() const { if ( mHistory.isEmpty() ) return 0; else return mHistory.last(); } int BreadCrumbNavigator::count() const { return mHistory.count(); } void BreadCrumbNavigator::updateLabel() { QString text; for( int i = 0; i < mHistory.size(); ++i ) { if ( !text.isEmpty() ) { text.append( " / " ); } else { #if 0 text.append( "/ " ); #endif } QString label = mHistory[ i ]->label(); if ( label.isEmpty() ) { label = "..."; } if ( i == mHistory.size() - 1 ) { text.append( "<b>" + label + "</b>" ); } else { text.append( "<a href=\"" + QString::number( i ) + "\">" + label + "</a>" ); } } mLabel->setHtml( "<qt>" + text + "</qt>" ); } void BreadCrumbNavigator::slotCrumbClicked( int index ) { if ( mHistory.size() <= index ) return; FormGui *gui = last(); gui->saveData(); while( mHistory.size() > index + 1 ) { gui = mHistory.pop(); } updateLabel(); emit guiSelected( last() ); } GuiHandlerFlat::GuiHandlerFlat( Manager *m ) : GuiHandler( m ) { } QWidget *GuiHandlerFlat::createRootGui( QWidget *parent ) { kDebug() << "GuiHandlerFlat::createRootGui()" << endl; mMainWidget = new QWidget( parent ); QBoxLayout *topLayout = new QVBoxLayout( mMainWidget ); topLayout->setMargin( 0 ); mBreadCrumbNavigator = new BreadCrumbNavigator( mMainWidget ); topLayout->addWidget( mBreadCrumbNavigator ); connect( mBreadCrumbNavigator, SIGNAL( guiSelected( FormGui * ) ), SLOT( showGui( FormGui * ) ) ); QFrame *line = new QFrame( mMainWidget ); topLayout->addWidget( line ); line->setFrameStyle( QFrame::HLine | QFrame::Plain ); line->setLineWidth( 1 ); mStackWidget = new QStackedWidget( mMainWidget ); topLayout->addWidget( mStackWidget, 1 ); Form *f = manager()->rootForm(); if ( !f ) { KMessageBox::sorry( parent, i18n("Root form not found.") ); return 0; } FormGui *gui = createGui( f, mStackWidget ); gui->setRef( '/' + f->ref() ); gui->parseElement( f->element() ); if ( manager()->hasData() ) { kDebug() << "Manager::createGui() Load data on creation" << endl; manager()->loadData( gui ); } mStackWidget->addWidget( gui ); QBoxLayout *buttonLayout = new QHBoxLayout(); topLayout->addLayout( buttonLayout ); buttonLayout->setMargin( KDialog::marginHint() ); buttonLayout->addStretch( 1 ); mBackButton = new QPushButton( i18n("Back"), mMainWidget ); buttonLayout->addWidget( mBackButton ); connect( mBackButton, SIGNAL( clicked() ), SLOT( goBack() ) ); mBackButton->setEnabled( false ); return mMainWidget; } void GuiHandlerFlat::createGui( const Reference &ref, QWidget *parent ) { kDebug() << "GuiHandlerFlat::createGui() ref: '" << ref.toString() << "'" << endl; if ( ref.isEmpty() ) { KMessageBox::sorry( parent, i18n("No reference.") ); return; } QString r = ref.segments().last().name(); Form *f = manager()->form( r ); if ( !f ) { KMessageBox::sorry( parent, i18n("Form '%1' not found.", ref.toString() ) ); return; } FormGui *gui = createGui( f, mMainWidget ); if ( !gui ) { KMessageBox::sorry( parent, i18n("Unable to create GUI for '%1'.", ref.toString() ) ); return; } gui->setRef( ref ); gui->parseElement( f->element() ); mStackWidget->addWidget( gui ); mBackButton->setEnabled( true ); if ( manager()->hasData() ) { kDebug() << "Manager::createGui() Load data on creation" << endl; manager()->loadData( gui ); } mStackWidget->setCurrentWidget( gui ); } FormGui *GuiHandlerFlat::createGui( Form *form, QWidget *parent ) { if ( !form ) { kError() << "KXForms::Manager::createGui(): form is null." << endl; return 0; } kDebug() << "Manager::createGui() form: '" << form->ref() << "'" << endl; FormGui *gui = new FormGui( form->label(), manager(), parent ); if ( gui ) { manager()->registerGui( gui ); mBreadCrumbNavigator->push( gui ); connect( gui, SIGNAL( editingFinished() ), SLOT( goBack() ) ); gui->setLabelHidden( true ); } return gui; } void GuiHandlerFlat::goBack() { mBreadCrumbNavigator->pop(); FormGui *current = mBreadCrumbNavigator->last(); showGui( current ); } void GuiHandlerFlat::showGui( FormGui *gui ) { if ( gui ) { mStackWidget->setCurrentWidget( gui ); manager()->loadData( gui ); } if ( mBreadCrumbNavigator->count() == 1 ) { mBackButton->setEnabled( false ); } } QLayout *GuiHandlerFlat::getTopLayout() const { if( layoutStyle() == GuiHandler::Grid ) { QGridLayout *l = new QGridLayout(); return l; } else { QVBoxLayout *l = new QVBoxLayout(); l->addStretch( 1 ); return l; } } void GuiHandlerFlat::addWidget( QLayout *l, QWidget *w ) const { if( layoutStyle() == GuiHandler::Grid ) { QGridLayout *gl = dynamic_cast< QGridLayout *>( l ); if( !gl ) return; gl->addWidget( w, gl->rowCount(), 0, 1, 2 ); } else { QVBoxLayout *vbl = dynamic_cast< QVBoxLayout *>( l ); if( !vbl ) return; vbl->insertWidget( l->count() - 1, w ); } } void GuiHandlerFlat::addElement( QLayout *l, QWidget *label, QWidget *widget, GuiElement::Properties *prop ) const { if( layoutStyle() == GuiHandler::Grid ) { QGridLayout *gl = dynamic_cast< QGridLayout *>( l ); if( !gl ) return; int row = gl->rowCount(); if( label ) { gl->addWidget( label, row, 0, prop->alignment() ); gl->addWidget( widget, row, 1, prop->alignment() ); } else { gl->addWidget( widget, row, 0, 1, 2, prop->alignment() ); } } else { QVBoxLayout *vbl = dynamic_cast< QVBoxLayout *>( l ); if( !vbl ) return; QBoxLayout *newLayout; newLayout = new QVBoxLayout(); newLayout->addWidget( label, prop->alignment() ); newLayout->addWidget( widget, prop->alignment() ); vbl->insertLayout( l->count() - 1, newLayout ); } } #include "guihandlerflat.moc" <commit_msg>Fix lost changes after a listitem was edited.<commit_after>/* This file is part of KXForms. Copyright (c) 2005,2006 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "guihandlerflat.h" #include "manager.h" #include <kdebug.h> #include <kmessagebox.h> #include <klocale.h> #include <kdialog.h> #include <QLabel> #include <QVBoxLayout> #include <QGridLayout> #include <QFrame> #include <QStackedWidget> #include <QPushButton> #include <QDebug> using namespace KXForms; BreadCrumbLabel::BreadCrumbLabel( QWidget *parent ) : K3ActiveLabel( parent ) { } void BreadCrumbLabel::openLink( const QUrl &link ) { emit crumbClicked( link.toString().toInt() ); } BreadCrumbNavigator::BreadCrumbNavigator( QWidget *parent ) : QFrame( parent ) { QBoxLayout *topLayout = new QVBoxLayout( this ); #if 0 // Why doesn't this work? QPalette p = palette(); p.setColor( QPalette::Window, "#ffffa0" ); setPalette( p ); #endif #if 0 setFrameStyle( Plain | Panel ); setLineWidth( 1 ); #endif mLabel = new BreadCrumbLabel( this ); topLayout->addWidget( mLabel ); connect( mLabel, SIGNAL( crumbClicked( int ) ), SLOT( slotCrumbClicked( int ) ) ); } void BreadCrumbNavigator::push( FormGui *gui ) { mHistory.push( gui ); updateLabel(); } FormGui *BreadCrumbNavigator::pop() { FormGui *result; if ( mHistory.isEmpty() ) result = 0; else result = mHistory.pop(); updateLabel(); result->saveData(); return result; } FormGui *BreadCrumbNavigator::last() const { if ( mHistory.isEmpty() ) return 0; else return mHistory.last(); } int BreadCrumbNavigator::count() const { return mHistory.count(); } void BreadCrumbNavigator::updateLabel() { QString text; for( int i = 0; i < mHistory.size(); ++i ) { if ( !text.isEmpty() ) { text.append( " / " ); } else { #if 0 text.append( "/ " ); #endif } QString label = mHistory[ i ]->label(); if ( label.isEmpty() ) { label = "..."; } if ( i == mHistory.size() - 1 ) { text.append( "<b>" + label + "</b>" ); } else { text.append( "<a href=\"" + QString::number( i ) + "\">" + label + "</a>" ); } } mLabel->setHtml( "<qt>" + text + "</qt>" ); } void BreadCrumbNavigator::slotCrumbClicked( int index ) { if ( mHistory.size() <= index ) return; FormGui *gui = last(); gui->saveData(); while( mHistory.size() > index + 1 ) { gui = mHistory.pop(); } updateLabel(); emit guiSelected( last() ); } GuiHandlerFlat::GuiHandlerFlat( Manager *m ) : GuiHandler( m ) { } QWidget *GuiHandlerFlat::createRootGui( QWidget *parent ) { kDebug() << "GuiHandlerFlat::createRootGui()" << endl; mMainWidget = new QWidget( parent ); QBoxLayout *topLayout = new QVBoxLayout( mMainWidget ); topLayout->setMargin( 0 ); mBreadCrumbNavigator = new BreadCrumbNavigator( mMainWidget ); topLayout->addWidget( mBreadCrumbNavigator ); connect( mBreadCrumbNavigator, SIGNAL( guiSelected( FormGui * ) ), SLOT( showGui( FormGui * ) ) ); QFrame *line = new QFrame( mMainWidget ); topLayout->addWidget( line ); line->setFrameStyle( QFrame::HLine | QFrame::Plain ); line->setLineWidth( 1 ); mStackWidget = new QStackedWidget( mMainWidget ); topLayout->addWidget( mStackWidget, 1 ); Form *f = manager()->rootForm(); if ( !f ) { KMessageBox::sorry( parent, i18n("Root form not found.") ); return 0; } FormGui *gui = createGui( f, mStackWidget ); gui->setRef( '/' + f->ref() ); gui->parseElement( f->element() ); if ( manager()->hasData() ) { kDebug() << "Manager::createGui() Load data on creation" << endl; manager()->loadData( gui ); } mStackWidget->addWidget( gui ); QBoxLayout *buttonLayout = new QHBoxLayout(); topLayout->addLayout( buttonLayout ); buttonLayout->setMargin( KDialog::marginHint() ); buttonLayout->addStretch( 1 ); mBackButton = new QPushButton( i18n("Back"), mMainWidget ); buttonLayout->addWidget( mBackButton ); connect( mBackButton, SIGNAL( clicked() ), SLOT( goBack() ) ); mBackButton->setEnabled( false ); return mMainWidget; } void GuiHandlerFlat::createGui( const Reference &ref, QWidget *parent ) { kDebug() << "GuiHandlerFlat::createGui() ref: '" << ref.toString() << "'" << endl; if ( ref.isEmpty() ) { KMessageBox::sorry( parent, i18n("No reference.") ); return; } QString r = ref.segments().last().name(); Form *f = manager()->form( r ); if ( !f ) { KMessageBox::sorry( parent, i18n("Form '%1' not found.", ref.toString() ) ); return; } FormGui *gui = createGui( f, mMainWidget ); if ( !gui ) { KMessageBox::sorry( parent, i18n("Unable to create GUI for '%1'.", ref.toString() ) ); return; } gui->setRef( ref ); gui->parseElement( f->element() ); mStackWidget->addWidget( gui ); mBackButton->setEnabled( true ); if ( manager()->hasData() ) { kDebug() << "Manager::createGui() Load data on creation" << endl; manager()->loadData( gui ); } mStackWidget->setCurrentWidget( gui ); } FormGui *GuiHandlerFlat::createGui( Form *form, QWidget *parent ) { if ( !form ) { kError() << "KXForms::Manager::createGui(): form is null." << endl; return 0; } kDebug() << "Manager::createGui() form: '" << form->ref() << "'" << endl; if( mStackWidget->currentWidget() ) static_cast<FormGui *>(mStackWidget->currentWidget())->saveData(); FormGui *gui = new FormGui( form->label(), manager(), parent ); if ( gui ) { manager()->registerGui( gui ); mBreadCrumbNavigator->push( gui ); connect( gui, SIGNAL( editingFinished() ), SLOT( goBack() ) ); gui->setLabelHidden( true ); } return gui; } void GuiHandlerFlat::goBack() { mBreadCrumbNavigator->pop(); FormGui *current = mBreadCrumbNavigator->last(); showGui( current ); } void GuiHandlerFlat::showGui( FormGui *gui ) { if ( gui ) { mStackWidget->setCurrentWidget( gui ); manager()->loadData( gui ); } if ( mBreadCrumbNavigator->count() == 1 ) { mBackButton->setEnabled( false ); } } QLayout *GuiHandlerFlat::getTopLayout() const { if( layoutStyle() == GuiHandler::Grid ) { QGridLayout *l = new QGridLayout(); return l; } else { QVBoxLayout *l = new QVBoxLayout(); l->addStretch( 1 ); return l; } } void GuiHandlerFlat::addWidget( QLayout *l, QWidget *w ) const { if( layoutStyle() == GuiHandler::Grid ) { QGridLayout *gl = dynamic_cast< QGridLayout *>( l ); if( !gl ) return; gl->addWidget( w, gl->rowCount(), 0, 1, 2 ); } else { QVBoxLayout *vbl = dynamic_cast< QVBoxLayout *>( l ); if( !vbl ) return; vbl->insertWidget( l->count() - 1, w ); } } void GuiHandlerFlat::addElement( QLayout *l, QWidget *label, QWidget *widget, GuiElement::Properties *prop ) const { if( layoutStyle() == GuiHandler::Grid ) { QGridLayout *gl = dynamic_cast< QGridLayout *>( l ); if( !gl ) return; int row = gl->rowCount(); if( label ) { gl->addWidget( label, row, 0, prop->alignment() ); gl->addWidget( widget, row, 1, prop->alignment() ); } else { gl->addWidget( widget, row, 0, 1, 2, prop->alignment() ); } } else { QVBoxLayout *vbl = dynamic_cast< QVBoxLayout *>( l ); if( !vbl ) return; QBoxLayout *newLayout; newLayout = new QVBoxLayout(); newLayout->addWidget( label, prop->alignment() ); newLayout->addWidget( widget, prop->alignment() ); vbl->insertLayout( l->count() - 1, newLayout ); } } #include "guihandlerflat.moc" <|endoftext|>
<commit_before>// // Created by Rachel Ren on 4/18/16. // #include <vector> #include <algorithm> using namespace std; struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; struct less_than_key { inline bool operator() (const Interval& interval1, const Interval& interval2) { return (interval1.start < interval2.start); } }; vector<Interval> merge(vector<Interval>& intervals) { if (intervals.size() < 2){ return intervals; } sort(intervals.begin(), intervals.end(), less_than_key()); vector<Interval> result; Interval common = intervals[0]; for (int i = 1; i < intervals.size(); i++){ if (intervals[i].start > common.end){ result.push_back(common); common = intervals[i]; }else{ if (common.end > intervals[i].end){ continue; }else{ common = Interval(common.start, intervals[i].end); } } } result.push_back(common); return result; }<commit_msg>finished merge_interval<commit_after>// // Created by Rachel Ren on 4/18/16. // Leetcode 56 Merge Intervals // #include <vector> #include <algorithm> using namespace std; struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; struct less_than_key { inline bool operator() (const Interval& interval1, const Interval& interval2) { return (interval1.start < interval2.start); } }; vector<Interval> merge(vector<Interval>& intervals) { if (intervals.size() < 2){ return intervals; } sort(intervals.begin(), intervals.end(), less_than_key()); vector<Interval> result; Interval common = intervals[0]; for (int i = 1; i < intervals.size(); i++){ if (intervals[i].start > common.end){ result.push_back(common); common = intervals[i]; }else{ if (common.end > intervals[i].end){ continue; }else{ common = Interval(common.start, intervals[i].end); } } } result.push_back(common); return result; }<|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qwidget.h> #include <qtooltip.h> #include <qlayout.h> #include <qvbox.h> #include <qbuttongroup.h> #include <qvgroupbox.h> #include <qwidgetstack.h> #include <qdatetime.h> #include <qlineedit.h> #include <qlabel.h> #include <qcheckbox.h> #include <qpushbutton.h> #include <qcombobox.h> #include <kglobal.h> #include <kdebug.h> #include <klocale.h> #include <kiconloader.h> #include <kmessagebox.h> #include <kfiledialog.h> #include <ksqueezedtextlabel.h> #include <kstandarddirs.h> #include <ktextedit.h> #include <krestrictedline.h> #include <libkcal/todo.h> #include <libkcal/event.h> #include <libkdepim/kdateedit.h> #include "koprefs.h" #include "koglobals.h" #include "koeditorgeneral.h" #include "koeditorgeneral.moc" KOEditorGeneral::KOEditorGeneral(QObject* parent, const char* name) : QObject( parent, name) { } KOEditorGeneral::~KOEditorGeneral() { } FocusLineEdit::FocusLineEdit( QWidget *parent ) : QLineEdit( parent ), mSkipFirst( true ) { } void FocusLineEdit::focusInEvent ( QFocusEvent *e ) { if ( !mSkipFirst ) { emit focusReceivedSignal(); } else { mSkipFirst = false; } QLineEdit::focusInEvent( e ); } void KOEditorGeneral::initHeader(QWidget *parent,QBoxLayout *topLayout) { QGridLayout *headerLayout = new QGridLayout(topLayout); #if 0 mOwnerLabel = new QLabel(i18n("Owner:"),parent); headerLayout->addMultiCellWidget(mOwnerLabel,0,0,0,1); #endif QLabel *summaryLabel = new QLabel(i18n("T&itle:"),parent); QFont f = summaryLabel->font(); f.setBold( true ); summaryLabel->setFont(f); headerLayout->addWidget(summaryLabel,1,0); mSummaryEdit = new FocusLineEdit(parent); connect( mSummaryEdit, SIGNAL( focusReceivedSignal() ), SIGNAL( focusReceivedSignal() ) ); headerLayout->addWidget(mSummaryEdit,1,1); summaryLabel->setBuddy( mSummaryEdit ); QLabel *locationLabel = new QLabel(i18n("&Location:"),parent); headerLayout->addWidget(locationLabel,2,0); mLocationEdit = new QLineEdit(parent); headerLayout->addWidget(mLocationEdit,2,1); locationLabel->setBuddy( mLocationEdit ); } void KOEditorGeneral::initCategories(QWidget *parent, QBoxLayout *topLayout) { QBoxLayout *categoriesLayout = new QHBoxLayout( topLayout ); mCategoriesButton = new QPushButton(parent); mCategoriesButton->setText(i18n("Select Cate&gories...")); connect(mCategoriesButton,SIGNAL(clicked()),SIGNAL(openCategoryDialog())); categoriesLayout->addWidget(mCategoriesButton); mCategoriesLabel = new KSqueezedTextLabel(parent); mCategoriesLabel->setFrameStyle(QFrame::Panel|QFrame::Sunken); categoriesLayout->addWidget(mCategoriesLabel,1); } void KOEditorGeneral::initSecrecy(QWidget *parent, QBoxLayout *topLayout) { QBoxLayout *secrecyLayout = new QHBoxLayout( topLayout ); QLabel *secrecyLabel = new QLabel(i18n("Acc&ess:"),parent); secrecyLayout->addWidget(secrecyLabel); mSecrecyCombo = new QComboBox(parent); mSecrecyCombo->insertStringList(Incidence::secrecyList()); secrecyLayout->addWidget(mSecrecyCombo); secrecyLabel->setBuddy( mSecrecyCombo ); } void KOEditorGeneral::initDescription(QWidget *parent,QBoxLayout *topLayout) { mDescriptionEdit = new KTextEdit(parent); mDescriptionEdit->append(""); mDescriptionEdit->setReadOnly(false); mDescriptionEdit->setOverwriteMode(false); mDescriptionEdit->setWordWrap( KTextEdit::WidgetWidth ); mDescriptionEdit->setTabChangesFocus( true );; topLayout->addWidget(mDescriptionEdit); } void KOEditorGeneral::initAlarm(QWidget *parent,QBoxLayout *topLayout) { QBoxLayout *alarmLayout = new QHBoxLayout(topLayout); mAlarmBell = new QLabel(parent); mAlarmBell->setPixmap(KOGlobals::self()->smallIcon("bell")); alarmLayout->addWidget(mAlarmBell); mAlarmButton = new QCheckBox(i18n("&Reminder:"),parent); connect(mAlarmButton, SIGNAL(toggled(bool)), SLOT(enableAlarmEdit(bool))); alarmLayout->addWidget(mAlarmButton); mAlarmTimeEdit = new KRestrictedLine(parent, "alarmTimeEdit", "1234567890"); mAlarmTimeEdit->setText(""); alarmLayout->addWidget(mAlarmTimeEdit); mAlarmIncrCombo = new QComboBox(false, parent); mAlarmIncrCombo->insertItem(i18n("minute(s)")); mAlarmIncrCombo->insertItem(i18n("hour(s)")); mAlarmIncrCombo->insertItem(i18n("day(s)")); // mAlarmIncrCombo->setMinimumHeight(20); alarmLayout->addWidget(mAlarmIncrCombo); mAlarmSoundButton = new QPushButton(parent); mAlarmSoundButton->setPixmap(KOGlobals::self()->smallIcon("playsound")); mAlarmSoundButton->setToggleButton(true); QToolTip::add(mAlarmSoundButton, i18n("No sound set")); connect(mAlarmSoundButton, SIGNAL(clicked()), SLOT(pickAlarmSound())); alarmLayout->addWidget(mAlarmSoundButton); mAlarmProgramButton = new QPushButton(parent); mAlarmProgramButton->setPixmap(KOGlobals::self()->smallIcon("runprog")); mAlarmProgramButton->setToggleButton(true); QToolTip::add(mAlarmProgramButton, i18n("No program set")); connect(mAlarmProgramButton, SIGNAL(clicked()), SLOT(pickAlarmProgram())); alarmLayout->addWidget(mAlarmProgramButton); if ( KOPrefs::instance()->mCompactDialogs ) { mAlarmSoundButton->hide(); mAlarmProgramButton->hide(); } } void KOEditorGeneral::pickAlarmSound() { QString prefix = KGlobal::dirs()->findResourceDir("data", "korganizer/sounds/alert.wav"); if (!mAlarmSoundButton->isOn()) { mAlarmSound = ""; QToolTip::remove(mAlarmSoundButton); QToolTip::add(mAlarmSoundButton, i18n("No sound set")); } else { QString fileName(KFileDialog::getOpenFileName(prefix, i18n("*.wav|Wav Files"), 0)); if (!fileName.isEmpty()) { mAlarmSound = fileName; QToolTip::remove(mAlarmSoundButton); QString dispStr = i18n("Playing '%1'").arg(fileName); QToolTip::add(mAlarmSoundButton, dispStr); mAlarmProgramButton->setOn(false); } } if (mAlarmSound.isEmpty()) mAlarmSoundButton->setOn(false); } void KOEditorGeneral::pickAlarmProgram() { if (!mAlarmProgramButton->isOn()) { mAlarmProgram = ""; QToolTip::remove(mAlarmProgramButton); QToolTip::add(mAlarmProgramButton, i18n("No program set")); } else { QString fileName(KFileDialog::getOpenFileName(QString::null, QString::null, 0)); if (!fileName.isEmpty()) { mAlarmProgram = fileName; QToolTip::remove(mAlarmProgramButton); QString dispStr = i18n("Running '%1'").arg(fileName); QToolTip::add(mAlarmProgramButton, dispStr); mAlarmSoundButton->setOn(false); } } if (mAlarmProgram.isEmpty()) mAlarmProgramButton->setOn(false); } void KOEditorGeneral::enableAlarmEdit(bool enable) { mAlarmTimeEdit->setEnabled(enable); mAlarmSoundButton->setEnabled(enable); mAlarmProgramButton->setEnabled(enable); mAlarmIncrCombo->setEnabled(enable); } void KOEditorGeneral::disableAlarmEdit(bool disable) { enableAlarmEdit( !disable ); } void KOEditorGeneral::enableAlarm( bool enable ) { enableAlarmEdit( enable ); } void KOEditorGeneral::alarmDisable(bool disable) { if (!disable) { mAlarmBell->setEnabled(true); mAlarmButton->setEnabled(true); } else { mAlarmBell->setEnabled(false); mAlarmButton->setEnabled(false); mAlarmButton->setChecked(false); mAlarmTimeEdit->setEnabled(false); mAlarmSoundButton->setEnabled(false); mAlarmProgramButton->setEnabled(false); mAlarmIncrCombo->setEnabled(false); } } void KOEditorGeneral::setCategories(const QString &str) { mCategoriesLabel->setText(str); mCategories = str; } void KOEditorGeneral::setDefaults(bool allDay) { #if 0 mOwnerLabel->setText(i18n("Owner: ") + KOPrefs::instance()->fullName()); #endif enableAlarmEdit( !allDay ); // @TODO: Implement a KPrefsComboItem to solve this in a clean way. int alarmTime; int a[] = { 1,5,10,15,30 }; int index = KOPrefs::instance()->mAlarmTime; if (index < 0 || index > 4) { alarmTime = 0; } else { alarmTime = a[index]; } mAlarmTimeEdit->setText(QString::number(alarmTime)); enableAlarmEdit( false ); mSecrecyCombo->setCurrentItem(Incidence::SecrecyPublic); } void KOEditorGeneral::readIncidence(Incidence *event) { mSummaryEdit->setText(event->summary()); mLocationEdit->setText(event->location()); mDescriptionEdit->setText(event->description()); #if 0 // organizer information mOwnerLabel->setText(i18n("Owner: ") + event->organizer()); #endif enableAlarmEdit( event->isAlarmEnabled() ); if(!event->isAlarmEnabled()) { // @TODO: Implement a KPrefsComboItem to solve this in a clean way. int alarmTime; int a[] = { 1,5,10,15,30 }; int index = KOPrefs::instance()->mAlarmTime; if (index < 0 || index > 4) { alarmTime = 0; } else { alarmTime = a[index]; } mAlarmTimeEdit->setText(QString::number(alarmTime)); } mSecrecyCombo->setCurrentItem(event->secrecy()); // set up alarm stuff Alarm::List alarms = event->alarms(); Alarm::List::ConstIterator it; for( it = alarms.begin(); it != alarms.end(); ++it ) { Alarm *alarm = *it; int offset; if ( alarm->hasTime() ) { QDateTime t = alarm->time(); offset = event->dtStart().secsTo( t ); } else { offset = alarm->startOffset().asSeconds(); } offset = offset / -60; // make minutes if (offset % 60 == 0) { // divides evenly into hours? offset = offset / 60; mAlarmIncrCombo->setCurrentItem(1); } if (offset % 24 == 0) { // divides evenly into days? offset = offset / 24; mAlarmIncrCombo->setCurrentItem(2); } mAlarmTimeEdit->setText(QString::number( offset )); if (alarm->type() == Alarm::Procedure) { mAlarmProgram = alarm->programFile(); mAlarmProgramButton->setOn(true); QString dispStr = i18n("Running '%1'").arg(mAlarmProgram); QToolTip::add(mAlarmProgramButton, dispStr); } else if (alarm->type() == Alarm::Audio) { mAlarmSound = alarm->audioFile(); mAlarmSoundButton->setOn(true); QString dispStr = i18n("Playing '%1'").arg(mAlarmSound); QToolTip::add(mAlarmSoundButton, dispStr); } mAlarmButton->setChecked(alarm->enabled()); enableAlarmEdit( alarm->enabled() ); // @TODO: Deal with multiple alarms break; // For now, stop after the first alarm } setCategories(event->categoriesStr()); } void KOEditorGeneral::writeIncidence(Incidence *event) { // kdDebug(5850) << "KOEditorGeneral::writeEvent()" << endl; event->setSummary(mSummaryEdit->text()); event->setLocation(mLocationEdit->text()); event->setDescription(mDescriptionEdit->text()); event->setCategories(mCategories); event->setSecrecy(mSecrecyCombo->currentItem()); // alarm stuff if (mAlarmButton->isChecked()) { if (event->alarms().count() == 0) event->newAlarm(); Alarm::List alarms = event->alarms(); Alarm::List::ConstIterator it; for( it = alarms.begin(); it != alarms.end(); ++it ) { Alarm *alarm = *it; alarm->setEnabled(true); QString tmpStr = mAlarmTimeEdit->text(); int j = tmpStr.toInt() * -60; if (mAlarmIncrCombo->currentItem() == 1) j = j * 60; else if (mAlarmIncrCombo->currentItem() == 2) j = j * (60 * 24); alarm->setStartOffset( j ); if (!mAlarmSound.isEmpty() && mAlarmSoundButton->isOn()) alarm->setAudioAlarm(mAlarmSound); else alarm->setDisplayAlarm(QString::null); // @TODO: Make sure all alarm options are correctly set and don't erase other options! if (!mAlarmProgram.isEmpty() && mAlarmProgramButton->isOn()) alarm->setProcedureAlarm(mAlarmProgram); // @TODO: Deal with multiple alarms break; // For now, stop after the first alarm } } else { if ( !event->alarms().isEmpty() ) { Alarm *alarm = event->alarms().first(); alarm->setEnabled(false); alarm->setType(Alarm::Invalid); } } } void KOEditorGeneral::setSummary( const QString &text ) { mSummaryEdit->setText( text ); } void KOEditorGeneral::setDescription( const QString &text ) { mDescriptionEdit->setText( text ); } QObject *KOEditorGeneral::typeAheadReceiver() const { return mSummaryEdit; } <commit_msg>Show the correct path when opening the sound selection dialog<commit_after>/* This file is part of KOrganizer. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> 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. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qwidget.h> #include <qtooltip.h> #include <qlayout.h> #include <qvbox.h> #include <qbuttongroup.h> #include <qvgroupbox.h> #include <qwidgetstack.h> #include <qdatetime.h> #include <qlineedit.h> #include <qlabel.h> #include <qcheckbox.h> #include <qpushbutton.h> #include <qcombobox.h> #include <kglobal.h> #include <kdebug.h> #include <klocale.h> #include <kiconloader.h> #include <kmessagebox.h> #include <kfiledialog.h> #include <ksqueezedtextlabel.h> #include <kstandarddirs.h> #include <ktextedit.h> #include <krestrictedline.h> #include <libkcal/todo.h> #include <libkcal/event.h> #include <libkdepim/kdateedit.h> #include "koprefs.h" #include "koglobals.h" #include "koeditorgeneral.h" #include "koeditorgeneral.moc" KOEditorGeneral::KOEditorGeneral(QObject* parent, const char* name) : QObject( parent, name) { } KOEditorGeneral::~KOEditorGeneral() { } FocusLineEdit::FocusLineEdit( QWidget *parent ) : QLineEdit( parent ), mSkipFirst( true ) { } void FocusLineEdit::focusInEvent ( QFocusEvent *e ) { if ( !mSkipFirst ) { emit focusReceivedSignal(); } else { mSkipFirst = false; } QLineEdit::focusInEvent( e ); } void KOEditorGeneral::initHeader(QWidget *parent,QBoxLayout *topLayout) { QGridLayout *headerLayout = new QGridLayout(topLayout); #if 0 mOwnerLabel = new QLabel(i18n("Owner:"),parent); headerLayout->addMultiCellWidget(mOwnerLabel,0,0,0,1); #endif QLabel *summaryLabel = new QLabel(i18n("T&itle:"),parent); QFont f = summaryLabel->font(); f.setBold( true ); summaryLabel->setFont(f); headerLayout->addWidget(summaryLabel,1,0); mSummaryEdit = new FocusLineEdit(parent); connect( mSummaryEdit, SIGNAL( focusReceivedSignal() ), SIGNAL( focusReceivedSignal() ) ); headerLayout->addWidget(mSummaryEdit,1,1); summaryLabel->setBuddy( mSummaryEdit ); QLabel *locationLabel = new QLabel(i18n("&Location:"),parent); headerLayout->addWidget(locationLabel,2,0); mLocationEdit = new QLineEdit(parent); headerLayout->addWidget(mLocationEdit,2,1); locationLabel->setBuddy( mLocationEdit ); } void KOEditorGeneral::initCategories(QWidget *parent, QBoxLayout *topLayout) { QBoxLayout *categoriesLayout = new QHBoxLayout( topLayout ); mCategoriesButton = new QPushButton(parent); mCategoriesButton->setText(i18n("Select Cate&gories...")); connect(mCategoriesButton,SIGNAL(clicked()),SIGNAL(openCategoryDialog())); categoriesLayout->addWidget(mCategoriesButton); mCategoriesLabel = new KSqueezedTextLabel(parent); mCategoriesLabel->setFrameStyle(QFrame::Panel|QFrame::Sunken); categoriesLayout->addWidget(mCategoriesLabel,1); } void KOEditorGeneral::initSecrecy(QWidget *parent, QBoxLayout *topLayout) { QBoxLayout *secrecyLayout = new QHBoxLayout( topLayout ); QLabel *secrecyLabel = new QLabel(i18n("Acc&ess:"),parent); secrecyLayout->addWidget(secrecyLabel); mSecrecyCombo = new QComboBox(parent); mSecrecyCombo->insertStringList(Incidence::secrecyList()); secrecyLayout->addWidget(mSecrecyCombo); secrecyLabel->setBuddy( mSecrecyCombo ); } void KOEditorGeneral::initDescription(QWidget *parent,QBoxLayout *topLayout) { mDescriptionEdit = new KTextEdit(parent); mDescriptionEdit->append(""); mDescriptionEdit->setReadOnly(false); mDescriptionEdit->setOverwriteMode(false); mDescriptionEdit->setWordWrap( KTextEdit::WidgetWidth ); mDescriptionEdit->setTabChangesFocus( true );; topLayout->addWidget(mDescriptionEdit); } void KOEditorGeneral::initAlarm(QWidget *parent,QBoxLayout *topLayout) { QBoxLayout *alarmLayout = new QHBoxLayout(topLayout); mAlarmBell = new QLabel(parent); mAlarmBell->setPixmap(KOGlobals::self()->smallIcon("bell")); alarmLayout->addWidget(mAlarmBell); mAlarmButton = new QCheckBox(i18n("&Reminder:"),parent); connect(mAlarmButton, SIGNAL(toggled(bool)), SLOT(enableAlarmEdit(bool))); alarmLayout->addWidget(mAlarmButton); mAlarmTimeEdit = new KRestrictedLine(parent, "alarmTimeEdit", "1234567890"); mAlarmTimeEdit->setText(""); alarmLayout->addWidget(mAlarmTimeEdit); mAlarmIncrCombo = new QComboBox(false, parent); mAlarmIncrCombo->insertItem(i18n("minute(s)")); mAlarmIncrCombo->insertItem(i18n("hour(s)")); mAlarmIncrCombo->insertItem(i18n("day(s)")); // mAlarmIncrCombo->setMinimumHeight(20); alarmLayout->addWidget(mAlarmIncrCombo); mAlarmSoundButton = new QPushButton(parent); mAlarmSoundButton->setPixmap(KOGlobals::self()->smallIcon("playsound")); mAlarmSoundButton->setToggleButton(true); QToolTip::add(mAlarmSoundButton, i18n("No sound set")); connect(mAlarmSoundButton, SIGNAL(clicked()), SLOT(pickAlarmSound())); alarmLayout->addWidget(mAlarmSoundButton); mAlarmProgramButton = new QPushButton(parent); mAlarmProgramButton->setPixmap(KOGlobals::self()->smallIcon("runprog")); mAlarmProgramButton->setToggleButton(true); QToolTip::add(mAlarmProgramButton, i18n("No program set")); connect(mAlarmProgramButton, SIGNAL(clicked()), SLOT(pickAlarmProgram())); alarmLayout->addWidget(mAlarmProgramButton); if ( KOPrefs::instance()->mCompactDialogs ) { mAlarmSoundButton->hide(); mAlarmProgramButton->hide(); } } void KOEditorGeneral::pickAlarmSound() { QString prefix = KGlobal::dirs()->findResourceDir("data", "korganizer/sounds/alert.wav"); prefix += "/korganizer/sounds/alert.wav"; if (!mAlarmSoundButton->isOn()) { mAlarmSound = ""; QToolTip::remove(mAlarmSoundButton); QToolTip::add(mAlarmSoundButton, i18n("No sound set")); } else { QString fileName(KFileDialog::getOpenFileName(prefix, i18n("*.wav|Wav Files"), 0)); if (!fileName.isEmpty()) { mAlarmSound = fileName; QToolTip::remove(mAlarmSoundButton); QString dispStr = i18n("Playing '%1'").arg(fileName); QToolTip::add(mAlarmSoundButton, dispStr); mAlarmProgramButton->setOn(false); } } if (mAlarmSound.isEmpty()) mAlarmSoundButton->setOn(false); } void KOEditorGeneral::pickAlarmProgram() { if (!mAlarmProgramButton->isOn()) { mAlarmProgram = ""; QToolTip::remove(mAlarmProgramButton); QToolTip::add(mAlarmProgramButton, i18n("No program set")); } else { QString fileName(KFileDialog::getOpenFileName(QString::null, QString::null, 0)); if (!fileName.isEmpty()) { mAlarmProgram = fileName; QToolTip::remove(mAlarmProgramButton); QString dispStr = i18n("Running '%1'").arg(fileName); QToolTip::add(mAlarmProgramButton, dispStr); mAlarmSoundButton->setOn(false); } } if (mAlarmProgram.isEmpty()) mAlarmProgramButton->setOn(false); } void KOEditorGeneral::enableAlarmEdit(bool enable) { mAlarmTimeEdit->setEnabled(enable); mAlarmSoundButton->setEnabled(enable); mAlarmProgramButton->setEnabled(enable); mAlarmIncrCombo->setEnabled(enable); } void KOEditorGeneral::disableAlarmEdit(bool disable) { enableAlarmEdit( !disable ); } void KOEditorGeneral::enableAlarm( bool enable ) { enableAlarmEdit( enable ); } void KOEditorGeneral::alarmDisable(bool disable) { if (!disable) { mAlarmBell->setEnabled(true); mAlarmButton->setEnabled(true); } else { mAlarmBell->setEnabled(false); mAlarmButton->setEnabled(false); mAlarmButton->setChecked(false); mAlarmTimeEdit->setEnabled(false); mAlarmSoundButton->setEnabled(false); mAlarmProgramButton->setEnabled(false); mAlarmIncrCombo->setEnabled(false); } } void KOEditorGeneral::setCategories(const QString &str) { mCategoriesLabel->setText(str); mCategories = str; } void KOEditorGeneral::setDefaults(bool allDay) { #if 0 mOwnerLabel->setText(i18n("Owner: ") + KOPrefs::instance()->fullName()); #endif enableAlarmEdit( !allDay ); // @TODO: Implement a KPrefsComboItem to solve this in a clean way. int alarmTime; int a[] = { 1,5,10,15,30 }; int index = KOPrefs::instance()->mAlarmTime; if (index < 0 || index > 4) { alarmTime = 0; } else { alarmTime = a[index]; } mAlarmTimeEdit->setText(QString::number(alarmTime)); enableAlarmEdit( false ); mSecrecyCombo->setCurrentItem(Incidence::SecrecyPublic); } void KOEditorGeneral::readIncidence(Incidence *event) { mSummaryEdit->setText(event->summary()); mLocationEdit->setText(event->location()); mDescriptionEdit->setText(event->description()); #if 0 // organizer information mOwnerLabel->setText(i18n("Owner: ") + event->organizer()); #endif enableAlarmEdit( event->isAlarmEnabled() ); if(!event->isAlarmEnabled()) { // @TODO: Implement a KPrefsComboItem to solve this in a clean way. int alarmTime; int a[] = { 1,5,10,15,30 }; int index = KOPrefs::instance()->mAlarmTime; if (index < 0 || index > 4) { alarmTime = 0; } else { alarmTime = a[index]; } mAlarmTimeEdit->setText(QString::number(alarmTime)); } mSecrecyCombo->setCurrentItem(event->secrecy()); // set up alarm stuff Alarm::List alarms = event->alarms(); Alarm::List::ConstIterator it; for( it = alarms.begin(); it != alarms.end(); ++it ) { Alarm *alarm = *it; int offset; if ( alarm->hasTime() ) { QDateTime t = alarm->time(); offset = event->dtStart().secsTo( t ); } else { offset = alarm->startOffset().asSeconds(); } offset = offset / -60; // make minutes if (offset % 60 == 0) { // divides evenly into hours? offset = offset / 60; mAlarmIncrCombo->setCurrentItem(1); } if (offset % 24 == 0) { // divides evenly into days? offset = offset / 24; mAlarmIncrCombo->setCurrentItem(2); } mAlarmTimeEdit->setText(QString::number( offset )); if (alarm->type() == Alarm::Procedure) { mAlarmProgram = alarm->programFile(); mAlarmProgramButton->setOn(true); QString dispStr = i18n("Running '%1'").arg(mAlarmProgram); QToolTip::add(mAlarmProgramButton, dispStr); } else if (alarm->type() == Alarm::Audio) { mAlarmSound = alarm->audioFile(); mAlarmSoundButton->setOn(true); QString dispStr = i18n("Playing '%1'").arg(mAlarmSound); QToolTip::add(mAlarmSoundButton, dispStr); } mAlarmButton->setChecked(alarm->enabled()); enableAlarmEdit( alarm->enabled() ); // @TODO: Deal with multiple alarms break; // For now, stop after the first alarm } setCategories(event->categoriesStr()); } void KOEditorGeneral::writeIncidence(Incidence *event) { // kdDebug(5850) << "KOEditorGeneral::writeEvent()" << endl; event->setSummary(mSummaryEdit->text()); event->setLocation(mLocationEdit->text()); event->setDescription(mDescriptionEdit->text()); event->setCategories(mCategories); event->setSecrecy(mSecrecyCombo->currentItem()); // alarm stuff if (mAlarmButton->isChecked()) { if (event->alarms().count() == 0) event->newAlarm(); Alarm::List alarms = event->alarms(); Alarm::List::ConstIterator it; for( it = alarms.begin(); it != alarms.end(); ++it ) { Alarm *alarm = *it; alarm->setEnabled(true); QString tmpStr = mAlarmTimeEdit->text(); int j = tmpStr.toInt() * -60; if (mAlarmIncrCombo->currentItem() == 1) j = j * 60; else if (mAlarmIncrCombo->currentItem() == 2) j = j * (60 * 24); alarm->setStartOffset( j ); if (!mAlarmSound.isEmpty() && mAlarmSoundButton->isOn()) alarm->setAudioAlarm(mAlarmSound); else alarm->setDisplayAlarm(QString::null); // @TODO: Make sure all alarm options are correctly set and don't erase other options! if (!mAlarmProgram.isEmpty() && mAlarmProgramButton->isOn()) alarm->setProcedureAlarm(mAlarmProgram); // @TODO: Deal with multiple alarms break; // For now, stop after the first alarm } } else { if ( !event->alarms().isEmpty() ) { Alarm *alarm = event->alarms().first(); alarm->setEnabled(false); alarm->setType(Alarm::Invalid); } } } void KOEditorGeneral::setSummary( const QString &text ) { mSummaryEdit->setText( text ); } void KOEditorGeneral::setDescription( const QString &text ) { mDescriptionEdit->setText( text ); } QObject *KOEditorGeneral::typeAheadReceiver() const { return mSummaryEdit; } <|endoftext|>
<commit_before>#include "rviz_ortho_view_controller/ortho_view_controller.h" #include <OgreCamera.h> #include <OgreSceneNode.h> #include <OgreViewport.h> #include <pluginlib/class_list_macros.h> #include <QEvent> #include <rviz/display_context.h> #include <rviz/geometry.h> #include <rviz/ogre_helpers/orthographic.h> #include <rviz/ogre_helpers/shape.h> #include <rviz/properties/enum_property.h> #include <rviz/properties/float_property.h> #include <rviz/properties/quaternion_property.h> #include <rviz/properties/vector_property.h> #include <rviz/viewport_mouse_event.h> #include <ros/console.h> namespace rviz_ortho_view_controller { static const double VIEW_DISTANCE = 500.0; static const double DEFAULT_SCALE = 100.0; static const char *STATUS = "<b>Left-Click:</b> Rotate PY. <b>Middle-Click:</b> Move XY. " "<b>Right-Click/Mouse Wheel:</b> Zoom. <b>Shift</b>: More options."; static const char *STATUS_SHIFT = "<b>Left-Click:</b> Rotate R. <b>Middle-Click:</b> Move XY. " "<b>Right-Click:</b> Move Z. <b>Mouse Wheel:</b> Zoom."; OrthoViewController::OrthoViewController() : plane_property_(new rviz::EnumProperty("Plane", "none", "Optionally lock the view to a plane", this)) , centre_property_(new rviz::VectorProperty("Centre", Ogre::Vector3::ZERO, "The focal point of the camera", this)) , orientation_property_(new rviz::QuaternionProperty("Orientation", Ogre::Quaternion::IDENTITY, "", this)) , scale_property_(new rviz::FloatProperty("Scale", DEFAULT_SCALE, "How much to scale up the scene", this)) { plane_property_->addOption("none", PLANE_NONE); plane_property_->addOption("XY", PLANE_XY); plane_property_->addOption("XZ", PLANE_XZ); plane_property_->addOption("YZ", PLANE_YZ); connect(plane_property_, SIGNAL(changed()), this, SLOT(onPlaneChanged())); } OrthoViewController::~OrthoViewController() { } void OrthoViewController::onInitialize() { FramePositionTrackingViewController::onInitialize(); camera_->setProjectionType(Ogre::PT_ORTHOGRAPHIC); // camera_->setFixedYawAxis(false); centre_shape_.reset(new rviz::Shape(rviz::Shape::Sphere, context_->getSceneManager(), target_scene_node_)); centre_shape_->setScale(Ogre::Vector3(0.05f, 0.05f, 0.01f)); centre_shape_->setColor(1.0f, 1.0f, 0.0f, 0.5f); centre_shape_->getRootNode()->setVisible(false); } void OrthoViewController::handleMouseEvent(rviz::ViewportMouseEvent &e) { bool moved = false; int dx = 0; int dy = 0; if (e.shift()) setStatus(STATUS_SHIFT); else setStatus(STATUS); if (e.type == QEvent::MouseButtonPress) { dragging_ = true; centre_shape_->getRootNode()->setVisible(true); } else if (e.type == QEvent::MouseButtonRelease) { dragging_ = false; centre_shape_->getRootNode()->setVisible(false); } else if (e.type == QEvent::MouseMove && dragging_) { moved = true; dx = e.x - e.last_x; dy = e.y - e.last_y; } bool rotate_z = e.shift() || getPlane() != PLANE_NONE; auto rotate_cursor = rotate_z ? Rotate2D : Rotate3D; auto rotate = [this](double angle, const Ogre::Vector3 &axis) { const auto &orientation = orientation_property_->getQuaternion(); Ogre::Quaternion q; q.FromAngleAxis(Ogre::Radian(angle), orientation * axis); q.normalise(); orientation_property_->setQuaternion(q * orientation); }; if (e.left()) { setCursor(rotate_cursor); if (rotate_z) { rotate(0.005 * dx, Ogre::Vector3::UNIT_Z); } else { rotate(-0.005 * dx, Ogre::Vector3::UNIT_Y); rotate(-0.005 * dy, Ogre::Vector3::UNIT_X); } } else if (e.middle() || (e.left() && e.shift())) { setCursor(MoveXY); auto scale = scale_property_->getFloat(); auto movement = orientation_property_->getQuaternion() * Ogre::Vector3(-dx / scale, dy / scale, 0); centre_property_->add(movement); } else if (e.right() && !e.shift()) { setCursor(Zoom); scale_property_->multiply(1 - 0.01 * dy); } else if (e.right() && e.shift()) { setCursor(MoveZ); auto scale = scale_property_->getFloat(); auto movement = orientation_property_->getQuaternion() * Ogre::Vector3(0, 0, dy / scale); centre_property_->add(movement); } else { setCursor(e.shift() ? MoveXY : rotate_cursor); } if (e.wheel_delta) { moved = true; scale_property_->multiply(1 + 0.001 * e.wheel_delta); } if (moved) { context_->queueRender(); emitConfigChanged(); } } void OrthoViewController::lookAt(const Ogre::Vector3 &p) { centre_property_->setVector(p - target_scene_node_->getPosition()); } void OrthoViewController::reset() { plane_property_->setString("none"); centre_property_->setVector(Ogre::Vector3::ZERO); orientation_property_->setQuaternion(Ogre::Quaternion::IDENTITY); scale_property_->setFloat(DEFAULT_SCALE); } void OrthoViewController::mimic(rviz::ViewController *source) { FramePositionTrackingViewController::mimic(source); if (auto *source_ortho = qobject_cast<OrthoViewController *>(source)) { plane_property_->setString(source_ortho->plane_property_->getString()); centre_property_->setVector(source_ortho->centre_property_->getVector()); orientation_property_->setQuaternion(source_ortho->orientation_property_->getQuaternion()); scale_property_->setFloat(source_ortho->scale_property_->getFloat()); } else { centre_property_->setVector(source->getCamera()->getPosition()); } } void OrthoViewController::update(float dt, float ros_dt) { FramePositionTrackingViewController::update(dt, ros_dt); // Build the projection matrix. auto scale = scale_property_->getFloat(); auto width = camera_->getViewport()->getActualWidth() / scale / 2; auto height = camera_->getViewport()->getActualHeight() / scale / 2; auto near = camera_->getNearClipDistance(); auto far = camera_->getFarClipDistance(); Ogre::Matrix4 projection; rviz::buildScaledOrthoMatrix(projection, -width, width, -height, height, near, far); camera_->setCustomProjectionMatrix(true, projection); // Set the camera pose. auto centre = centre_property_->getVector(); auto orientation = orientation_property_->getQuaternion(); camera_->setOrientation(orientation); camera_->setPosition(centre + orientation * Ogre::Vector3::UNIT_Z * VIEW_DISTANCE); centre_shape_->setPosition(centre); } void OrthoViewController::onPlaneChanged() { auto plane = getPlane(); bool locked = plane != PLANE_NONE; orientation_property_->setReadOnly(locked); orientation_property_->setHidden(locked); if (locked) { // TODO fix XZ and YZ planes. if (plane == PLANE_XY) orientation_property_->setQuaternion(Ogre::Quaternion::IDENTITY); if (plane == PLANE_XZ) orientation_property_->setQuaternion(Ogre::Quaternion::IDENTITY); else if (plane == PLANE_YZ) orientation_property_->setQuaternion(Ogre::Quaternion::IDENTITY); } } OrthoViewController::Plane OrthoViewController::getPlane() const { return static_cast<Plane>(plane_property_->getOptionInt()); } } PLUGINLIB_EXPORT_CLASS(rviz_ortho_view_controller::OrthoViewController, rviz::ViewController); <commit_msg>Fix frame lock<commit_after>#include "rviz_ortho_view_controller/ortho_view_controller.h" #include <OgreCamera.h> #include <OgreSceneNode.h> #include <OgreViewport.h> #include <pluginlib/class_list_macros.h> #include <QEvent> #include <rviz/display_context.h> #include <rviz/geometry.h> #include <rviz/ogre_helpers/orthographic.h> #include <rviz/ogre_helpers/shape.h> #include <rviz/properties/enum_property.h> #include <rviz/properties/float_property.h> #include <rviz/properties/quaternion_property.h> #include <rviz/properties/vector_property.h> #include <rviz/viewport_mouse_event.h> #include <ros/console.h> namespace rviz_ortho_view_controller { static const double VIEW_DISTANCE = 500.0; static const double DEFAULT_SCALE = 100.0; static const char *STATUS = "<b>Left-Click:</b> Rotate PY. <b>Middle-Click:</b> Move XY. " "<b>Right-Click/Mouse Wheel:</b> Zoom. <b>Shift</b>: More options."; static const char *STATUS_SHIFT = "<b>Left-Click:</b> Rotate R. <b>Middle-Click:</b> Move XY. " "<b>Right-Click:</b> Move Z. <b>Mouse Wheel:</b> Zoom."; OrthoViewController::OrthoViewController() : plane_property_(new rviz::EnumProperty("Plane", "none", "Optionally lock the view to a plane", this)) , centre_property_(new rviz::VectorProperty("Centre", Ogre::Vector3::ZERO, "The focal point of the camera", this)) , orientation_property_(new rviz::QuaternionProperty("Orientation", Ogre::Quaternion::IDENTITY, "", this)) , scale_property_(new rviz::FloatProperty("Scale", DEFAULT_SCALE, "How much to scale up the scene", this)) { plane_property_->addOption("none", PLANE_NONE); plane_property_->addOption("XY", PLANE_XY); plane_property_->addOption("XZ", PLANE_XZ); plane_property_->addOption("YZ", PLANE_YZ); connect(plane_property_, SIGNAL(changed()), this, SLOT(onPlaneChanged())); } OrthoViewController::~OrthoViewController() { } void OrthoViewController::onInitialize() { FramePositionTrackingViewController::onInitialize(); camera_->setProjectionType(Ogre::PT_ORTHOGRAPHIC); // camera_->setFixedYawAxis(false); centre_shape_.reset(new rviz::Shape(rviz::Shape::Sphere, context_->getSceneManager(), target_scene_node_)); centre_shape_->setScale(Ogre::Vector3(0.05f, 0.05f, 0.01f)); centre_shape_->setColor(1.0f, 1.0f, 0.0f, 0.5f); centre_shape_->getRootNode()->setVisible(false); } void OrthoViewController::handleMouseEvent(rviz::ViewportMouseEvent &e) { bool moved = false; int dx = 0; int dy = 0; if (e.shift()) setStatus(STATUS_SHIFT); else setStatus(STATUS); if (e.type == QEvent::MouseButtonPress) { dragging_ = true; centre_shape_->getRootNode()->setVisible(true); } else if (e.type == QEvent::MouseButtonRelease) { dragging_ = false; centre_shape_->getRootNode()->setVisible(false); } else if (e.type == QEvent::MouseMove && dragging_) { moved = true; dx = e.x - e.last_x; dy = e.y - e.last_y; } bool rotate_z = e.shift() || getPlane() != PLANE_NONE; auto rotate_cursor = rotate_z ? Rotate2D : Rotate3D; auto rotate = [this](double angle, const Ogre::Vector3 &axis) { const auto &orientation = orientation_property_->getQuaternion(); Ogre::Quaternion q; q.FromAngleAxis(Ogre::Radian(angle), orientation * axis); q.normalise(); orientation_property_->setQuaternion(q * orientation); }; if (e.left()) { setCursor(rotate_cursor); if (rotate_z) { rotate(0.005 * dx, Ogre::Vector3::UNIT_Z); } else { rotate(-0.005 * dx, Ogre::Vector3::UNIT_Y); rotate(-0.005 * dy, Ogre::Vector3::UNIT_X); } } else if (e.middle() || (e.left() && e.shift())) { setCursor(MoveXY); auto scale = scale_property_->getFloat(); auto movement = orientation_property_->getQuaternion() * Ogre::Vector3(-dx / scale, dy / scale, 0); centre_property_->add(movement); } else if (e.right() && !e.shift()) { setCursor(Zoom); scale_property_->multiply(1 - 0.01 * dy); } else if (e.right() && e.shift()) { setCursor(MoveZ); auto scale = scale_property_->getFloat(); auto movement = orientation_property_->getQuaternion() * Ogre::Vector3(0, 0, dy / scale); centre_property_->add(movement); } else { setCursor(e.shift() ? MoveXY : rotate_cursor); } if (e.wheel_delta) { moved = true; scale_property_->multiply(1 + 0.001 * e.wheel_delta); } if (moved) { context_->queueRender(); emitConfigChanged(); } } void OrthoViewController::lookAt(const Ogre::Vector3 &p) { centre_property_->setVector(p - target_scene_node_->getPosition()); } void OrthoViewController::reset() { plane_property_->setString("none"); centre_property_->setVector(Ogre::Vector3::ZERO); orientation_property_->setQuaternion(Ogre::Quaternion::IDENTITY); scale_property_->setFloat(DEFAULT_SCALE); } void OrthoViewController::mimic(rviz::ViewController *source) { FramePositionTrackingViewController::mimic(source); if (auto *source_ortho = qobject_cast<OrthoViewController *>(source)) { plane_property_->setString(source_ortho->plane_property_->getString()); centre_property_->setVector(source_ortho->centre_property_->getVector()); orientation_property_->setQuaternion(source_ortho->orientation_property_->getQuaternion()); scale_property_->setFloat(source_ortho->scale_property_->getFloat()); } else { centre_property_->setVector(source->getCamera()->getPosition()); } } void OrthoViewController::update(float dt, float ros_dt) { FramePositionTrackingViewController::update(dt, ros_dt); // Build the projection matrix. auto scale = scale_property_->getFloat(); auto width = camera_->getViewport()->getActualWidth() / scale / 2; auto height = camera_->getViewport()->getActualHeight() / scale / 2; auto near = camera_->getNearClipDistance(); auto far = camera_->getFarClipDistance(); Ogre::Matrix4 projection; rviz::buildScaledOrthoMatrix(projection, -width, width, -height, height, near, far); camera_->setCustomProjectionMatrix(true, projection); // Set the camera pose. auto centre = centre_property_->getVector(); auto orientation = orientation_property_->getQuaternion(); camera_->setOrientation(orientation); camera_->setPosition(centre + orientation * Ogre::Vector3::UNIT_Z * VIEW_DISTANCE); centre_shape_->setPosition(centre); } void OrthoViewController::onPlaneChanged() { auto plane = getPlane(); bool locked = plane != PLANE_NONE; orientation_property_->setReadOnly(locked); orientation_property_->setHidden(locked); if (locked) { auto orientation = Ogre::Quaternion::IDENTITY; // TODO fix XZ and YZ planes. if (plane == PLANE_XZ) orientation.FromAngleAxis(Ogre::Radian(M_PI / 2), Ogre::Vector3::UNIT_X); else if (plane == PLANE_YZ) orientation.FromAngleAxis(Ogre::Radian(M_PI / 2), Ogre::Vector3::UNIT_Y); orientation_property_->setQuaternion(orientation); } } OrthoViewController::Plane OrthoViewController::getPlane() const { return static_cast<Plane>(plane_property_->getOptionInt()); } } PLUGINLIB_EXPORT_CLASS(rviz_ortho_view_controller::OrthoViewController, rviz::ViewController); <|endoftext|>
<commit_before>//===- IListTest.cpp ------------------------------------------------------===// // // The Bold Project // // This file is distributed under the New BSD License. // See LICENSE for details. // //===----------------------------------------------------------------------===// #include <pat/pat.h> #include <bold/ADT/IList.h> #include <bold/ADT/IListNode.h> #include <vector> using namespace bold; namespace { struct IntNode : public IListNode<IntNode> { int value; }; } // anonymous namespace //===----------------------------------------------------------------------===// // Testcases //===----------------------------------------------------------------------===// PAT_F(IListTest, default_constructor) { IList<IntNode> int_list; ASSERT_TRUE(0 == int_list.size()); ASSERT_TRUE(int_list.empty()); ASSERT_TRUE(int_list.begin() == int_list.end()); } PAT_F( IListTest, push_back_test) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); ASSERT_FALSE(int_list.empty()); ASSERT_TRUE(2 == int_list.size()); ASSERT_TRUE(7 == int_list.front().value); ASSERT_TRUE(13 == int_list.back().value); } PAT_F( IListTest, push_front_test) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_front(&a); int_list.push_front(&b); ASSERT_FALSE(int_list.empty()); ASSERT_TRUE(2 == int_list.size()); ASSERT_TRUE(13 == int_list.front().value); ASSERT_TRUE(7 == int_list.back().value); } PAT_F( IListTest, iterate_list) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); IList<IntNode>::iterator it, iEnd = int_list.end(); int counter = 0; for (it = int_list.begin(); it != iEnd; ++it) { ++counter; } ASSERT_TRUE(2 == counter); it = int_list.begin(); ASSERT_TRUE(7 == it->value); ++it; ASSERT_TRUE(13 == it->value); ++it; ++it; ++it; ASSERT_TRUE(int_list.end() == it); } PAT_F( IListTest, reverse_iterate_list) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); IList<IntNode>::reverse_iterator it, iEnd = int_list.rend(); int counter = 0; for (it = int_list.rbegin(); it != iEnd; ++it) { ++counter; } ASSERT_TRUE(2 == counter); it = int_list.rbegin(); ASSERT_TRUE(13 == it->value); ++it; ASSERT_TRUE(7 == it->value); ++it; ASSERT_TRUE(int_list.rend() == it); } PAT_F( IListTest, pop_front_test ) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); ASSERT_TRUE(2 == int_list.size()); int_list.pop_front(); ASSERT_TRUE(1 == int_list.size()); ASSERT_TRUE(13 == int_list.front().value); int_list.pop_front(); ASSERT_TRUE(0 == int_list.size()); } PAT_F( IListTest, pop_back_test ) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); ASSERT_TRUE(2 == int_list.size()); int_list.pop_back(); ASSERT_TRUE(1 == int_list.size()); ASSERT_TRUE(7 == int_list.back().value); int_list.pop_front(); ASSERT_TRUE(0 == int_list.size()); } PAT_F( IListTest, clear_test) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); ASSERT_TRUE(2 == int_list.size()); int_list.clear(); ASSERT_TRUE(0 == int_list.size()); ASSERT_TRUE(NULL == a.getPrev()); ASSERT_TRUE(NULL == a.getNext()); ASSERT_TRUE(NULL == b.getPrev()); ASSERT_TRUE(NULL == b.getNext()); } PAT_F( IListTest, swap_test) { IntNode a; IntNode b; IntNode c; IntNode d; a.value = 7; b.value = 13; c.value = 17; d.value = 19; IList<IntNode> prime_list; prime_list.push_back(&a); prime_list.push_back(&b); prime_list.push_back(&c); prime_list.push_back(&d); IntNode x; IntNode y; IntNode z; x.value = 2; y.value = 4; z.value = 6; IList<IntNode> even_list; even_list.push_back(&x); even_list.push_back(&y); even_list.push_back(&z); ASSERT_TRUE(4 == prime_list.size()); ASSERT_TRUE(3 == even_list.size()); prime_list.swap(even_list); ASSERT_TRUE(3 == prime_list.size()); ASSERT_TRUE(4 == even_list.size()); ASSERT_TRUE(2 == prime_list.front().value); } PAT_F( IListTest, insert_in_the_middle_test) { IntNode a; IntNode b; IntNode c; IntNode d; a.value = 7; b.value = 13; c.value = 17; d.value = 19; IList<IntNode> prime_list; prime_list.push_back(&a); prime_list.push_back(&b); prime_list.push_back(&c); prime_list.push_back(&d); IntNode x; x.value = 2; IList<IntNode>::iterator it = prime_list.begin(); ++it; ++it; prime_list.insert(it, &x); ASSERT_TRUE(5 == prime_list.size()); ASSERT_TRUE(7 == prime_list.front().value); ASSERT_TRUE(19 == prime_list.back().value); ASSERT_TRUE(17 == it->value); --it; ASSERT_TRUE(2 == it->value); } PAT_F( IListTest, erase_in_the_middle_test) { IntNode a; IntNode b; IntNode c; IntNode d; a.value = 7; b.value = 13; c.value = 17; d.value = 19; IList<IntNode> prime_list; prime_list.push_back(&a); prime_list.push_back(&b); prime_list.push_back(&c); prime_list.push_back(&d); IList<IntNode>::iterator it = prime_list.begin(); ++it; ++it; it = prime_list.erase(it); ASSERT_TRUE(3 == prime_list.size()); ASSERT_TRUE(7 == prime_list.front().value); ASSERT_TRUE(19 == prime_list.back().value); ASSERT_TRUE(19 == it->value); --it; ASSERT_TRUE(13 == it->value); } PAT_F( IListTest, constant_iterator_test) { IntNode a; IntNode b; IntNode c; IntNode d; a.value = 7; b.value = 13; c.value = 17; d.value = 19; IList<IntNode> prime_list; prime_list.push_back(&a); prime_list.push_back(&b); prime_list.push_back(&c); prime_list.push_back(&d); IList<IntNode>::const_iterator it = const_cast<const IList<IntNode>* >(&prime_list)->begin(); ++it; ++it; ASSERT_TRUE(4 == prime_list.size()); ASSERT_TRUE(7 == prime_list.front().value); ASSERT_TRUE(19 == prime_list.back().value); ASSERT_TRUE(17 == it->value); --it; ASSERT_TRUE(13 == it->value); } <commit_msg>Replace some TRUE assertions by EQ assertions.<commit_after>//===- IListTest.cpp ------------------------------------------------------===// // // The Bold Project // // This file is distributed under the New BSD License. // See LICENSE for details. // //===----------------------------------------------------------------------===// #include <pat/pat.h> #include <bold/ADT/IList.h> #include <bold/ADT/IListNode.h> #include <vector> using namespace bold; namespace { struct IntNode : public IListNode<IntNode> { using IListNode<IntNode>::Base; int value; }; } // anonymous namespace //===----------------------------------------------------------------------===// // Testcases //===----------------------------------------------------------------------===// PAT_F(IListTest, default_constructor) { IList<IntNode> int_list; ASSERT_EQ(int_list.size(), 0); ASSERT_TRUE(int_list.empty()); ASSERT_TRUE(int_list.begin() == int_list.end()); } PAT_F( IListTest, push_back_test) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); ASSERT_FALSE(int_list.empty()); ASSERT_TRUE(2 == int_list.size()); ASSERT_TRUE(7 == int_list.front().value); ASSERT_TRUE(13 == int_list.back().value); } PAT_F( IListTest, push_front_test) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_front(&a); int_list.push_front(&b); ASSERT_FALSE(int_list.empty()); ASSERT_TRUE(2 == int_list.size()); ASSERT_TRUE(13 == int_list.front().value); ASSERT_TRUE(7 == int_list.back().value); } PAT_F( IListTest, iterate_list) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); IList<IntNode>::iterator it, iEnd = int_list.end(); int counter = 0; for (it = int_list.begin(); it != iEnd; ++it) { ++counter; } ASSERT_TRUE(2 == counter); it = int_list.begin(); ASSERT_TRUE(7 == it->value); ++it; ASSERT_TRUE(13 == it->value); ++it; ++it; ++it; ASSERT_TRUE(int_list.end() == it); } PAT_F( IListTest, reverse_iterate_list) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); IList<IntNode>::reverse_iterator it, iEnd = int_list.rend(); int counter = 0; for (it = int_list.rbegin(); it != iEnd; ++it) { ++counter; } ASSERT_TRUE(2 == counter); it = int_list.rbegin(); ASSERT_TRUE(13 == it->value); ++it; ASSERT_TRUE(7 == it->value); ++it; ASSERT_TRUE(int_list.rend() == it); } PAT_F( IListTest, pop_front_test ) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); ASSERT_TRUE(2 == int_list.size()); int_list.pop_front(); ASSERT_TRUE(1 == int_list.size()); ASSERT_TRUE(13 == int_list.front().value); int_list.pop_front(); ASSERT_TRUE(0 == int_list.size()); } PAT_F( IListTest, pop_back_test ) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); ASSERT_TRUE(2 == int_list.size()); int_list.pop_back(); ASSERT_TRUE(1 == int_list.size()); ASSERT_TRUE(7 == int_list.back().value); int_list.pop_front(); ASSERT_TRUE(0 == int_list.size()); } PAT_F( IListTest, clear_test) { IntNode a; IntNode b; a.value = 7; b.value = 13; IList<IntNode> int_list; int_list.push_back(&a); int_list.push_back(&b); ASSERT_TRUE(2 == int_list.size()); int_list.clear(); ASSERT_TRUE(0 == int_list.size()); ASSERT_TRUE(NULL == a.getPrev()); ASSERT_TRUE(NULL == a.getNext()); ASSERT_TRUE(NULL == b.getPrev()); ASSERT_TRUE(NULL == b.getNext()); } PAT_F( IListTest, swap_test) { IntNode a; IntNode b; IntNode c; IntNode d; a.value = 7; b.value = 13; c.value = 17; d.value = 19; IList<IntNode> prime_list; prime_list.push_back(&a); prime_list.push_back(&b); prime_list.push_back(&c); prime_list.push_back(&d); IntNode x; IntNode y; IntNode z; x.value = 2; y.value = 4; z.value = 6; IList<IntNode> even_list; even_list.push_back(&x); even_list.push_back(&y); even_list.push_back(&z); ASSERT_EQ(4, prime_list.size()); ASSERT_EQ(3, even_list.size()); prime_list.swap(even_list); ASSERT_EQ(prime_list.size(), 3); ASSERT_EQ(even_list.size(), 4); ASSERT_EQ(prime_list.front().value, 2); } PAT_F( IListTest, insert_in_the_middle_test) { IntNode a; IntNode b; IntNode c; IntNode d; a.value = 7; b.value = 13; c.value = 17; d.value = 19; IList<IntNode> prime_list; prime_list.push_back(&a); prime_list.push_back(&b); prime_list.push_back(&c); prime_list.push_back(&d); IntNode x; x.value = 2; IList<IntNode>::iterator it = prime_list.begin(); ++it; ++it; prime_list.insert(it, &x); ASSERT_TRUE(5 == prime_list.size()); ASSERT_TRUE(7 == prime_list.front().value); ASSERT_TRUE(19 == prime_list.back().value); ASSERT_TRUE(17 == it->value); --it; ASSERT_TRUE(2 == it->value); } PAT_F( IListTest, erase_in_the_middle_test) { IntNode a; IntNode b; IntNode c; IntNode d; a.value = 7; b.value = 13; c.value = 17; d.value = 19; IList<IntNode> prime_list; prime_list.push_back(&a); prime_list.push_back(&b); prime_list.push_back(&c); prime_list.push_back(&d); IList<IntNode>::iterator it = prime_list.begin(); ++it; ++it; it = prime_list.erase(it); ASSERT_TRUE(3 == prime_list.size()); ASSERT_TRUE(7 == prime_list.front().value); ASSERT_TRUE(19 == prime_list.back().value); ASSERT_TRUE(19 == it->value); --it; ASSERT_TRUE(13 == it->value); } PAT_F( IListTest, constant_iterator_test) { IntNode a; IntNode b; IntNode c; IntNode d; a.value = 7; b.value = 13; c.value = 17; d.value = 19; IList<IntNode> prime_list; prime_list.push_back(&a); prime_list.push_back(&b); prime_list.push_back(&c); prime_list.push_back(&d); IList<IntNode>::const_iterator it = const_cast<const IList<IntNode>* >(&prime_list)->begin(); ++it; ++it; ASSERT_TRUE(4 == prime_list.size()); ASSERT_TRUE(7 == prime_list.front().value); ASSERT_TRUE(19 == prime_list.back().value); ASSERT_TRUE(17 == it->value); --it; ASSERT_TRUE(13 == it->value); } <|endoftext|>
<commit_before>#ifndef VIENNAGRID_STORAGE_INSERTER_HPP #define VIENNAGRID_STORAGE_INSERTER_HPP //#include "viennagrid/storage/reference.hpp" #include "viennagrid/storage/container_collection.hpp" #include "viennagrid/storage/container_collection_element.hpp" namespace viennagrid { namespace storage { template<typename container_collection_type> class inserter_base_t { public: inserter_base_t(container_collection_type & _collection) : collection(_collection) {} protected: container_collection_type & collection; }; template<typename container_collection_type, typename id_generator_type__> class physical_inserter_t { public: typedef container_collection_type physical_container_collection_type; typedef id_generator_type__ id_generator_type; physical_inserter_t(container_collection_type & _collection, id_generator_type id_generator__) : collection(_collection), id_generator(id_generator__) {} template<typename value_type, typename inserter_type> std::pair< typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type, bool > physical_insert( value_type element, inserter_type & inserter ) { typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::iterator iterator; typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type container_type; typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_tag hook_tag; typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type hook_type; container_type & container = viennagrid::storage::container_collection::get< value_type >( collection ); if ( !container.is_present( element ) ) viennagrid::storage::id::set_id(element, id_generator( viennameta::tag<value_type>() ) ); std::pair<hook_type, bool> ret = viennagrid::storage::container_collection::get< value_type >( collection ).insert( element ); //container.dereference_hook(ret.first).set_container(collection); viennagrid::storage::container_collection_element::insert_callback( container.dereference_hook(ret.first), ret.second, inserter, collection ); //viennagrid::storage::container_collection_element::insert_callback(*ret.first, ret.second, inserter); inserter.hook_insert( ret.first, viennameta::tag<value_type>() ); return ret; } template<typename hook_type, typename value_type> void hook_insert( hook_type ref, viennameta::tag<value_type> ) {} template<typename value_type> std::pair< typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type, bool > operator()( const value_type & element ) { return physical_insert( element, *this ); } private: container_collection_type & collection; id_generator_type id_generator; }; template<typename view_collection_type, typename dependend_inserter_type> class recursive_inserter_t : public dependend_inserter_type { public: typedef dependend_inserter_type base; recursive_inserter_t(view_collection_type & _collection, const dependend_inserter_type & dependend_inserter) : dependend_inserter_type(dependend_inserter), view_collection(_collection) {} template<typename hook_type, typename value_type> void hook_insert( hook_type ref, viennameta::tag<value_type> ) { viennagrid::storage::container_collection::hook_or_ignore( view_collection, ref, viennameta::tag<value_type>() ); base::hook_insert( ref, viennameta::tag<value_type>() ); } typedef typename base::physical_container_collection_type physical_container_collection_type; template<typename value_type, typename inserter_type> std::pair< typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type, bool > physical_insert( const value_type & element, inserter_type & inserter ) { return base::physical_insert( element, inserter ); } template<typename value_type> std::pair< typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type, bool > operator()( const value_type & element ) { return physical_insert( element, *this ); } private: view_collection_type & view_collection; }; namespace inserter { //typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::pointer_reference_tag ) pointer_reference_config; //typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::iterator_reference_tag ) iterator_reference_config; template<typename dependend_inserter_type, typename container_collection_type> recursive_inserter_t<container_collection_type, dependend_inserter_type> get_recursive( const dependend_inserter_type & inserter, container_collection_type & collection ) { return recursive_inserter_t<container_collection_type, dependend_inserter_type>(inserter, collection); } } namespace result_of { template<typename container_collection_type, typename dependend_inserter_type> struct recursive_inserter { typedef recursive_inserter_t<container_collection_type, dependend_inserter_type> type; }; template<typename container_collection_type, typename id_generator_type> struct physical_inserter { typedef physical_inserter_t<container_collection_type, id_generator_type> type; }; } } } #endif<commit_msg>callback doesn't take a container collection any more added getter for physical container collection<commit_after>#ifndef VIENNAGRID_STORAGE_INSERTER_HPP #define VIENNAGRID_STORAGE_INSERTER_HPP //#include "viennagrid/storage/reference.hpp" #include "viennagrid/storage/container_collection.hpp" #include "viennagrid/storage/container_collection_element.hpp" namespace viennagrid { namespace storage { template<typename container_collection_type> class inserter_base_t { public: inserter_base_t(container_collection_type & _collection) : collection(_collection) {} protected: container_collection_type & collection; }; template<typename container_collection_type, typename id_generator_type__> class physical_inserter_t { public: typedef container_collection_type physical_container_collection_type; typedef id_generator_type__ id_generator_type; physical_inserter_t(container_collection_type & _collection, id_generator_type id_generator__) : collection(_collection), id_generator(id_generator__) {} template<typename value_type, typename inserter_type> std::pair< typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type, bool > physical_insert( value_type element, inserter_type & inserter ) { typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::iterator iterator; typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type container_type; typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_tag hook_tag; typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type hook_type; container_type & container = viennagrid::storage::container_collection::get< value_type >( collection ); if ( !container.is_present( element ) ) viennagrid::storage::id::set_id(element, id_generator( viennameta::tag<value_type>() ) ); std::pair<hook_type, bool> ret = viennagrid::storage::container_collection::get< value_type >( collection ).insert( element ); //container.dereference_hook(ret.first).set_container(collection); viennagrid::storage::container_collection_element::insert_callback( container.dereference_hook(ret.first), ret.second, inserter); //viennagrid::storage::container_collection_element::insert_callback(*ret.first, ret.second, inserter); inserter.hook_insert( ret.first, viennameta::tag<value_type>() ); return ret; } template<typename hook_type, typename value_type> void hook_insert( hook_type ref, viennameta::tag<value_type> ) {} template<typename value_type> std::pair< typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type, bool > operator()( const value_type & element ) { return physical_insert( element, *this ); } container_collection_type & get_physical_container_collection() { return collection; } private: container_collection_type & collection; id_generator_type id_generator; }; template<typename view_collection_type, typename dependend_inserter_type> class recursive_inserter_t : public dependend_inserter_type { public: typedef dependend_inserter_type base; recursive_inserter_t(view_collection_type & _collection, const dependend_inserter_type & dependend_inserter) : dependend_inserter_type(dependend_inserter), view_collection(_collection) {} template<typename hook_type, typename value_type> void hook_insert( hook_type ref, viennameta::tag<value_type> ) { viennagrid::storage::container_collection::hook_or_ignore( view_collection, ref, viennameta::tag<value_type>() ); base::hook_insert( ref, viennameta::tag<value_type>() ); } typedef typename base::physical_container_collection_type physical_container_collection_type; template<typename value_type, typename inserter_type> std::pair< typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type, bool > physical_insert( const value_type & element, inserter_type & inserter ) { return base::physical_insert( element, inserter ); } template<typename value_type> std::pair< typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type, bool > operator()( const value_type & element ) { return physical_insert( element, *this ); } private: view_collection_type & view_collection; }; namespace inserter { //typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::pointer_reference_tag ) pointer_reference_config; //typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::iterator_reference_tag ) iterator_reference_config; template<typename dependend_inserter_type, typename container_collection_type> recursive_inserter_t<container_collection_type, dependend_inserter_type> get_recursive( const dependend_inserter_type & inserter, container_collection_type & collection ) { return recursive_inserter_t<container_collection_type, dependend_inserter_type>(inserter, collection); } } namespace result_of { template<typename container_collection_type, typename dependend_inserter_type> struct recursive_inserter { typedef recursive_inserter_t<container_collection_type, dependend_inserter_type> type; }; template<typename container_collection_type, typename id_generator_type> struct physical_inserter { typedef physical_inserter_t<container_collection_type, id_generator_type> type; }; } } } #endif<|endoftext|>
<commit_before>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/util.h> // for wxExAlignText const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { std::map< int, std::set<wxString> >::const_iterator it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { wxString keywords; for ( std::set<wxString>::const_iterator it = kset.begin(); it != kset.end(); ++it) { keywords += *it + " "; } return keywords.Trim(); // remove the ending space } bool wxExLexer::IsKeyword(const wxString& word) const { std::set<wxString>::const_iterator it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { for ( std::set<wxString>::const_iterator it = m_Keywords.begin(); it != m_Keywords.end(); ++it) { if (it->Upper().StartsWith(word.Upper())) { return true; } } return false; } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxUniChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const int fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } bool wxExLexer::SetKeywords(const wxString& value) { if (!m_Keywords.empty()) { m_Keywords.clear(); } if (!m_KeywordsSet.empty()) { m_KeywordsSet.clear(); } std::set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const int new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } int wxExLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <commit_msg>don't use Upper for auto completion<commit_after>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/util.h> // for wxExAlignText const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { std::map< int, std::set<wxString> >::const_iterator it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { wxString keywords; for ( std::set<wxString>::const_iterator it = kset.begin(); it != kset.end(); ++it) { keywords += *it + " "; } return keywords.Trim(); // remove the ending space } bool wxExLexer::IsKeyword(const wxString& word) const { std::set<wxString>::const_iterator it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { for ( std::set<wxString>::const_iterator it = m_Keywords.begin(); it != m_Keywords.end(); ++it) { if (it->StartsWith(word)) { return true; } } return false; } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxUniChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const int fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } bool wxExLexer::SetKeywords(const wxString& value) { if (!m_Keywords.empty()) { m_Keywords.clear(); } if (!m_KeywordsSet.empty()) { m_KeywordsSet.clear(); } std::set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const int new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } int wxExLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <|endoftext|>
<commit_before>//============================================================================== // Single cell view information solvers widget //============================================================================== #include "cellmlfileruntime.h" #include "coreutils.h" #include "singlecellviewinformationsolverswidget.h" #include "singlecellviewsimulation.h" //============================================================================== namespace OpenCOR { namespace SingleCellView { //============================================================================== SingleCellViewInformationSolversWidgetData::SingleCellViewInformationSolversWidgetData(Core::Property *pSolversProperty, Core::Property *pSolversListProperty, const QMap<QString, Core::Properties> &pSolversProperties) : mSolversProperty(pSolversProperty), mSolversListProperty(pSolversListProperty), mSolversProperties(pSolversProperties) { } //============================================================================== Core::Property * SingleCellViewInformationSolversWidgetData::solversProperty() const { // Return our solvers property return mSolversProperty; } //============================================================================== Core::Property * SingleCellViewInformationSolversWidgetData::solversListProperty() const { // Return our solvers list property return mSolversListProperty; } //============================================================================== QMap<QString, Core::Properties> SingleCellViewInformationSolversWidgetData::solversProperties() const { // Return our solvers properties return mSolversProperties; } //============================================================================== SingleCellViewInformationSolversWidget::SingleCellViewInformationSolversWidget(QWidget *pParent) : PropertyEditorWidget(true, pParent), mOdeSolverData(0), mDaeSolverData(0), mNlaSolverData(0), mGuiStates(QMap<QString, Core::PropertyEditorWidgetGuiState *>()), mDefaultGuiState(0), mDescriptions(QMap<Core::Property *, Descriptions>()) { // Update the tool tip of any property which value gets changed by the user connect(this, SIGNAL(propertyChanged(Core::Property *)), this, SLOT(updatePropertyToolTip(Core::Property *))); } //============================================================================== SingleCellViewInformationSolversWidget::~SingleCellViewInformationSolversWidget() { // Delete some internal objects delete mOdeSolverData; delete mDaeSolverData; delete mNlaSolverData; resetAllGuiStates(); } //============================================================================== void SingleCellViewInformationSolversWidget::retranslateUi() { // Update our property names if (mOdeSolverData) { setStringPropertyItem(mOdeSolverData->solversProperty()->name(), tr("ODE solver")); setStringPropertyItem(mOdeSolverData->solversListProperty()->name(), tr("Name")); mOdeSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available")); } if (mDaeSolverData) { setStringPropertyItem(mDaeSolverData->solversProperty()->name(), tr("DAE solver")); setStringPropertyItem(mDaeSolverData->solversListProperty()->name(), tr("Name")); mDaeSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available")); } if (mNlaSolverData) { setStringPropertyItem(mNlaSolverData->solversProperty()->name(), tr("NLA solver")); setStringPropertyItem(mNlaSolverData->solversListProperty()->name(), tr("Name")); mNlaSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available")); } // Update the name of our various properties, should they have a description // associated with them // Note: this is effectively to have the description of our solvers' // properties properly updated... foreach (Core::Property *property, properties()) if (mDescriptions.contains(property)) { // The property has a description associated with it, so retrieve // the version, if any, which corresponds to our current locale Descriptions descriptions = mDescriptions.value(property); QString description = descriptions.value(Core::locale()); if (description.isEmpty()) // No description exists for the current locale, so retrieve // the english description (which, hopefully, should exist) description = descriptions.value("en"); // Set the name of the property to the description setStringPropertyItem(property->name(), description); } // Retranslate the tool tip of all our solvers' properties updateToolTips(); // Default retranslation // Note: we must do it last since we set the empty list value of some // properties above... PropertyEditorWidget::retranslateUi(); } //============================================================================== void SingleCellViewInformationSolversWidget::updatePropertyToolTip(Core::Property *pProperty) { // Update the tool tip of the given property if (pProperty->name()->type() != Core::PropertyItem::Section) { // We are dealing with a property (as opposed to a section), so we can // update its tool tip QString propertyToolTip = pProperty->name()->text()+tr(": "); if (pProperty->value()->text().isEmpty()) propertyToolTip += "???"; else propertyToolTip += pProperty->value()->text(); if (!pProperty->unit()->text().isEmpty()) propertyToolTip += " "+pProperty->unit()->text(); pProperty->name()->setToolTip(propertyToolTip); pProperty->value()->setToolTip(propertyToolTip); pProperty->unit()->setToolTip(propertyToolTip); } } //============================================================================== void SingleCellViewInformationSolversWidget::updateToolTips() { // Update the tool tip of all our solvers' properties foreach (Core::Property *property, properties()) updatePropertyToolTip(property); } //============================================================================== void SingleCellViewInformationSolversWidget::resetAllGuiStates() { // Reset all our GUI states including our default one foreach (Core::PropertyEditorWidgetGuiState *guiState, mGuiStates) delete guiState; mGuiStates.clear(); delete mDefaultGuiState; } //============================================================================== SingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces, const Solver::Type &pSolverType) { // Make sure that we have at least one solver interface if (pSolverInterfaces.isEmpty()) return 0; // Add our section property Core::Property *solversProperty = addSectionProperty(); // Add our list property for the solvers Core::Property *solversListProperty = addListProperty(QString(), solversProperty); // Retrieve the name of the solvers which type is the one in whhich we are // interested QStringList solvers = QStringList(); QMap<QString, Core::Properties> solversProperties = QMap<QString, Core::Properties>(); foreach (SolverInterface *solverInterface, pSolverInterfaces) if (solverInterface->type() == pSolverType) { // Keep track of the solver's name solvers << solverInterface->name(); // Add the solver's properties Core::Property *property; Core::Properties properties = Core::Properties(); foreach (const Solver::Property &solverInterfaceProperty, solverInterface->properties()) { // Add the solver's property and set its default value switch (solverInterfaceProperty.type()) { case Solver::Double: property = addDoubleProperty(solverInterfaceProperty.id(), solversProperty); property->setEditable(true); setDoublePropertyItem(property->value(), solverInterfaceProperty.defaultValue().toDouble()); break; default: // Solver::Integer property = addIntegerProperty(solverInterfaceProperty.id(), solversProperty); property->setEditable(true); setIntegerPropertyItem(property->value(), solverInterfaceProperty.defaultValue().toInt()); } // Set the solver's property's 'unit', if needed if (solverInterfaceProperty.hasVoiUnit()) setStringPropertyItem(property->unit(), "???"); // Note: to assign a non-empty string to our unit item is // just a way for us to make sure that the property's // will get initialised (see setPropertiesUnit())... // Keep track of the solver's property properties << property; // Keep track of the solver's property's descriptions mDescriptions.insert(property, solverInterfaceProperty.descriptions()); } // Keep track of the solver's properties solversProperties.insert(solverInterface->name(), properties); } // Sort our list of solvers solvers.sort(); // Add the list of solvers to our list property value item solversListProperty->value()->setList(solvers); // Keep track of changes to list properties connect(this, SIGNAL(listPropertyChanged(const QString &)), this, SLOT(solverChanged(const QString &))); // Return our solver data return new SingleCellViewInformationSolversWidgetData(solversProperty, solversListProperty, solversProperties); } //============================================================================== void SingleCellViewInformationSolversWidget::setSolverInterfaces(const SolverInterfaces &pSolverInterfaces) { // Remove all our properties removeAllProperties(); // Add properties for our different solvers delete mOdeSolverData; delete mDaeSolverData; delete mNlaSolverData; mDescriptions.clear(); mOdeSolverData = addSolverProperties(pSolverInterfaces, Solver::Ode); mDaeSolverData = addSolverProperties(pSolverInterfaces, Solver::Dae); mNlaSolverData = addSolverProperties(pSolverInterfaces, Solver::Nla); // Show/hide the relevant properties if (mOdeSolverData) doSolverChanged(mOdeSolverData, mOdeSolverData->solversListProperty()->value()->text(), true); if (mDaeSolverData) doSolverChanged(mDaeSolverData, mDaeSolverData->solversListProperty()->value()->text(), true); if (mNlaSolverData) doSolverChanged(mNlaSolverData, mNlaSolverData->solversListProperty()->value()->text(), true); // Expand all our properties expandAll(); // Clear any track of previous GUI states and retrieve our default GUI state resetAllGuiStates(); mDefaultGuiState = guiState(); } //============================================================================== void SingleCellViewInformationSolversWidget::setPropertiesUnit(SingleCellViewInformationSolversWidgetData *pSolverData, const QString &pVoiUnit) { // Make sure that we have some solver's data if (!pSolverData) return; // Go through the solvers' properties and set the unit of the relevant ones foreach (const Core::Properties &properties, pSolverData->solversProperties()) foreach (Core::Property *property, properties) if (!property->unit()->text().isEmpty()) setStringPropertyItem(property->unit(), pVoiUnit); } //============================================================================== void SingleCellViewInformationSolversWidget::initialize(const QString &pFileName, CellMLSupport::CellmlFileRuntime *pRuntime, SingleCellViewSimulationData *pSimulationData) { // Retrieve and initialise our GUI state setGuiState(mGuiStates.contains(pFileName)? mGuiStates.value(pFileName): mDefaultGuiState); // Make sure that the CellML file runtime is valid if (pRuntime->isValid()) { // Show/hide the ODE/DAE solver information if (mOdeSolverData) setPropertyVisible(mOdeSolverData->solversProperty(), pRuntime->needOdeSolver()); if (mDaeSolverData) setPropertyVisible(mDaeSolverData->solversProperty(), pRuntime->needDaeSolver()); // Show/hide the NLA solver information if (mNlaSolverData) setPropertyVisible(mNlaSolverData->solversProperty(), pRuntime->needNlaSolver()); } // Set the unit of our different properties, if needed QString voiUnit = pRuntime->variableOfIntegration()->unit(); setPropertiesUnit(mOdeSolverData, voiUnit); setPropertiesUnit(mDaeSolverData, voiUnit); setPropertiesUnit(mNlaSolverData, voiUnit); // Update the tool tip of all our solvers' properties updateToolTips(); // Initialise our simulation's NLA solver's properties, so that we can then // properly reset our simulation the first time round if (mNlaSolverData) { pSimulationData->setNlaSolverName(mNlaSolverData->solversListProperty()->value()->text(), false); foreach (Core::Property *property, mNlaSolverData->solversProperties().value(pSimulationData->nlaSolverName())) pSimulationData->addNlaSolverProperty(property->id(), (property->value()->type() == Core::PropertyItem::Integer)? Core::PropertyEditorWidget::integerPropertyItem(property->value()): Core::PropertyEditorWidget::doublePropertyItem(property->value()), false); } } //============================================================================== void SingleCellViewInformationSolversWidget::backup(const QString &pFileName) { // Keep track of our GUI state mGuiStates.insert(pFileName, guiState()); } //============================================================================== void SingleCellViewInformationSolversWidget::finalize(const QString &pFileName) { // Remove any track of our GUI state mGuiStates.remove(pFileName); } //============================================================================== QStringList SingleCellViewInformationSolversWidget::odeSolvers() const { // Return the available ODE solvers, if any return mOdeSolverData?mOdeSolverData->solversListProperty()->value()->list():QStringList(); } //============================================================================== QStringList SingleCellViewInformationSolversWidget::daeSolvers() const { // Return the available DAE solvers, if any return mDaeSolverData?mDaeSolverData->solversListProperty()->value()->list():QStringList(); } //============================================================================== QStringList SingleCellViewInformationSolversWidget::nlaSolvers() const { // Return the available NLA solvers, if any return mNlaSolverData?mNlaSolverData->solversListProperty()->value()->list():QStringList(); } //============================================================================== SingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::odeSolverData() const { // Return our ODE solver data return mOdeSolverData; } //============================================================================== SingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::daeSolverData() const { // Return our DAE solver data return mDaeSolverData; } //============================================================================== SingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::nlaSolverData() const { // Return our NLA solver data return mNlaSolverData; } //============================================================================== bool SingleCellViewInformationSolversWidget::doSolverChanged(SingleCellViewInformationSolversWidgetData *pSolverData, const QString &pSolverName, const bool &pForceHandling) { // By default, we don't handle the change in the list property bool res = false; // Check whether the list property that got changed is the one we are after if ( (pSolverData->solversListProperty() == currentProperty()) || pForceHandling) { // It is the list property we are after or we want to force the // handling, so update our result res = true; // Go through the different properties for the given type of solver and // show/hide whatever needs showing/hiding for (QMap<QString, Core::Properties>::ConstIterator iter = pSolverData->solversProperties().constBegin(), iterEnd = pSolverData->solversProperties().constEnd(); iter != iterEnd; ++iter) { bool propertyVisible = !iter.key().compare(pSolverName); foreach (Core::Property *property, iter.value()) setPropertyVisible(property, propertyVisible); } } // Return our result return res; } //============================================================================== void SingleCellViewInformationSolversWidget::solverChanged(const QString &pValue) { // Try, for the ODE, DAE and NLA solvers list property, to handle the change // in the list property if (!doSolverChanged(mOdeSolverData, pValue)) if (!doSolverChanged(mDaeSolverData, pValue)) doSolverChanged(mNlaSolverData, pValue); } //============================================================================== } // namespace SingleCellView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor refactoring (#31).<commit_after>//============================================================================== // Single cell view information solvers widget //============================================================================== #include "cellmlfileruntime.h" #include "coreutils.h" #include "singlecellviewinformationsolverswidget.h" #include "singlecellviewsimulation.h" //============================================================================== namespace OpenCOR { namespace SingleCellView { //============================================================================== SingleCellViewInformationSolversWidgetData::SingleCellViewInformationSolversWidgetData(Core::Property *pSolversProperty, Core::Property *pSolversListProperty, const QMap<QString, Core::Properties> &pSolversProperties) : mSolversProperty(pSolversProperty), mSolversListProperty(pSolversListProperty), mSolversProperties(pSolversProperties) { } //============================================================================== Core::Property * SingleCellViewInformationSolversWidgetData::solversProperty() const { // Return our solvers property return mSolversProperty; } //============================================================================== Core::Property * SingleCellViewInformationSolversWidgetData::solversListProperty() const { // Return our solvers list property return mSolversListProperty; } //============================================================================== QMap<QString, Core::Properties> SingleCellViewInformationSolversWidgetData::solversProperties() const { // Return our solvers properties return mSolversProperties; } //============================================================================== SingleCellViewInformationSolversWidget::SingleCellViewInformationSolversWidget(QWidget *pParent) : PropertyEditorWidget(true, pParent), mOdeSolverData(0), mDaeSolverData(0), mNlaSolverData(0), mGuiStates(QMap<QString, Core::PropertyEditorWidgetGuiState *>()), mDefaultGuiState(0), mDescriptions(QMap<Core::Property *, Descriptions>()) { // Update the tool tip of any property which value gets changed by the user connect(this, SIGNAL(propertyChanged(Core::Property *)), this, SLOT(updatePropertyToolTip(Core::Property *))); } //============================================================================== SingleCellViewInformationSolversWidget::~SingleCellViewInformationSolversWidget() { // Delete some internal objects delete mOdeSolverData; delete mDaeSolverData; delete mNlaSolverData; resetAllGuiStates(); } //============================================================================== void SingleCellViewInformationSolversWidget::retranslateUi() { // Update our property names if (mOdeSolverData) { setStringPropertyItem(mOdeSolverData->solversProperty()->name(), tr("ODE solver")); setStringPropertyItem(mOdeSolverData->solversListProperty()->name(), tr("Name")); mOdeSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available")); } if (mDaeSolverData) { setStringPropertyItem(mDaeSolverData->solversProperty()->name(), tr("DAE solver")); setStringPropertyItem(mDaeSolverData->solversListProperty()->name(), tr("Name")); mDaeSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available")); } if (mNlaSolverData) { setStringPropertyItem(mNlaSolverData->solversProperty()->name(), tr("NLA solver")); setStringPropertyItem(mNlaSolverData->solversListProperty()->name(), tr("Name")); mNlaSolverData->solversListProperty()->value()->setEmptyListValue(tr("None available")); } // Update the name of our various properties, should they have a description // associated with them // Note: this is effectively to have the description of our solvers' // properties properly updated... foreach (Core::Property *property, properties()) if (mDescriptions.contains(property)) { // The property has a description associated with it, so retrieve // the version, if any, which corresponds to our current locale Descriptions descriptions = mDescriptions.value(property); QString description = descriptions.value(Core::locale()); if (description.isEmpty()) // No description exists for the current locale, so retrieve // the english description (which, hopefully, should exist) description = descriptions.value("en"); // Set the name of the property to the description setStringPropertyItem(property->name(), description); } // Retranslate the tool tip of all our solvers' properties updateToolTips(); // Default retranslation // Note: we must do it last since we set the empty list value of some // properties above... PropertyEditorWidget::retranslateUi(); } //============================================================================== void SingleCellViewInformationSolversWidget::updatePropertyToolTip(Core::Property *pProperty) { // Update the tool tip of the given property if (pProperty->name()->type() != Core::PropertyItem::Section) { // We are dealing with a property (as opposed to a section), so we can // update its tool tip QString propertyToolTip = pProperty->name()->text()+tr(": "); if (pProperty->value()->text().isEmpty()) propertyToolTip += "???"; else propertyToolTip += pProperty->value()->text(); if (!pProperty->unit()->text().isEmpty()) propertyToolTip += " "+pProperty->unit()->text(); pProperty->name()->setToolTip(propertyToolTip); pProperty->value()->setToolTip(propertyToolTip); pProperty->unit()->setToolTip(propertyToolTip); } } //============================================================================== void SingleCellViewInformationSolversWidget::updateToolTips() { // Update the tool tip of all our solvers' properties foreach (Core::Property *property, properties()) updatePropertyToolTip(property); } //============================================================================== void SingleCellViewInformationSolversWidget::resetAllGuiStates() { // Reset all our GUI states including our default one foreach (Core::PropertyEditorWidgetGuiState *guiState, mGuiStates) delete guiState; mGuiStates.clear(); delete mDefaultGuiState; } //============================================================================== SingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::addSolverProperties(const SolverInterfaces &pSolverInterfaces, const Solver::Type &pSolverType) { // Make sure that we have at least one solver interface if (pSolverInterfaces.isEmpty()) return 0; // Add our section property Core::Property *solversProperty = addSectionProperty(); // Add our list property for the solvers Core::Property *solversListProperty = addListProperty(QString(), solversProperty); // Retrieve the name of the solvers which type is the one in whhich we are // interested QStringList solvers = QStringList(); QMap<QString, Core::Properties> solversProperties = QMap<QString, Core::Properties>(); foreach (SolverInterface *solverInterface, pSolverInterfaces) if (solverInterface->type() == pSolverType) { // Keep track of the solver's name solvers << solverInterface->name(); // Add the solver's properties Core::Property *property; Core::Properties properties = Core::Properties(); foreach (const Solver::Property &solverInterfaceProperty, solverInterface->properties()) { // Add the solver's property and set its default value switch (solverInterfaceProperty.type()) { case Solver::Double: property = addDoubleProperty(solverInterfaceProperty.id(), solversProperty); setDoublePropertyItem(property->value(), solverInterfaceProperty.defaultValue().toDouble()); break; default: // Solver::Integer property = addIntegerProperty(solverInterfaceProperty.id(), solversProperty); setIntegerPropertyItem(property->value(), solverInterfaceProperty.defaultValue().toInt()); } // Make the property editable property->setEditable(true); // Set the solver's property's 'unit', if needed if (solverInterfaceProperty.hasVoiUnit()) setStringPropertyItem(property->unit(), "???"); // Note: to assign a non-empty string to our unit item is // just a way for us to make sure that the property's // will get initialised (see setPropertiesUnit())... // Keep track of the solver's property properties << property; // Keep track of the solver's property's descriptions mDescriptions.insert(property, solverInterfaceProperty.descriptions()); } // Keep track of the solver's properties solversProperties.insert(solverInterface->name(), properties); } // Sort our list of solvers solvers.sort(); // Add the list of solvers to our list property value item solversListProperty->value()->setList(solvers); // Keep track of changes to list properties connect(this, SIGNAL(listPropertyChanged(const QString &)), this, SLOT(solverChanged(const QString &))); // Return our solver data return new SingleCellViewInformationSolversWidgetData(solversProperty, solversListProperty, solversProperties); } //============================================================================== void SingleCellViewInformationSolversWidget::setSolverInterfaces(const SolverInterfaces &pSolverInterfaces) { // Remove all our properties removeAllProperties(); // Add properties for our different solvers delete mOdeSolverData; delete mDaeSolverData; delete mNlaSolverData; mDescriptions.clear(); mOdeSolverData = addSolverProperties(pSolverInterfaces, Solver::Ode); mDaeSolverData = addSolverProperties(pSolverInterfaces, Solver::Dae); mNlaSolverData = addSolverProperties(pSolverInterfaces, Solver::Nla); // Show/hide the relevant properties if (mOdeSolverData) doSolverChanged(mOdeSolverData, mOdeSolverData->solversListProperty()->value()->text(), true); if (mDaeSolverData) doSolverChanged(mDaeSolverData, mDaeSolverData->solversListProperty()->value()->text(), true); if (mNlaSolverData) doSolverChanged(mNlaSolverData, mNlaSolverData->solversListProperty()->value()->text(), true); // Expand all our properties expandAll(); // Clear any track of previous GUI states and retrieve our default GUI state resetAllGuiStates(); mDefaultGuiState = guiState(); } //============================================================================== void SingleCellViewInformationSolversWidget::setPropertiesUnit(SingleCellViewInformationSolversWidgetData *pSolverData, const QString &pVoiUnit) { // Make sure that we have some solver's data if (!pSolverData) return; // Go through the solvers' properties and set the unit of the relevant ones foreach (const Core::Properties &properties, pSolverData->solversProperties()) foreach (Core::Property *property, properties) if (!property->unit()->text().isEmpty()) setStringPropertyItem(property->unit(), pVoiUnit); } //============================================================================== void SingleCellViewInformationSolversWidget::initialize(const QString &pFileName, CellMLSupport::CellmlFileRuntime *pRuntime, SingleCellViewSimulationData *pSimulationData) { // Retrieve and initialise our GUI state setGuiState(mGuiStates.contains(pFileName)? mGuiStates.value(pFileName): mDefaultGuiState); // Make sure that the CellML file runtime is valid if (pRuntime->isValid()) { // Show/hide the ODE/DAE solver information if (mOdeSolverData) setPropertyVisible(mOdeSolverData->solversProperty(), pRuntime->needOdeSolver()); if (mDaeSolverData) setPropertyVisible(mDaeSolverData->solversProperty(), pRuntime->needDaeSolver()); // Show/hide the NLA solver information if (mNlaSolverData) setPropertyVisible(mNlaSolverData->solversProperty(), pRuntime->needNlaSolver()); } // Set the unit of our different properties, if needed QString voiUnit = pRuntime->variableOfIntegration()->unit(); setPropertiesUnit(mOdeSolverData, voiUnit); setPropertiesUnit(mDaeSolverData, voiUnit); setPropertiesUnit(mNlaSolverData, voiUnit); // Update the tool tip of all our solvers' properties updateToolTips(); // Initialise our simulation's NLA solver's properties, so that we can then // properly reset our simulation the first time round if (mNlaSolverData) { pSimulationData->setNlaSolverName(mNlaSolverData->solversListProperty()->value()->text(), false); foreach (Core::Property *property, mNlaSolverData->solversProperties().value(pSimulationData->nlaSolverName())) pSimulationData->addNlaSolverProperty(property->id(), (property->value()->type() == Core::PropertyItem::Integer)? Core::PropertyEditorWidget::integerPropertyItem(property->value()): Core::PropertyEditorWidget::doublePropertyItem(property->value()), false); } } //============================================================================== void SingleCellViewInformationSolversWidget::backup(const QString &pFileName) { // Keep track of our GUI state mGuiStates.insert(pFileName, guiState()); } //============================================================================== void SingleCellViewInformationSolversWidget::finalize(const QString &pFileName) { // Remove any track of our GUI state mGuiStates.remove(pFileName); } //============================================================================== QStringList SingleCellViewInformationSolversWidget::odeSolvers() const { // Return the available ODE solvers, if any return mOdeSolverData?mOdeSolverData->solversListProperty()->value()->list():QStringList(); } //============================================================================== QStringList SingleCellViewInformationSolversWidget::daeSolvers() const { // Return the available DAE solvers, if any return mDaeSolverData?mDaeSolverData->solversListProperty()->value()->list():QStringList(); } //============================================================================== QStringList SingleCellViewInformationSolversWidget::nlaSolvers() const { // Return the available NLA solvers, if any return mNlaSolverData?mNlaSolverData->solversListProperty()->value()->list():QStringList(); } //============================================================================== SingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::odeSolverData() const { // Return our ODE solver data return mOdeSolverData; } //============================================================================== SingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::daeSolverData() const { // Return our DAE solver data return mDaeSolverData; } //============================================================================== SingleCellViewInformationSolversWidgetData * SingleCellViewInformationSolversWidget::nlaSolverData() const { // Return our NLA solver data return mNlaSolverData; } //============================================================================== bool SingleCellViewInformationSolversWidget::doSolverChanged(SingleCellViewInformationSolversWidgetData *pSolverData, const QString &pSolverName, const bool &pForceHandling) { // By default, we don't handle the change in the list property bool res = false; // Check whether the list property that got changed is the one we are after if ( (pSolverData->solversListProperty() == currentProperty()) || pForceHandling) { // It is the list property we are after or we want to force the // handling, so update our result res = true; // Go through the different properties for the given type of solver and // show/hide whatever needs showing/hiding for (QMap<QString, Core::Properties>::ConstIterator iter = pSolverData->solversProperties().constBegin(), iterEnd = pSolverData->solversProperties().constEnd(); iter != iterEnd; ++iter) { bool propertyVisible = !iter.key().compare(pSolverName); foreach (Core::Property *property, iter.value()) setPropertyVisible(property, propertyVisible); } } // Return our result return res; } //============================================================================== void SingleCellViewInformationSolversWidget::solverChanged(const QString &pValue) { // Try, for the ODE, DAE and NLA solvers list property, to handle the change // in the list property if (!doSolverChanged(mOdeSolverData, pValue)) if (!doSolverChanged(mDaeSolverData, pValue)) doSolverChanged(mNlaSolverData, pValue); } //============================================================================== } // namespace SingleCellView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Output.hxx" #include "Error.hxx" #include "event/SocketEvent.hxx" #include "direct.hxx" #include "io/Splice.hxx" #include "io/FileDescriptor.hxx" #include "system/Error.hxx" #include "istream/Handler.hxx" #include "istream/Pointer.hxx" #include "istream/UnusedPtr.hxx" #include "pool/pool.hxx" #include <was/protocol.h> #include <errno.h> #include <string.h> #include <unistd.h> static constexpr struct timeval was_output_timeout = { .tv_sec = 120, .tv_usec = 0, }; class WasOutput final : IstreamHandler { public: FileDescriptor fd; SocketEvent event; WasOutputHandler &handler; IstreamPointer input; uint64_t sent = 0; bool known_length = false; WasOutput(EventLoop &event_loop, FileDescriptor _fd, UnusedIstreamPtr _input, WasOutputHandler &_handler) :fd(_fd), event(event_loop, fd.Get(), SocketEvent::WRITE, BIND_THIS_METHOD(WriteEventCallback)), handler(_handler), input(std::move(_input), *this, ISTREAM_TO_PIPE) { ScheduleWrite(); } void ScheduleWrite() { event.Add(was_output_timeout); } void AbortError(std::exception_ptr ep) { event.Delete(); if (input.IsDefined()) input.ClearAndClose(); handler.WasOutputError(ep); } bool CheckLength(); void WriteEventCallback(unsigned events); /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) override; ssize_t OnDirect(FdType type, int fd, size_t max_length) override; void OnEof() noexcept override; void OnError(std::exception_ptr ep) noexcept override; }; bool WasOutput::CheckLength() { if (known_length) return true; off_t available = input.GetAvailable(false); if (available < 0) return true; known_length = true; return handler.WasOutputLength(sent + available); } /* * libevent callback * */ inline void WasOutput::WriteEventCallback(unsigned events) { assert(fd.IsDefined()); assert(input.IsDefined()); if (gcc_unlikely(events & SocketEvent::TIMEOUT)) { AbortError(std::make_exception_ptr(WasError("send timeout"))); return; } if (CheckLength()) input.Read(); } /* * istream handler for the request * */ inline size_t WasOutput::OnData(const void *p, size_t length) { assert(fd.IsDefined()); assert(input.IsDefined()); ssize_t nbytes = fd.Write(p, length); if (gcc_likely(nbytes > 0)) { sent += nbytes; ScheduleWrite(); } else if (nbytes < 0) { if (errno == EAGAIN) { ScheduleWrite(); return 0; } AbortError(std::make_exception_ptr(MakeErrno("Write to WAS process failed"))); return 0; } return (size_t)nbytes; } inline ssize_t WasOutput::OnDirect(gcc_unused FdType type, int source_fd, size_t max_length) { assert(fd.IsDefined()); ssize_t nbytes = SpliceToPipe(source_fd, fd.Get(), max_length); if (gcc_likely(nbytes > 0)) { sent += nbytes; ScheduleWrite(); } else if (nbytes < 0 && errno == EAGAIN) { if (!fd.IsReadyForWriting()) { ScheduleWrite(); return ISTREAM_RESULT_BLOCKING; } /* try again, just in case fd has become ready between the first istream_direct_to_pipe() call and fd.IsReadyForWriting() */ nbytes = SpliceToPipe(source_fd, fd.Get(), max_length); } return nbytes; } void WasOutput::OnEof() noexcept { assert(input.IsDefined()); input.Clear(); event.Delete(); if (!known_length && !handler.WasOutputLength(sent)) return; handler.WasOutputEof(); } void WasOutput::OnError(std::exception_ptr ep) noexcept { assert(input.IsDefined()); input.Clear(); event.Delete(); handler.WasOutputPremature(sent, ep); } /* * constructor * */ WasOutput * was_output_new(struct pool &pool, EventLoop &event_loop, FileDescriptor fd, UnusedIstreamPtr input, WasOutputHandler &handler) { assert(fd.IsDefined()); return NewFromPool<WasOutput>(pool, event_loop, fd, std::move(input), handler); } uint64_t was_output_free(WasOutput *output) { assert(output != nullptr); if (output->input.IsDefined()) output->input.ClearAndClose(); output->event.Delete(); return output->sent; } bool was_output_check_length(WasOutput &output) { return output.CheckLength(); } <commit_msg>was/output: separate TimerEvent for the timeout<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Output.hxx" #include "Error.hxx" #include "event/SocketEvent.hxx" #include "event/TimerEvent.hxx" #include "direct.hxx" #include "io/Splice.hxx" #include "io/FileDescriptor.hxx" #include "system/Error.hxx" #include "istream/Handler.hxx" #include "istream/Pointer.hxx" #include "istream/UnusedPtr.hxx" #include "pool/pool.hxx" #include <was/protocol.h> #include <errno.h> #include <string.h> #include <unistd.h> static constexpr struct timeval was_output_timeout = { .tv_sec = 120, .tv_usec = 0, }; class WasOutput final : IstreamHandler { public: FileDescriptor fd; SocketEvent event; TimerEvent timeout_event; WasOutputHandler &handler; IstreamPointer input; uint64_t sent = 0; bool known_length = false; WasOutput(EventLoop &event_loop, FileDescriptor _fd, UnusedIstreamPtr _input, WasOutputHandler &_handler) :fd(_fd), event(event_loop, fd.Get(), SocketEvent::WRITE, BIND_THIS_METHOD(WriteEventCallback)), timeout_event(event_loop, BIND_THIS_METHOD(OnTimeout)), handler(_handler), input(std::move(_input), *this, ISTREAM_TO_PIPE) { ScheduleWrite(); } void ScheduleWrite() { event.Add(); timeout_event.Add(was_output_timeout); } void AbortError(std::exception_ptr ep) { event.Delete(); timeout_event.Cancel(); if (input.IsDefined()) input.ClearAndClose(); handler.WasOutputError(ep); } bool CheckLength(); void WriteEventCallback(unsigned events); void OnTimeout() noexcept { AbortError(std::make_exception_ptr(WasError("send timeout"))); } /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) override; ssize_t OnDirect(FdType type, int fd, size_t max_length) override; void OnEof() noexcept override; void OnError(std::exception_ptr ep) noexcept override; }; bool WasOutput::CheckLength() { if (known_length) return true; off_t available = input.GetAvailable(false); if (available < 0) return true; known_length = true; return handler.WasOutputLength(sent + available); } /* * libevent callback * */ inline void WasOutput::WriteEventCallback(unsigned) { assert(fd.IsDefined()); assert(input.IsDefined()); timeout_event.Cancel(); if (CheckLength()) input.Read(); } /* * istream handler for the request * */ inline size_t WasOutput::OnData(const void *p, size_t length) { assert(fd.IsDefined()); assert(input.IsDefined()); ssize_t nbytes = fd.Write(p, length); if (gcc_likely(nbytes > 0)) { sent += nbytes; ScheduleWrite(); } else if (nbytes < 0) { if (errno == EAGAIN) { ScheduleWrite(); return 0; } AbortError(std::make_exception_ptr(MakeErrno("Write to WAS process failed"))); return 0; } return (size_t)nbytes; } inline ssize_t WasOutput::OnDirect(gcc_unused FdType type, int source_fd, size_t max_length) { assert(fd.IsDefined()); ssize_t nbytes = SpliceToPipe(source_fd, fd.Get(), max_length); if (gcc_likely(nbytes > 0)) { sent += nbytes; ScheduleWrite(); } else if (nbytes < 0 && errno == EAGAIN) { if (!fd.IsReadyForWriting()) { ScheduleWrite(); return ISTREAM_RESULT_BLOCKING; } /* try again, just in case fd has become ready between the first istream_direct_to_pipe() call and fd.IsReadyForWriting() */ nbytes = SpliceToPipe(source_fd, fd.Get(), max_length); } return nbytes; } void WasOutput::OnEof() noexcept { assert(input.IsDefined()); input.Clear(); event.Delete(); timeout_event.Cancel(); if (!known_length && !handler.WasOutputLength(sent)) return; handler.WasOutputEof(); } void WasOutput::OnError(std::exception_ptr ep) noexcept { assert(input.IsDefined()); input.Clear(); event.Delete(); timeout_event.Cancel(); handler.WasOutputPremature(sent, ep); } /* * constructor * */ WasOutput * was_output_new(struct pool &pool, EventLoop &event_loop, FileDescriptor fd, UnusedIstreamPtr input, WasOutputHandler &handler) { assert(fd.IsDefined()); return NewFromPool<WasOutput>(pool, event_loop, fd, std::move(input), handler); } uint64_t was_output_free(WasOutput *output) { assert(output != nullptr); if (output->input.IsDefined()) output->input.ClearAndClose(); output->event.Delete(); output->timeout_event.Cancel(); return output->sent; } bool was_output_check_length(WasOutput &output) { return output.CheckLength(); } <|endoftext|>
<commit_before>#include "partition/partitioner.hpp" #include "partition/annotated_partition.hpp" #include "partition/bisection_graph.hpp" #include "partition/compressed_node_based_graph_reader.hpp" #include "partition/edge_based_graph_reader.hpp" #include "partition/node_based_graph_to_edge_based_graph_mapping_reader.hpp" #include "partition/recursive_bisection.hpp" #include "util/coordinate.hpp" #include "util/geojson_debug_logger.hpp" #include "util/geojson_debug_policies.hpp" #include "util/integer_range.hpp" #include "util/json_container.hpp" #include "util/log.hpp" #include <iterator> #include <vector> #include <boost/assert.hpp> #include "util/geojson_debug_logger.hpp" #include "util/geojson_debug_policies.hpp" #include "util/json_container.hpp" #include "util/timing_util.hpp" namespace osrm { namespace partition { void LogStatistics(const std::string &filename, std::vector<std::uint32_t> bisection_ids) { auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename); util::Log() << "Loaded compressed node based graph: " << compressed_node_based_graph.edges.size() << " edges, " << compressed_node_based_graph.coordinates.size() << " nodes"; groupEdgesBySource(begin(compressed_node_based_graph.edges), end(compressed_node_based_graph.edges)); auto graph = makeBisectionGraph(compressed_node_based_graph.coordinates, adaptToBisectionEdge(std::move(compressed_node_based_graph.edges))); TIMER_START(annotation); AnnotatedPartition partition(graph, bisection_ids); TIMER_STOP(annotation); std::cout << "Annotation took " << TIMER_SEC(annotation) << " seconds" << std::endl; } void LogGeojson(const std::string &filename, const std::vector<std::uint32_t> &bisection_ids) { // reload graph, since we destroyed the old one auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename); util::Log() << "Loaded compressed node based graph: " << compressed_node_based_graph.edges.size() << " edges, " << compressed_node_based_graph.coordinates.size() << " nodes"; groupEdgesBySource(begin(compressed_node_based_graph.edges), end(compressed_node_based_graph.edges)); auto graph = makeBisectionGraph(compressed_node_based_graph.coordinates, adaptToBisectionEdge(std::move(compressed_node_based_graph.edges))); const auto get_level = [](const std::uint32_t lhs, const std::uint32_t rhs) { auto xored = lhs ^ rhs; std::uint32_t level = log(xored) / log(2.0); return level; }; std::vector<std::vector<util::Coordinate>> border_vertices(33); for (NodeID nid = 0; nid < graph.NumberOfNodes(); ++nid) { const auto source_id = bisection_ids[nid]; for (const auto &edge : graph.Edges(nid)) { const auto target_id = bisection_ids[edge.target]; if (source_id != target_id) { auto level = get_level(source_id, target_id); border_vertices[level].push_back(graph.Node(nid).coordinate); border_vertices[level].push_back(graph.Node(edge.target).coordinate); } } } util::ScopedGeojsonLoggerGuard<util::CoordinateVectorToMultiPoint> guard( "border_vertices.geojson"); std::size_t level = 0; for (auto &bv : border_vertices) { if (!bv.empty()) { std::sort(bv.begin(), bv.end(), [](const auto lhs, const auto rhs) { return std::tie(lhs.lon, lhs.lat) < std::tie(rhs.lon, rhs.lat); }); bv.erase(std::unique(bv.begin(), bv.end()), bv.end()); util::json::Object jslevel; jslevel.values["level"] = util::json::Number(level++); guard.Write(bv, jslevel); } } } int Partitioner::Run(const PartitionConfig &config) { auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(config.compressed_node_based_graph_path.string()); util::Log() << "Loaded compressed node based graph: " << compressed_node_based_graph.edges.size() << " edges, " << compressed_node_based_graph.coordinates.size() << " nodes"; groupEdgesBySource(begin(compressed_node_based_graph.edges), end(compressed_node_based_graph.edges)); auto graph = makeBisectionGraph(compressed_node_based_graph.coordinates, adaptToBisectionEdge(std::move(compressed_node_based_graph.edges))); util::Log() << " running partition: " << config.maximum_cell_size << " " << config.balance << " " << config.boundary_factor << " " << config.num_optimizing_cuts << " " << config.small_component_size << " # max_cell_size balance boundary cuts small_component_size"; RecursiveBisection recursive_bisection(graph, config.maximum_cell_size, config.balance, config.boundary_factor, config.num_optimizing_cuts, config.small_component_size); LogStatistics(config.compressed_node_based_graph_path.string(), recursive_bisection.BisectionIDs()); auto mapping = LoadNodeBasedGraphToEdgeBasedGraphMapping(config.nbg_ebg_mapping_path.string()); util::Log() << "Loaded node based graph to edge based graph mapping"; auto edge_based_graph = LoadEdgeBasedGraph(config.edge_based_graph_path.string()); util::Log() << "Loaded edge based graph for mapping partition ids: " << edge_based_graph->GetNumberOfEdges() << " edges, " << edge_based_graph->GetNumberOfNodes() << " nodes"; for (const auto node_id : util::irange(0u, edge_based_graph->GetNumberOfNodes())) { const auto node_based_nodes = mapping.Lookup(node_id); const auto u = node_based_nodes.u; const auto v = node_based_nodes.v; auto partition_id = [](auto) { return 0; /*dummy*/ }; if (partition_id(u) != partition_id(v)) { // TODO: resolve border nodes u, v } } return 0; } } // namespace partition } // namespace osrm <commit_msg>First try at artificial nodes<commit_after>#include "partition/partitioner.hpp" #include "partition/annotated_partition.hpp" #include "partition/bisection_graph.hpp" #include "partition/compressed_node_based_graph_reader.hpp" #include "partition/edge_based_graph_reader.hpp" #include "partition/node_based_graph_to_edge_based_graph_mapping_reader.hpp" #include "partition/recursive_bisection.hpp" #include "util/coordinate.hpp" #include "util/geojson_debug_logger.hpp" #include "util/geojson_debug_policies.hpp" #include "util/integer_range.hpp" #include "util/json_container.hpp" #include "util/log.hpp" #include <algorithm> #include <iterator> #include <vector> #include <boost/assert.hpp> #include "util/geojson_debug_logger.hpp" #include "util/geojson_debug_policies.hpp" #include "util/json_container.hpp" #include "util/timing_util.hpp" namespace osrm { namespace partition { void LogStatistics(const std::string &filename, std::vector<std::uint32_t> bisection_ids) { auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename); util::Log() << "Loaded compressed node based graph: " << compressed_node_based_graph.edges.size() << " edges, " << compressed_node_based_graph.coordinates.size() << " nodes"; groupEdgesBySource(begin(compressed_node_based_graph.edges), end(compressed_node_based_graph.edges)); auto graph = makeBisectionGraph(compressed_node_based_graph.coordinates, adaptToBisectionEdge(std::move(compressed_node_based_graph.edges))); TIMER_START(annotation); AnnotatedPartition partition(graph, bisection_ids); TIMER_STOP(annotation); std::cout << "Annotation took " << TIMER_SEC(annotation) << " seconds" << std::endl; } void LogGeojson(const std::string &filename, const std::vector<std::uint32_t> &bisection_ids) { // reload graph, since we destroyed the old one auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(filename); util::Log() << "Loaded compressed node based graph: " << compressed_node_based_graph.edges.size() << " edges, " << compressed_node_based_graph.coordinates.size() << " nodes"; groupEdgesBySource(begin(compressed_node_based_graph.edges), end(compressed_node_based_graph.edges)); auto graph = makeBisectionGraph(compressed_node_based_graph.coordinates, adaptToBisectionEdge(std::move(compressed_node_based_graph.edges))); const auto get_level = [](const std::uint32_t lhs, const std::uint32_t rhs) { auto xored = lhs ^ rhs; std::uint32_t level = log(xored) / log(2.0); return level; }; std::vector<std::vector<util::Coordinate>> border_vertices(33); for (NodeID nid = 0; nid < graph.NumberOfNodes(); ++nid) { const auto source_id = bisection_ids[nid]; for (const auto &edge : graph.Edges(nid)) { const auto target_id = bisection_ids[edge.target]; if (source_id != target_id) { auto level = get_level(source_id, target_id); border_vertices[level].push_back(graph.Node(nid).coordinate); border_vertices[level].push_back(graph.Node(edge.target).coordinate); } } } util::ScopedGeojsonLoggerGuard<util::CoordinateVectorToMultiPoint> guard( "border_vertices.geojson"); std::size_t level = 0; for (auto &bv : border_vertices) { if (!bv.empty()) { std::sort(bv.begin(), bv.end(), [](const auto lhs, const auto rhs) { return std::tie(lhs.lon, lhs.lat) < std::tie(rhs.lon, rhs.lat); }); bv.erase(std::unique(bv.begin(), bv.end()), bv.end()); util::json::Object jslevel; jslevel.values["level"] = util::json::Number(level++); guard.Write(bv, jslevel); } } } int Partitioner::Run(const PartitionConfig &config) { auto compressed_node_based_graph = LoadCompressedNodeBasedGraph(config.compressed_node_based_graph_path.string()); util::Log() << "Loaded compressed node based graph: " << compressed_node_based_graph.edges.size() << " edges, " << compressed_node_based_graph.coordinates.size() << " nodes"; groupEdgesBySource(begin(compressed_node_based_graph.edges), end(compressed_node_based_graph.edges)); auto graph = makeBisectionGraph(compressed_node_based_graph.coordinates, adaptToBisectionEdge(std::move(compressed_node_based_graph.edges))); util::Log() << " running partition: " << config.maximum_cell_size << " " << config.balance << " " << config.boundary_factor << " " << config.num_optimizing_cuts << " " << config.small_component_size << " # max_cell_size balance boundary cuts small_component_size"; RecursiveBisection recursive_bisection(graph, config.maximum_cell_size, config.balance, config.boundary_factor, config.num_optimizing_cuts, config.small_component_size); LogStatistics(config.compressed_node_based_graph_path.string(), recursive_bisection.BisectionIDs()); // Up until now we worked on the compressed node based graph. // But what we actually need is a partition for the edge based graph to work on. // The following loads a mapping from node based graph to edge based graph. // Then loads the edge based graph tanslates the partition and modifies it. // For details see #3205 auto mapping = LoadNodeBasedGraphToEdgeBasedGraphMapping(config.nbg_ebg_mapping_path.string()); util::Log() << "Loaded node based graph to edge based graph mapping"; auto edge_based_graph = LoadEdgeBasedGraph(config.edge_based_graph_path.string()); util::Log() << "Loaded edge based graph for mapping partition ids: " << edge_based_graph->GetNumberOfEdges() << " edges, " << edge_based_graph->GetNumberOfNodes() << " nodes"; // TODO: put translation into own function / file const auto &partition_ids = recursive_bisection.BisectionIDs(); // Keyed by ebg node - stores flag if ebg node is border node or not. std::vector<bool> is_edge_based_border_node(edge_based_graph->GetNumberOfNodes()); // Extract edge based border nodes, based on node based partition and mapping. for (const auto node_id : util::irange(0u, edge_based_graph->GetNumberOfNodes())) { const auto node_based_nodes = mapping.Lookup(node_id); const auto u = node_based_nodes.u; const auto v = node_based_nodes.v; if (partition_ids[u] == partition_ids[v]) { // Can use partition_ids[u/v] as partition for edge based graph `node_id` is_edge_based_border_node[node_id] = false; } else { // Border nodes u,v - need to be resolved. What we can do: // - 1) Pick one of the partitions randomly or by minimizing border edges. // - 2) Or: modify edge based graph, introducing artificial edges. We do this. is_edge_based_border_node[node_id] = true; } } const auto num_border_nodes = std::count(begin(is_edge_based_border_node), end(is_edge_based_border_node), true); util::Log() << "Fixing " << num_border_nodes << " edge based graph border nodes"; // Keyed by ebg node - stores associated border nodes for nodes std::unordered_map<NodeID, NodeID> edge_based_border_node; edge_based_border_node.reserve(num_border_nodes); // For all edges in the edge based graph: if they start and end in different partitions // introduce artificial nodes and re-wire incoming / outgoing edges to these artificial ones. for (const auto source : util::irange(0u, edge_based_graph->GetNumberOfNodes())) { for (auto edge : edge_based_graph->GetAdjacentEdgeRange(source)) { const auto target = edge_based_graph->GetTarget(edge); const auto opposite_edge = edge_based_graph->FindEdge(target, source); if (!is_edge_based_border_node[source] || !is_edge_based_border_node[target]) continue; // TODO: assign and store partition ids to new nodes const auto artificial_node = edge_based_graph->InsertNode(); EdgeBasedGraphEdgeData dummy{SPECIAL_EDGEID, /*is_boundary_arc=*/1, 0, 0, false, false}; } } return 0; } } // namespace partition } // namespace osrm <|endoftext|>
<commit_before>#include "bs_mesh_stdafx.h" #include "py_rs_mesh.h" #include "bs_mesh_grdecl.h" #include "export_python_wrapper.h" #include "py_pair_converter.h" #include <boost/python/tuple.hpp> #ifdef BSPY_EXPORTING_PLUGIN using namespace boost::python; namespace blue_sky { namespace python { PY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter) .def ("get_ext_to_int", &T::get_ext_to_int, args(""), "Return reference to external-to-internal mesh index") .def ("get_int_to_ext", &T::get_int_to_ext, args(""), "Return reference to internal-to-external mesh index") .def ("get_volumes", &T::get_volumes, args(""), "Return reference to volumes vector") .def ("get_dimensions_range", &T::get_dimensions_range, args("dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min"), "Get dimensions ranges") .def ("get_element_size", &T::get_element_size, args ("n_elem, dx, dy, dz"), "get elements sizes") .def ("get_element_ijk_to_int", &T::get_element_ijk_to_int, args ("i, j, k"), "get elements sizes") .def ("get_n_active_elements", &T::get_n_active_elements, args (""), "Get elements sizes") .def ("calc_element_tops", &T::calc_element_tops, args (""), "Calc element tops") .def ("calc_element_center", &T::calc_element_center, args (""), "Calc element center"); PY_EXPORTER_END; }} // eof blue_sky::python namespace { using namespace blue_sky; using namespace blue_sky::python; // same as grdecl exporter, but also export gen_coord_zcorn template <typename T> struct mesh_grdecl_exporter_plus { typedef t_long int_t; typedef t_double fp_t; typedef spv_float spfp_storarr_t; typedef spv_long spi_arr_t; typedef typename spi_arr_t::pure_pointed_t int_arr_t; typedef std::pair< spv_float, spv_float > coord_zcorn_pair; // gen_coord_zcorn overloads static coord_zcorn_pair gen_coord_zcorn1(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz, fp_t x0, fp_t y0) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0, y0); } static coord_zcorn_pair gen_coord_zcorn2(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz, fp_t x0) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0); } static coord_zcorn_pair gen_coord_zcorn3(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz); } // refine_mesh_deltas with overloads static tuple refine_mesh_deltas(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_deltas1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points) { return refine_mesh_deltas(nx, ny, coord, points); } static tuple refine_mesh_deltas2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh_deltas(nx, ny, coord, points, m_thresh); } // refine_mesh with overloads static tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) { return refine_mesh(nx, ny, coord, zcorn, points); } static tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh(nx, ny, coord, zcorn, points, m_thresh); } // refine_mesh_deltas with overloads // (i,j) points format static tuple refine_mesh_deltas_ij(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points_pos, points_param, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_deltas_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param) { return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param); } static tuple refine_mesh_deltas_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh) { return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param, m_thresh); } // refine_mesh with overloads // (i, j) points format static tuple refine_mesh_ij(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points_pos, points_param, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param) { return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param); } static tuple refine_mesh_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh) { return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param, m_thresh); } template <typename class_t> static class_t & export_class (class_t &class__) { using namespace boost::python; mesh_grdecl_exporter<T>::export_class (class__) .def("gen_coord_zcorn", &T::gen_coord_zcorn, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn1, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn2, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn3, "Generate COORD & ZCORN from given dimensions") .staticmethod("gen_coord_zcorn") .def("refine_mesh_deltas", &refine_mesh_deltas, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas1, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas2, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij1, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij2, "Calc dx and dy arrays for refined mesh in given points") .staticmethod("refine_mesh_deltas") .def("refine_mesh", &refine_mesh, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh2, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij2, "Refine existing mesh in given points") .staticmethod("refine_mesh") ; return class__; } }; template< class fp_type > void reg_sparray_pair() { // register converter from pair of returned arrayes to python list typedef smart_ptr< bs_array< fp_type, bs_nparray > > spfp_array; typedef std::pair< spfp_array, spfp_array > array_pair; typedef bspy_converter< pair_traits< array_pair > > array_pair_converter; array_pair_converter::register_to_py(); array_pair_converter::register_from_py(); } } // eof hidden namespace namespace blue_sky { namespace python { void py_export_mesh_grdecl () { class_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class ("mesh_grdecl"); //reg_sparray_pair< float >(); reg_sparray_pair< double >(); } }} // namespace blue_sky::python #endif <commit_msg>BS_MESH: add Python binding for calc_cells_vertices()<commit_after>#include "bs_mesh_stdafx.h" #include "py_rs_mesh.h" #include "bs_mesh_grdecl.h" #include "export_python_wrapper.h" #include "py_pair_converter.h" #include <boost/python/tuple.hpp> #ifdef BSPY_EXPORTING_PLUGIN using namespace boost::python; namespace blue_sky { namespace python { PY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter) .def ("get_ext_to_int", &T::get_ext_to_int, args(""), "Return reference to external-to-internal mesh index") .def ("get_int_to_ext", &T::get_int_to_ext, args(""), "Return reference to internal-to-external mesh index") .def ("get_volumes", &T::get_volumes, args(""), "Return reference to volumes vector") .def ("get_dimensions_range", &T::get_dimensions_range, args("dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min"), "Get dimensions ranges") .def ("get_element_size", &T::get_element_size, args ("n_elem, dx, dy, dz"), "get elements sizes") .def ("get_element_ijk_to_int", &T::get_element_ijk_to_int, args ("i, j, k"), "get elements sizes") .def ("get_n_active_elements", &T::get_n_active_elements, args (""), "Get elements sizes") .def ("calc_element_tops", &T::calc_element_tops, args (""), "Calc element tops") .def ("calc_element_center", &T::calc_element_center, args (""), "Calc element center") .def ("calc_cells_vertices", &T::calc_cells_vertices) ; PY_EXPORTER_END; }} // eof blue_sky::python namespace { using namespace blue_sky; using namespace blue_sky::python; // same as grdecl exporter, but also export gen_coord_zcorn template <typename T> struct mesh_grdecl_exporter_plus { typedef t_long int_t; typedef t_double fp_t; typedef spv_float spfp_storarr_t; typedef spv_long spi_arr_t; typedef typename spi_arr_t::pure_pointed_t int_arr_t; typedef std::pair< spv_float, spv_float > coord_zcorn_pair; // gen_coord_zcorn overloads static coord_zcorn_pair gen_coord_zcorn1(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz, fp_t x0, fp_t y0) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0, y0); } static coord_zcorn_pair gen_coord_zcorn2(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz, fp_t x0) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0); } static coord_zcorn_pair gen_coord_zcorn3(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz) { return T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz); } // refine_mesh_deltas with overloads static tuple refine_mesh_deltas(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_deltas1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points) { return refine_mesh_deltas(nx, ny, coord, points); } static tuple refine_mesh_deltas2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh_deltas(nx, ny, coord, points, m_thresh); } // refine_mesh with overloads static tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) { return refine_mesh(nx, ny, coord, zcorn, points); } static tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh(nx, ny, coord, zcorn, points, m_thresh); } // refine_mesh_deltas with overloads // (i,j) points format static tuple refine_mesh_deltas_ij(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points_pos, points_param, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_deltas_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param) { return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param); } static tuple refine_mesh_deltas_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh) { return refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param, m_thresh); } // refine_mesh with overloads // (i, j) points format static tuple refine_mesh_ij(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points_pos, points_param, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } static tuple refine_mesh_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param) { return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param); } static tuple refine_mesh_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh) { return refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param, m_thresh); } template <typename class_t> static class_t & export_class (class_t &class__) { using namespace boost::python; mesh_grdecl_exporter<T>::export_class (class__) .def("gen_coord_zcorn", &T::gen_coord_zcorn, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn1, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn2, "Generate COORD & ZCORN from given dimensions") .def("gen_coord_zcorn", &gen_coord_zcorn3, "Generate COORD & ZCORN from given dimensions") .staticmethod("gen_coord_zcorn") .def("refine_mesh_deltas", &refine_mesh_deltas, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas1, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas2, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij1, "Calc dx and dy arrays for refined mesh in given points") .def("refine_mesh_deltas", &refine_mesh_deltas_ij2, "Calc dx and dy arrays for refined mesh in given points") .staticmethod("refine_mesh_deltas") .def("refine_mesh", &refine_mesh, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh2, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh_ij2, "Refine existing mesh in given points") .staticmethod("refine_mesh") ; return class__; } }; template< class fp_type > void reg_sparray_pair() { // register converter from pair of returned arrayes to python list typedef smart_ptr< bs_array< fp_type, bs_nparray > > spfp_array; typedef std::pair< spfp_array, spfp_array > array_pair; typedef bspy_converter< pair_traits< array_pair > > array_pair_converter; array_pair_converter::register_to_py(); array_pair_converter::register_from_py(); } } // eof hidden namespace namespace blue_sky { namespace python { void py_export_mesh_grdecl () { class_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class ("mesh_grdecl"); //reg_sparray_pair< float >(); reg_sparray_pair< double >(); } }} // namespace blue_sky::python #endif <|endoftext|>
<commit_before>#include "world.hh" #include <ACGL/OpenGL/Creator/VertexArrayObjectCreator.hh> #include <ACGL/OpenGL/Managers.hh> #include <ACGL/OpenGL/Creator/ShaderProgramCreator.hh> #include <ACGL/OpenGL/Data/TextureLoadStore.hh> #include "../audio/loadWavFile.hh" using namespace std; using namespace ACGL; using namespace ACGL::Utils; using namespace ACGL::OpenGL; glm::vec3 droidPosition1 = glm::vec3(-3.0f, 1.0f, -5.0f); glm::vec3 droidPosition2 = glm::vec3(0.0f, 1.0f, -5.0f); glm::vec3 droidPosition3 = glm::vec3(3.0f, 1.0f, -5.0f); bool LocalContactProcessedCallback(btManifoldPoint& cp, void* body0, void* body1); World::World() : mDroids{Droid(droidPosition1), Droid(droidPosition2), Droid(droidPosition3)}{ debug() << "loading game world..." << endl; mLevel.LoadMesh("geometry/L1/level.obj"); mDice.LoadMesh("geometry/test/dice.obj"); mQuad.LoadMesh(""); mTex.VLoadTexture("geometry/L1/Textures/metalbridgetoprailbig.jpg"); mBunnyShader = ShaderProgramFileManager::the()->get( ShaderProgramCreator("Bunny") ); CGEngine::LoadLightsFromFile("geometry/L1/level_lights.dae", mDirLights, mPointLights); glm::mat4 t = glm::translate(glm::mat4(1.0), glm::vec3(0.0, -1.0, 0.0)); for (unsigned int i = 0 ; i < mPointLights.size() ; ++i) mPointLights[i].Transform(t); mpRotProcess = GameLogic::RotationProcessPtr( new GameLogic::RotationProcess() ); mpProcessManager = GameLogic::CProcessManager::getInstance(); mpProcessManager->attachProcess( mpRotProcess ); //GLint n = mBunnyShader->getAttributeLocation("aNormal"); //GLint v = mBunnyShader->getAttributeLocation("aPosition"); //GLint t = mBunnyShader->getAttributeLocation("aTexCoord"); //mBunnyGeometry->setAttributeLocations( mBunnyShader->getAttributeLocations() ); //mBunnyTexture = loadTexture2D( "clownfishBunny.png" ); //initialize bullet ============================================================== btBroadphaseInterface* broadphase = new btDbvtBroadphase(); // Set up the collision configuration and dispatcher btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); // The actual physics solver btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; // The world. dynamicsWorld = new btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration); //dynamicsWorld->setGravity(btVector3(0,-10,0)); btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0),0.0); btScalar mass = 1.0; btVector3 fallInertia(0,0,0); //sphereShape->calculateLocalInertia(mass,fallInertia); btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0))); btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0)); btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI); //dynamicsWorld->addRigidBody(groundRigidBody); dynamicsWorld->addRigidBody(mDroids[0].mPhysicObject.rigidBody); dynamicsWorld->addRigidBody(mDroids[1].mPhysicObject.rigidBody); dynamicsWorld->addRigidBody(mDroids[2].mPhysicObject.rigidBody); dynamicsWorld->addRigidBody(mPlayer.mLightsaber.mPhysicObject.rigidBody); //===================================================================================== // load audio assets: mBeep = new SimpleSound( "audio/musiccensor.wav" ); mBeep->setLooping( true ); //mBeep->play(); } World::~World() { cout << "deleting world..." << endl; delete mBeep; delete dynamicsWorld; delete droidsPhysic; } void World::setPlayerCamera(ACGL::HardwareSupport::SimpleRiftController *riftControl) { mPlayer.setCamera(riftControl->getCamera()); } glm::vec3 World::getPlayerPosition() { return mPlayer.getPosition(); } void World::getPlayerOrientation(ALfloat *playerOrientation) { glm::mat4 HMDView = glm::inverse(mPlayer.getHMDViewMatrix()); glm::vec4 orientation = HMDView * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f); glm::vec4 lookUpVector = HMDView * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f); for (int i = 0; i < 3; i++) { playerOrientation[i] = (float) orientation[i]; playerOrientation[i + 3] = (float) lookUpVector[i]; } } void World::render() { mMatrixStack.LoadIdentity(); mMatrixStack.Translate(CGEngine::Vec3(0.0, -1.0, 0.0)); glm::mat4 modelMatrix = mMatrixStack.getCompleteTransform(); glm::mat4 viewMatrix = mPlayer.getHMDViewMatrix(); glm::mat4 projectionMatrix = mPlayer.getProjectionMatrix(); { mBunnyShader->use(); mBunnyShader->setUniform( "uModelMatrix", modelMatrix ); mBunnyShader->setUniform( "uViewMatrix", viewMatrix ); mBunnyShader->setUniform( "uProjectionMatrix", mPlayer.getProjectionMatrix() ); mBunnyShader->setUniform( "uNormalMatrix", glm::inverseTranspose(glm::mat3(viewMatrix)*glm::mat3(modelMatrix)) ); // At least 16 texture units can be used, but multiple texture can also be placed in one // texture array and thus only occupy one texture unit! mBunnyShader->setUniform( "uTexture", 0 ); } // // draw geometry // mLevel.VOnDraw(); mMatrixStack.LoadIdentity(); mMatrixStack.Translate(CGEngine::Vec3(0.0,1.0,-4.0)); mMatrixStack.Rotate( glm::radians( mpRotProcess->rotAngle ), CGEngine::Vec3(0.0,1.0,0.0) ); modelMatrix = mMatrixStack.getCompleteTransform(); viewMatrix = mPlayer.getHMDViewMatrix(); { mBunnyShader->use(); mBunnyShader->setUniform( "uModelMatrix", modelMatrix ); mBunnyShader->setUniform( "uViewMatrix", viewMatrix ); mBunnyShader->setUniform( "uProjectionMatrix", mPlayer.getProjectionMatrix() ); mBunnyShader->setUniform( "uNormalMatrix", glm::inverseTranspose(glm::mat3(viewMatrix)*glm::mat3(modelMatrix)) ); mBunnyShader->setUniform( "uTexture", 0 ); } mTex.Bind(GL_TEXTURE0); mDice.VOnDraw(); ======= mPlayer.mLightsaber.render(viewMatrix, projectionMatrix); mPlayer.mLightsaber.mPhysicObject.SetPosition(mPlayer.mLightsaber.getPosition()); if (mDroids[0].mDroidRenderFlag){ mDroids[0].render(viewMatrix, projectionMatrix); //mDroids[0].setPosition(mDroids[0].mPhysicObject.GetPosition()); } if (mDroids[1].mDroidRenderFlag){ mDroids[1].render(viewMatrix, projectionMatrix); //mDroids[1].setPosition(mDroids[1].mPhysicObject.GetPosition()); mDroids[1].move(glm::vec3(0.0f, 0.0f, 0.001f)); } if (mDroids[2].mDroidRenderFlag){ mDroids[2].render(viewMatrix, projectionMatrix); //mDroids[2].setPosition(mDroids[2].mPhysicObject.GetPosition()); } dynamicsWorld->stepSimulation(0.0166f,10); int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds(); for (int i=0;i<numManifolds;i++) { btPersistentManifold* contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i); btRigidBody *obj1 = btRigidBody::upcast((btCollisionObject*)contactManifold->getBody0()); btRigidBody *obj2 = btRigidBody::upcast((btCollisionObject*)contactManifold->getBody1()); //checking for lightsaber collision if (obj1 == mPlayer.mLightsaber.mPhysicObject.rigidBody || obj2 == mPlayer.mLightsaber.mPhysicObject.rigidBody){ if (obj1 == mPlayer.mLightsaber.mPhysicObject.rigidBody){ if ( mDroids[i].mPhysicObject.rigidBody == obj2){ //mDroids[i].; } } else{ for (int i = 0; i < 3; i++){ if ( mDroids[i].mPhysicObject.rigidBody == obj1){ mDroids[i].mDroidRenderFlag = false; } } } } } } void World::movePlayer(const glm::vec3 &direction) { mPlayer.move(direction); // simple game logic: // don't walk below the floor (y = 0) glm::vec3 playerPos = mPlayer.getPosition(); if (playerPos.y < 0.0f) { playerPos.y = 0.0f; mPlayer.setPosition(playerPos); } mPlayer.mLightsaber.setPlayerPosition(playerPos); mPlayer.mLightsaber.move(direction); } void World::rotatePlayer(float dYaw) { float yaw = 0.0f; float pitch = 0.0f; float dPitch = 0.0f; glm::mat3 R = mPlayer.getRotationMatrix3(); // get roll / pitch / yaw from the current rotation matrix: float yaw1 = asin(-R[2][0]); float yaw2 = M_PI - asin(-R[2][0]); float pitch1 = (cos(yaw1) > 0) ? atan2(R[2][1], R[2][2]) : atan2(-R[2][1], -R[2][2]); float pitch2 = (cos(yaw2) > 0) ? atan2(R[2][1], R[2][2]) : atan2(-R[2][1], -R[2][2]); float roll1 = (cos(yaw1) > 0) ? atan2(R[1][0], R[0][0]) : atan2(-R[1][0], -R[0][0]); float roll2 = (cos(yaw2) > 0) ? atan2(R[1][0], R[0][0]) : atan2(-R[1][0], -R[0][0]); // we assume no roll at all, in that case one of the roll variants will be 0.0 // if not, use the smaller one -> minimize the camera "jump" as this will destroy // information if (std::abs(roll1) <= std::abs(roll2)) { yaw = -yaw1; pitch = -pitch1; } else { yaw = -yaw2; pitch = -pitch2; } // add rotation diffs given: yaw = yaw + dYaw; pitch = glm::clamp(pitch + dPitch, -0.5f * (float) M_PI, 0.5f * (float) M_PI); // create rotation matices, seperated so we have full control over the order: glm::mat4 newRotY = glm::yawPitchRoll(yaw, 0.0f, 0.0f); glm::mat4 newRotX = glm::yawPitchRoll(0.0f, pitch, 0.0f); // multiplication order is important to prevent roll: mPlayer.setRotationMatrix(newRotX * newRotY); } void World::duckPlayer(float duckingValue) { mPlayer.duck(duckingValue); } void World::useForcePlayer() { mPlayer.useForce(); if (!mBeep->isPlaying()) { //mBeep->play(); } } void World::moveLightsaber(const glm::vec3 &direction) { mPlayer.mLightsaber.move(direction); } void World::toggleLightsaber() { mPlayer.mLightsaber.toggle(); } void World::rotateLightsaber(float dYaw, float dRoll, float dPitch){ mPlayer.mLightsaber.rotate(dYaw, dRoll, dPitch); } void World::update(int time) { mpProcessManager->updateProcesses(time); } void World::setWidthHeight(unsigned int _w, unsigned int _h) { window_width = _w; window_height = _h; } void World::DSRender() { m_GBuffer.StartFrame(); DSGeometryPass(); // We need stencil to be enabled in the stencil pass to get the stencil buffer // updated and we also need it in the light pass because we render the light // only if the stencil passes. glEnable(GL_STENCIL_TEST); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_CULL_FACE); unsigned int num_lights1 = mPointLights.size(); for (unsigned int i = 0 ; i < num_lights1; i++) { //DSStencilPass(i); DSPointLightPass(i); } // The directional light does not need a stencil test because its volume // is unlimited and the final pass simply copies the texture. glDisable(GL_STENCIL_TEST); //DSDirectionalLightPass(); //DSFinalPass(); } <commit_msg>Clean code<commit_after>#include "world.hh" #include <ACGL/OpenGL/Creator/VertexArrayObjectCreator.hh> #include <ACGL/OpenGL/Managers.hh> #include <ACGL/OpenGL/Creator/ShaderProgramCreator.hh> #include <ACGL/OpenGL/Data/TextureLoadStore.hh> #include "../audio/loadWavFile.hh" using namespace std; using namespace ACGL; using namespace ACGL::Utils; using namespace ACGL::OpenGL; glm::vec3 droidPosition1 = glm::vec3(-3.0f, 1.0f, -5.0f); glm::vec3 droidPosition2 = glm::vec3(0.0f, 1.0f, -5.0f); glm::vec3 droidPosition3 = glm::vec3(3.0f, 1.0f, -5.0f); bool LocalContactProcessedCallback(btManifoldPoint& cp, void* body0, void* body1); World::World() : mDroids{Droid(droidPosition1), Droid(droidPosition2), Droid(droidPosition3)}{ debug() << "loading game world..." << endl; mLevel.LoadMesh("geometry/L1/level.obj"); mDice.LoadMesh("geometry/test/dice.obj"); mQuad.LoadMesh(""); mTex.VLoadTexture("geometry/L1/Textures/metalbridgetoprailbig.jpg"); mBunnyShader = ShaderProgramFileManager::the()->get( ShaderProgramCreator("Bunny") ); CGEngine::LoadLightsFromFile("geometry/L1/level_lights.dae", mDirLights, mPointLights); glm::mat4 t = glm::translate(glm::mat4(1.0), glm::vec3(0.0, -1.0, 0.0)); for (unsigned int i = 0 ; i < mPointLights.size() ; ++i) mPointLights[i].Transform(t); mpRotProcess = GameLogic::RotationProcessPtr( new GameLogic::RotationProcess() ); mpProcessManager = GameLogic::CProcessManager::getInstance(); mpProcessManager->attachProcess( mpRotProcess ); //GLint n = mBunnyShader->getAttributeLocation("aNormal"); //GLint v = mBunnyShader->getAttributeLocation("aPosition"); //GLint t = mBunnyShader->getAttributeLocation("aTexCoord"); //mBunnyGeometry->setAttributeLocations( mBunnyShader->getAttributeLocations() ); //mBunnyTexture = loadTexture2D( "clownfishBunny.png" ); //initialize bullet ============================================================== btBroadphaseInterface* broadphase = new btDbvtBroadphase(); // Set up the collision configuration and dispatcher btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); // The actual physics solver btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; // The world. dynamicsWorld = new btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration); //dynamicsWorld->setGravity(btVector3(0,-10,0)); btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0),0.0); btScalar mass = 1.0; btVector3 fallInertia(0,0,0); //sphereShape->calculateLocalInertia(mass,fallInertia); btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0))); btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0)); btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI); //dynamicsWorld->addRigidBody(groundRigidBody); dynamicsWorld->addRigidBody(mDroids[0].mPhysicObject.rigidBody); dynamicsWorld->addRigidBody(mDroids[1].mPhysicObject.rigidBody); dynamicsWorld->addRigidBody(mDroids[2].mPhysicObject.rigidBody); dynamicsWorld->addRigidBody(mPlayer.mLightsaber.mPhysicObject.rigidBody); //===================================================================================== // load audio assets: mBeep = new SimpleSound( "audio/musiccensor.wav" ); mBeep->setLooping( true ); //mBeep->play(); } World::~World() { cout << "deleting world..." << endl; delete mBeep; delete dynamicsWorld; delete droidsPhysic; } void World::setPlayerCamera(ACGL::HardwareSupport::SimpleRiftController *riftControl) { mPlayer.setCamera(riftControl->getCamera()); } glm::vec3 World::getPlayerPosition() { return mPlayer.getPosition(); } void World::getPlayerOrientation(ALfloat *playerOrientation) { glm::mat4 HMDView = glm::inverse(mPlayer.getHMDViewMatrix()); glm::vec4 orientation = HMDView * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f); glm::vec4 lookUpVector = HMDView * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f); for (int i = 0; i < 3; i++) { playerOrientation[i] = (float) orientation[i]; playerOrientation[i + 3] = (float) lookUpVector[i]; } } void World::render() { mMatrixStack.LoadIdentity(); mMatrixStack.Translate(CGEngine::Vec3(0.0, -1.0, 0.0)); glm::mat4 modelMatrix = mMatrixStack.getCompleteTransform(); glm::mat4 viewMatrix = mPlayer.getHMDViewMatrix(); glm::mat4 projectionMatrix = mPlayer.getProjectionMatrix(); { mBunnyShader->use(); mBunnyShader->setUniform( "uModelMatrix", modelMatrix ); mBunnyShader->setUniform( "uViewMatrix", viewMatrix ); mBunnyShader->setUniform( "uProjectionMatrix", mPlayer.getProjectionMatrix() ); mBunnyShader->setUniform( "uNormalMatrix", glm::inverseTranspose(glm::mat3(viewMatrix)*glm::mat3(modelMatrix)) ); // At least 16 texture units can be used, but multiple texture can also be placed in one // texture array and thus only occupy one texture unit! mBunnyShader->setUniform( "uTexture", 0 ); } // // draw geometry // mLevel.VOnDraw(); mMatrixStack.LoadIdentity(); mMatrixStack.Translate(CGEngine::Vec3(0.0,1.0,-4.0)); mMatrixStack.Rotate( glm::radians( mpRotProcess->rotAngle ), CGEngine::Vec3(0.0,1.0,0.0) ); modelMatrix = mMatrixStack.getCompleteTransform(); viewMatrix = mPlayer.getHMDViewMatrix(); { mBunnyShader->use(); mBunnyShader->setUniform( "uModelMatrix", modelMatrix ); mBunnyShader->setUniform( "uViewMatrix", viewMatrix ); mBunnyShader->setUniform( "uProjectionMatrix", mPlayer.getProjectionMatrix() ); mBunnyShader->setUniform( "uNormalMatrix", glm::inverseTranspose(glm::mat3(viewMatrix)*glm::mat3(modelMatrix)) ); mBunnyShader->setUniform( "uTexture", 0 ); } mTex.Bind(GL_TEXTURE0); mDice.VOnDraw(); mPlayer.mLightsaber.render(viewMatrix, projectionMatrix); mPlayer.mLightsaber.mPhysicObject.SetPosition(mPlayer.mLightsaber.getPosition()); if (mDroids[0].mDroidRenderFlag){ mDroids[0].render(viewMatrix, projectionMatrix); //mDroids[0].setPosition(mDroids[0].mPhysicObject.GetPosition()); } if (mDroids[1].mDroidRenderFlag){ mDroids[1].render(viewMatrix, projectionMatrix); //mDroids[1].setPosition(mDroids[1].mPhysicObject.GetPosition()); mDroids[1].move(glm::vec3(0.0f, 0.0f, 0.001f)); } if (mDroids[2].mDroidRenderFlag){ mDroids[2].render(viewMatrix, projectionMatrix); //mDroids[2].setPosition(mDroids[2].mPhysicObject.GetPosition()); } dynamicsWorld->stepSimulation(0.0166f,10); int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds(); for (int i=0;i<numManifolds;i++) { btPersistentManifold* contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i); btRigidBody *obj1 = btRigidBody::upcast((btCollisionObject*)contactManifold->getBody0()); btRigidBody *obj2 = btRigidBody::upcast((btCollisionObject*)contactManifold->getBody1()); //checking for lightsaber collision if (obj1 == mPlayer.mLightsaber.mPhysicObject.rigidBody || obj2 == mPlayer.mLightsaber.mPhysicObject.rigidBody){ if (obj1 == mPlayer.mLightsaber.mPhysicObject.rigidBody){ if ( mDroids[i].mPhysicObject.rigidBody == obj2){ //mDroids[i].; } } else{ for (int i = 0; i < 3; i++){ if ( mDroids[i].mPhysicObject.rigidBody == obj1){ mDroids[i].mDroidRenderFlag = false; } } } } } } void World::movePlayer(const glm::vec3 &direction) { mPlayer.move(direction); // simple game logic: // don't walk below the floor (y = 0) glm::vec3 playerPos = mPlayer.getPosition(); if (playerPos.y < 0.0f) { playerPos.y = 0.0f; mPlayer.setPosition(playerPos); } mPlayer.mLightsaber.setPlayerPosition(playerPos); mPlayer.mLightsaber.move(direction); } void World::rotatePlayer(float dYaw) { float yaw = 0.0f; float pitch = 0.0f; float dPitch = 0.0f; glm::mat3 R = mPlayer.getRotationMatrix3(); // get roll / pitch / yaw from the current rotation matrix: float yaw1 = asin(-R[2][0]); float yaw2 = M_PI - asin(-R[2][0]); float pitch1 = (cos(yaw1) > 0) ? atan2(R[2][1], R[2][2]) : atan2(-R[2][1], -R[2][2]); float pitch2 = (cos(yaw2) > 0) ? atan2(R[2][1], R[2][2]) : atan2(-R[2][1], -R[2][2]); float roll1 = (cos(yaw1) > 0) ? atan2(R[1][0], R[0][0]) : atan2(-R[1][0], -R[0][0]); float roll2 = (cos(yaw2) > 0) ? atan2(R[1][0], R[0][0]) : atan2(-R[1][0], -R[0][0]); // we assume no roll at all, in that case one of the roll variants will be 0.0 // if not, use the smaller one -> minimize the camera "jump" as this will destroy // information if (std::abs(roll1) <= std::abs(roll2)) { yaw = -yaw1; pitch = -pitch1; } else { yaw = -yaw2; pitch = -pitch2; } // add rotation diffs given: yaw = yaw + dYaw; pitch = glm::clamp(pitch + dPitch, -0.5f * (float) M_PI, 0.5f * (float) M_PI); // create rotation matices, seperated so we have full control over the order: glm::mat4 newRotY = glm::yawPitchRoll(yaw, 0.0f, 0.0f); glm::mat4 newRotX = glm::yawPitchRoll(0.0f, pitch, 0.0f); // multiplication order is important to prevent roll: mPlayer.setRotationMatrix(newRotX * newRotY); } void World::duckPlayer(float duckingValue) { mPlayer.duck(duckingValue); } void World::useForcePlayer() { mPlayer.useForce(); if (!mBeep->isPlaying()) { //mBeep->play(); } } void World::moveLightsaber(const glm::vec3 &direction) { mPlayer.mLightsaber.move(direction); } void World::toggleLightsaber() { mPlayer.mLightsaber.toggle(); } void World::rotateLightsaber(float dYaw, float dRoll, float dPitch){ mPlayer.mLightsaber.rotate(dYaw, dRoll, dPitch); } void World::update(int time) { mpProcessManager->updateProcesses(time); } void World::setWidthHeight(unsigned int _w, unsigned int _h) { window_width = _w; window_height = _h; } void World::DSRender() { m_GBuffer.StartFrame(); DSGeometryPass(); // We need stencil to be enabled in the stencil pass to get the stencil buffer // updated and we also need it in the light pass because we render the light // only if the stencil passes. glEnable(GL_STENCIL_TEST); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_CULL_FACE); unsigned int num_lights1 = mPointLights.size(); for (unsigned int i = 0 ; i < num_lights1; i++) { //DSStencilPass(i); DSPointLightPass(i); } // The directional light does not need a stencil test because its volume // is unlimited and the final pass simply copies the texture. glDisable(GL_STENCIL_TEST); //DSDirectionalLightPass(); //DSFinalPass(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <config.h> #include <vector> #include <libport/cstdlib> #include <libport/containers.hh> #include <libport/debug.hh> #include <libport/detect-win32.h> #include <libport/program-name.hh> #include <libport/separate.hh> #include <libport/unistd.h> GD_INIT(); GD_ADD_CATEGORY(urbi); int main(int argc, char* argv[]) { libport::program_initialize(argc, argv); // Installation prefix. std::string urbi_root = libport::xgetenv("URBI_ROOT", URBI_ROOT); std::string urbi_launch = libport::xgetenv("URBI_LAUNCH", urbi_root + "/bin/urbi-launch" EXEEXT); std::vector<const char*> args; args.reserve(3 + argc + 1); libport::OptionParser opt_parser; opt_parser << libport::opts::debug; opt_parser(libport::program_arguments()); args << urbi_launch.c_str() << "--start"; if (libport::opts::debug.filled()) args << "--debug" << libport::opts::debug.value().c_str(); args << "--"; args.insert(args.end(), argv + 1, argv + argc); GD_CATEGORY(urbi); GD_FINFO_DEBUG("exec: %s", (libport::separate(args, " "))); libport::exec(args); } <commit_msg>urbi: die verbosly.<commit_after>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <config.h> #include <vector> #include <libport/cstdlib> #include <libport/containers.hh> #include <libport/debug.hh> #include <libport/detect-win32.h> #include <libport/program-name.hh> #include <libport/separate.hh> #include <libport/sysexits.hh> #include <libport/unistd.h> GD_INIT(); GD_ADD_CATEGORY(urbi); int main(int argc, char* argv[]) { libport::program_initialize(argc, argv); // Installation prefix. std::string urbi_root = libport::xgetenv("URBI_ROOT", URBI_ROOT); std::string urbi_launch = libport::xgetenv("URBI_LAUNCH", urbi_root + "/bin/urbi-launch" EXEEXT); std::vector<const char*> args; args.reserve(3 + argc + 1); libport::OptionParser opt_parser; opt_parser << libport::opts::debug; opt_parser(libport::program_arguments()); args << urbi_launch.c_str() << "--start"; if (libport::opts::debug.filled()) args << "--debug" << libport::opts::debug.value().c_str(); args << "--"; args.insert(args.end(), argv + 1, argv + argc); GD_CATEGORY(urbi); GD_FINFO_DEBUG("exec: %s", (libport::separate(args, " "))); try { libport::exec(args); } catch (const std::exception& e) { std::cerr << e.what() << std::endl << libport::exit(EX_OSFILE); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: filtergrouping.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2003-03-27 11:28:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SFX2_FILTERGROUPING_HXX #define SFX2_FILTERGROUPING_HXX #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_ #include <com/sun/star/ui/dialogs/XFilterManager.hpp> #endif #ifndef _SFX_FILEDLGIMPL_HXX #include "filedlgimpl.hxx" #endif class SfxFilterMatcherIter; //........................................................................ namespace sfx2 { //........................................................................ //-------------------------------------------------------------------- /** adds the given filters to the filter manager. <p>To be used when saving generic files.</p> */ void appendFiltersForSave( SfxFilterMatcherIter& _rFilterMatcher, const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilterManager >& _rFilterManager, ::rtl::OUString& /* [out] */ _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl ); void appendExportFilters( SfxFilterMatcherIter& _rFilterMatcher, const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilterManager >& _rFilterManager, ::rtl::OUString& /* [out] */ _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl ); //-------------------------------------------------------------------- /** adds the given filters to the filter manager. <p>To be used when opening generic files.</p> */ void appendFiltersForOpen( SfxFilterMatcherIter& _rFilterMatcher, const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilterManager >& _rFilterManager, ::rtl::OUString& /* [out] */ _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl ); //-------------------------------------------------------------------- /** adds the given extension to the display text. <p>To be used when opening or save generic files.</p> */ ::rtl::OUString addExtension( const ::rtl::OUString& _rDisplayText, const ::rtl::OUString& _rExtension, sal_Bool _bForOpen, FileDialogHelper_Impl& _rFileDlgImpl ); //........................................................................ } // namespace sfx2 //........................................................................ #endif // SFX2_FILTERGROUPING_HXX <commit_msg>INTEGRATION: CWS os12 (1.5.88); FILE MERGED 2004/03/09 12:18:03 as 1.5.88.1: #114059# use new DEFAULTFILTER mechanism<commit_after>/************************************************************************* * * $RCSfile: filtergrouping.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2004-04-29 16:41:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SFX2_FILTERGROUPING_HXX #define SFX2_FILTERGROUPING_HXX #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_ #include <com/sun/star/ui/dialogs/XFilterManager.hpp> #endif #ifndef _SFX_FILEDLGIMPL_HXX #include "filedlgimpl.hxx" #endif class SfxFilterMatcherIter; //........................................................................ namespace sfx2 { //........................................................................ //-------------------------------------------------------------------- /** adds the given filters to the filter manager. <p>To be used when saving generic files.</p> */ void appendFiltersForSave( SfxFilterMatcherIter& _rFilterMatcher, const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilterManager >& _rFilterManager, ::rtl::OUString& /* [out] */ _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl, const ::rtl::OUString& _rFactory ); void appendExportFilters( SfxFilterMatcherIter& _rFilterMatcher, const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilterManager >& _rFilterManager, ::rtl::OUString& /* [out] */ _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl ); //-------------------------------------------------------------------- /** adds the given filters to the filter manager. <p>To be used when opening generic files.</p> */ void appendFiltersForOpen( SfxFilterMatcherIter& _rFilterMatcher, const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilterManager >& _rFilterManager, ::rtl::OUString& /* [out] */ _rFirstNonEmpty, FileDialogHelper_Impl& _rFileDlgImpl ); //-------------------------------------------------------------------- /** adds the given extension to the display text. <p>To be used when opening or save generic files.</p> */ ::rtl::OUString addExtension( const ::rtl::OUString& _rDisplayText, const ::rtl::OUString& _rExtension, sal_Bool _bForOpen, FileDialogHelper_Impl& _rFileDlgImpl ); //........................................................................ } // namespace sfx2 //........................................................................ #endif // SFX2_FILTERGROUPING_HXX <|endoftext|>
<commit_before>/** * Unit tests for rf * @author Alexander Misevich * Copyright 2018 MIPT-MIPS */ // generic C #include <cassert> #include <cstdlib> // Google Test library #include <gtest/gtest.h> // MIPS-MIPS modules #include <mips/mips.h> #include "../rf.h" #define GTEST_ASSERT_NO_DEATH(statement) \ ASSERT_EXIT({{ statement } ::exit(EXIT_SUCCESS); }, ::testing::ExitedWithCode(0), "") class TestRF : public RF<MIPS> { public: TestRF() : RF<MIPS>() {}; using RF<MIPS>::read; using RF<MIPS>::write; }; static_assert(MIPSRegister::MAX_REG >= 32); TEST( RF, read_write_rf) { auto rf = std::make_unique<TestRF>(); // Fill array using write() and check correctness using read() for( size_t i = 0; i < 32; ++i) { rf->write( MIPSRegister(i), i); // Try to write something in zero register rf->write( MIPSRegister::zero, i); // Checks ASSERT_EQ( rf->read( MIPSRegister(i)), i); ASSERT_EQ( rf->read( MIPSRegister::zero), 0u); } // Additional checks for mips_hi_lo rf->write( MIPSRegister::mips_hi_lo, static_cast<uint64>(MAX_VAL32) + 1u); ASSERT_EQ( rf->read( MIPSRegister::mips_hi), 1u); ASSERT_EQ( rf->read( MIPSRegister::mips_lo), 0u); } TEST( RF, read_sources_write_dst_rf) { auto rf = std::make_unique<TestRF>(); // Fill Reg 25(it's src2) with some value rf->write( MIPSRegister(25), 1); // Create the instr( for example, "add") auto instr = std::make_unique<MIPSInstr>( 0x01398820); // Use read_sources( "add") method( initialize src1 and src2) rf->read_sources( instr.get()); // Execute instruction( to change v_dst field) instr->execute(); // Check ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); // Same instr = std::make_unique<MIPSInstr>( 0x01398821); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398824); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x0139880a); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x0139880b); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x71398802); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398827); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398825); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x03298804); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x03298806); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398822); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398823); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398826); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x0139882a); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x0139882b); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); } int main( int argc, char* argv[]) { ::testing::InitGoogleTest( &argc, argv); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); } <commit_msg>Add unit test for read_hi_lo()<commit_after>/** * Unit tests for rf * @author Alexander Misevich * Copyright 2018 MIPT-MIPS */ // generic C #include <cassert> #include <cstdlib> // Google Test library #include <gtest/gtest.h> // MIPS-MIPS modules #include <mips/mips.h> #include "../rf.h" #define GTEST_ASSERT_NO_DEATH(statement) \ ASSERT_EXIT({{ statement } ::exit(EXIT_SUCCESS); }, ::testing::ExitedWithCode(0), "") class TestRF : public RF<MIPS> { public: TestRF() : RF<MIPS>() {}; using RF<MIPS>::read; using RF<MIPS>::write; using RF<MIPS>::read_hi_lo; }; static_assert(MIPSRegister::MAX_REG >= 32); TEST( RF, read_write_rf) { auto rf = std::make_unique<TestRF>(); // Fill array using write() and check correctness using read() for( size_t i = 0; i < 32; ++i) { rf->write( MIPSRegister(i), i); // Try to write something in zero register rf->write( MIPSRegister::zero, i); // Checks ASSERT_EQ( rf->read( MIPSRegister(i)), i); ASSERT_EQ( rf->read( MIPSRegister::zero), 0u); } // Additional checks for mips_hi_lo rf->write( MIPSRegister::mips_hi_lo, static_cast<uint64>(MAX_VAL32) + 1u); ASSERT_EQ( rf->read( MIPSRegister::mips_hi), 1u); ASSERT_EQ( rf->read( MIPSRegister::mips_lo), 0u); ASSERT_EQ( rf->read_hi_lo(), static_cast<uint64>(MAX_VAL32) + 1u); } TEST( RF, read_sources_write_dst_rf) { auto rf = std::make_unique<TestRF>(); // Fill Reg 25(it's src2) with some value rf->write( MIPSRegister(25), 1); // Create the instr( for example, "add") auto instr = std::make_unique<MIPSInstr>( 0x01398820); // Use read_sources( "add") method( initialize src1 and src2) rf->read_sources( instr.get()); // Execute instruction( to change v_dst field) instr->execute(); // Check ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); // Same instr = std::make_unique<MIPSInstr>( 0x01398821); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398824); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x0139880a); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x0139880b); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x71398802); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398827); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398825); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x03298804); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x03298806); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398822); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398823); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x01398826); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x0139882a); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); instr = std::make_unique<MIPSInstr>( 0x0139882b); rf->read_sources( instr.get()); instr->execute(); ASSERT_EQ( instr->get_v_src2(), 1u); ASSERT_NE( instr->get_v_dst(), NO_VAL64); } int main( int argc, char* argv[]) { ::testing::InitGoogleTest( &argc, argv); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>//===-- DynamicLibrary.cpp - Runtime link/load libraries --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header file implements the operating system DynamicLibrary concept. // // FIXME: This file leaks ExplicitSymbols and OpenedHandles! // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Mutex.h" #include "llvm/Config/config.h" #include <cstdio> #include <cstring> // Collection of symbol name/value pairs to be searched prior to any libraries. static llvm::StringMap<void *> *ExplicitSymbols = 0; namespace { struct ExplicitSymbolsDeleter { ~ExplicitSymbolsDeleter() { delete ExplicitSymbols; } }; } static ExplicitSymbolsDeleter Dummy; static llvm::sys::SmartMutex<true>& getMutex() { static llvm::sys::SmartMutex<true> HandlesMutex; return HandlesMutex; } void llvm::sys::DynamicLibrary::AddSymbol(StringRef symbolName, void *symbolValue) { SmartScopedLock<true> lock(getMutex()); if (ExplicitSymbols == 0) ExplicitSymbols = new llvm::StringMap<void*>(); (*ExplicitSymbols)[symbolName] = symbolValue; } #ifdef LLVM_ON_WIN32 #include "Windows/DynamicLibrary.inc" #else #if HAVE_DLFCN_H #include <dlfcn.h> using namespace llvm; using namespace llvm::sys; //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only TRULY operating system //=== independent code. //===----------------------------------------------------------------------===// static DenseSet<void *> *OpenedHandles = 0; DynamicLibrary DynamicLibrary::getPermanentLibrary(const char *filename, std::string *errMsg) { void *handle = dlopen(filename, RTLD_LAZY|RTLD_GLOBAL); if (handle == 0) { if (errMsg) *errMsg = dlerror(); return DynamicLibrary(); } #ifdef __CYGWIN__ // Cygwin searches symbols only in the main // with the handle of dlopen(NULL, RTLD_GLOBAL). if (filename == NULL) handle = RTLD_DEFAULT; #endif SmartScopedLock<true> lock(getMutex()); if (OpenedHandles == 0) OpenedHandles = new DenseSet<void *>(); // If we've already loaded this library, dlclose() the handle in order to // keep the internal refcount at +1. if (!OpenedHandles->insert(handle).second) dlclose(handle); return DynamicLibrary(handle); } void *DynamicLibrary::getAddressOfSymbol(const char *symbolName) { if (!isValid()) return NULL; return dlsym(Data, symbolName); } #else using namespace llvm; using namespace llvm::sys; DynamicLibrary DynamicLibrary::getPermanentLibrary(const char *filename, std::string *errMsg) { if (errMsg) *errMsg = "dlopen() not supported on this platform"; return DynamicLibrary(); } void *DynamicLibrary::getAddressOfSymbol(const char *symbolName) { return NULL; } #endif namespace llvm { void *SearchForAddressOfSpecialSymbol(const char* symbolName); } void* DynamicLibrary::SearchForAddressOfSymbol(const char *symbolName) { SmartScopedLock<true> Lock(getMutex()); // First check symbols added via AddSymbol(). if (ExplicitSymbols) { StringMap<void *>::iterator i = ExplicitSymbols->find(symbolName); if (i != ExplicitSymbols->end()) return i->second; } #if HAVE_DLFCN_H // Now search the libraries. if (OpenedHandles) { for (DenseSet<void *>::iterator I = OpenedHandles->begin(), E = OpenedHandles->end(); I != E; ++I) { //lt_ptr ptr = lt_dlsym(*I, symbolName); void *ptr = dlsym(*I, symbolName); if (ptr) { return ptr; } } } #endif if (void *Result = llvm::SearchForAddressOfSpecialSymbol(symbolName)) return Result; // This macro returns the address of a well-known, explicit symbol #define EXPLICIT_SYMBOL(SYM) \ if (!strcmp(symbolName, #SYM)) return &SYM // On linux we have a weird situation. The stderr/out/in symbols are both // macros and global variables because of standards requirements. So, we // boldly use the EXPLICIT_SYMBOL macro without checking for a #define first. #if defined(__linux__) { EXPLICIT_SYMBOL(stderr); EXPLICIT_SYMBOL(stdout); EXPLICIT_SYMBOL(stdin); } #else // For everything else, we want to check to make sure the symbol isn't defined // as a macro before using EXPLICIT_SYMBOL. { #ifndef stdin EXPLICIT_SYMBOL(stdin); #endif #ifndef stdout EXPLICIT_SYMBOL(stdout); #endif #ifndef stderr EXPLICIT_SYMBOL(stderr); #endif } #endif #undef EXPLICIT_SYMBOL return 0; } #endif // LLVM_ON_WIN32 <commit_msg>Static fields require an out-of-line definition. Fix DynamicLibrary for real.<commit_after>//===-- DynamicLibrary.cpp - Runtime link/load libraries --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header file implements the operating system DynamicLibrary concept. // // FIXME: This file leaks ExplicitSymbols and OpenedHandles! // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Mutex.h" #include "llvm/Config/config.h" #include <cstdio> #include <cstring> // Collection of symbol name/value pairs to be searched prior to any libraries. static llvm::StringMap<void *> *ExplicitSymbols = 0; namespace { struct ExplicitSymbolsDeleter { ~ExplicitSymbolsDeleter() { delete ExplicitSymbols; } }; } static ExplicitSymbolsDeleter Dummy; static llvm::sys::SmartMutex<true>& getMutex() { static llvm::sys::SmartMutex<true> HandlesMutex; return HandlesMutex; } void llvm::sys::DynamicLibrary::AddSymbol(StringRef symbolName, void *symbolValue) { SmartScopedLock<true> lock(getMutex()); if (ExplicitSymbols == 0) ExplicitSymbols = new llvm::StringMap<void*>(); (*ExplicitSymbols)[symbolName] = symbolValue; } char llvm::sys::DynamicLibrary::Invalid = 0; #ifdef LLVM_ON_WIN32 #include "Windows/DynamicLibrary.inc" #else #if HAVE_DLFCN_H #include <dlfcn.h> using namespace llvm; using namespace llvm::sys; //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only TRULY operating system //=== independent code. //===----------------------------------------------------------------------===// static DenseSet<void *> *OpenedHandles = 0; DynamicLibrary DynamicLibrary::getPermanentLibrary(const char *filename, std::string *errMsg) { void *handle = dlopen(filename, RTLD_LAZY|RTLD_GLOBAL); if (handle == 0) { if (errMsg) *errMsg = dlerror(); return DynamicLibrary(); } #ifdef __CYGWIN__ // Cygwin searches symbols only in the main // with the handle of dlopen(NULL, RTLD_GLOBAL). if (filename == NULL) handle = RTLD_DEFAULT; #endif SmartScopedLock<true> lock(getMutex()); if (OpenedHandles == 0) OpenedHandles = new DenseSet<void *>(); // If we've already loaded this library, dlclose() the handle in order to // keep the internal refcount at +1. if (!OpenedHandles->insert(handle).second) dlclose(handle); return DynamicLibrary(handle); } void *DynamicLibrary::getAddressOfSymbol(const char *symbolName) { if (!isValid()) return NULL; return dlsym(Data, symbolName); } #else using namespace llvm; using namespace llvm::sys; DynamicLibrary DynamicLibrary::getPermanentLibrary(const char *filename, std::string *errMsg) { if (errMsg) *errMsg = "dlopen() not supported on this platform"; return DynamicLibrary(); } void *DynamicLibrary::getAddressOfSymbol(const char *symbolName) { return NULL; } #endif namespace llvm { void *SearchForAddressOfSpecialSymbol(const char* symbolName); } void* DynamicLibrary::SearchForAddressOfSymbol(const char *symbolName) { SmartScopedLock<true> Lock(getMutex()); // First check symbols added via AddSymbol(). if (ExplicitSymbols) { StringMap<void *>::iterator i = ExplicitSymbols->find(symbolName); if (i != ExplicitSymbols->end()) return i->second; } #if HAVE_DLFCN_H // Now search the libraries. if (OpenedHandles) { for (DenseSet<void *>::iterator I = OpenedHandles->begin(), E = OpenedHandles->end(); I != E; ++I) { //lt_ptr ptr = lt_dlsym(*I, symbolName); void *ptr = dlsym(*I, symbolName); if (ptr) { return ptr; } } } #endif if (void *Result = llvm::SearchForAddressOfSpecialSymbol(symbolName)) return Result; // This macro returns the address of a well-known, explicit symbol #define EXPLICIT_SYMBOL(SYM) \ if (!strcmp(symbolName, #SYM)) return &SYM // On linux we have a weird situation. The stderr/out/in symbols are both // macros and global variables because of standards requirements. So, we // boldly use the EXPLICIT_SYMBOL macro without checking for a #define first. #if defined(__linux__) { EXPLICIT_SYMBOL(stderr); EXPLICIT_SYMBOL(stdout); EXPLICIT_SYMBOL(stdin); } #else // For everything else, we want to check to make sure the symbol isn't defined // as a macro before using EXPLICIT_SYMBOL. { #ifndef stdin EXPLICIT_SYMBOL(stdin); #endif #ifndef stdout EXPLICIT_SYMBOL(stdout); #endif #ifndef stderr EXPLICIT_SYMBOL(stderr); #endif } #endif #undef EXPLICIT_SYMBOL return 0; } #endif // LLVM_ON_WIN32 <|endoftext|>
<commit_before>//===--- TargetRegistry.cpp - Target registration -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/TargetRegistry.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <vector> using namespace llvm; // Clients are responsible for avoid race conditions in registration. static Target *FirstTarget = nullptr; iterator_range<TargetRegistry::iterator> TargetRegistry::targets() { return make_range(iterator(FirstTarget), iterator()); } const Target *TargetRegistry::lookupTarget(const std::string &ArchName, Triple &TheTriple, std::string &Error) { // Allocate target machine. First, check whether the user has explicitly // specified an architecture to compile for. If so we have to look it up by // name, because it might be a backend that has no mapping to a target triple. const Target *TheTarget = nullptr; if (!ArchName.empty()) { auto I = std::find_if(targets().begin(), targets().end(), [&](const Target &T) { return ArchName == T.getName(); }); if (I == targets().end()) { Error = "error: invalid target '" + ArchName + "'.\n"; return nullptr; } TheTarget = &*I; // Adjust the triple to match (if known), otherwise stick with the // given triple. Triple::ArchType Type = Triple::getArchTypeForLLVMName(ArchName); if (Type != Triple::UnknownArch) TheTriple.setArch(Type); } else { // Get the target specific parser. std::string TempError; TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), TempError); if (!TheTarget) { Error = ": error: unable to get target for '" + TheTriple.getTriple() + "', see --version and --triple.\n"; return nullptr; } } return TheTarget; } const Target *TargetRegistry::lookupTarget(const std::string &TT, std::string &Error) { // Provide special warning when no targets are initialized. if (targets().begin() == targets().end()) { Error = "Unable to find target for this triple (no targets are registered)"; return nullptr; } Triple::ArchType Arch = Triple(TT).getArch(); auto ArchMatch = [&](const Target &T) { return T.ArchMatchFn(Arch); }; auto I = std::find_if(targets().begin(), targets().end(), ArchMatch); if (I == targets().end()) { Error = "No available targets are compatible with this triple, " "see -version for the available targets."; return nullptr; } auto J = std::find_if(std::next(I), targets().end(), ArchMatch); if (J != targets().end()) { Error = std::string("Cannot choose between targets \"") + I->Name + "\" and \"" + J->Name + "\""; return nullptr; } return &*I; } void TargetRegistry::RegisterTarget(Target &T, const char *Name, const char *ShortDesc, Target::ArchMatchFnTy ArchMatchFn, bool HasJIT) { assert(Name && ShortDesc && ArchMatchFn && "Missing required target information!"); // Check if this target has already been initialized, we allow this as a // convenience to some clients. if (T.Name) return; // Add to the list of targets. T.Next = FirstTarget; FirstTarget = &T; T.Name = Name; T.ShortDesc = ShortDesc; T.ArchMatchFn = ArchMatchFn; T.HasJIT = HasJIT; } static int TargetArraySortFn(const std::pair<StringRef, const Target *> *LHS, const std::pair<StringRef, const Target *> *RHS) { return LHS->first.compare(RHS->first); } void TargetRegistry::printRegisteredTargetsForVersion() { std::vector<std::pair<StringRef, const Target*> > Targets; size_t Width = 0; for (const auto &T : TargetRegistry::targets()) { Targets.push_back(std::make_pair(T.getName(), &T)); Width = std::max(Width, Targets.back().first.size()); } array_pod_sort(Targets.begin(), Targets.end(), TargetArraySortFn); raw_ostream &OS = outs(); OS << " Registered Targets:\n"; for (unsigned i = 0, e = Targets.size(); i != e; ++i) { OS << " " << Targets[i].first; OS.indent(Width - Targets[i].first.size()) << " - " << Targets[i].second->getShortDescription() << '\n'; } if (Targets.empty()) OS << " (none)\n"; } <commit_msg>Don't mention a command line option in an error.<commit_after>//===--- TargetRegistry.cpp - Target registration -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/TargetRegistry.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <vector> using namespace llvm; // Clients are responsible for avoid race conditions in registration. static Target *FirstTarget = nullptr; iterator_range<TargetRegistry::iterator> TargetRegistry::targets() { return make_range(iterator(FirstTarget), iterator()); } const Target *TargetRegistry::lookupTarget(const std::string &ArchName, Triple &TheTriple, std::string &Error) { // Allocate target machine. First, check whether the user has explicitly // specified an architecture to compile for. If so we have to look it up by // name, because it might be a backend that has no mapping to a target triple. const Target *TheTarget = nullptr; if (!ArchName.empty()) { auto I = std::find_if(targets().begin(), targets().end(), [&](const Target &T) { return ArchName == T.getName(); }); if (I == targets().end()) { Error = "error: invalid target '" + ArchName + "'.\n"; return nullptr; } TheTarget = &*I; // Adjust the triple to match (if known), otherwise stick with the // given triple. Triple::ArchType Type = Triple::getArchTypeForLLVMName(ArchName); if (Type != Triple::UnknownArch) TheTriple.setArch(Type); } else { // Get the target specific parser. std::string TempError; TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), TempError); if (!TheTarget) { Error = ": error: unable to get target for '" + TheTriple.getTriple() + "', see --version and --triple.\n"; return nullptr; } } return TheTarget; } const Target *TargetRegistry::lookupTarget(const std::string &TT, std::string &Error) { // Provide special warning when no targets are initialized. if (targets().begin() == targets().end()) { Error = "Unable to find target for this triple (no targets are registered)"; return nullptr; } Triple::ArchType Arch = Triple(TT).getArch(); auto ArchMatch = [&](const Target &T) { return T.ArchMatchFn(Arch); }; auto I = std::find_if(targets().begin(), targets().end(), ArchMatch); if (I == targets().end()) { Error = "No available targets are compatible with this triple."; return nullptr; } auto J = std::find_if(std::next(I), targets().end(), ArchMatch); if (J != targets().end()) { Error = std::string("Cannot choose between targets \"") + I->Name + "\" and \"" + J->Name + "\""; return nullptr; } return &*I; } void TargetRegistry::RegisterTarget(Target &T, const char *Name, const char *ShortDesc, Target::ArchMatchFnTy ArchMatchFn, bool HasJIT) { assert(Name && ShortDesc && ArchMatchFn && "Missing required target information!"); // Check if this target has already been initialized, we allow this as a // convenience to some clients. if (T.Name) return; // Add to the list of targets. T.Next = FirstTarget; FirstTarget = &T; T.Name = Name; T.ShortDesc = ShortDesc; T.ArchMatchFn = ArchMatchFn; T.HasJIT = HasJIT; } static int TargetArraySortFn(const std::pair<StringRef, const Target *> *LHS, const std::pair<StringRef, const Target *> *RHS) { return LHS->first.compare(RHS->first); } void TargetRegistry::printRegisteredTargetsForVersion() { std::vector<std::pair<StringRef, const Target*> > Targets; size_t Width = 0; for (const auto &T : TargetRegistry::targets()) { Targets.push_back(std::make_pair(T.getName(), &T)); Width = std::max(Width, Targets.back().first.size()); } array_pod_sort(Targets.begin(), Targets.end(), TargetArraySortFn); raw_ostream &OS = outs(); OS << " Registered Targets:\n"; for (unsigned i = 0, e = Targets.size(); i != e; ++i) { OS << " " << Targets[i].first; OS.indent(Width - Targets[i].first.size()) << " - " << Targets[i].second->getShortDescription() << '\n'; } if (Targets.empty()) OS << " (none)\n"; } <|endoftext|>
<commit_before>#include "reservasrv.h" #include "tools.h" Reserva ReservaSrv::add(std::string cedulaCliente, std::string nombreEspacio, time_t fechaReservacion, time_t fechaFinReservacion) { validarCedula(cedulaCliente); validarString(nombreEspacio); validarFechas(fechaReservacion, fechaFinReservacion); ClienteDAO clienteDAO; Cliente cliente = clienteDAO.get(cedulaCliente); Espacio* espacio = getEspacio(nombreEspacio); Reserva reserva(cliente, *espacio, fechaReservacion, fechaFinReservacion); dataBase.add(reserva); return reserva; } Reserva ReservaSrv::mod(std::string cedulaCliente, std::string nombreEspacio, time_t fechaReservacion, time_t fechaFinReservacion, std::string nuevoEspacio, time_t nuevaFechaReservacion, time_t nuevaFechaFinReservacion ) { validarCedula(cedulaCliente); validarString(nuevoEspacio); validarFechas(nuevaFechaReservacion, nuevaFechaFinReservacion); Reserva reserva = get(cedulaCliente, nombreEspacio, fechaReservacion, fechaFinReservacion); reserva.fechaReservacion = nuevaFechaReservacion; reserva.fechaFinReservacion = nuevaFechaFinReservacion; reserva.espacio = getEspacio(nuevoEspacio); dataBase.del(cedulaCliente, nombreEspacio, fechaReservacion, fechaFinReservacion); dataBase.add(reserva); return reserva; } void ReservaSrv::del(std::string cedulaCliente, std::string nombreEspacio, time_t fechaReservacion, time_t fechaFinReservacion) { dataBase.del(cedulaCliente, nombreEspacio, fechaReservacion, fechaFinReservacion); } std::vector<Reserva> ReservaSrv::get(std::string cedulaCliente) { return dataBase.get(cedulaCliente); } std::vector<Reserva> ReservaSrv::get(time_t fecha) { return get(fecha); } std::vector<Reserva> ReservaSrv::get(std::string cedulaCliente, time_t fecha) { return get(cedulaCliente, fecha); } std::vector<Reserva> ReservaSrv::get(time_t fechaInicial, time_t fechaFinal) { return get(fechaInicial, fechaFinal); } std::vector<Reserva> ReservaSrv::get(std::string cedulaCliente, time_t fechaInicial, time_t fechaFinal) { return get(cedulaCliente, fechaInicial, fechaFinal); } std::vector<Reserva> ReservaSrv::get() { return get(); } Espacio *ReservaSrv::getEspacio(std::string nombreEspacio) { Espacio* espacio; EspacioComplementarioDAO espacioComplementarioDAO; EspacioDeportivoDAO espacioDeportivoDAO; try { EspacioComplementario e = espacioComplementarioDAO.get(nombreEspacio); espacio = new EspacioComplementario(e.nombre, e.descripcion, e.precioPorhora, e.capacidad, e.estado, e.horario, e.tipo); } catch (...) { try { EspacioDeportivo e = espacioDeportivoDAO.get(nombreEspacio); espacio = new EspacioDeportivo(e.nombre, e.descripcion, e.precioPorhora, e.capacidad, e.estado, e.horario, e.tipo); } catch (...) { throw "Espacio no encontrado."; } } return espacio; } <commit_msg>implementado<commit_after>#include "reservasrv.h" #include "tools.h" Reserva ReservaSrv::add(std::string cedulaCliente, std::string nombreEspacio, time_t fechaReservacion, time_t fechaFinReservacion) { validarCedula(cedulaCliente); validarString(nombreEspacio); validarFechas(fechaReservacion, fechaFinReservacion); ClienteDAO clienteDAO; Cliente cliente = clienteDAO.get(cedulaCliente); Espacio* espacio = getEspacio(nombreEspacio); Reserva reserva(cliente, *espacio, fechaReservacion, fechaFinReservacion); dataBase.add(reserva); return reserva; } Reserva ReservaSrv::mod(std::string cedulaCliente, std::string nombreEspacio, time_t fechaReservacion, time_t fechaFinReservacion, std::string nuevoEspacio, time_t nuevaFechaReservacion, time_t nuevaFechaFinReservacion ) { validarCedula(cedulaCliente); validarString(nuevoEspacio); validarFechas(nuevaFechaReservacion, nuevaFechaFinReservacion); Reserva reserva = get(cedulaCliente, nombreEspacio, fechaReservacion, fechaFinReservacion); reserva.fechaReservacion = nuevaFechaReservacion; reserva.fechaFinReservacion = nuevaFechaFinReservacion; reserva.espacio = getEspacio(nuevoEspacio); dataBase.del(cedulaCliente, nombreEspacio, fechaReservacion, fechaFinReservacion); dataBase.add(reserva); return reserva; } void ReservaSrv::del(std::string cedulaCliente, std::string nombreEspacio, time_t fechaReservacion, time_t fechaFinReservacion) { dataBase.del(cedulaCliente, nombreEspacio, fechaReservacion, fechaFinReservacion); } Reserva ReservaSrv::get(std::string cedula, std::string nombreEspacio, time_t fechaReservacion, time_t fechaFinReservacion) { return get(cedula, nombreEspacio, fechaReservacion, fechaFinReservacion); } std::vector<Reserva> ReservaSrv::get(std::string cedulaCliente) { return dataBase.get(cedulaCliente); } std::vector<Reserva> ReservaSrv::get(time_t fecha) { return get(fecha); } std::vector<Reserva> ReservaSrv::get(std::string cedulaCliente, time_t fecha) { return get(cedulaCliente, fecha); } std::vector<Reserva> ReservaSrv::get(time_t fechaInicial, time_t fechaFinal) { return get(fechaInicial, fechaFinal); } std::vector<Reserva> ReservaSrv::get(std::string cedulaCliente, time_t fechaInicial, time_t fechaFinal) { return get(cedulaCliente, fechaInicial, fechaFinal); } std::vector<Reserva> ReservaSrv::get() { return get(); } Espacio *ReservaSrv::getEspacio(std::string nombreEspacio) { Espacio* espacio; EspacioComplementarioDAO espacioComplementarioDAO; EspacioDeportivoDAO espacioDeportivoDAO; try { EspacioComplementario e = espacioComplementarioDAO.get(nombreEspacio); espacio = new EspacioComplementario(e.nombre, e.descripcion, e.precioPorhora, e.capacidad, e.estado, e.horario, e.tipo); } catch (...) { try { EspacioDeportivo e = espacioDeportivoDAO.get(nombreEspacio); espacio = new EspacioDeportivo(e.nombre, e.descripcion, e.precioPorhora, e.capacidad, e.estado, e.horario, e.tipo); } catch (...) { throw "Espacio no encontrado."; } } return espacio; } <|endoftext|>
<commit_before>/* Copyright 2013-2014 Daniele Di Sarli 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 <string> #include <stdio.h> #include <stdlib.h> #include "client.h" #include "comsock.h" using namespace std; Client::Client(int argc, char *argv[], string socketPath) { this->socketPath = socketPath; if(argc >= 2) { string arg1(argv[1]); if(arg1 == "-e") { enable = true; } else if(arg1 == "-d") { disable = true; } else if(arg1 == "-s") { status = true; } } } void Client::Run() { if(enable) { int g_serverFd = connectOrExit(); int sent; message_t msg; msg.type = MSG_ENABLE; msg.buffer = NULL; msg.length = 0; sent = sendMessage(g_serverFd, &msg); if(sent == -1) { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } closeConnection(g_serverFd); } else if(disable) { int g_serverFd = connectOrExit(); int sent; message_t msg; msg.type = MSG_DISABLE; msg.buffer = NULL; msg.length = 0; sent = sendMessage(g_serverFd, &msg); if(sent == -1) { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } closeConnection(g_serverFd); } else if(status) { int g_serverFd = connectOrExit(); int sent; message_t msg; msg.type = MSG_STATUS; msg.buffer = NULL; msg.length = 0; sent = sendMessage(g_serverFd, &msg); if(sent == -1) { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } if(receiveMessage(g_serverFd, &msg) == -1) { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } if(msg.type == MSG_ENABLED) printf("1\n"); else if(msg.type == MSG_DISABLED) printf("0\n"); else { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } closeConnection(g_serverFd); } } int Client::connectOrExit() { int g_serverFd = openConnection((char*)this->socketPath.c_str(), NTRIAL, NSEC); if(g_serverFd == -1) { perror("Connessione al server"); exit(EXIT_FAILURE); } return g_serverFd; } <commit_msg>Replace Italian with English error message.<commit_after>/* Copyright 2013-2014 Daniele Di Sarli 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 <string> #include <stdio.h> #include <stdlib.h> #include "client.h" #include "comsock.h" using namespace std; Client::Client(int argc, char *argv[], string socketPath) { this->socketPath = socketPath; if(argc >= 2) { string arg1(argv[1]); if(arg1 == "-e") { enable = true; } else if(arg1 == "-d") { disable = true; } else if(arg1 == "-s") { status = true; } } } void Client::Run() { if(enable) { int g_serverFd = connectOrExit(); int sent; message_t msg; msg.type = MSG_ENABLE; msg.buffer = NULL; msg.length = 0; sent = sendMessage(g_serverFd, &msg); if(sent == -1) { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } closeConnection(g_serverFd); } else if(disable) { int g_serverFd = connectOrExit(); int sent; message_t msg; msg.type = MSG_DISABLE; msg.buffer = NULL; msg.length = 0; sent = sendMessage(g_serverFd, &msg); if(sent == -1) { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } closeConnection(g_serverFd); } else if(status) { int g_serverFd = connectOrExit(); int sent; message_t msg; msg.type = MSG_STATUS; msg.buffer = NULL; msg.length = 0; sent = sendMessage(g_serverFd, &msg); if(sent == -1) { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } if(receiveMessage(g_serverFd, &msg) == -1) { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } if(msg.type == MSG_ENABLED) printf("1\n"); else if(msg.type == MSG_DISABLED) printf("0\n"); else { perror("Error"); closeConnection(g_serverFd); exit(EXIT_FAILURE); } closeConnection(g_serverFd); } } int Client::connectOrExit() { int g_serverFd = openConnection((char*)this->socketPath.c_str(), NTRIAL, NSEC); if(g_serverFd == -1) { perror("No connection to the server."); exit(EXIT_FAILURE); } return g_serverFd; } <|endoftext|>
<commit_before>//===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is designed to be a very quick global transformation that // eliminates global common subexpressions from a function. It does this by // using an existing value numbering implementation to identify the common // subexpressions, eliminating them when possible. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/BasicBlock.h" #include "llvm/Constant.h" #include "llvm/Instructions.h" #include "llvm/Type.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/ValueNumbering.h" #include "llvm/Transforms/Utils/Local.h" #include "Support/DepthFirstIterator.h" #include "Support/Statistic.h" #include <algorithm> using namespace llvm; namespace { Statistic<> NumInstRemoved("gcse", "Number of instructions removed"); Statistic<> NumLoadRemoved("gcse", "Number of loads removed"); Statistic<> NumCallRemoved("gcse", "Number of calls removed"); Statistic<> NumNonInsts ("gcse", "Number of instructions removed due " "to non-instruction values"); Statistic<> NumArgsRepl ("gcse", "Number of function arguments replaced " "with constant values"); struct GCSE : public FunctionPass { virtual bool runOnFunction(Function &F); private: void ReplaceInstructionWith(Instruction *I, Value *V); // This transformation requires dominator and immediate dominator info virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<DominatorSet>(); AU.addRequired<DominatorTree>(); AU.addRequired<ValueNumbering>(); } }; RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination"); } // createGCSEPass - The public interface to this file... FunctionPass *llvm::createGCSEPass() { return new GCSE(); } // GCSE::runOnFunction - This is the main transformation entry point for a // function. // bool GCSE::runOnFunction(Function &F) { bool Changed = false; // Get pointers to the analysis results that we will be using... DominatorSet &DS = getAnalysis<DominatorSet>(); ValueNumbering &VN = getAnalysis<ValueNumbering>(); DominatorTree &DT = getAnalysis<DominatorTree>(); std::vector<Value*> EqualValues; // Check for value numbers of arguments. If the value numbering // implementation can prove that an incoming argument is a constant or global // value address, substitute it, making the argument dead. for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI) if (!AI->use_empty()) { VN.getEqualNumberNodes(AI, EqualValues); if (!EqualValues.empty()) { for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) if (isa<Constant>(EqualValues[i])) { AI->replaceAllUsesWith(EqualValues[i]); ++NumArgsRepl; Changed = true; break; } EqualValues.clear(); } } // Traverse the CFG of the function in dominator order, so that we see each // instruction after we see its operands. for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()), E = df_end(DT.getRootNode()); DI != E; ++DI) { BasicBlock *BB = DI->getBlock(); // Remember which instructions we've seen in this basic block as we scan. std::set<Instruction*> BlockInsts; for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { Instruction *Inst = I++; // If this instruction computes a value, try to fold together common // instructions that compute it. // if (Inst->getType() != Type::VoidTy) { VN.getEqualNumberNodes(Inst, EqualValues); // If this instruction computes a value that is already computed // elsewhere, try to recycle the old value. if (!EqualValues.empty()) { if (Inst == &*BB->begin()) I = BB->end(); else { I = Inst; --I; } // First check to see if we were able to value number this instruction // to a non-instruction value. If so, prefer that value over other // instructions which may compute the same thing. for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) if (!isa<Instruction>(EqualValues[i])) { ++NumNonInsts; // Keep track of # of insts repl with values // Change all users of Inst to use the replacement and remove it // from the program. ReplaceInstructionWith(Inst, EqualValues[i]); Inst = 0; EqualValues.clear(); // don't enter the next loop break; } // If there were no non-instruction values that this instruction // produces, find a dominating instruction that produces the same // value. If we find one, use it's value instead of ours. for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) { Instruction *OtherI = cast<Instruction>(EqualValues[i]); bool Dominates = false; if (OtherI->getParent() == BB) Dominates = BlockInsts.count(OtherI); else Dominates = DS.dominates(OtherI->getParent(), BB); if (Dominates) { // Okay, we found an instruction with the same value as this one // and that dominates this one. Replace this instruction with the // specified one. ReplaceInstructionWith(Inst, OtherI); Inst = 0; break; } } EqualValues.clear(); if (Inst) { I = Inst; ++I; // Deleted no instructions } else if (I == BB->end()) { // Deleted first instruction I = BB->begin(); } else { // Deleted inst in middle of block. ++I; } } if (Inst) BlockInsts.insert(Inst); } } } // When the worklist is empty, return whether or not we changed anything... return Changed; } void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) { if (isa<LoadInst>(I)) ++NumLoadRemoved; // Keep track of loads eliminated if (isa<CallInst>(I)) ++NumCallRemoved; // Keep track of calls eliminated ++NumInstRemoved; // Keep track of number of insts eliminated // Update value numbering getAnalysis<ValueNumbering>().deleteValue(I); // If we are not replacing the instruction with a constant, we cannot do // anything special. if (!isa<Constant>(V) || isa<GlobalValue>(V)) { I->replaceAllUsesWith(V); if (InvokeInst *II = dyn_cast<InvokeInst>(I)) { // Removing an invoke instruction requires adding a branch to the normal // destination and removing PHI node entries in the exception destination. new BranchInst(II->getNormalDest(), II); II->getUnwindDest()->removePredecessor(II->getParent()); } // Erase the instruction from the program. I->getParent()->getInstList().erase(I); return; } Constant *C = cast<Constant>(V); std::vector<User*> Users(I->use_begin(), I->use_end()); // Perform the replacement. I->replaceAllUsesWith(C); if (InvokeInst *II = dyn_cast<InvokeInst>(I)) { // Removing an invoke instruction requires adding a branch to the normal // destination and removing PHI node entries in the exception destination. new BranchInst(II->getNormalDest(), II); II->getUnwindDest()->removePredecessor(II->getParent()); } // Erase the instruction from the program. I->getParent()->getInstList().erase(I); // Check each user to see if we can constant fold it. while (!Users.empty()) { Instruction *U = cast<Instruction>(Users.back()); Users.pop_back(); if (Constant *C = ConstantFoldInstruction(U)) { ReplaceInstructionWith(U, C); // If the instruction used I more than once, it could be on the user list // multiple times. Make sure we don't reprocess it. std::vector<User*>::iterator It = std::find(Users.begin(), Users.end(),U); while (It != Users.end()) { Users.erase(It); It = std::find(Users.begin(), Users.end(), U); } } } } <commit_msg>Expand the scope to include global values because they are now constants too.<commit_after>//===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass is designed to be a very quick global transformation that // eliminates global common subexpressions from a function. It does this by // using an existing value numbering implementation to identify the common // subexpressions, eliminating them when possible. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/BasicBlock.h" #include "llvm/Constant.h" #include "llvm/Instructions.h" #include "llvm/Type.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/ValueNumbering.h" #include "llvm/Transforms/Utils/Local.h" #include "Support/DepthFirstIterator.h" #include "Support/Statistic.h" #include <algorithm> using namespace llvm; namespace { Statistic<> NumInstRemoved("gcse", "Number of instructions removed"); Statistic<> NumLoadRemoved("gcse", "Number of loads removed"); Statistic<> NumCallRemoved("gcse", "Number of calls removed"); Statistic<> NumNonInsts ("gcse", "Number of instructions removed due " "to non-instruction values"); Statistic<> NumArgsRepl ("gcse", "Number of function arguments replaced " "with constant values"); struct GCSE : public FunctionPass { virtual bool runOnFunction(Function &F); private: void ReplaceInstructionWith(Instruction *I, Value *V); // This transformation requires dominator and immediate dominator info virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<DominatorSet>(); AU.addRequired<DominatorTree>(); AU.addRequired<ValueNumbering>(); } }; RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination"); } // createGCSEPass - The public interface to this file... FunctionPass *llvm::createGCSEPass() { return new GCSE(); } // GCSE::runOnFunction - This is the main transformation entry point for a // function. // bool GCSE::runOnFunction(Function &F) { bool Changed = false; // Get pointers to the analysis results that we will be using... DominatorSet &DS = getAnalysis<DominatorSet>(); ValueNumbering &VN = getAnalysis<ValueNumbering>(); DominatorTree &DT = getAnalysis<DominatorTree>(); std::vector<Value*> EqualValues; // Check for value numbers of arguments. If the value numbering // implementation can prove that an incoming argument is a constant or global // value address, substitute it, making the argument dead. for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI) if (!AI->use_empty()) { VN.getEqualNumberNodes(AI, EqualValues); if (!EqualValues.empty()) { for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) if (isa<Constant>(EqualValues[i])) { AI->replaceAllUsesWith(EqualValues[i]); ++NumArgsRepl; Changed = true; break; } EqualValues.clear(); } } // Traverse the CFG of the function in dominator order, so that we see each // instruction after we see its operands. for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()), E = df_end(DT.getRootNode()); DI != E; ++DI) { BasicBlock *BB = DI->getBlock(); // Remember which instructions we've seen in this basic block as we scan. std::set<Instruction*> BlockInsts; for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { Instruction *Inst = I++; // If this instruction computes a value, try to fold together common // instructions that compute it. // if (Inst->getType() != Type::VoidTy) { VN.getEqualNumberNodes(Inst, EqualValues); // If this instruction computes a value that is already computed // elsewhere, try to recycle the old value. if (!EqualValues.empty()) { if (Inst == &*BB->begin()) I = BB->end(); else { I = Inst; --I; } // First check to see if we were able to value number this instruction // to a non-instruction value. If so, prefer that value over other // instructions which may compute the same thing. for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) if (!isa<Instruction>(EqualValues[i])) { ++NumNonInsts; // Keep track of # of insts repl with values // Change all users of Inst to use the replacement and remove it // from the program. ReplaceInstructionWith(Inst, EqualValues[i]); Inst = 0; EqualValues.clear(); // don't enter the next loop break; } // If there were no non-instruction values that this instruction // produces, find a dominating instruction that produces the same // value. If we find one, use it's value instead of ours. for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) { Instruction *OtherI = cast<Instruction>(EqualValues[i]); bool Dominates = false; if (OtherI->getParent() == BB) Dominates = BlockInsts.count(OtherI); else Dominates = DS.dominates(OtherI->getParent(), BB); if (Dominates) { // Okay, we found an instruction with the same value as this one // and that dominates this one. Replace this instruction with the // specified one. ReplaceInstructionWith(Inst, OtherI); Inst = 0; break; } } EqualValues.clear(); if (Inst) { I = Inst; ++I; // Deleted no instructions } else if (I == BB->end()) { // Deleted first instruction I = BB->begin(); } else { // Deleted inst in middle of block. ++I; } } if (Inst) BlockInsts.insert(Inst); } } } // When the worklist is empty, return whether or not we changed anything... return Changed; } void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) { if (isa<LoadInst>(I)) ++NumLoadRemoved; // Keep track of loads eliminated if (isa<CallInst>(I)) ++NumCallRemoved; // Keep track of calls eliminated ++NumInstRemoved; // Keep track of number of insts eliminated // Update value numbering getAnalysis<ValueNumbering>().deleteValue(I); // If we are not replacing the instruction with a constant, we cannot do // anything special. if (!isa<Constant>(V)) { I->replaceAllUsesWith(V); if (InvokeInst *II = dyn_cast<InvokeInst>(I)) { // Removing an invoke instruction requires adding a branch to the normal // destination and removing PHI node entries in the exception destination. new BranchInst(II->getNormalDest(), II); II->getUnwindDest()->removePredecessor(II->getParent()); } // Erase the instruction from the program. I->getParent()->getInstList().erase(I); return; } Constant *C = cast<Constant>(V); std::vector<User*> Users(I->use_begin(), I->use_end()); // Perform the replacement. I->replaceAllUsesWith(C); if (InvokeInst *II = dyn_cast<InvokeInst>(I)) { // Removing an invoke instruction requires adding a branch to the normal // destination and removing PHI node entries in the exception destination. new BranchInst(II->getNormalDest(), II); II->getUnwindDest()->removePredecessor(II->getParent()); } // Erase the instruction from the program. I->getParent()->getInstList().erase(I); // Check each user to see if we can constant fold it. while (!Users.empty()) { Instruction *U = cast<Instruction>(Users.back()); Users.pop_back(); if (Constant *C = ConstantFoldInstruction(U)) { ReplaceInstructionWith(U, C); // If the instruction used I more than once, it could be on the user list // multiple times. Make sure we don't reprocess it. std::vector<User*>::iterator It = std::find(Users.begin(), Users.end(),U); while (It != Users.end()) { Users.erase(It); It = std::find(Users.begin(), Users.end(), U); } } } } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // // Main.cpp // // Minimal application to test OpenZWave for Lua. // // Creates an OpenZWave::Driver and the waits. In Debug builds // you should see verbose logging to the console, which will // indicate that communications with the Z-Wave network are working. // // Copyright (c) 2010 Mal Lansell <mal@openzwave.com> // Copyright (c) 2013 Justin Hammond <justin@dynam.ac> // // SOFTWARE NOTICE AND LICENSE // // This file was taken from OpenZWave. // // OpenZWave is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // OpenZWave 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 OpenZWave. If not, see <http://www.gnu.org/licenses/>. // //----------------------------------------------------------------------------- #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <Options.h> #include <Manager.h> #include <Driver.h> #include <Node.h> #include <Group.h> #include <Notification.h> #include <ValueStore.h> #include <Value.h> #include <ValueBool.h> #include <Log.h> #include "openzwavelua.hpp" using namespace OpenZWave; static uint32 g_homeId = 0; static bool g_initFailed = false; typedef struct { uint32 m_homeId; uint8 m_nodeId; bool m_polled; list<ValueID> m_values; }NodeInfo; static list<NodeInfo*> g_nodes; static pthread_mutex_t g_criticalSection; static pthread_cond_t initCond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t initMutex = PTHREAD_MUTEX_INITIALIZER; OZW4Lua *ozw4lua; //----------------------------------------------------------------------------- // <GetNodeInfo> // Return the NodeInfo object associated with this notification //----------------------------------------------------------------------------- NodeInfo* GetNodeInfo ( Notification const* _notification ) { uint32 const homeId = _notification->GetHomeId(); uint8 const nodeId = _notification->GetNodeId(); for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it ) { NodeInfo* nodeInfo = *it; if( ( nodeInfo->m_homeId == homeId ) && ( nodeInfo->m_nodeId == nodeId ) ) { return nodeInfo; } } return NULL; } //----------------------------------------------------------------------------- // <OnNotification> // Callback that is triggered when a value, group or node changes //----------------------------------------------------------------------------- void OnNotification ( Notification const* _notification, void* _context ) { // Must do this inside a critical section to avoid conflicts with the main thread pthread_mutex_lock( &g_criticalSection ); ozw4lua->DoNotification(_notification); pthread_mutex_unlock( &g_criticalSection ); } //----------------------------------------------------------------------------- // <main> // Create the driver and then wait //----------------------------------------------------------------------------- int main( int argc, char* argv[] ) { pthread_mutexattr_t mutexattr; pthread_mutexattr_init ( &mutexattr ); pthread_mutexattr_settype( &mutexattr, PTHREAD_MUTEX_RECURSIVE ); pthread_mutex_init( &g_criticalSection, &mutexattr ); pthread_mutexattr_destroy( &mutexattr ); pthread_mutex_lock( &initMutex ); // Create the OpenZWave Manager. // The first argument is the path to the config files (where the manufacturer_specific.xml file is located // The second argument is the path for saved Z-Wave network state and the log file. If you leave it NULL // the log file will appear in the program's working directory. Options::Create( "/etc/openzwave/config/", "", "" ); Options::Get()->AddOptionInt( "SaveLogLevel", LogLevel_Detail ); Options::Get()->AddOptionInt( "QueueLogLevel", LogLevel_Debug ); Options::Get()->AddOptionInt( "DumpTrigger", LogLevel_Error ); Options::Get()->AddOptionInt( "PollInterval", 500 ); Options::Get()->AddOptionBool( "IntervalBetweenPolls", true ); Options::Get()->AddOptionBool("ValidateValueChanges", true); Options::Get()->Lock(); Manager::Create(); ozw4lua = new OZW4Lua(); if (!ozw4lua->InitManager(Manager::Get(), "example.lua")) { std::cerr << "OZW4Lua Couldn't Initialize" << std::endl; exit(-1); } // Add a callback handler to the manager. The second argument is a context that // is passed to the OnNotification method. If the OnNotification is a method of // a class, the context would usually be a pointer to that class object, to // avoid the need for the notification handler to be a static. Manager::Get()->AddWatcher( OnNotification, NULL ); // Add a Z-Wave Driver // Modify this line to set the correct serial port for your PC interface. string port = "/dev/ttyUSB1"; if ( argc > 1 ) { port = argv[1]; } if( strcasecmp( port.c_str(), "usb" ) == 0 ) { Manager::Get()->AddDriver( "HID Controller", Driver::ControllerInterface_Hid ); } else { Manager::Get()->AddDriver( port ); } // Now we just wait for either the AwakeNodesQueried or AllNodesQueried notification, // then write out the config file. // In a normal app, we would be handling notifications and building a UI for the user. pthread_cond_wait( &initCond, &initMutex ); // Since the configuration file contains command class information that is only // known after the nodes on the network are queried, wait until all of the nodes // on the network have been queried (at least the "listening" ones) before // writing the configuration file. (Maybe write again after sleeping nodes have // been queried as well.) if( !g_initFailed ) { Manager::Get()->WriteConfig( g_homeId ); // The section below demonstrates setting up polling for a variable. In this simple // example, it has been hardwired to poll COMMAND_CLASS_BASIC on the each node that // supports this setting. pthread_mutex_lock( &g_criticalSection ); for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it ) { NodeInfo* nodeInfo = *it; // skip the controller (most likely node 1) if( nodeInfo->m_nodeId == 1) continue; for( list<ValueID>::iterator it2 = nodeInfo->m_values.begin(); it2 != nodeInfo->m_values.end(); ++it2 ) { ValueID v = *it2; if( v.GetCommandClassId() == 0x20 ) { // Manager::Get()->EnablePoll( v, 2 ); // enables polling with "intensity" of 2, though this is irrelevant with only one value polled break; } } } pthread_mutex_unlock( &g_criticalSection ); // If we want to access our NodeInfo list, that has been built from all the // notification callbacks we received from the library, we have to do so // from inside a Critical Section. This is because the callbacks occur on other // threads, and we cannot risk the list being changed while we are using it. // We must hold the critical section for as short a time as possible, to avoid // stalling the OpenZWave drivers. // At this point, the program just waits for 3 minutes (to demonstrate polling), // then exits for( int i = 0; i < 60*3; i++ ) { pthread_mutex_lock( &g_criticalSection ); // but NodeInfo list and similar data should be inside critical section pthread_mutex_unlock( &g_criticalSection ); sleep(1); } Driver::DriverData data; Manager::Get()->GetDriverStatistics( g_homeId, &data ); printf("SOF: %d ACK Waiting: %d Read Aborts: %d Bad Checksums: %d\n", data.m_SOFCnt, data.m_ACKWaiting, data.m_readAborts, data.m_badChecksum); printf("Reads: %d Writes: %d CAN: %d NAK: %d ACK: %d Out of Frame: %d\n", data.m_readCnt, data.m_writeCnt, data.m_CANCnt, data.m_NAKCnt, data.m_ACKCnt, data.m_OOFCnt); printf("Dropped: %d Retries: %d\n", data.m_dropped, data.m_retries); } // program exit (clean up) if( strcasecmp( port.c_str(), "usb" ) == 0 ) { Manager::Get()->RemoveDriver( "HID Controller" ); } else { Manager::Get()->RemoveDriver( port ); } Manager::Get()->RemoveWatcher( OnNotification, NULL ); Manager::Destroy(); Options::Destroy(); pthread_mutex_destroy( &g_criticalSection ); return 0; } <commit_msg>fix CentOS Builds again<commit_after>//----------------------------------------------------------------------------- // // Main.cpp // // Minimal application to test OpenZWave for Lua. // // Creates an OpenZWave::Driver and the waits. In Debug builds // you should see verbose logging to the console, which will // indicate that communications with the Z-Wave network are working. // // Copyright (c) 2010 Mal Lansell <mal@openzwave.com> // Copyright (c) 2013 Justin Hammond <justin@dynam.ac> // // SOFTWARE NOTICE AND LICENSE // // This file was taken from OpenZWave. // // OpenZWave is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // OpenZWave 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 OpenZWave. If not, see <http://www.gnu.org/licenses/>. // //----------------------------------------------------------------------------- #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <iostream> #include <Options.h> #include <Manager.h> #include <Driver.h> #include <Node.h> #include <Group.h> #include <Notification.h> #include <ValueStore.h> #include <Value.h> #include <ValueBool.h> #include <Log.h> #include "openzwavelua.hpp" using namespace OpenZWave; static uint32 g_homeId = 0; static bool g_initFailed = false; typedef struct { uint32 m_homeId; uint8 m_nodeId; bool m_polled; list<ValueID> m_values; }NodeInfo; static list<NodeInfo*> g_nodes; static pthread_mutex_t g_criticalSection; static pthread_cond_t initCond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t initMutex = PTHREAD_MUTEX_INITIALIZER; OZW4Lua *ozw4lua; //----------------------------------------------------------------------------- // <GetNodeInfo> // Return the NodeInfo object associated with this notification //----------------------------------------------------------------------------- NodeInfo* GetNodeInfo ( Notification const* _notification ) { uint32 const homeId = _notification->GetHomeId(); uint8 const nodeId = _notification->GetNodeId(); for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it ) { NodeInfo* nodeInfo = *it; if( ( nodeInfo->m_homeId == homeId ) && ( nodeInfo->m_nodeId == nodeId ) ) { return nodeInfo; } } return NULL; } //----------------------------------------------------------------------------- // <OnNotification> // Callback that is triggered when a value, group or node changes //----------------------------------------------------------------------------- void OnNotification ( Notification const* _notification, void* _context ) { // Must do this inside a critical section to avoid conflicts with the main thread pthread_mutex_lock( &g_criticalSection ); ozw4lua->DoNotification(_notification); pthread_mutex_unlock( &g_criticalSection ); } //----------------------------------------------------------------------------- // <main> // Create the driver and then wait //----------------------------------------------------------------------------- int main( int argc, char* argv[] ) { pthread_mutexattr_t mutexattr; pthread_mutexattr_init ( &mutexattr ); pthread_mutexattr_settype( &mutexattr, PTHREAD_MUTEX_RECURSIVE ); pthread_mutex_init( &g_criticalSection, &mutexattr ); pthread_mutexattr_destroy( &mutexattr ); pthread_mutex_lock( &initMutex ); // Create the OpenZWave Manager. // The first argument is the path to the config files (where the manufacturer_specific.xml file is located // The second argument is the path for saved Z-Wave network state and the log file. If you leave it NULL // the log file will appear in the program's working directory. Options::Create( "/etc/openzwave/config/", "", "" ); Options::Get()->AddOptionInt( "SaveLogLevel", LogLevel_Detail ); Options::Get()->AddOptionInt( "QueueLogLevel", LogLevel_Debug ); Options::Get()->AddOptionInt( "DumpTrigger", LogLevel_Error ); Options::Get()->AddOptionInt( "PollInterval", 500 ); Options::Get()->AddOptionBool( "IntervalBetweenPolls", true ); Options::Get()->AddOptionBool("ValidateValueChanges", true); Options::Get()->Lock(); Manager::Create(); ozw4lua = new OZW4Lua(); if (!ozw4lua->InitManager(Manager::Get(), "example.lua")) { std::cerr << "OZW4Lua Couldn't Initialize" << std::endl; exit(-1); } // Add a callback handler to the manager. The second argument is a context that // is passed to the OnNotification method. If the OnNotification is a method of // a class, the context would usually be a pointer to that class object, to // avoid the need for the notification handler to be a static. Manager::Get()->AddWatcher( OnNotification, NULL ); // Add a Z-Wave Driver // Modify this line to set the correct serial port for your PC interface. string port = "/dev/ttyUSB1"; if ( argc > 1 ) { port = argv[1]; } if( strcasecmp( port.c_str(), "usb" ) == 0 ) { Manager::Get()->AddDriver( "HID Controller", Driver::ControllerInterface_Hid ); } else { Manager::Get()->AddDriver( port ); } // Now we just wait for either the AwakeNodesQueried or AllNodesQueried notification, // then write out the config file. // In a normal app, we would be handling notifications and building a UI for the user. pthread_cond_wait( &initCond, &initMutex ); // Since the configuration file contains command class information that is only // known after the nodes on the network are queried, wait until all of the nodes // on the network have been queried (at least the "listening" ones) before // writing the configuration file. (Maybe write again after sleeping nodes have // been queried as well.) if( !g_initFailed ) { Manager::Get()->WriteConfig( g_homeId ); // The section below demonstrates setting up polling for a variable. In this simple // example, it has been hardwired to poll COMMAND_CLASS_BASIC on the each node that // supports this setting. pthread_mutex_lock( &g_criticalSection ); for( list<NodeInfo*>::iterator it = g_nodes.begin(); it != g_nodes.end(); ++it ) { NodeInfo* nodeInfo = *it; // skip the controller (most likely node 1) if( nodeInfo->m_nodeId == 1) continue; for( list<ValueID>::iterator it2 = nodeInfo->m_values.begin(); it2 != nodeInfo->m_values.end(); ++it2 ) { ValueID v = *it2; if( v.GetCommandClassId() == 0x20 ) { // Manager::Get()->EnablePoll( v, 2 ); // enables polling with "intensity" of 2, though this is irrelevant with only one value polled break; } } } pthread_mutex_unlock( &g_criticalSection ); // If we want to access our NodeInfo list, that has been built from all the // notification callbacks we received from the library, we have to do so // from inside a Critical Section. This is because the callbacks occur on other // threads, and we cannot risk the list being changed while we are using it. // We must hold the critical section for as short a time as possible, to avoid // stalling the OpenZWave drivers. // At this point, the program just waits for 3 minutes (to demonstrate polling), // then exits for( int i = 0; i < 60*3; i++ ) { pthread_mutex_lock( &g_criticalSection ); // but NodeInfo list and similar data should be inside critical section pthread_mutex_unlock( &g_criticalSection ); sleep(1); } Driver::DriverData data; Manager::Get()->GetDriverStatistics( g_homeId, &data ); printf("SOF: %d ACK Waiting: %d Read Aborts: %d Bad Checksums: %d\n", data.m_SOFCnt, data.m_ACKWaiting, data.m_readAborts, data.m_badChecksum); printf("Reads: %d Writes: %d CAN: %d NAK: %d ACK: %d Out of Frame: %d\n", data.m_readCnt, data.m_writeCnt, data.m_CANCnt, data.m_NAKCnt, data.m_ACKCnt, data.m_OOFCnt); printf("Dropped: %d Retries: %d\n", data.m_dropped, data.m_retries); } // program exit (clean up) if( strcasecmp( port.c_str(), "usb" ) == 0 ) { Manager::Get()->RemoveDriver( "HID Controller" ); } else { Manager::Get()->RemoveDriver( port ); } Manager::Get()->RemoveWatcher( OnNotification, NULL ); Manager::Destroy(); Options::Destroy(); pthread_mutex_destroy( &g_criticalSection ); return 0; } <|endoftext|>
<commit_before>#include "VideoView.h" #ifdef USE_FFMPEG #include <QFileDialog> #include <QMap> using namespace QGBA; QMap<QString, QString> VideoView::s_acodecMap; QMap<QString, QString> VideoView::s_vcodecMap; QMap<QString, QString> VideoView::s_containerMap; VideoView::VideoView(QWidget* parent) : QWidget(parent) , m_audioCodecCstr(nullptr) , m_videoCodecCstr(nullptr) , m_containerCstr(nullptr) { m_ui.setupUi(this); if (s_acodecMap.empty()) { s_acodecMap["aac"] = "libfaac"; s_acodecMap["mp3"] = "libmp3lame"; s_acodecMap["uncompressed"] = "pcm_s16le"; } if (s_vcodecMap.empty()) { s_vcodecMap["h264"] = "libx264rgb"; } if (s_containerMap.empty()) { s_containerMap["mkv"] = "matroska"; } connect(m_ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); connect(m_ui.start, SIGNAL(clicked()), this, SLOT(startRecording())); connect(m_ui.stop, SIGNAL(clicked()), this, SLOT(stopRecording())); connect(m_ui.selectFile, SIGNAL(clicked()), this, SLOT(selectFile())); connect(m_ui.filename, SIGNAL(textChanged(const QString&)), this, SLOT(setFilename(const QString&))); connect(m_ui.audio, SIGNAL(activated(const QString&)), this, SLOT(setAudioCodec(const QString&))); connect(m_ui.video, SIGNAL(activated(const QString&)), this, SLOT(setVideoCodec(const QString&))); connect(m_ui.container, SIGNAL(activated(const QString&)), this, SLOT(setContainer(const QString&))); connect(m_ui.abr, SIGNAL(valueChanged(int)), this, SLOT(setAudioBitrate(int))); connect(m_ui.vbr, SIGNAL(valueChanged(int)), this, SLOT(setVideoBitrate(int))); FFmpegEncoderInit(&m_encoder); setAudioCodec(m_ui.audio->currentText()); setVideoCodec(m_ui.video->currentText()); setAudioBitrate(m_ui.abr->value()); setVideoBitrate(m_ui.vbr->value()); setContainer(m_ui.container->currentText()); } VideoView::~VideoView() { stopRecording(); free(m_audioCodecCstr); free(m_videoCodecCstr); free(m_containerCstr); } void VideoView::startRecording() { if (!validateSettings()) { return; } if (!FFmpegEncoderOpen(&m_encoder, m_filename.toLocal8Bit().constData())) { return; } m_ui.start->setEnabled(false); m_ui.stop->setEnabled(true); emit recordingStarted(&m_encoder.d); } void VideoView::stopRecording() { emit recordingStopped(); FFmpegEncoderClose(&m_encoder); m_ui.stop->setEnabled(false); validateSettings(); } void VideoView::selectFile() { QString filename = QFileDialog::getSaveFileName(this, tr("Select output file")); if (!filename.isEmpty()) { m_ui.filename->setText(filename); } } void VideoView::setFilename(const QString& fname) { m_filename = fname; validateSettings(); } void VideoView::setAudioCodec(const QString& codec) { free(m_audioCodecCstr); m_audioCodec = sanitizeCodec(codec); if (s_acodecMap.contains(m_audioCodec)) { m_audioCodec = s_acodecMap[m_audioCodec]; } m_audioCodecCstr = strdup(m_audioCodec.toLocal8Bit().constData()); if (!FFmpegEncoderSetAudio(&m_encoder, m_audioCodecCstr, m_abr)) { free(m_audioCodecCstr); m_audioCodecCstr = nullptr; } validateSettings(); } void VideoView::setVideoCodec(const QString& codec) { free(m_videoCodecCstr); m_videoCodec = sanitizeCodec(codec); if (s_vcodecMap.contains(m_videoCodec)) { m_videoCodec = s_vcodecMap[m_videoCodec]; } m_videoCodecCstr = strdup(m_videoCodec.toLocal8Bit().constData()); if (!FFmpegEncoderSetVideo(&m_encoder, m_videoCodecCstr, m_vbr)) { free(m_videoCodecCstr); m_videoCodecCstr = nullptr; } validateSettings(); } void VideoView::setContainer(const QString& container) { free(m_containerCstr); m_container = sanitizeCodec(container); if (s_containerMap.contains(m_container)) { m_container = s_containerMap[m_container]; } m_containerCstr = strdup(m_container.toLocal8Bit().constData()); if (!FFmpegEncoderSetContainer(&m_encoder, m_containerCstr)) { free(m_containerCstr); m_containerCstr = nullptr; } validateSettings(); } void VideoView::setAudioBitrate(int br) { m_abr = br * 1000; FFmpegEncoderSetAudio(&m_encoder, m_audioCodecCstr, m_abr); validateSettings(); } void VideoView::setVideoBitrate(int br) { m_abr = br * 1000; FFmpegEncoderSetVideo(&m_encoder, m_videoCodecCstr, m_vbr); validateSettings(); } bool VideoView::validateSettings() { bool valid = true; if (!m_audioCodecCstr) { valid = false; m_ui.audio->setStyleSheet("QComboBox { color: red; }"); } else { m_ui.audio->setStyleSheet(""); } if (!m_videoCodecCstr) { valid = false; m_ui.video->setStyleSheet("QComboBox { color: red; }"); } else { m_ui.video->setStyleSheet(""); } if (!m_containerCstr) { valid = false; m_ui.container->setStyleSheet("QComboBox { color: red; }"); } else { m_ui.container->setStyleSheet(""); } // This |valid| check is necessary as if one of the cstrs // is null, the encoder likely has a dangling pointer if (valid && !FFmpegEncoderVerifyContainer(&m_encoder)) { valid = false; } m_ui.start->setEnabled(valid && !m_filename.isNull()); return valid; } QString VideoView::sanitizeCodec(const QString& codec) { QString sanitized = codec.toLower(); return sanitized.remove(QChar('.')); } #endif <commit_msg>Qt: Fix VBR<commit_after>#include "VideoView.h" #ifdef USE_FFMPEG #include <QFileDialog> #include <QMap> using namespace QGBA; QMap<QString, QString> VideoView::s_acodecMap; QMap<QString, QString> VideoView::s_vcodecMap; QMap<QString, QString> VideoView::s_containerMap; VideoView::VideoView(QWidget* parent) : QWidget(parent) , m_audioCodecCstr(nullptr) , m_videoCodecCstr(nullptr) , m_containerCstr(nullptr) { m_ui.setupUi(this); if (s_acodecMap.empty()) { s_acodecMap["aac"] = "libfaac"; s_acodecMap["mp3"] = "libmp3lame"; s_acodecMap["uncompressed"] = "pcm_s16le"; } if (s_vcodecMap.empty()) { s_vcodecMap["h264"] = "libx264rgb"; } if (s_containerMap.empty()) { s_containerMap["mkv"] = "matroska"; } connect(m_ui.buttonBox, SIGNAL(rejected()), this, SLOT(close())); connect(m_ui.start, SIGNAL(clicked()), this, SLOT(startRecording())); connect(m_ui.stop, SIGNAL(clicked()), this, SLOT(stopRecording())); connect(m_ui.selectFile, SIGNAL(clicked()), this, SLOT(selectFile())); connect(m_ui.filename, SIGNAL(textChanged(const QString&)), this, SLOT(setFilename(const QString&))); connect(m_ui.audio, SIGNAL(activated(const QString&)), this, SLOT(setAudioCodec(const QString&))); connect(m_ui.video, SIGNAL(activated(const QString&)), this, SLOT(setVideoCodec(const QString&))); connect(m_ui.container, SIGNAL(activated(const QString&)), this, SLOT(setContainer(const QString&))); connect(m_ui.abr, SIGNAL(valueChanged(int)), this, SLOT(setAudioBitrate(int))); connect(m_ui.vbr, SIGNAL(valueChanged(int)), this, SLOT(setVideoBitrate(int))); FFmpegEncoderInit(&m_encoder); setAudioCodec(m_ui.audio->currentText()); setVideoCodec(m_ui.video->currentText()); setAudioBitrate(m_ui.abr->value()); setVideoBitrate(m_ui.vbr->value()); setContainer(m_ui.container->currentText()); } VideoView::~VideoView() { stopRecording(); free(m_audioCodecCstr); free(m_videoCodecCstr); free(m_containerCstr); } void VideoView::startRecording() { if (!validateSettings()) { return; } if (!FFmpegEncoderOpen(&m_encoder, m_filename.toLocal8Bit().constData())) { return; } m_ui.start->setEnabled(false); m_ui.stop->setEnabled(true); emit recordingStarted(&m_encoder.d); } void VideoView::stopRecording() { emit recordingStopped(); FFmpegEncoderClose(&m_encoder); m_ui.stop->setEnabled(false); validateSettings(); } void VideoView::selectFile() { QString filename = QFileDialog::getSaveFileName(this, tr("Select output file")); if (!filename.isEmpty()) { m_ui.filename->setText(filename); } } void VideoView::setFilename(const QString& fname) { m_filename = fname; validateSettings(); } void VideoView::setAudioCodec(const QString& codec) { free(m_audioCodecCstr); m_audioCodec = sanitizeCodec(codec); if (s_acodecMap.contains(m_audioCodec)) { m_audioCodec = s_acodecMap[m_audioCodec]; } m_audioCodecCstr = strdup(m_audioCodec.toLocal8Bit().constData()); if (!FFmpegEncoderSetAudio(&m_encoder, m_audioCodecCstr, m_abr)) { free(m_audioCodecCstr); m_audioCodecCstr = nullptr; } validateSettings(); } void VideoView::setVideoCodec(const QString& codec) { free(m_videoCodecCstr); m_videoCodec = sanitizeCodec(codec); if (s_vcodecMap.contains(m_videoCodec)) { m_videoCodec = s_vcodecMap[m_videoCodec]; } m_videoCodecCstr = strdup(m_videoCodec.toLocal8Bit().constData()); if (!FFmpegEncoderSetVideo(&m_encoder, m_videoCodecCstr, m_vbr)) { free(m_videoCodecCstr); m_videoCodecCstr = nullptr; } validateSettings(); } void VideoView::setContainer(const QString& container) { free(m_containerCstr); m_container = sanitizeCodec(container); if (s_containerMap.contains(m_container)) { m_container = s_containerMap[m_container]; } m_containerCstr = strdup(m_container.toLocal8Bit().constData()); if (!FFmpegEncoderSetContainer(&m_encoder, m_containerCstr)) { free(m_containerCstr); m_containerCstr = nullptr; } validateSettings(); } void VideoView::setAudioBitrate(int br) { m_abr = br * 1000; FFmpegEncoderSetAudio(&m_encoder, m_audioCodecCstr, m_abr); validateSettings(); } void VideoView::setVideoBitrate(int br) { m_vbr = br * 1000; FFmpegEncoderSetVideo(&m_encoder, m_videoCodecCstr, m_vbr); validateSettings(); } bool VideoView::validateSettings() { bool valid = true; if (!m_audioCodecCstr) { valid = false; m_ui.audio->setStyleSheet("QComboBox { color: red; }"); } else { m_ui.audio->setStyleSheet(""); } if (!m_videoCodecCstr) { valid = false; m_ui.video->setStyleSheet("QComboBox { color: red; }"); } else { m_ui.video->setStyleSheet(""); } if (!m_containerCstr) { valid = false; m_ui.container->setStyleSheet("QComboBox { color: red; }"); } else { m_ui.container->setStyleSheet(""); } // This |valid| check is necessary as if one of the cstrs // is null, the encoder likely has a dangling pointer if (valid && !FFmpegEncoderVerifyContainer(&m_encoder)) { valid = false; } m_ui.start->setEnabled(valid && !m_filename.isNull()); return valid; } QString VideoView::sanitizeCodec(const QString& codec) { QString sanitized = codec.toLower(); return sanitized.remove(QChar('.')); } #endif <|endoftext|>
<commit_before> // // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "SubscriberInfo.h" #include "../base/Exception.h" #include <boost/python/slice.hpp> using namespace std; namespace avg { py::object SubscriberInfo::s_MethodrefModule; SubscriberInfo::SubscriberInfo(int id, const py::object& callable) : m_ID(id) { if (s_MethodrefModule.ptr() == py::object().ptr()) { s_MethodrefModule = py::import("libavg.methodref"); } // Use the methodref module to manage the lifetime of the callables. This makes // sure that we can delete bound-method callbacks when the object they are bound // to disappears. m_Callable = py::object(s_MethodrefModule.attr("methodref")(callable)); } SubscriberInfo::~SubscriberInfo() { } bool SubscriberInfo::hasExpired() const { py::object func = m_Callable(); return (func.ptr() == py::object().ptr()); } void SubscriberInfo::invoke(py::list args) const { py::object callWeakRef = s_MethodrefModule.attr("callWeakRef"); py::list argsCopy(args[py::slice()]); argsCopy.insert(0, m_Callable); py::tuple argsTuple(argsCopy); PyObject * pResult = PyObject_CallObject(callWeakRef.ptr(), argsTuple.ptr()); if (pResult == 0) { throw py::error_already_set(); } } int SubscriberInfo::getID() const { return m_ID; } bool SubscriberInfo::isCallable(const py::object& callable) const { bool bResult = py::call_method<bool>(m_Callable.ptr(), "isSameFunc", callable); return bResult; } } <commit_msg>uilib branch: Added ObjectCounter support to SubscriberInfo.<commit_after> // // libavg - Media Playback Engine. // Copyright (C) 2003-2011 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "SubscriberInfo.h" #include "../base/Exception.h" #include "../base/ObjectCounter.h" #include <boost/python/slice.hpp> using namespace std; namespace avg { py::object SubscriberInfo::s_MethodrefModule; SubscriberInfo::SubscriberInfo(int id, const py::object& callable) : m_ID(id) { ObjectCounter::get()->incRef(&typeid(*this)); if (s_MethodrefModule.ptr() == py::object().ptr()) { s_MethodrefModule = py::import("libavg.methodref"); } // Use the methodref module to manage the lifetime of the callables. This makes // sure that we can delete bound-method callbacks when the object they are bound // to disappears. m_Callable = py::object(s_MethodrefModule.attr("methodref")(callable)); } SubscriberInfo::~SubscriberInfo() { ObjectCounter::get()->decRef(&typeid(*this)); } bool SubscriberInfo::hasExpired() const { py::object func = m_Callable(); return (func.ptr() == py::object().ptr()); } void SubscriberInfo::invoke(py::list args) const { py::object callWeakRef = s_MethodrefModule.attr("callWeakRef"); py::list argsCopy(args[py::slice()]); argsCopy.insert(0, m_Callable); py::tuple argsTuple(argsCopy); PyObject * pResult = PyObject_CallObject(callWeakRef.ptr(), argsTuple.ptr()); if (pResult == 0) { throw py::error_already_set(); } } int SubscriberInfo::getID() const { return m_ID; } bool SubscriberInfo::isCallable(const py::object& callable) const { bool bResult = py::call_method<bool>(m_Callable.ptr(), "isSameFunc", callable); return bResult; } } <|endoftext|>
<commit_before>/* os.cc Mathieu Stefani, 13 August 2015 */ #include "os.h" #include "common.h" #include <unistd.h> #include <fcntl.h> #include <fstream> #include <iterator> #include <algorithm> #include <sys/epoll.h> #include <sys/eventfd.h> using namespace std; int hardware_concurrency() { std::ifstream cpuinfo("/proc/cpuinfo"); if (cpuinfo) { return std::count(std::istream_iterator<std::string>(cpuinfo), std::istream_iterator<std::string>(), std::string("processor")); } return sysconf(_SC_NPROCESSORS_ONLN); } bool make_non_blocking(int sfd) { int flags = fcntl (sfd, F_GETFL, 0); if (flags == -1) return false; flags |= O_NONBLOCK; int ret = fcntl (sfd, F_SETFL, flags); if (ret == -1) return false; return true; } CpuSet::CpuSet() { bits.reset(); } CpuSet::CpuSet(std::initializer_list<size_t> cpus) { set(cpus); } void CpuSet::clear() { bits.reset(); } CpuSet& CpuSet::set(size_t cpu) { if (cpu >= Size) { throw std::invalid_argument("Trying to set invalid cpu number"); } bits.set(cpu); return *this; } CpuSet& CpuSet::unset(size_t cpu) { if (cpu >= Size) { throw std::invalid_argument("Trying to unset invalid cpu number"); } bits.set(cpu, false); return *this; } CpuSet& CpuSet::set(std::initializer_list<size_t> cpus) { for (auto cpu: cpus) set(cpu); return *this; } CpuSet& CpuSet::unset(std::initializer_list<size_t> cpus) { for (auto cpu: cpus) unset(cpu); return *this; } CpuSet& CpuSet::setRange(size_t begin, size_t end) { if (begin > end) { throw std::range_error("Invalid range, begin > end"); } for (size_t cpu = begin; cpu < end; ++cpu) { set(cpu); } return *this; } CpuSet& CpuSet::unsetRange(size_t begin, size_t end) { if (begin > end) { throw std::range_error("Invalid range, begin > end"); } for (size_t cpu = begin; cpu < end; ++cpu) { unset(cpu); } return *this; } bool CpuSet::isSet(size_t cpu) const { if (cpu >= Size) { throw std::invalid_argument("Trying to test invalid cpu number"); } return bits.test(cpu); } size_t CpuSet::count() const { return bits.count(); } cpu_set_t CpuSet::toPosix() const { cpu_set_t cpu_set; CPU_ZERO(&cpu_set); for (size_t cpu = 0; cpu < Size; ++cpu) { if (bits.test(cpu)) CPU_SET(cpu, &cpu_set); } return cpu_set; }; namespace Polling { Epoll::Epoll(size_t max) { epoll_fd = TRY_RET(epoll_create(max)); } void Epoll::addFd(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) { struct epoll_event ev; ev.events = toEpollEvents(interest); if (mode == Mode::Edge) ev.events |= EPOLLET; ev.data.u64 = tag.value_; TRY(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev)); } void Epoll::addFdOneShot(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) { struct epoll_event ev; ev.events = toEpollEvents(interest); ev.events |= EPOLLONESHOT; if (mode == Mode::Edge) ev.events |= EPOLLET; ev.data.u64 = tag.value_; TRY(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev)); } void Epoll::removeFd(Fd fd) { struct epoll_event ev; TRY(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &ev)); } void Epoll::rearmFd(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) { struct epoll_event ev; ev.events = toEpollEvents(interest); if (mode == Mode::Edge) ev.events |= EPOLLET; ev.data.u64 = tag.value_; TRY(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ev)); } int Epoll::poll(std::vector<Event>& events, size_t maxEvents, std::chrono::milliseconds timeout) const { struct epoll_event evs[Const::MaxEvents]; int ready_fds = epoll_wait(epoll_fd, evs, maxEvents, timeout.count()); if (ready_fds > 0) { for (int i = 0; i < ready_fds; ++i) { const struct epoll_event *ev = evs + i; const Tag tag(ev->data.u64); Event event(tag); event.flags = toNotifyOn(ev->events); events.push_back(event); } } return ready_fds; } int Epoll::toEpollEvents(Flags<NotifyOn> interest) const { int events = 0; if (interest.hasFlag(NotifyOn::Read)) events |= EPOLLIN; if (interest.hasFlag(NotifyOn::Write)) events |= EPOLLOUT; if (interest.hasFlag(NotifyOn::Hangup)) events |= EPOLLHUP; if (interest.hasFlag(NotifyOn::Shutdown)) events |= EPOLLRDHUP; return events; } Flags<NotifyOn> Epoll::toNotifyOn(int events) const { Flags<NotifyOn> flags; if (events & EPOLLIN) flags.setFlag(NotifyOn::Read); if (events & EPOLLOUT) flags.setFlag(NotifyOn::Write); if (events & EPOLLHUP) flags.setFlag(NotifyOn::Hangup); if (events & EPOLLRDHUP) { flags.setFlag(NotifyOn::Shutdown); } return flags; } } // namespace Poller Polling::Tag NotifyFd::bind(Polling::Epoll& poller) { event_fd = TRY_RET(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC)); Polling::Tag tag(event_fd); poller.addFd(event_fd, Polling::NotifyOn::Read, tag, Polling::Mode::Edge); return tag; } bool NotifyFd::isBound() const { return event_fd != -1; } Polling::Tag NotifyFd::tag() const { return Polling::Tag(event_fd); } void NotifyFd::notify() const { if (!isBound()) throw std::runtime_error("Can not notify an unbound fd"); eventfd_t val = 1; TRY(eventfd_write(event_fd, val)); } void NotifyFd::read() const { if (!isBound()) throw std::runtime_error("Can not read an unbound fd"); eventfd_t val; TRY(eventfd_read(event_fd, &val)); } bool NotifyFd::tryRead() const { eventfd_t val; int res = eventfd_read(event_fd, &val); if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) return false; throw std::runtime_error("Failed to read eventfd"); } return true; } <commit_msg>Enables gdb debugging by fixing the polling code to allow interrupts.<commit_after>/* os.cc Mathieu Stefani, 13 August 2015 */ #include "os.h" #include "common.h" #include <unistd.h> #include <fcntl.h> #include <fstream> #include <iterator> #include <algorithm> #include <sys/epoll.h> #include <sys/eventfd.h> using namespace std; int hardware_concurrency() { std::ifstream cpuinfo("/proc/cpuinfo"); if (cpuinfo) { return std::count(std::istream_iterator<std::string>(cpuinfo), std::istream_iterator<std::string>(), std::string("processor")); } return sysconf(_SC_NPROCESSORS_ONLN); } bool make_non_blocking(int sfd) { int flags = fcntl (sfd, F_GETFL, 0); if (flags == -1) return false; flags |= O_NONBLOCK; int ret = fcntl (sfd, F_SETFL, flags); if (ret == -1) return false; return true; } CpuSet::CpuSet() { bits.reset(); } CpuSet::CpuSet(std::initializer_list<size_t> cpus) { set(cpus); } void CpuSet::clear() { bits.reset(); } CpuSet& CpuSet::set(size_t cpu) { if (cpu >= Size) { throw std::invalid_argument("Trying to set invalid cpu number"); } bits.set(cpu); return *this; } CpuSet& CpuSet::unset(size_t cpu) { if (cpu >= Size) { throw std::invalid_argument("Trying to unset invalid cpu number"); } bits.set(cpu, false); return *this; } CpuSet& CpuSet::set(std::initializer_list<size_t> cpus) { for (auto cpu: cpus) set(cpu); return *this; } CpuSet& CpuSet::unset(std::initializer_list<size_t> cpus) { for (auto cpu: cpus) unset(cpu); return *this; } CpuSet& CpuSet::setRange(size_t begin, size_t end) { if (begin > end) { throw std::range_error("Invalid range, begin > end"); } for (size_t cpu = begin; cpu < end; ++cpu) { set(cpu); } return *this; } CpuSet& CpuSet::unsetRange(size_t begin, size_t end) { if (begin > end) { throw std::range_error("Invalid range, begin > end"); } for (size_t cpu = begin; cpu < end; ++cpu) { unset(cpu); } return *this; } bool CpuSet::isSet(size_t cpu) const { if (cpu >= Size) { throw std::invalid_argument("Trying to test invalid cpu number"); } return bits.test(cpu); } size_t CpuSet::count() const { return bits.count(); } cpu_set_t CpuSet::toPosix() const { cpu_set_t cpu_set; CPU_ZERO(&cpu_set); for (size_t cpu = 0; cpu < Size; ++cpu) { if (bits.test(cpu)) CPU_SET(cpu, &cpu_set); } return cpu_set; }; namespace Polling { Epoll::Epoll(size_t max) { epoll_fd = TRY_RET(epoll_create(max)); } void Epoll::addFd(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) { struct epoll_event ev; ev.events = toEpollEvents(interest); if (mode == Mode::Edge) ev.events |= EPOLLET; ev.data.u64 = tag.value_; TRY(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev)); } void Epoll::addFdOneShot(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) { struct epoll_event ev; ev.events = toEpollEvents(interest); ev.events |= EPOLLONESHOT; if (mode == Mode::Edge) ev.events |= EPOLLET; ev.data.u64 = tag.value_; TRY(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev)); } void Epoll::removeFd(Fd fd) { struct epoll_event ev; TRY(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &ev)); } void Epoll::rearmFd(Fd fd, Flags<NotifyOn> interest, Tag tag, Mode mode) { struct epoll_event ev; ev.events = toEpollEvents(interest); if (mode == Mode::Edge) ev.events |= EPOLLET; ev.data.u64 = tag.value_; TRY(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &ev)); } int Epoll::poll(std::vector<Event>& events, size_t maxEvents, std::chrono::milliseconds timeout) const { struct epoll_event evs[Const::MaxEvents]; int ready_fds = -1; do { ready_fds = epoll_wait(epoll_fd, evs, maxEvents, timeout.count()); } while (ready_fds < 0 && errno == EINTR); if (ready_fds > 0) { for (int i = 0; i < ready_fds; ++i) { const struct epoll_event *ev = evs + i; const Tag tag(ev->data.u64); Event event(tag); event.flags = toNotifyOn(ev->events); events.push_back(event); } } return ready_fds; } int Epoll::toEpollEvents(Flags<NotifyOn> interest) const { int events = 0; if (interest.hasFlag(NotifyOn::Read)) events |= EPOLLIN; if (interest.hasFlag(NotifyOn::Write)) events |= EPOLLOUT; if (interest.hasFlag(NotifyOn::Hangup)) events |= EPOLLHUP; if (interest.hasFlag(NotifyOn::Shutdown)) events |= EPOLLRDHUP; return events; } Flags<NotifyOn> Epoll::toNotifyOn(int events) const { Flags<NotifyOn> flags; if (events & EPOLLIN) flags.setFlag(NotifyOn::Read); if (events & EPOLLOUT) flags.setFlag(NotifyOn::Write); if (events & EPOLLHUP) flags.setFlag(NotifyOn::Hangup); if (events & EPOLLRDHUP) { flags.setFlag(NotifyOn::Shutdown); } return flags; } } // namespace Poller Polling::Tag NotifyFd::bind(Polling::Epoll& poller) { event_fd = TRY_RET(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC)); Polling::Tag tag(event_fd); poller.addFd(event_fd, Polling::NotifyOn::Read, tag, Polling::Mode::Edge); return tag; } bool NotifyFd::isBound() const { return event_fd != -1; } Polling::Tag NotifyFd::tag() const { return Polling::Tag(event_fd); } void NotifyFd::notify() const { if (!isBound()) throw std::runtime_error("Can not notify an unbound fd"); eventfd_t val = 1; TRY(eventfd_write(event_fd, val)); } void NotifyFd::read() const { if (!isBound()) throw std::runtime_error("Can not read an unbound fd"); eventfd_t val; TRY(eventfd_read(event_fd, &val)); } bool NotifyFd::tryRead() const { eventfd_t val; int res = eventfd_read(event_fd, &val); if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) return false; throw std::runtime_error("Failed to read eventfd"); } return true; } <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include <BALL/VIEW/DIALOGS/downloadPDBFile.h> #include <BALL/FORMAT/lineBasedFile.h> #include <BALL/FORMAT/PDBFile.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/KERNEL/message.h> #include <BALL/KERNEL/system.h> #include <qcombobox.h> #include <qlineedit.h> #include <qtextedit.h> #include <qfile.h> #include <qurl.h> #include <qradiobutton.h> #include <qcheckbox.h> #include <qimage.h> #include <qpushbutton.h> namespace BALL { namespace VIEW { DownloadPDBFile::DownloadPDBFile( QWidget* parent, const char* name, bool modal, WFlags fl ) throw() : DownloadPDBFileData(parent, name, modal, fl), ModularWidget(name) { #ifdef BALL_VIEW_DEBUG Log.error() << "new DownloadPDBFile" << this << std::endl; #endif // register the widget with the MainControl registerWidget(this); hide(); connect(results, SIGNAL(activated(const QString&)), this, SLOT(slotNewId(const QString&))); } DownloadPDBFile::~DownloadPDBFile() throw() { #ifdef BALL_VIEW_DEBUG Log.info() << "Destructing object " << (void *)this << " of class DownloadPDBFile" << std::endl; #endif } void DownloadPDBFile::initializeWidget(MainControl& main_control) throw() { String hint("Download a PDB file from www.rcsb.org"); main_control.insertMenuEntry(MainControl::FILE_OPEN, "&Download Structure", (QObject *)this, SLOT(show()), CTRL+Key_D, -1, hint); } void DownloadPDBFile::finalizeWidget(MainControl& main_control) throw() { main_control.removeMenuEntry(MainControl::FILE_OPEN, "&Download Structure", (QObject *)this, SLOT(show()), CTRL+Key_R); } void DownloadPDBFile::checkMenuEntries() throw() { } void DownloadPDBFile::slotSearch() { results->clear(); QString filename = "http://www.rcsb.org/pdb/cgi/resultBrowser.cgi?Lucene::keyword="; QString search_contents = searchField->text(); QUrl::encode(search_contents); filename+=search_contents; filename+="&Lucene::keyword_op="; filename+=(fullText->isOn()) ? "fullText" : "name"; if (exactMatch->isOn()) filename+="&exact=1"; else filename+="&exact=0"; if (removeSimilar->isOn()) filename+="&SelectorRedundFilt::on=1"; try { LineBasedFile search_result(filename.latin1()); vector<String> result; String tmp; while (search_result.readLine()) { tmp = search_result.getLine(); Size pos = tmp.find("name=\"PDBID_"); if (pos != string::npos) { Size end_pos = tmp.find("\"", pos+12); result.push_back(tmp.substr(pos+12,end_pos-(pos+12))); } } for (Size i=0; i<result.size(); i++) { results->insertItem(result[i].c_str()); } if (result.size() != 0) pdbId->setText(result[0].c_str()); } catch (...) { } } void DownloadPDBFile::slotDownload() { System *system = new System(); try { String filename = "http://www.rcsb.org/pdb/cgi/export.cgi/"; filename += pdbId->text().latin1(); filename += ".pdb?format=PDB&pdbId="; filename += pdbId->text().latin1(); filename +="&compression=None"; PDBFile pdb_file(filename); pdb_file >> *system; pdb_file.close(); Log.info() << "> read " << system->countAtoms() << " atoms from URL \"" << filename<< "\"" << std::endl; if (system->countAtoms() == 0) { delete system; setStatusbarText("Could not fetch the given PDBFile"); return; } if (system->getName() == "") { system->setName(pdbId->text().latin1()); } system->setProperty("FROM_FILE", filename); getMainControl()->insert(*system, pdbId->text().latin1()); } catch(...) { Log.info() << "> download PDB file failed." << std::endl; delete system; } } void DownloadPDBFile::slotShowDetail() { QString filename = "http://www.rcsb.org/pdb/cgi/explore.cgi?job=summary&pdbId="; filename += pdbId->text(); filename += "&page="; displayHTML(filename); } void DownloadPDBFile::slotNewId(const QString& new_id) { pdbId->setText(new_id); } void DownloadPDBFile::displayHTML(const QString& url) { try { qb_ = new QTextBrowser(); QString filename; if (url.find("http://") == -1) filename = "http://www.rcsb.org/"+url; else filename = url; Log.info() << "Reading " << filename << std::endl; LineBasedFile search_result(filename.latin1()); String result; HashMap<String, QImage> hm; String current_line; while (search_result.readLine()) { current_line = search_result.getLine(); result += current_line + "\n"; // find out all the images String tmp = current_line; tmp.toUpper(); Size pos_1 = 0; Size pos_2 = 0; while ( (pos_1 = tmp.find("<IMG", pos_2)) != string::npos ) { pos_1 = tmp.find("SRC=\"", pos_1); pos_2 = current_line.find("\"", pos_1+9); String img_url = current_line.substr(pos_1+5, pos_2 - (pos_1+5)); if (!hm.has(img_url)) { LineBasedFile img("http://www.rcsb.org/"+img_url); String tmp_filename; File::createTemporaryFilename(tmp_filename); img.copyTo(tmp_filename); QImage qi; qi.load(tmp_filename); File temp(tmp_filename); temp.remove(); hm[img_url] = qi; } } } HashMap<String, QImage>::Iterator hi; for (hi = hm.begin(); hi!=hm.end(); hi++) { qb_->mimeSourceFactory()->setImage(hi->first, hi->second); } qb_->setText(QString(result.c_str())); connect(qb_, SIGNAL(linkClicked(const QString&)), this, SLOT(displayHTML(const QString&))); qb_->show(); } catch (...) { } } void DownloadPDBFile::idChanged() { download->setEnabled(pdbId->text() != ""); } } } <commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include <BALL/VIEW/DIALOGS/downloadPDBFile.h> #include <BALL/FORMAT/lineBasedFile.h> #include <BALL/FORMAT/PDBFile.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/KERNEL/message.h> #include <BALL/KERNEL/system.h> #include <qcombobox.h> #include <qlineedit.h> #include <qtextedit.h> #include <qfile.h> #include <qurl.h> #include <qradiobutton.h> #include <qcheckbox.h> #include <qimage.h> #include <qpushbutton.h> namespace BALL { namespace VIEW { DownloadPDBFile::DownloadPDBFile( QWidget* parent, const char* name, bool modal, WFlags fl ) throw() : DownloadPDBFileData(parent, name, modal, fl), ModularWidget(name) { #ifdef BALL_VIEW_DEBUG Log.error() << "new DownloadPDBFile" << this << std::endl; #endif // register the widget with the MainControl registerWidget(this); hide(); connect(results, SIGNAL(activated(const QString&)), this, SLOT(slotNewId(const QString&))); } DownloadPDBFile::~DownloadPDBFile() throw() { #ifdef BALL_VIEW_DEBUG Log.info() << "Destructing object " << (void *)this << " of class DownloadPDBFile" << std::endl; #endif } void DownloadPDBFile::initializeWidget(MainControl& main_control) throw() { String hint("Download a PDB file from www.rcsb.org"); main_control.insertMenuEntry(MainControl::FILE_OPEN, "&Download Structure", (QObject *)this, SLOT(show()), CTRL+Key_D, -1, hint); } void DownloadPDBFile::finalizeWidget(MainControl& main_control) throw() { main_control.removeMenuEntry(MainControl::FILE_OPEN, "&Download Structure", (QObject *)this, SLOT(show()), CTRL+Key_R); } void DownloadPDBFile::checkMenuEntries() throw() { } void DownloadPDBFile::slotSearch() { results->clear(); QString filename = "http://www.rcsb.org/pdb/cgi/resultBrowser.cgi?Lucene::keyword="; QString search_contents = searchField->text(); QUrl::encode(search_contents); filename+=search_contents; filename+="&Lucene::keyword_op="; filename+=(fullText->isOn()) ? "fullText" : "name"; if (exactMatch->isOn()) filename+="&exact=1"; else filename+="&exact=0"; if (removeSimilar->isOn()) filename+="&SelectorRedundFilt::on=1"; try { LineBasedFile search_result(filename.latin1()); vector<String> result; String tmp; while (search_result.readLine()) { tmp = search_result.getLine(); Size pos = tmp.find("name=\"PDBID_"); if (pos != string::npos) { Size end_pos = tmp.find("\"", pos+12); result.push_back(tmp.substr(pos+12,end_pos-(pos+12))); } } for (Size i=0; i<result.size(); i++) { results->insertItem(result[i].c_str()); } if (result.size() != 0) pdbId->setText(result[0].c_str()); } catch (...) { } } void DownloadPDBFile::slotDownload() { System *system = new System(); try { String filename = "http://www.rcsb.org/pdb/cgi/export.cgi/"; filename += pdbId->text().latin1(); filename += ".pdb?format=PDB&pdbId="; filename += pdbId->text().latin1(); filename +="&compression=None"; PDBFile pdb_file(filename); pdb_file >> *system; pdb_file.close(); Log.info() << "> read " << system->countAtoms() << " atoms from URL \"" << filename<< "\"" << std::endl; if (system->countAtoms() == 0) { delete system; setStatusbarText("Could not fetch the given PDBFile"); return; } if (system->getName() == "") { system->setName(pdbId->text().latin1()); } system->setProperty("FROM_FILE", filename); getMainControl()->insert(*system, pdbId->text().latin1()); } catch(...) { Log.info() << "> download PDB file failed." << std::endl; delete system; } } void DownloadPDBFile::slotShowDetail() { QString filename = "http://www.rcsb.org/pdb/cgi/explore.cgi?job=summary&pdbId="; filename += pdbId->text(); filename += "&page="; displayHTML(filename); } void DownloadPDBFile::slotNewId(const QString& new_id) { pdbId->setText(new_id); } void DownloadPDBFile::displayHTML(const QString& url) { try { qb_ = new QTextBrowser(); QString filename; if (url.find("http://") == -1) filename = "http://www.rcsb.org/"+url; else filename = url; Log.info() << "Reading " << filename << std::endl; LineBasedFile search_result(filename.latin1()); String result; HashMap<String, QImage> hm; String current_line; while (search_result.readLine()) { current_line = search_result.getLine(); result += current_line + "\n"; // find out all the images String tmp = current_line; tmp.toUpper(); Size pos_1 = 0; Size pos_2 = 0; while ( (pos_1 = tmp.find("<IMG", pos_2)) != string::npos ) { pos_1 = tmp.find("SRC=\"", pos_1); pos_2 = current_line.find("\"", pos_1+9); String img_url = current_line.substr(pos_1+5, pos_2 - (pos_1+5)); if (!hm.has(img_url)) { LineBasedFile img("http://www.rcsb.org/"+img_url); String tmp_filename; File::createTemporaryFilename(tmp_filename); img.copyTo(tmp_filename); QImage qi; qi.load(tmp_filename.c_str()); File temp(tmp_filename); temp.remove(); hm[img_url] = qi; } } } HashMap<String, QImage>::Iterator hi; for (hi = hm.begin(); hi!=hm.end(); hi++) { qb_->mimeSourceFactory()->setImage(hi->first, hi->second); } qb_->setText(QString(result.c_str())); connect(qb_, SIGNAL(linkClicked(const QString&)), this, SLOT(displayHTML(const QString&))); qb_->show(); } catch (...) { } } void DownloadPDBFile::idChanged() { download->setEnabled(pdbId->text() != ""); } } } <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "desktop/screen_capturer_gdi.h" #include <dwmapi.h> #include "base/logging.h" #include "desktop/win/effects_disabler.h" #include "desktop/win/screen_capture_utils.h" #include "desktop/win/wallpaper_disabler.h" #include "desktop/desktop_frame_dib.h" #include "desktop/differ.h" namespace desktop { ScreenCapturerGDI::ScreenCapturerGDI(uint32_t flags) : flags_(flags) { // Nothing } ScreenCapturerGDI::~ScreenCapturerGDI() = default; int ScreenCapturerGDI::screenCount() { return ScreenCaptureUtils::screenCount(); } bool ScreenCapturerGDI::screenList(ScreenList* screens) { return ScreenCaptureUtils::screenList(screens); } bool ScreenCapturerGDI::selectScreen(ScreenId screen_id) { if (!ScreenCaptureUtils::isScreenValid(screen_id, &current_device_key_)) return false; // At next screen capture, the resources are recreated. desktop_dc_rect_ = QRect(); current_screen_id_ = screen_id; return true; } const Frame* ScreenCapturerGDI::captureFrame() { queue_.moveToNextFrame(); if (!prepareCaptureResources()) return nullptr; QRect screen_rect = ScreenCaptureUtils::screenRect(current_screen_id_, current_device_key_); if (screen_rect.isEmpty()) { LOG(LS_WARNING) << "Failed to get screen rect"; return nullptr; } if (!queue_.currentFrame() || queue_.currentFrame()->size() != screen_rect.size()) { DCHECK(desktop_dc_); DCHECK(memory_dc_); std::unique_ptr<Frame> frame = FrameDib::create( screen_rect.size(), PixelFormat::ARGB(), memory_dc_); if (!frame) { LOG(LS_WARNING) << "Failed to create frame buffer"; return nullptr; } queue_.replaceCurrentFrame(std::move(frame)); } FrameDib* current = static_cast<FrameDib*>(queue_.currentFrame()); FrameDib* previous = static_cast<FrameDib*>(queue_.previousFrame()); HGDIOBJ old_bitmap = SelectObject(memory_dc_, current->bitmap()); if (old_bitmap) { BitBlt(memory_dc_, 0, 0, screen_rect.width(), screen_rect.height(), *desktop_dc_, screen_rect.left(), screen_rect.top(), CAPTUREBLT | SRCCOPY); SelectObject(memory_dc_, old_bitmap); } current->setTopLeft(screen_rect.topLeft()); if (!previous || previous->size() != current->size()) { differ_ = std::make_unique<Differ>(screen_rect.size()); *current->updatedRegion() += QRect(QPoint(), screen_rect.size()); } else { differ_->calcDirtyRegion(previous->frameData(), current->frameData(), current->updatedRegion()); } return current; } bool ScreenCapturerGDI::prepareCaptureResources() { // Switch to the desktop receiving user input if different from the // current one. base::Desktop input_desktop(base::Desktop::inputDesktop()); if (input_desktop.isValid() && !desktop_.isSame(input_desktop)) { // Release GDI resources otherwise SetThreadDesktop will fail. desktop_dc_.reset(); memory_dc_.reset(); effects_disabler_.reset(); wallpaper_disabler_.reset(); // If SetThreadDesktop() fails, the thread is still assigned a desktop. // So we can continue capture screen bits, just from the wrong desktop. desktop_.setThreadDesktop(std::move(input_desktop)); } QRect desktop_rect = ScreenCaptureUtils::fullScreenRect(); // If the display bounds have changed then recreate GDI resources. if (desktop_rect != desktop_dc_rect_) { desktop_dc_.reset(); memory_dc_.reset(); desktop_dc_rect_ = QRect(); } if (!desktop_dc_) { DCHECK(!memory_dc_); // Vote to disable Aero composited desktop effects while capturing. // Windows will restore Aero automatically if the process exits. // This has no effect under Windows 8 or higher. See crbug.com/124018. DwmEnableComposition(DWM_EC_DISABLECOMPOSITION); if (flags_ & DISABLE_EFFECTS) effects_disabler_ = std::make_unique<EffectsDisabler>(); if (flags_ & DISABLE_WALLPAPER) wallpaper_disabler_ = std::make_unique<WallpaperDisabler>(); // Create GDI device contexts to capture from the desktop into memory. desktop_dc_ = std::make_unique<base::win::ScopedGetDC>(nullptr); memory_dc_.reset(CreateCompatibleDC(*desktop_dc_)); if (!memory_dc_) { LOG(LS_WARNING) << "CreateCompatibleDC failed"; return false; } desktop_dc_rect_ = desktop_rect; // Make sure the frame buffers will be reallocated. queue_.reset(); } return true; } } // namespace desktop <commit_msg>- Fixed disabling effects and wallpapers when switching the monitor.<commit_after>// // Aspia Project // Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "desktop/screen_capturer_gdi.h" #include <dwmapi.h> #include "base/logging.h" #include "desktop/win/effects_disabler.h" #include "desktop/win/screen_capture_utils.h" #include "desktop/win/wallpaper_disabler.h" #include "desktop/desktop_frame_dib.h" #include "desktop/differ.h" namespace desktop { ScreenCapturerGDI::ScreenCapturerGDI(uint32_t flags) : flags_(flags) { // Nothing } ScreenCapturerGDI::~ScreenCapturerGDI() = default; int ScreenCapturerGDI::screenCount() { return ScreenCaptureUtils::screenCount(); } bool ScreenCapturerGDI::screenList(ScreenList* screens) { return ScreenCaptureUtils::screenList(screens); } bool ScreenCapturerGDI::selectScreen(ScreenId screen_id) { if (!ScreenCaptureUtils::isScreenValid(screen_id, &current_device_key_)) return false; // At next screen capture, the resources are recreated. desktop_dc_rect_ = QRect(); current_screen_id_ = screen_id; return true; } const Frame* ScreenCapturerGDI::captureFrame() { queue_.moveToNextFrame(); if (!prepareCaptureResources()) return nullptr; QRect screen_rect = ScreenCaptureUtils::screenRect(current_screen_id_, current_device_key_); if (screen_rect.isEmpty()) { LOG(LS_WARNING) << "Failed to get screen rect"; return nullptr; } if (!queue_.currentFrame() || queue_.currentFrame()->size() != screen_rect.size()) { DCHECK(desktop_dc_); DCHECK(memory_dc_); std::unique_ptr<Frame> frame = FrameDib::create( screen_rect.size(), PixelFormat::ARGB(), memory_dc_); if (!frame) { LOG(LS_WARNING) << "Failed to create frame buffer"; return nullptr; } queue_.replaceCurrentFrame(std::move(frame)); } FrameDib* current = static_cast<FrameDib*>(queue_.currentFrame()); FrameDib* previous = static_cast<FrameDib*>(queue_.previousFrame()); HGDIOBJ old_bitmap = SelectObject(memory_dc_, current->bitmap()); if (old_bitmap) { BitBlt(memory_dc_, 0, 0, screen_rect.width(), screen_rect.height(), *desktop_dc_, screen_rect.left(), screen_rect.top(), CAPTUREBLT | SRCCOPY); SelectObject(memory_dc_, old_bitmap); } current->setTopLeft(screen_rect.topLeft()); if (!previous || previous->size() != current->size()) { differ_ = std::make_unique<Differ>(screen_rect.size()); *current->updatedRegion() += QRect(QPoint(), screen_rect.size()); } else { differ_->calcDirtyRegion(previous->frameData(), current->frameData(), current->updatedRegion()); } return current; } bool ScreenCapturerGDI::prepareCaptureResources() { // Switch to the desktop receiving user input if different from the // current one. base::Desktop input_desktop(base::Desktop::inputDesktop()); if (input_desktop.isValid() && !desktop_.isSame(input_desktop)) { // Release GDI resources otherwise SetThreadDesktop will fail. desktop_dc_.reset(); memory_dc_.reset(); effects_disabler_.reset(); wallpaper_disabler_.reset(); // If SetThreadDesktop() fails, the thread is still assigned a desktop. // So we can continue capture screen bits, just from the wrong desktop. desktop_.setThreadDesktop(std::move(input_desktop)); } QRect desktop_rect = ScreenCaptureUtils::fullScreenRect(); // If the display bounds have changed then recreate GDI resources. if (desktop_rect != desktop_dc_rect_) { desktop_dc_.reset(); memory_dc_.reset(); effects_disabler_.reset(); wallpaper_disabler_.reset(); desktop_dc_rect_ = QRect(); } if (!desktop_dc_) { DCHECK(!memory_dc_); // Vote to disable Aero composited desktop effects while capturing. // Windows will restore Aero automatically if the process exits. // This has no effect under Windows 8 or higher. See crbug.com/124018. DwmEnableComposition(DWM_EC_DISABLECOMPOSITION); if (flags_ & DISABLE_EFFECTS) effects_disabler_ = std::make_unique<EffectsDisabler>(); if (flags_ & DISABLE_WALLPAPER) wallpaper_disabler_ = std::make_unique<WallpaperDisabler>(); // Create GDI device contexts to capture from the desktop into memory. desktop_dc_ = std::make_unique<base::win::ScopedGetDC>(nullptr); memory_dc_.reset(CreateCompatibleDC(*desktop_dc_)); if (!memory_dc_) { LOG(LS_WARNING) << "CreateCompatibleDC failed"; return false; } desktop_dc_rect_ = desktop_rect; // Make sure the frame buffers will be reallocated. queue_.reset(); } return true; } } // namespace desktop <|endoftext|>
<commit_before>/** * \file * * \brief Plugin which acts as proxy and calls other plugins written in python * * \copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #ifndef SWIG_TYPE_TABLE # error Build system error, SWIG_TYPE_TABLE is not defined #endif #include <Python.h> #ifndef HAVE_KDBCONFIG # include <kdbconfig.h> #endif #include <kdbhelper.h> #include SWIG_RUNTIME #include "python.hpp" #include <key.hpp> #include <keyset.hpp> #include <libgen.h> #include <pthread.h> using namespace ckdb; #include <kdberrors.h> #define PYTHON_PLUGIN_NAME_STR2(x) ELEKTRA_QUOTE(x) #define PYTHON_PLUGIN_NAME_STR PYTHON_PLUGIN_NAME_STR2(PYTHON_PLUGIN_NAME) static PyObject *Python_fromSWIG(ckdb::Key *key) { swig_type_info *ti = SWIG_TypeQuery("kdb::Key *"); if (key == NULL || ti == NULL) return Py_None; return SWIG_NewPointerObj(new kdb::Key(key), ti, 0); } static PyObject *Python_fromSWIG(ckdb::KeySet *keyset) { swig_type_info *ti = SWIG_TypeQuery("kdb::KeySet *"); if (keyset == NULL || ti == NULL) return Py_None; return SWIG_NewPointerObj(new kdb::KeySet(keyset), ti, 0); } class Python_LockSwap { public: Python_LockSwap(PyThreadState *newstate) { gstate = PyGILState_Ensure(); tstate = PyThreadState_Swap(newstate); } ~Python_LockSwap() { PyThreadState_Swap(tstate); PyGILState_Release(gstate); } private: PyGILState_STATE gstate; PyThreadState *tstate; }; extern "C" { typedef struct { PyThreadState *tstate; PyObject *instance; int printError; int shutdown; } moduleData; static int Python_AppendToSysPath(const char *path) { if (path == NULL) return 0; PyObject *sysPath = PySys_GetObject((char *)"path"); PyObject *pyPath = PyUnicode_FromString(path); PyList_Append(sysPath, pyPath); Py_DECREF(pyPath); return 1; } static PyObject *Python_CallFunction(PyObject *object, PyObject *args) { if (!PyCallable_Check(object)) return NULL; PyObject *res = PyObject_CallObject(object, args ? args : PyTuple_New (0)); Py_XINCREF(res); return res; } static int Python_CallFunction_Int(moduleData *data, PyObject *object, PyObject *args, ckdb::Key *errorKey) { int ret = -1; PyObject *res = Python_CallFunction(object, args); if (!res) { ELEKTRA_SET_ERROR(111, errorKey, "Error while calling python function"); if (data->printError) PyErr_Print(); } else { #if PY_MAJOR_VERSION >= 3 if (!PyLong_Check(res)) #else if (!PyInt_Check(res)) #endif ELEKTRA_SET_ERROR(111, errorKey, "Return value is no integer"); else ret = PyLong_AsLong(res); } Py_XDECREF(res); return ret; } static int Python_CallFunction_Helper1(moduleData *data, const char *funcName, ckdb::Key *errorKey) { int ret = 0; Python_LockSwap pylock(data->tstate); PyObject *func = PyObject_GetAttrString(data->instance, funcName); if (func) { PyObject *arg0 = Python_fromSWIG(errorKey); PyObject *args = Py_BuildValue("(O)", arg0); ret = Python_CallFunction_Int(data, func, args, errorKey); Py_DECREF(arg0); Py_DECREF(args); Py_DECREF(func); } return ret; } static int Python_CallFunction_Helper2(moduleData *data, const char *funcName, ckdb::KeySet *returned, ckdb::Key *parentKey) { int ret = 0; Python_LockSwap pylock(data->tstate); PyObject *func = PyObject_GetAttrString(data->instance, funcName); if (func) { PyObject *arg0 = Python_fromSWIG(returned); PyObject *arg1 = Python_fromSWIG(parentKey); PyObject *args = Py_BuildValue("(OO)", arg0, arg1); ret = Python_CallFunction_Int(data, func, args, parentKey); Py_DECREF(arg0); Py_DECREF(arg1); Py_DECREF(args); Py_DECREF(func); } return ret; } static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static unsigned open_cnt = 0; static void Python_Shutdown(moduleData *data) { /* destroy python if plugin isn't used anymore */ if (Py_IsInitialized()) { if (data->tstate) { Python_LockSwap pylock(data->tstate); /* clean up references */ Py_XDECREF(data->instance); data->instance = NULL; /* destroy sub interpreter */ Py_EndInterpreter(data->tstate); } pthread_mutex_lock(&mutex); if (open_cnt && !--open_cnt && data->shutdown) // order matters! Py_Finalize(); pthread_mutex_unlock(&mutex); } } int PYTHON_PLUGIN_FUNCTION(Open)(ckdb::Plugin *handle, ckdb::Key *errorKey) { KeySet *config = elektraPluginGetConfig(handle); if (ksLookupByName(config, "/module", 0) != NULL) return 0; // by convention: success if /module exists Key *script = ksLookupByName(config, "/script", 0); if (script == NULL || !strlen(keyString(script))) { ELEKTRA_SET_ERROR(111, errorKey, "No python script set"); return -1; } /* create module data */ moduleData *data = new moduleData; data->tstate = NULL; data->instance = NULL; data->printError = (ksLookupByName(config, "/print", 0) != NULL); /* shutdown flag is integer by design. This way users can set the * expected behaviour without worring about default values */ data->shutdown = (ksLookupByName(config, "/shutdown", 0) && !!strcmp(keyString(ksLookupByName(config, "/shutdown", 0)), "0")); { /* initialize python interpreter if necessary */ pthread_mutex_lock(&mutex); if (!Py_IsInitialized()) { Py_Initialize(); if (!Py_IsInitialized()) { pthread_mutex_unlock(&mutex); goto error; } open_cnt++; } else if (open_cnt) // we have initialized python before open_cnt++; pthread_mutex_unlock(&mutex); /* init threads */ PyEval_InitThreads(); /* acquire GIL */ Python_LockSwap pylock(NULL); /* create a new sub-interpreter */ data->tstate = Py_NewInterpreter(); if (data->tstate == NULL) { ELEKTRA_SET_ERROR(111, errorKey, "Unable to create sub intepreter"); goto error; } PyThreadState_Swap(data->tstate); /* import kdb */ PyObject *kdbModule = PyImport_ImportModule("kdb"); if (kdbModule == NULL) { ELEKTRA_SET_ERROR(111, errorKey, "Unable to import kdb module"); goto error_print; } Py_XDECREF(kdbModule); /* extend sys path */ char *tmpScript = elektraStrDup(keyString(script)); const char *dname = dirname(tmpScript); if (!Python_AppendToSysPath(dname)) { ELEKTRA_SET_ERROR(111, errorKey, "Unable to extend sys.path"); elektraFree(tmpScript); goto error; } elektraFree(tmpScript); /* import module/script */ tmpScript = elektraStrDup(keyString(script)); char *bname = basename(tmpScript); size_t bname_len = strlen(bname); if (bname_len >= 4 && strcmp(bname + bname_len - 3, ".py") == 0) bname[bname_len - 3] = '\0'; PyObject *pModule = PyImport_ImportModule(bname); if (pModule == NULL) { ELEKTRA_SET_ERRORF(111, errorKey,"Unable to import python script %s", keyString(script)); elektraFree(tmpScript); goto error_print; } elektraFree(tmpScript); /* get class */ PyObject *klass = PyObject_GetAttrString(pModule, "ElektraPlugin"); Py_DECREF(pModule); if (klass == NULL) { ELEKTRA_SET_ERROR(111, errorKey, "Module doesn't provide a ElektraPlugin class"); goto error_print; } /* create instance of class */ PyObject *inst_args = Py_BuildValue("()"); PyObject *inst = PyEval_CallObject(klass, inst_args); Py_DECREF(klass); Py_DECREF(inst_args); if (inst == NULL) { ELEKTRA_SET_ERROR(111, errorKey, "Unable to create instance of ElektraPlugin"); goto error_print; } data->instance = inst; } /* store module data after everything is set up */ elektraPluginSetData(handle, data); /* call python function */ return Python_CallFunction_Helper1(data, "open", errorKey); error_print: if (data->printError) PyErr_Print(); error: /* destroy python */ Python_Shutdown(data); delete data; return -1; } int PYTHON_PLUGIN_FUNCTION(Close)(ckdb::Plugin *handle, ckdb::Key *errorKey) { moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle)); if (data == NULL) return 0; int ret = Python_CallFunction_Helper1(data, "close", errorKey); /* destroy python */ Python_Shutdown(data); delete data; return ret; } int PYTHON_PLUGIN_FUNCTION(Get)(ckdb::Plugin *handle, ckdb::KeySet *returned, ckdb::Key *parentKey) { #define _MODULE_CONFIG_PATH "system/elektra/modules/" PYTHON_PLUGIN_NAME_STR if (!strcmp(keyName(parentKey), _MODULE_CONFIG_PATH)) { KeySet *n; ksAppend(returned, n = ksNew(30, keyNew(_MODULE_CONFIG_PATH, KEY_VALUE, "python interpreter waits for your orders", KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports", KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/get", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Get), KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/set", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Set), KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/error", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Error), KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/open", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Open), KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/close", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Close), KEY_END), #include ELEKTRA_README(PYTHON_PLUGIN_NAME) keyNew(_MODULE_CONFIG_PATH "/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END)); ksDel(n); } moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle)); if (data != NULL) return Python_CallFunction_Helper2(data, "get", returned, parentKey); return 0; } int PYTHON_PLUGIN_FUNCTION(Set)(ckdb::Plugin *handle, ckdb::KeySet *returned, ckdb::Key *parentKey) { moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle)); if (data != NULL) return Python_CallFunction_Helper2(data, "set", returned, parentKey); return 0; } int PYTHON_PLUGIN_FUNCTION(Error)(ckdb::Plugin *handle, ckdb::KeySet *returned, ckdb::Key *parentKey) { moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle)); if (data != NULL) return Python_CallFunction_Helper2(data, "error", returned, parentKey); return 0; } ckdb::Plugin *PYTHON_PLUGIN_EXPORT(PYTHON_PLUGIN_NAME) { return elektraPluginExport(PYTHON_PLUGIN_NAME_STR, ELEKTRA_PLUGIN_OPEN, &PYTHON_PLUGIN_FUNCTION(Open), ELEKTRA_PLUGIN_CLOSE, &PYTHON_PLUGIN_FUNCTION(Close), ELEKTRA_PLUGIN_GET, &PYTHON_PLUGIN_FUNCTION(Get), ELEKTRA_PLUGIN_SET, &PYTHON_PLUGIN_FUNCTION(Set), ELEKTRA_PLUGIN_ERROR, &PYTHON_PLUGIN_FUNCTION(Error), ELEKTRA_PLUGIN_END); } } <commit_msg>python: get rid of pthread_mutex_t and use std::mutex<commit_after>/** * \file * * \brief Plugin which acts as proxy and calls other plugins written in python * * \copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #ifndef SWIG_TYPE_TABLE # error Build system error, SWIG_TYPE_TABLE is not defined #endif #include <Python.h> #ifndef HAVE_KDBCONFIG # include <kdbconfig.h> #endif #include <kdbhelper.h> #include SWIG_RUNTIME #include "python.hpp" #include <key.hpp> #include <keyset.hpp> #include <libgen.h> #include <mutex> using namespace ckdb; #include <kdberrors.h> #define PYTHON_PLUGIN_NAME_STR2(x) ELEKTRA_QUOTE(x) #define PYTHON_PLUGIN_NAME_STR PYTHON_PLUGIN_NAME_STR2(PYTHON_PLUGIN_NAME) static PyObject *Python_fromSWIG(ckdb::Key *key) { swig_type_info *ti = SWIG_TypeQuery("kdb::Key *"); if (key == NULL || ti == NULL) return Py_None; return SWIG_NewPointerObj(new kdb::Key(key), ti, 0); } static PyObject *Python_fromSWIG(ckdb::KeySet *keyset) { swig_type_info *ti = SWIG_TypeQuery("kdb::KeySet *"); if (keyset == NULL || ti == NULL) return Py_None; return SWIG_NewPointerObj(new kdb::KeySet(keyset), ti, 0); } class Python_LockSwap { public: Python_LockSwap(PyThreadState *newstate) { gstate = PyGILState_Ensure(); tstate = PyThreadState_Swap(newstate); } ~Python_LockSwap() { PyThreadState_Swap(tstate); PyGILState_Release(gstate); } private: PyGILState_STATE gstate; PyThreadState *tstate; }; typedef struct { PyThreadState *tstate; PyObject *instance; int printError; int shutdown; } moduleData; static int Python_AppendToSysPath(const char *path) { if (path == NULL) return 0; PyObject *sysPath = PySys_GetObject((char *)"path"); PyObject *pyPath = PyUnicode_FromString(path); PyList_Append(sysPath, pyPath); Py_DECREF(pyPath); return 1; } static PyObject *Python_CallFunction(PyObject *object, PyObject *args) { if (!PyCallable_Check(object)) return NULL; PyObject *res = PyObject_CallObject(object, args ? args : PyTuple_New (0)); Py_XINCREF(res); return res; } static int Python_CallFunction_Int(moduleData *data, PyObject *object, PyObject *args, ckdb::Key *errorKey) { int ret = -1; PyObject *res = Python_CallFunction(object, args); if (!res) { ELEKTRA_SET_ERROR(111, errorKey, "Error while calling python function"); if (data->printError) PyErr_Print(); } else { #if PY_MAJOR_VERSION >= 3 if (!PyLong_Check(res)) #else if (!PyInt_Check(res)) #endif ELEKTRA_SET_ERROR(111, errorKey, "Return value is no integer"); else ret = PyLong_AsLong(res); } Py_XDECREF(res); return ret; } static int Python_CallFunction_Helper1(moduleData *data, const char *funcName, ckdb::Key *errorKey) { int ret = 0; Python_LockSwap pylock(data->tstate); PyObject *func = PyObject_GetAttrString(data->instance, funcName); if (func) { PyObject *arg0 = Python_fromSWIG(errorKey); PyObject *args = Py_BuildValue("(O)", arg0); ret = Python_CallFunction_Int(data, func, args, errorKey); Py_DECREF(arg0); Py_DECREF(args); Py_DECREF(func); } return ret; } static int Python_CallFunction_Helper2(moduleData *data, const char *funcName, ckdb::KeySet *returned, ckdb::Key *parentKey) { int ret = 0; Python_LockSwap pylock(data->tstate); PyObject *func = PyObject_GetAttrString(data->instance, funcName); if (func) { PyObject *arg0 = Python_fromSWIG(returned); PyObject *arg1 = Python_fromSWIG(parentKey); PyObject *args = Py_BuildValue("(OO)", arg0, arg1); ret = Python_CallFunction_Int(data, func, args, parentKey); Py_DECREF(arg0); Py_DECREF(arg1); Py_DECREF(args); Py_DECREF(func); } return ret; } static std::mutex mutex; static unsigned open_cnt = 0; static void Python_Shutdown(moduleData *data) { /* destroy python if plugin isn't used anymore */ if (Py_IsInitialized()) { if (data->tstate) { Python_LockSwap pylock(data->tstate); /* clean up references */ Py_XDECREF(data->instance); data->instance = NULL; /* destroy sub interpreter */ Py_EndInterpreter(data->tstate); } mutex.lock(); if (open_cnt && !--open_cnt && data->shutdown) // order matters! Py_Finalize(); mutex.unlock(); } } extern "C" { int PYTHON_PLUGIN_FUNCTION(Open)(ckdb::Plugin *handle, ckdb::Key *errorKey) { KeySet *config = elektraPluginGetConfig(handle); if (ksLookupByName(config, "/module", 0) != NULL) return 0; // by convention: success if /module exists Key *script = ksLookupByName(config, "/script", 0); if (script == NULL || !strlen(keyString(script))) { ELEKTRA_SET_ERROR(111, errorKey, "No python script set"); return -1; } /* create module data */ moduleData *data = new moduleData; data->tstate = NULL; data->instance = NULL; data->printError = (ksLookupByName(config, "/print", 0) != NULL); /* shutdown flag is integer by design. This way users can set the * expected behaviour without worring about default values */ data->shutdown = (ksLookupByName(config, "/shutdown", 0) && !!strcmp(keyString(ksLookupByName(config, "/shutdown", 0)), "0")); { /* initialize python interpreter if necessary */ mutex.lock(); if (!Py_IsInitialized()) { Py_Initialize(); if (!Py_IsInitialized()) { mutex.unlock(); goto error; } open_cnt++; } else if (open_cnt) // we have initialized python before open_cnt++; mutex.unlock(); /* init threads */ PyEval_InitThreads(); /* acquire GIL */ Python_LockSwap pylock(NULL); /* create a new sub-interpreter */ data->tstate = Py_NewInterpreter(); if (data->tstate == NULL) { ELEKTRA_SET_ERROR(111, errorKey, "Unable to create sub intepreter"); goto error; } PyThreadState_Swap(data->tstate); /* import kdb */ PyObject *kdbModule = PyImport_ImportModule("kdb"); if (kdbModule == NULL) { ELEKTRA_SET_ERROR(111, errorKey, "Unable to import kdb module"); goto error_print; } Py_XDECREF(kdbModule); /* extend sys path */ char *tmpScript = elektraStrDup(keyString(script)); const char *dname = dirname(tmpScript); if (!Python_AppendToSysPath(dname)) { ELEKTRA_SET_ERROR(111, errorKey, "Unable to extend sys.path"); elektraFree(tmpScript); goto error; } elektraFree(tmpScript); /* import module/script */ tmpScript = elektraStrDup(keyString(script)); char *bname = basename(tmpScript); size_t bname_len = strlen(bname); if (bname_len >= 4 && strcmp(bname + bname_len - 3, ".py") == 0) bname[bname_len - 3] = '\0'; PyObject *pModule = PyImport_ImportModule(bname); if (pModule == NULL) { ELEKTRA_SET_ERRORF(111, errorKey,"Unable to import python script %s", keyString(script)); elektraFree(tmpScript); goto error_print; } elektraFree(tmpScript); /* get class */ PyObject *klass = PyObject_GetAttrString(pModule, "ElektraPlugin"); Py_DECREF(pModule); if (klass == NULL) { ELEKTRA_SET_ERROR(111, errorKey, "Module doesn't provide a ElektraPlugin class"); goto error_print; } /* create instance of class */ PyObject *inst_args = Py_BuildValue("()"); PyObject *inst = PyEval_CallObject(klass, inst_args); Py_DECREF(klass); Py_DECREF(inst_args); if (inst == NULL) { ELEKTRA_SET_ERROR(111, errorKey, "Unable to create instance of ElektraPlugin"); goto error_print; } data->instance = inst; } /* store module data after everything is set up */ elektraPluginSetData(handle, data); /* call python function */ return Python_CallFunction_Helper1(data, "open", errorKey); error_print: if (data->printError) PyErr_Print(); error: /* destroy python */ Python_Shutdown(data); delete data; return -1; } int PYTHON_PLUGIN_FUNCTION(Close)(ckdb::Plugin *handle, ckdb::Key *errorKey) { moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle)); if (data == NULL) return 0; int ret = Python_CallFunction_Helper1(data, "close", errorKey); /* destroy python */ Python_Shutdown(data); delete data; return ret; } int PYTHON_PLUGIN_FUNCTION(Get)(ckdb::Plugin *handle, ckdb::KeySet *returned, ckdb::Key *parentKey) { #define _MODULE_CONFIG_PATH "system/elektra/modules/" PYTHON_PLUGIN_NAME_STR if (!strcmp(keyName(parentKey), _MODULE_CONFIG_PATH)) { KeySet *n; ksAppend(returned, n = ksNew(30, keyNew(_MODULE_CONFIG_PATH, KEY_VALUE, "python interpreter waits for your orders", KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports", KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/get", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Get), KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/set", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Set), KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/error", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Error), KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/open", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Open), KEY_END), keyNew(_MODULE_CONFIG_PATH "/exports/close", KEY_FUNC, PYTHON_PLUGIN_FUNCTION(Close), KEY_END), #include ELEKTRA_README(PYTHON_PLUGIN_NAME) keyNew(_MODULE_CONFIG_PATH "/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END)); ksDel(n); } moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle)); if (data != NULL) return Python_CallFunction_Helper2(data, "get", returned, parentKey); return 0; } int PYTHON_PLUGIN_FUNCTION(Set)(ckdb::Plugin *handle, ckdb::KeySet *returned, ckdb::Key *parentKey) { moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle)); if (data != NULL) return Python_CallFunction_Helper2(data, "set", returned, parentKey); return 0; } int PYTHON_PLUGIN_FUNCTION(Error)(ckdb::Plugin *handle, ckdb::KeySet *returned, ckdb::Key *parentKey) { moduleData *data = static_cast<moduleData *>(elektraPluginGetData(handle)); if (data != NULL) return Python_CallFunction_Helper2(data, "error", returned, parentKey); return 0; } ckdb::Plugin *PYTHON_PLUGIN_EXPORT(PYTHON_PLUGIN_NAME) { return elektraPluginExport(PYTHON_PLUGIN_NAME_STR, ELEKTRA_PLUGIN_OPEN, &PYTHON_PLUGIN_FUNCTION(Open), ELEKTRA_PLUGIN_CLOSE, &PYTHON_PLUGIN_FUNCTION(Close), ELEKTRA_PLUGIN_GET, &PYTHON_PLUGIN_FUNCTION(Get), ELEKTRA_PLUGIN_SET, &PYTHON_PLUGIN_FUNCTION(Set), ELEKTRA_PLUGIN_ERROR, &PYTHON_PLUGIN_FUNCTION(Error), ELEKTRA_PLUGIN_END); } } <|endoftext|>
<commit_before>/** * @file * * @brief Write key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "write.hpp" #include "log.hpp" #include "yaml-cpp/yaml.h" #include <kdb.hpp> #include <kdbease.h> #include <kdblogger.h> #include <fstream> #include <stack> namespace { using std::endl; using std::istringstream; using std::ofstream; using std::ostringstream; using std::stack; using std::string; using kdb::Key; using kdb::KeySet; using kdb::NameIterator; /** * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`. * * @pre The parameter `key` must be a child of `parent`. * * @param key This is the key for which this function returns a relative iterator. * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function. * * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`. */ NameIterator relativeKeyIterator (Key const & key, Key const & parent) { auto parentIterator = parent.begin (); auto keyIterator = key.begin (); while (parentIterator != parent.end () && keyIterator != key.end ()) { parentIterator++; keyIterator++; } return keyIterator; } /** * @brief This function returns the array index for a given key part. * * @param nameIterator This iterator specifies the name of the key. * * @retval The index of the array element, or `0` if the given key part is not an array element. */ unsigned long long getArrayIndex (NameIterator const & nameIterator) { string const name = *nameIterator; auto const offsetIndex = ckdb::elektraArrayValidateBaseNameString (name.c_str ()); auto const isArrayElement = offsetIndex >= 1; return isArrayElement ? stoull (name.substr (static_cast<size_t> (offsetIndex))) : 0; } /** * @brief This function creates a YAML node representing a key value. * * @param key This key specifies the data that should be saved in the YAML node returned by this function. * * @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string * `Unsupported binary value!`. If you need support for binary data, please load the Base64 plugin before you use YAML CPP. * * @returns A new YAML node containing the data specified in `key` */ YAML::Node createNode (Key const & key) { if (key.hasMeta ("array")) { return YAML::Node (YAML::NodeType::Sequence); } if (key.getBinarySize () == 0) { return YAML::Node (YAML::NodeType::Null); } if (key.isBinary ()) { return YAML::Node ("Unsupported binary value!"); } auto value = key.get<string> (); if (value == "0" || value == "1") { return YAML::Node (key.get<bool> ()); } return YAML::Node (value); } /** * @brief This function creates a YAML Node containing a key value and optionally metadata. * * @param key This key specifies the data that should be saved in the YAML node returned by this function. * * @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string * `Unsupported binary value!`. If you need support for binary data, please load the Base64 before you use YAML CPP. * * @returns A new YAML node containing the data and metadata specified in `key` */ YAML::Node createLeafNode (Key & key) { YAML::Node metaNode{ YAML::NodeType::Map }; YAML::Node dataNode = createNode (key); key.rewindMeta (); while (Key meta = key.nextMeta ()) { if (meta.getName () == "array" || meta.getName () == "binary") continue; if (meta.getName () == "type" && meta.getString () == "binary") { dataNode.SetTag ("tag:yaml.org,2002:binary"); continue; } metaNode[meta.getName ()] = meta.getString (); ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", meta.getName ().c_str (), meta.getString ().c_str ()); } if (metaNode.size () <= 0) { ELEKTRA_LOG_DEBUG ("Return leaf node with value “%s”", dataNode.IsNull () ? "~" : dataNode.IsSequence () ? "[]" : dataNode.as<string> ().c_str ()); return dataNode; } YAML::Node node{ YAML::NodeType::Sequence }; node.SetTag ("!elektra/meta"); node.push_back (dataNode); node.push_back (metaNode); #ifdef HAVE_LOGGER ostringstream data; data << node; ELEKTRA_LOG_DEBUG ("Return meta leaf node with value “%s”", data.str ().c_str ()); #endif return node; } /** * @brief This function adds `null` elements to the given YAML collection. * * @param sequence This node stores the collection to which this function adds `numberOfElements` empty elements. * @param numberOfElements This parameter specifies the number of empty element this function adds to `sequence`. */ void addEmptyArrayElements (YAML::Node & sequence, unsigned long long const numberOfElements) { ELEKTRA_LOG_DEBUG ("Add %llu empty array elements", numberOfElements); for (auto missingFields = numberOfElements; missingFields > 0; missingFields--) { sequence.push_back ({}); } } /** * @brief This function adds a key to a YAML node. * * @param data This node stores the data specified via `keyIterator`. * @param keyIterator This iterator specifies the current part of the key name this function adds to `data`. * @param key This parameter specifies the key that should be added to `data`. * @param converted This partial key specifies the part of `key` that is already part of `data`. * @param arrayParent This key stores the (possible) array parent of the current part of `key` this function should add to `data`. */ void addKey (YAML::Node & data, NameIterator & keyIterator, Key & key, Key & converted, Key * arrayParent) { if (keyIterator == key.end ()) { ELEKTRA_LOG_DEBUG ("Create leaf node for value “%s”", key.getString ().c_str ()); data = createLeafNode (key); return; } converted.addBaseName (*keyIterator); auto const isArrayElement = data.IsSequence () || (arrayParent && converted.isDirectBelow (*arrayParent)); auto const arrayIndex = isArrayElement ? getArrayIndex (keyIterator) : 0; ELEKTRA_LOG_DEBUG ("Add key part “%s”", (*keyIterator).c_str ()); if (data.IsScalar ()) data = YAML::Node (); if (isArrayElement) { YAML::Node node = arrayIndex < data.size () ? data[arrayIndex] : YAML::Node (); addKey (node, ++keyIterator, key, converted, arrayParent); if (arrayIndex > data.size ()) addEmptyArrayElements (data, arrayIndex - data.size ()); data[arrayIndex] = node; } else { string part = *keyIterator; YAML::Node node = data[part] ? data[part] : YAML::Node (); addKey (node, ++keyIterator, key, converted, arrayParent); data[part] = node; } } /** * @brief This function adds a key set to a YAML node. * * @param data This node stores the data specified via `mappings`. * @param mappings This keyset specifies all keys and values this function adds to `data`. * @param parent This key is the root of all keys stored in `mappings`. */ void addKeys (YAML::Node & data, KeySet const & mappings, Key const & parent) { stack<Key> arrayParents; for (auto key : mappings) { ELEKTRA_LOG_DEBUG ("Convert key “%s”: “%s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!"); NameIterator keyIterator = relativeKeyIterator (key, parent); if (key.hasMeta ("array")) { ELEKTRA_LOG_DEBUG ("Add array parent “%s”", key.getName ().c_str ()); arrayParents.push (key); } else if (!arrayParents.empty () && !key.isBelow (arrayParents.top ())) { ELEKTRA_LOG_DEBUG ("Remove array parent “%s”", arrayParents.top ().getName ().c_str ()); arrayParents.pop (); } Key converted{ parent.getName (), KEY_END }; addKey (data, keyIterator, key, converted, arrayParents.empty () ? nullptr : &arrayParents.top ()); #ifdef HAVE_LOGGER ostringstream output; output << data; ELEKTRA_LOG_DEBUG ("Converted Data:"); ELEKTRA_LOG_DEBUG ("——————————"); istringstream stream (output.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif } } } // end namespace /** * @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`. * * @param mappings This key set stores the mappings that should be saved as YAML data. * @param parent This key specifies the path to the YAML data file that should be written. */ void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent) { KeySet keys = mappings; YAML::Node data; addKeys (data, keys, parent); #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Write Data:"); ELEKTRA_LOG_DEBUG ("——————————"); ostringstream outputString; outputString << data; istringstream stream (outputString.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif ofstream output (parent.getString ()); output << data << endl; } <commit_msg>YAML CPP: Update comments for write code<commit_after>/** * @file * * @brief Write key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "write.hpp" #include "log.hpp" #include "yaml-cpp/yaml.h" #include <kdb.hpp> #include <kdbease.h> #include <kdblogger.h> #include <fstream> #include <stack> namespace { using std::endl; using std::istringstream; using std::ofstream; using std::ostringstream; using std::stack; using std::string; using kdb::Key; using kdb::KeySet; using kdb::NameIterator; /** * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`. * * @pre The parameter `key` must be a child of `parent`. * * @param key This is the key for which this function returns a relative iterator. * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function. * * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`. */ NameIterator relativeKeyIterator (Key const & key, Key const & parent) { auto parentIterator = parent.begin (); auto keyIterator = key.begin (); while (parentIterator != parent.end () && keyIterator != key.end ()) { parentIterator++; keyIterator++; } return keyIterator; } /** * @brief This function returns the array index for a given key part. * * @param nameIterator This iterator specifies the name of the key. * * @retval The index of the array element, or `0` if the given key part is not an array element. */ unsigned long long getArrayIndex (NameIterator const & nameIterator) { string const name = *nameIterator; auto const offsetIndex = ckdb::elektraArrayValidateBaseNameString (name.c_str ()); auto const isArrayElement = offsetIndex >= 1; return isArrayElement ? stoull (name.substr (static_cast<size_t> (offsetIndex))) : 0; } /** * @brief This function creates a YAML node representing a key value. * * @param key This key specifies the data that should be saved in the YAML node returned by this function. * * @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string * `Unsupported binary value!`. If you need support for binary data, please load the Base64 plugin before you use YAML CPP. * * @returns A new YAML node containing the data specified in `key` */ YAML::Node createNode (Key const & key) { if (key.hasMeta ("array")) { return YAML::Node (YAML::NodeType::Sequence); } if (key.getBinarySize () == 0) { return YAML::Node (YAML::NodeType::Null); } if (key.isBinary ()) { return YAML::Node ("Unsupported binary value!"); } auto value = key.get<string> (); if (value == "0" || value == "1") { return YAML::Node (key.get<bool> ()); } return YAML::Node (value); } /** * @brief This function creates a YAML Node containing a key value and optionally metadata. * * @param key This key specifies the data that should be saved in the YAML node returned by this function. * * @note Since YAML does not support non-empty binary data directly this function replaces data stored in binary keys with the string * `Unsupported binary value!`. If you need support for binary data, please load the Base64 before you use YAML CPP. * * @returns A new YAML node containing the data and metadata specified in `key` */ YAML::Node createLeafNode (Key & key) { YAML::Node metaNode{ YAML::NodeType::Map }; YAML::Node dataNode = createNode (key); key.rewindMeta (); while (Key meta = key.nextMeta ()) { if (meta.getName () == "array" || meta.getName () == "binary") continue; if (meta.getName () == "type" && meta.getString () == "binary") { dataNode.SetTag ("tag:yaml.org,2002:binary"); continue; } metaNode[meta.getName ()] = meta.getString (); ELEKTRA_LOG_DEBUG ("Add metakey “%s: %s”", meta.getName ().c_str (), meta.getString ().c_str ()); } if (metaNode.size () <= 0) { ELEKTRA_LOG_DEBUG ("Return leaf node with value “%s”", dataNode.IsNull () ? "~" : dataNode.IsSequence () ? "[]" : dataNode.as<string> ().c_str ()); return dataNode; } YAML::Node node{ YAML::NodeType::Sequence }; node.SetTag ("!elektra/meta"); node.push_back (dataNode); node.push_back (metaNode); #ifdef HAVE_LOGGER ostringstream data; data << node; ELEKTRA_LOG_DEBUG ("Return meta leaf node with value “%s”", data.str ().c_str ()); #endif return node; } /** * @brief This function adds `null` elements to the given YAML sequence. * * @param sequence This node stores the collection to which this function adds `numberOfElements` empty elements. * @param numberOfElements This parameter specifies the number of empty element this function adds to `sequence`. */ void addEmptyArrayElements (YAML::Node & sequence, unsigned long long const numberOfElements) { ELEKTRA_LOG_DEBUG ("Add %llu empty array elements", numberOfElements); for (auto missingFields = numberOfElements; missingFields > 0; missingFields--) { sequence.push_back ({}); } } /** * @brief This function adds a key to a YAML node. * * @param data This node stores the data specified via the other parameters of this function. * @param keyIterator This iterator specifies the current part of the key name this function adds to `data`. * @param key This parameter specifies the key that should be added to `data`. * @param converted This partial key specifies the part of `key` that is already part of `data`. * @param arrayParent This key stores the array parent of the current part of `key` this function should add to `data`. This parameter must * only contain a valid array parent for the first element key of an array. */ void addKey (YAML::Node & data, NameIterator & keyIterator, Key & key, Key & converted, Key * arrayParent) { if (keyIterator == key.end ()) { ELEKTRA_LOG_DEBUG ("Create leaf node for value “%s”", key.getString ().c_str ()); data = createLeafNode (key); return; } converted.addBaseName (*keyIterator); auto const isArrayElement = data.IsSequence () || (arrayParent && converted.isDirectBelow (*arrayParent)); auto const arrayIndex = isArrayElement ? getArrayIndex (keyIterator) : 0; ELEKTRA_LOG_DEBUG ("Add key part “%s”", (*keyIterator).c_str ()); if (data.IsScalar ()) data = YAML::Node (); if (isArrayElement) { YAML::Node node = arrayIndex < data.size () ? data[arrayIndex] : YAML::Node (); addKey (node, ++keyIterator, key, converted, arrayParent); if (arrayIndex > data.size ()) addEmptyArrayElements (data, arrayIndex - data.size ()); data[arrayIndex] = node; } else { string part = *keyIterator; YAML::Node node = data[part] ? data[part] : YAML::Node (); addKey (node, ++keyIterator, key, converted, arrayParent); data[part] = node; } } /** * @brief This function adds a key set to a YAML node. * * @param data This node stores the data specified via the other parameters of this function. * @param mappings This keyset specifies all keys and values this function adds to `data`. * @param parent This key is the root of all keys stored in `mappings`. */ void addKeys (YAML::Node & data, KeySet const & mappings, Key const & parent) { /* This stack stores the current array parents for a certain part of a key. The code below only guarantees that the array parents will be correct for the first array element below a parent. */ stack<Key> arrayParents; for (auto key : mappings) { ELEKTRA_LOG_DEBUG ("Convert key “%s”: “%s”", key.getName ().c_str (), key.getBinarySize () == 0 ? "NULL" : key.isString () ? key.getString ().c_str () : "binary value!"); NameIterator keyIterator = relativeKeyIterator (key, parent); if (key.hasMeta ("array")) { ELEKTRA_LOG_DEBUG ("Add array parent “%s”", key.getName ().c_str ()); arrayParents.push (key); } else if (!arrayParents.empty () && !key.isBelow (arrayParents.top ())) { ELEKTRA_LOG_DEBUG ("Remove array parent “%s”", arrayParents.top ().getName ().c_str ()); arrayParents.pop (); } Key converted{ parent.getName (), KEY_END }; addKey (data, keyIterator, key, converted, arrayParents.empty () ? nullptr : &arrayParents.top ()); #ifdef HAVE_LOGGER ostringstream output; output << data; ELEKTRA_LOG_DEBUG ("Converted Data:"); ELEKTRA_LOG_DEBUG ("——————————"); istringstream stream (output.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif } } } // end namespace /** * @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`. * * @param mappings This key set stores the mappings that should be saved as YAML data. * @param parent This key specifies the path to the YAML data file that should be written. */ void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent) { KeySet keys = mappings; YAML::Node data; addKeys (data, keys, parent); #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Write Data:"); ELEKTRA_LOG_DEBUG ("——————————"); ostringstream outputString; outputString << data; istringstream stream (outputString.str ()); for (string line; std::getline (stream, line);) { ELEKTRA_LOG_DEBUG ("%s", line.c_str ()); } ELEKTRA_LOG_DEBUG ("——————————"); #endif ofstream output (parent.getString ()); output << data << endl; } <|endoftext|>
<commit_before>#include "clay.hpp" #include "invokeutil2.hpp" // // declarations // struct CValue; typedef Pointer<CValue> CValuePtr; struct CValue : public Object { TypePtr type; llvm::Value *llval; CValue(TypePtr type, llvm::Value *llval) : Object(CVALUE), type(type), llval(llval) {} }; llvm::Function *llvmFunction; llvm::IRBuilder<> *initBuilder; llvm::IRBuilder<> *builder; // value operations codegen llvm::Value * codegenAllocValue(TypePtr t); void codegenValueInit(CValuePtr dest); void codegenValueDestroy(CValuePtr dest); void codegenValueCopy(CValuePtr dest, CValuePtr src); void codegenValueAssign(CValuePtr dest, CValuePtr src); llvm::Value * codegen(ExprPtr expr, EnvPtr env, llvm::Value *outPtr); llvm::Value * codegenIndexing(ObjectPtr obj, ArgListPtr args, llvm::Value *outPtr); llvm::Value * codegenInvoke(ObjectPtr obj, ArgListPtr args, llvm::Value *outPtr); void codegenValue(ValuePtr v, llvm::Value *outPtr); static llvm::Value * numericConstant(ValuePtr v); // // codegenAllocValue // llvm::Value * codegenAllocValue(TypePtr t) { const llvm::Type *llt = llvmType(t); return initBuilder->CreateAlloca(llt); } // // codegen // llvm::Value * codegen(ExprPtr expr, EnvPtr env, llvm::Value *outPtr) { LocationContext loc(expr->location); switch (expr->objKind) { case BOOL_LITERAL : case INT_LITERAL : case FLOAT_LITERAL : { ValuePtr v = evaluateToStatic(expr, env); llvm::Value *val = numericConstant(v); builder->CreateStore(val, outPtr); return outPtr; } case CHAR_LITERAL : { CharLiteral *x = (CharLiteral *)expr.ptr(); if (!x->converted) x->converted = convertCharLiteral(x->value); return codegen(x->converted, env, outPtr); } case STRING_LITERAL : { StringLiteral *x = (StringLiteral *)expr.ptr(); if (!x->converted) x->converted = convertStringLiteral(x->value); return codegen(x->converted, env, outPtr); } case NAME_REF : { NameRef *x = (NameRef *)expr.ptr(); ObjectPtr y = lookupEnv(env, x->name); if (y->objKind == VALUE) { Value *z = (Value *)y.ptr(); codegenValue(z, outPtr); return outPtr; } else if (y->objKind == CVALUE) { CValue *z = (CValue *)y.ptr(); assert(outPtr == NULL); return z->llval; } else { ValuePtr z = coToValue(y); codegenValue(z, outPtr); return outPtr; } } case TUPLE : { Tuple *x = (Tuple *)expr.ptr(); if (!x->converted) x->converted = convertTuple(x); return codegen(x->converted, env, outPtr); } case ARRAY : { Array *x = (Array *)expr.ptr(); if (!x->converted) x->converted = convertArray(x); return codegen(x->converted, env, outPtr); } case INDEXING : { Indexing *x = (Indexing *)expr.ptr(); PValuePtr indexable = partialEval(x->expr, env); if ((indexable->type == compilerObjectType) && indexable->isStatic) { ObjectPtr indexable2 = lower(evaluateToStatic(x->expr, env)); ArgListPtr args = new ArgList(x->args, env); return codegenIndexing(indexable2, args, outPtr); } error("invalid indexing operation"); return NULL; } case CALL : { Call *x = (Call *)expr.ptr(); PValuePtr callable = partialEval(x->expr, env); if ((callable->type == compilerObjectType) && callable->isStatic) { ObjectPtr callable2 = lower(evaluateToStatic(x->expr, env)); ArgListPtr args = new ArgList(x->args, env); return codegenInvoke(callable2, args, outPtr); } error("invalid call operation"); return NULL; } case FIELD_REF : { FieldRef *x = (FieldRef *)expr.ptr(); ValuePtr name = coToValue(x->name.ptr()); vector<ExprPtr> args; args.push_back(x->expr); args.push_back(new ValueExpr(name)); ObjectPtr prim = primName("recordFieldRefByName"); return codegenInvoke(prim, new ArgList(args, env), outPtr); } case TUPLE_REF : { TupleRef *x = (TupleRef *)expr.ptr(); ValuePtr index = intToValue(x->index); vector<ExprPtr> args; args.push_back(x->expr); args.push_back(new ValueExpr(index)); ObjectPtr prim = primName("tupleRef"); return codegenInvoke(prim, new ArgList(args, env), outPtr); } case UNARY_OP : { UnaryOp *x = (UnaryOp *)expr.ptr(); if (!x->converted) x->converted = convertUnaryOp(x); return codegen(x->converted, env, outPtr); } case BINARY_OP : { BinaryOp *x = (BinaryOp *)expr.ptr(); if (!x->converted) x->converted = convertBinaryOp(x); return codegen(x->converted, env, outPtr); } case AND : { And *x = (And *)expr.ptr(); PValuePtr pv1 = partialEval(x->expr1, env); PValuePtr pv2 = partialEval(x->expr2, env); if (pv1->type != pv2->type) error("type mismatch in 'and' expression"); if (pv1->isTemp || pv2->isTemp) { // codegenTemp(expr1, env, outPtr); // llvm::Value *tempBool = codegenAllocValue(boolType); // codegenInvoke(boolTruth, [outPtr], tempBool) // codegen(if !tempBool goto end) // codegenValueDestroy(outPtr); // codegenTemp(expr2, env, outPtr); // codegen(goto end) // return outPtr } else { // result = codegenRef(expr1, env); // tempBool = alloc bool value // codegenInvoke(boolTruth, [result], tempBool) // codegen(if !tempBool goto end) // result = codegenRef(expr2, env); // codegen(goto end) // return result } if (pv1->type != boolType) error("expecting bool type in 'and' expression"); } default : assert(false); } return NULL; } // // codegenIndexing // llvm::Value * codegenIndexing(ObjectPtr obj, ArgListPtr args, llvm::Value *outPtr) { } // // codegenInvoke // llvm::Value * codegenInvoke(ObjectPtr obj, ArgListPtr args, llvm::Value *outPtr) { } // // codegenValue // void codegenValue(ValuePtr v, llvm::Value *outPtr) { switch (v->type->typeKind) { case BOOL_TYPE : { const llvm::Type *llt = llvmType(v->type); int bv = valueToBool(v) ? 1 : 0; llvm::Value *llv = llvm::ConstantInt::get(llt, bv); builder->CreateStore(llv, outPtr); break; } case INTEGER_TYPE : case FLOAT_TYPE : { llvm::Value *llv = numericConstant(v); builder->CreateStore(llv, outPtr); break; } case COMPILER_OBJECT_TYPE : { const llvm::Type *llt = llvmType(v->type); int i = *((int *)v->buf); llvm::Value *llv = llvm::ConstantInt::get(llt, i); builder->CreateStore(llv, outPtr); break; } default : assert(false); } } // // numericConstant // template <typename T> llvm::Value * _sintConstant(ValuePtr v) { return llvm::ConstantInt::getSigned(llvmType(v->type), *((T *)v->buf)); } template <typename T> llvm::Value * _uintConstant(ValuePtr v) { return llvm::ConstantInt::get(llvmType(v->type), *((T *)v->buf)); } static llvm::Value * numericConstant(ValuePtr v) { llvm::Value *val = NULL; switch (v->type->typeKind) { case INTEGER_TYPE : { IntegerType *t = (IntegerType *)v->type.ptr(); if (t->isSigned) { switch (t->bits) { case 8 : val = _sintConstant<char>(v); break; case 16 : val = _sintConstant<short>(v); break; case 32 : val = _sintConstant<long>(v); break; case 64 : val = _sintConstant<long long>(v); break; default : assert(false); } } else { switch (t->bits) { case 8 : val = _uintConstant<unsigned char>(v); break; case 16 : val = _uintConstant<unsigned short>(v); break; case 32 : val = _uintConstant<unsigned long>(v); break; case 64 : val = _uintConstant<unsigned long long>(v); break; default : assert(false); } } } case FLOAT_TYPE : { FloatType *t = (FloatType *)v->type.ptr(); switch (t->bits) { case 32 : val = llvm::ConstantFP::get(llvmType(t), *((float *)v->buf)); break; case 64 : val = llvm::ConstantFP::get(llvmType(t), *((double *)v->buf)); break; default : assert(false); } } default : assert(false); } return val; } <commit_msg>formatting changes.<commit_after>#include "clay.hpp" #include "invokeutil2.hpp" // // declarations // struct CValue; typedef Pointer<CValue> CValuePtr; struct CValue : public Object { TypePtr type; llvm::Value *llval; CValue(TypePtr type, llvm::Value *llval) : Object(CVALUE), type(type), llval(llval) {} }; llvm::Function *llvmFunction; llvm::IRBuilder<> *initBuilder; llvm::IRBuilder<> *builder; // value operations codegen llvm::Value * codegenAllocValue(TypePtr t); void codegenValueInit(CValuePtr dest); void codegenValueDestroy(CValuePtr dest); void codegenValueCopy(CValuePtr dest, CValuePtr src); void codegenValueAssign(CValuePtr dest, CValuePtr src); llvm::Value * codegen(ExprPtr expr, EnvPtr env, llvm::Value *outPtr); llvm::Value * codegenIndexing(ObjectPtr obj, ArgListPtr args, llvm::Value *outPtr); llvm::Value * codegenInvoke(ObjectPtr obj, ArgListPtr args, llvm::Value *outPtr); void codegenValue(ValuePtr v, llvm::Value *outPtr); static llvm::Value * numericConstant(ValuePtr v); // // codegenAllocValue // llvm::Value * codegenAllocValue(TypePtr t) { const llvm::Type *llt = llvmType(t); return initBuilder->CreateAlloca(llt); } // // codegen // llvm::Value * codegen(ExprPtr expr, EnvPtr env, llvm::Value *outPtr) { LocationContext loc(expr->location); switch (expr->objKind) { case BOOL_LITERAL : case INT_LITERAL : case FLOAT_LITERAL : { ValuePtr v = evaluateToStatic(expr, env); llvm::Value *val = numericConstant(v); builder->CreateStore(val, outPtr); return outPtr; } case CHAR_LITERAL : { CharLiteral *x = (CharLiteral *)expr.ptr(); if (!x->converted) x->converted = convertCharLiteral(x->value); return codegen(x->converted, env, outPtr); } case STRING_LITERAL : { StringLiteral *x = (StringLiteral *)expr.ptr(); if (!x->converted) x->converted = convertStringLiteral(x->value); return codegen(x->converted, env, outPtr); } case NAME_REF : { NameRef *x = (NameRef *)expr.ptr(); ObjectPtr y = lookupEnv(env, x->name); if (y->objKind == VALUE) { Value *z = (Value *)y.ptr(); codegenValue(z, outPtr); return outPtr; } else if (y->objKind == CVALUE) { CValue *z = (CValue *)y.ptr(); assert(outPtr == NULL); return z->llval; } else { ValuePtr z = coToValue(y); codegenValue(z, outPtr); return outPtr; } } case TUPLE : { Tuple *x = (Tuple *)expr.ptr(); if (!x->converted) x->converted = convertTuple(x); return codegen(x->converted, env, outPtr); } case ARRAY : { Array *x = (Array *)expr.ptr(); if (!x->converted) x->converted = convertArray(x); return codegen(x->converted, env, outPtr); } case INDEXING : { Indexing *x = (Indexing *)expr.ptr(); PValuePtr indexable = partialEval(x->expr, env); if ((indexable->type == compilerObjectType) && indexable->isStatic) { ObjectPtr indexable2 = lower(evaluateToStatic(x->expr, env)); ArgListPtr args = new ArgList(x->args, env); return codegenIndexing(indexable2, args, outPtr); } error("invalid indexing operation"); return NULL; } case CALL : { Call *x = (Call *)expr.ptr(); PValuePtr callable = partialEval(x->expr, env); if ((callable->type == compilerObjectType) && callable->isStatic) { ObjectPtr callable2 = lower(evaluateToStatic(x->expr, env)); ArgListPtr args = new ArgList(x->args, env); return codegenInvoke(callable2, args, outPtr); } error("invalid call operation"); return NULL; } case FIELD_REF : { FieldRef *x = (FieldRef *)expr.ptr(); ValuePtr name = coToValue(x->name.ptr()); vector<ExprPtr> args; args.push_back(x->expr); args.push_back(new ValueExpr(name)); ObjectPtr prim = primName("recordFieldRefByName"); return codegenInvoke(prim, new ArgList(args, env), outPtr); } case TUPLE_REF : { TupleRef *x = (TupleRef *)expr.ptr(); ValuePtr index = intToValue(x->index); vector<ExprPtr> args; args.push_back(x->expr); args.push_back(new ValueExpr(index)); ObjectPtr prim = primName("tupleRef"); return codegenInvoke(prim, new ArgList(args, env), outPtr); } case UNARY_OP : { UnaryOp *x = (UnaryOp *)expr.ptr(); if (!x->converted) x->converted = convertUnaryOp(x); return codegen(x->converted, env, outPtr); } case BINARY_OP : { BinaryOp *x = (BinaryOp *)expr.ptr(); if (!x->converted) x->converted = convertBinaryOp(x); return codegen(x->converted, env, outPtr); } case AND : { And *x = (And *)expr.ptr(); PValuePtr pv1 = partialEval(x->expr1, env); PValuePtr pv2 = partialEval(x->expr2, env); if (pv1->type != pv2->type) error("type mismatch in 'and' expression"); if (pv1->isTemp || pv2->isTemp) { // codegenTemp(expr1, env, outPtr); // llvm::Value *tempBool = codegenAllocValue(boolType); // codegenInvoke(boolTruth, [outPtr], tempBool) // codegen(if !tempBool goto end) // codegenValueDestroy(outPtr); // codegenTemp(expr2, env, outPtr); // codegen(goto end) // return outPtr } else { // result = codegenRef(expr1, env); // tempBool = alloc bool value // codegenInvoke(boolTruth, [result], tempBool) // codegen(if !tempBool goto end) // result = codegenRef(expr2, env); // codegen(goto end) // return result } if (pv1->type != boolType) error("expecting bool type in 'and' expression"); } default : assert(false); } return NULL; } // // codegenIndexing // llvm::Value * codegenIndexing(ObjectPtr obj, ArgListPtr args, llvm::Value *outPtr) { } // // codegenInvoke // llvm::Value * codegenInvoke(ObjectPtr obj, ArgListPtr args, llvm::Value *outPtr) { } // // codegenValue // void codegenValue(ValuePtr v, llvm::Value *outPtr) { switch (v->type->typeKind) { case BOOL_TYPE : { const llvm::Type *llt = llvmType(v->type); int bv = valueToBool(v) ? 1 : 0; llvm::Value *llv = llvm::ConstantInt::get(llt, bv); builder->CreateStore(llv, outPtr); break; } case INTEGER_TYPE : case FLOAT_TYPE : { llvm::Value *llv = numericConstant(v); builder->CreateStore(llv, outPtr); break; } case COMPILER_OBJECT_TYPE : { const llvm::Type *llt = llvmType(v->type); int i = *((int *)v->buf); llvm::Value *llv = llvm::ConstantInt::get(llt, i); builder->CreateStore(llv, outPtr); break; } default : assert(false); } } // // numericConstant // template <typename T> llvm::Value * _sintConstant(ValuePtr v) { return llvm::ConstantInt::getSigned(llvmType(v->type), *((T *)v->buf)); } template <typename T> llvm::Value * _uintConstant(ValuePtr v) { return llvm::ConstantInt::get(llvmType(v->type), *((T *)v->buf)); } static llvm::Value * numericConstant(ValuePtr v) { llvm::Value *val = NULL; switch (v->type->typeKind) { case INTEGER_TYPE : { IntegerType *t = (IntegerType *)v->type.ptr(); if (t->isSigned) { switch (t->bits) { case 8 : val = _sintConstant<char>(v); break; case 16 : val = _sintConstant<short>(v); break; case 32 : val = _sintConstant<long>(v); break; case 64 : val = _sintConstant<long long>(v); break; default : assert(false); } } else { switch (t->bits) { case 8 : val = _uintConstant<unsigned char>(v); break; case 16 : val = _uintConstant<unsigned short>(v); break; case 32 : val = _uintConstant<unsigned long>(v); break; case 64 : val = _uintConstant<unsigned long long>(v); break; default : assert(false); } } } case FLOAT_TYPE : { FloatType *t = (FloatType *)v->type.ptr(); switch (t->bits) { case 32 : val = llvm::ConstantFP::get(llvmType(t), *((float *)v->buf)); break; case 64 : val = llvm::ConstantFP::get(llvmType(t), *((double *)v->buf)); break; default : assert(false); } } default : assert(false); } return val; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 - 2022 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information * * SPDX-License-Identifier: MIT */ #include <stdbool.h> #include <stdio.h> #include <string.h> #include <onyx/bootmem.h> #include <onyx/page.h> #include <onyx/paging.h> #include <onyx/panic.h> #include <onyx/serial.h> #define DEFAULT_NR_MEMORY_RANGES 128 struct memory_range { unsigned long start; size_t size; }; memory_range phys_ranges[DEFAULT_NR_MEMORY_RANGES]; unsigned int nr_phys_ranges = 0; memory_range resv_ranges[DEFAULT_NR_MEMORY_RANGES]; unsigned int nr_resv_ranges = 0; void for_every_phys_region(void (*callback)(unsigned long start, size_t size)) { for (unsigned int i = 0; i < nr_phys_ranges; i++) callback(phys_ranges[i].start, phys_ranges[i].size); } void __bootmem_add_range(unsigned long start, size_t size) { if (nr_phys_ranges == DEFAULT_NR_MEMORY_RANGES) { panic("Out of space for memory range [%016lx, %016lx]", start, start + size - 1); } phys_ranges[nr_phys_ranges++] = memory_range{start, size}; } void bootmem_re_reserve_memory(); void bootmem_add_range(unsigned long start, size_t size) { __bootmem_add_range(start, size); // We need to run this because we might already have memory reservations registered bootmem_re_reserve_memory(); } void bootmem_remove_range(unsigned int index) { auto tail_ranges = nr_phys_ranges - index - 1; memcpy(&phys_ranges[index], &phys_ranges[index + 1], tail_ranges * sizeof(phys_ranges)); nr_phys_ranges--; } static void bootmem_add_reserve(unsigned long start, size_t size) { if (nr_resv_ranges == DEFAULT_NR_MEMORY_RANGES) { panic("Out of space for reserved memory range [%016lx, %016lx]", start, start + size - 1); } printf("bootmem: Added reserved memory range [%016lx, %016lx]\n", start, start + size - 1); resv_ranges[nr_resv_ranges++] = memory_range{start, size}; } static void bootmem_reserve_memory_ranges(unsigned long start, size_t size) { for (unsigned int i = 0; i < nr_phys_ranges; i++) { auto &range = phys_ranges[i]; bool overlaps = check_for_overlap(start, start + size - 1, range.start, range.start + range.size - 1); if (!overlaps) { continue; } if (range.start >= start) { unsigned long offset = range.start - start; const auto tail_size = (size - offset) > range.size ? 0 : range.size - (size - offset); if (!tail_size) { // If we end up not having a tail, remove the range altogether bootmem_remove_range(i); } else { // Trim the start of the range range.size = tail_size; range.start = range.start + (size - offset); } } else if (range.start < start) { unsigned long offset = start - range.start; unsigned long remainder = range.size - offset; auto to_shave_off = size < remainder ? size : remainder; if (to_shave_off == range.size) { range.size -= to_shave_off; } else { unsigned long second_region_start = start + to_shave_off; unsigned long second_region_size = remainder - to_shave_off; range.size = offset; __bootmem_add_range(second_region_start, second_region_size); } } } } /** * @brief Run the reservation code on all the memory that has been registered * */ void bootmem_re_reserve_memory() { for (unsigned int i = 0; i < nr_resv_ranges; i++) { bootmem_reserve_memory_ranges(resv_ranges[i].start, resv_ranges[i].size); } } void bootmem_reserve(unsigned long start, size_t size) { // Reservations align downwards on the start and upwards on the size start &= -PAGE_SIZE; size = (size_t) page_align_up((void *) size); bootmem_add_reserve(start, size); bootmem_reserve_memory_ranges(start, size); } void *alloc_boot_page(size_t nr_pages, long flags) { size_t size = nr_pages << PAGE_SHIFT; for (unsigned int i = 0; i < nr_phys_ranges; i++) { auto &ranges = phys_ranges[i]; if (ranges.size >= size) { auto ret = (void *) ranges.start; ranges.start += size; ranges.size -= size; if (!ranges.size) { // Clean up if we allocated the whole range bootmem_remove_range(i); } #ifdef CONFIG_BOOTMEM_DEBUG printf("alloc_boot_page: Allocated [%016lx, %016lx]\n", (unsigned long) ret, (unsigned long) ret + size); #endif return ret; } } panic("alloc_boot_page of %lu pages failed", nr_pages); } <commit_msg>bootmem: Fix bug in bootmem_remove_range<commit_after>/* * Copyright (c) 2016 - 2022 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information * * SPDX-License-Identifier: MIT */ #include <stdbool.h> #include <stdio.h> #include <string.h> #include <onyx/bootmem.h> #include <onyx/page.h> #include <onyx/paging.h> #include <onyx/panic.h> #include <onyx/serial.h> #define DEFAULT_NR_MEMORY_RANGES 128 struct memory_range { unsigned long start; size_t size; }; memory_range phys_ranges[DEFAULT_NR_MEMORY_RANGES]; unsigned int nr_phys_ranges = 0; memory_range resv_ranges[DEFAULT_NR_MEMORY_RANGES]; unsigned int nr_resv_ranges = 0; void for_every_phys_region(void (*callback)(unsigned long start, size_t size)) { for (unsigned int i = 0; i < nr_phys_ranges; i++) callback(phys_ranges[i].start, phys_ranges[i].size); } void __bootmem_add_range(unsigned long start, size_t size) { if (nr_phys_ranges == DEFAULT_NR_MEMORY_RANGES) { panic("Out of space for memory range [%016lx, %016lx]", start, start + size - 1); } phys_ranges[nr_phys_ranges++] = memory_range{start, size}; } void bootmem_re_reserve_memory(); void bootmem_add_range(unsigned long start, size_t size) { __bootmem_add_range(start, size); // We need to run this because we might already have memory reservations registered bootmem_re_reserve_memory(); } void bootmem_remove_range(unsigned int index) { auto tail_ranges = nr_phys_ranges - index - 1; memcpy(&phys_ranges[index], &phys_ranges[index + 1], tail_ranges * sizeof(memory_range)); nr_phys_ranges--; } static void bootmem_add_reserve(unsigned long start, size_t size) { if (nr_resv_ranges == DEFAULT_NR_MEMORY_RANGES) { panic("Out of space for reserved memory range [%016lx, %016lx]", start, start + size - 1); } printf("bootmem: Added reserved memory range [%016lx, %016lx]\n", start, start + size - 1); resv_ranges[nr_resv_ranges++] = memory_range{start, size}; } static void bootmem_reserve_memory_ranges(unsigned long start, size_t size) { for (unsigned int i = 0; i < nr_phys_ranges; i++) { auto &range = phys_ranges[i]; bool overlaps = check_for_overlap(start, start + size - 1, range.start, range.start + range.size - 1); if (!overlaps) { continue; } if (range.start >= start) { unsigned long offset = range.start - start; const auto tail_size = (size - offset) > range.size ? 0 : range.size - (size - offset); if (!tail_size) { // If we end up not having a tail, remove the range altogether bootmem_remove_range(i); } else { // Trim the start of the range range.size = tail_size; range.start = range.start + (size - offset); } } else if (range.start < start) { unsigned long offset = start - range.start; unsigned long remainder = range.size - offset; auto to_shave_off = size < remainder ? size : remainder; if (to_shave_off == range.size) { range.size -= to_shave_off; } else { unsigned long second_region_start = start + to_shave_off; unsigned long second_region_size = remainder - to_shave_off; range.size = offset; __bootmem_add_range(second_region_start, second_region_size); } } } } /** * @brief Run the reservation code on all the memory that has been registered * */ void bootmem_re_reserve_memory() { for (unsigned int i = 0; i < nr_resv_ranges; i++) { bootmem_reserve_memory_ranges(resv_ranges[i].start, resv_ranges[i].size); } } void bootmem_reserve(unsigned long start, size_t size) { // Reservations align downwards on the start and upwards on the size start &= -PAGE_SIZE; size = (size_t) page_align_up((void *) size); bootmem_add_reserve(start, size); bootmem_reserve_memory_ranges(start, size); } void *alloc_boot_page(size_t nr_pages, long flags) { size_t size = nr_pages << PAGE_SHIFT; for (unsigned int i = 0; i < nr_phys_ranges; i++) { auto &ranges = phys_ranges[i]; if (ranges.size >= size) { auto ret = (void *) ranges.start; ranges.start += size; ranges.size -= size; if (!ranges.size) { // Clean up if we allocated the whole range bootmem_remove_range(i); } #ifdef CONFIG_BOOTMEM_DEBUG printf("alloc_boot_page: Allocated [%016lx, %016lx]\n", (unsigned long) ret, (unsigned long) ret + size); #endif return ret; } } panic("alloc_boot_page of %lu pages failed", nr_pages); } <|endoftext|>
<commit_before><commit_msg>Remove unnecessary SubsetterContext base class<commit_after><|endoftext|>
<commit_before>/* -*- c++ -*- subscriptiondialog.cpp This file is part of KMail, the KDE mail client. Copyright (C) 2002 Carsten Burghardt <burghardt@kde.org> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "subscriptiondialog.h" #include "kmmessage.h" #include "folderstorage.h" #include "listjob.h" #include <klocale.h> #include <kdebug.h> namespace KMail { SubscriptionDialog::SubscriptionDialog( QWidget *parent, const QString &caption, KAccount *acct, QString startPath ) : KSubscription( parent, caption, acct, User1, QString::null, false ), mStartPath( startPath ), mSubscribed( false ) { // hide unneeded checkboxes hideTreeCheckbox(); hideNewOnlyCheckbox(); // ok-button connect(this, SIGNAL(okClicked()), SLOT(slotSave())); // reload-list button connect(this, SIGNAL(user1Clicked()), SLOT(slotLoadFolders())); // get the folders slotLoadFolders(); } //------------------------------------------------------------------------------ void SubscriptionDialog::slotListDirectory( const QStringList& subfolderNames, const QStringList& subfolderPaths, const QStringList& subfolderMimeTypes, const QStringList& subfolderAttributes, const ImapAccountBase::jobData& jobData ) { mFolderNames = subfolderNames; mFolderPaths = subfolderPaths; mFolderMimeTypes = subfolderMimeTypes; mFolderAttributes = subfolderAttributes; mJobData = jobData; mCount = 0; createItems(); } //------------------------------------------------------------------------------ void SubscriptionDialog::createItems() { bool onlySubscribed = mJobData.onlySubscribed; GroupItem *parent = 0; uint done = 0; // kdDebug(5006) << "createItems subscribed=" << onlySubscribed <<",folders=" // << mFolderNames.join(",") << endl; for (uint i = mCount; i < mFolderNames.count(); ++i) { // give the dialog a chance to repaint if (done == 1000) { emit listChanged(); QTimer::singleShot(0, this, SLOT(createItems())); return; } ++mCount; ++done; GroupItem *item = 0; if (!onlySubscribed && mFolderPaths.size() > 0) { // get the parent GroupItem *oldItem = 0; QString parentPath; findParentItem( mFolderNames[i], mFolderPaths[i], parentPath, &parent, &oldItem ); if (!parent && parentPath != "/") { // the parent is not available and it's no root-item // this happens when the folders do not arrive in hierarchical order // so we create each parent in advance QStringList folders = QStringList::split(mDelimiter, parentPath); uint i = 0; for ( QStringList::Iterator it = folders.begin(); it != folders.end(); ++it ) { QString name = *it; if (name.startsWith("/")) name = name.right(name.length()-1); if (name.endsWith("/")) name.truncate(name.length()-1); KGroupInfo info(name); info.subscribed = false; QStringList tmpPath; for ( uint j = 0; j <= i; ++j ) tmpPath << folders[j]; QString path = tmpPath.join(mDelimiter); if (!path.startsWith("/")) path = "/" + path; if (!path.endsWith("/")) path = path + "/"; info.path = path; item = 0; if (folders.count() > 1) { // we have to create more then one level, so better check if this // folder already exists somewhere item = mItemDict[path]; } // as these items are "dummies" we create them non-checkable if (!item) { if (parent) item = new GroupItem(parent, info, this, false); else item = new GroupItem(folderTree(), info, this, false); mItemDict.insert(info.path, item); } parent = item; ++i; } // folders } // parent KGroupInfo info(mFolderNames[i]); info.path = mFolderPaths[i]; if ( info.path == "/INBOX/" ) info.name = i18n("inbox"); // only checkable when the folder is selectable bool checkable = ( mFolderMimeTypes[i] == "inode/directory" ) ? false : true; // create a new item if (parent) item = new GroupItem(parent, info, this, checkable); else item = new GroupItem(folderTree(), info, this, checkable); if (oldItem) // remove old item mItemDict.remove(info.path); mItemDict.insert(info.path, item); if (oldItem) { // move the old childs to the new item QPtrList<QListViewItem> itemsToMove; QListViewItem * myChild = oldItem->firstChild(); while (myChild) { itemsToMove.append(myChild); myChild = myChild->nextSibling(); } QPtrListIterator<QListViewItem> it( itemsToMove ); QListViewItem *cur; while ((cur = it.current())) { oldItem->takeItem(cur); item->insertItem(cur); if ( cur->isSelected() ) // we have new parents so open them folderTree()->ensureItemVisible( cur ); ++it; } delete oldItem; itemsToMove.clear(); } // select the start item if ( mFolderPaths[i] == mStartPath ) { item->setSelected( true ); folderTree()->ensureItemVisible( item ); } } else if (onlySubscribed) { // find the item if ( mItemDict[mFolderPaths[i]] ) { GroupItem* item = mItemDict[mFolderPaths[i]]; item->setOn( true ); } } } processNext(); } //------------------------------------------------------------------------------ void SubscriptionDialog::findParentItem( QString &name, QString &path, QString &parentPath, GroupItem **parent, GroupItem **oldItem ) { // remove the name (and the separator) from the path to get the parent path int start = path.length() - (name.length()+2); int length = name.length()+1; if (start < 0) start = 0; parentPath = path; parentPath.remove(start, length); // find the parent by it's path *parent = mItemDict[parentPath]; // check if the item already exists *oldItem = mItemDict[path]; } //------------------------------------------------------------------------------ void SubscriptionDialog::slotSave() { // subscribe QListViewItemIterator it(subView); for ( ; it.current(); ++it) { static_cast<ImapAccountBase*>(account())->changeSubscription(true, static_cast<GroupItem*>(it.current())->info().path); } // unsubscribe QListViewItemIterator it2(unsubView); for ( ; it2.current(); ++it2) { static_cast<ImapAccountBase*>(account())->changeSubscription(false, static_cast<GroupItem*>(it2.current())->info().path); } } //------------------------------------------------------------------------------ void SubscriptionDialog::slotLoadFolders() { // clear the views KSubscription::slotLoadFolders(); mItemDict.clear(); ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); // we need a connection if ( ai->makeConnection() == ImapAccountBase::Error ) { kdWarning(5006) << "SubscriptionDialog - got no connection" << endl; return; } else if ( ai->makeConnection() == ImapAccountBase::Connecting ) { // We'll wait for the connectionResult signal from the account. kdDebug(5006) << "SubscriptionDialog - waiting for connection" << endl; connect( ai, SIGNAL( connectionResult(int, const QString&) ), this, SLOT( slotConnectionResult(int, const QString&) ) ); return; } initPrefixList(); processNext(); } //------------------------------------------------------------------------------ void SubscriptionDialog::processNext() { if ( mPrefixList.empty() ) { if ( !mSubscribed ) { mSubscribed = true; initPrefixList(); } else { slotLoadingComplete(); return; } } ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); ImapAccountBase::ListType type = ( mSubscribed ? ImapAccountBase::ListSubscribedNoCheck : ImapAccountBase::List ); bool completeListing = true; mCurrentNamespace = mPrefixList.first(); mDelimiter = ai->delimiterForNamespace( mCurrentNamespace ); mPrefixList.pop_front(); if ( mCurrentNamespace == "/INBOX/" ) { type = mSubscribed ? ImapAccountBase::ListFolderOnlySubscribed : ImapAccountBase::ListFolderOnly; completeListing = false; } // kdDebug(5006) << "process " << mCurrentNamespace << ",subscribed=" << mSubscribed << endl; ListJob* job = new ListJob( ai, type, 0, ai->addPathToNamespace( mCurrentNamespace ), completeListing ); connect( job, SIGNAL(receivedFolders(const QStringList&, const QStringList&, const QStringList&, const QStringList&, const ImapAccountBase::jobData&)), this, SLOT(slotListDirectory(const QStringList&, const QStringList&, const QStringList&, const QStringList&, const ImapAccountBase::jobData&))); job->start(); } //------------------------------------------------------------------------------ void SubscriptionDialog::initPrefixList() { ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); ImapAccountBase::nsMap map = ai->namespaces(); mPrefixList.clear(); bool hasInbox = false; const QStringList ns = map[ImapAccountBase::PersonalNS]; for ( QStringList::ConstIterator it = ns.begin(); it != ns.end(); ++it ) { if ( (*it).isEmpty() ) hasInbox = true; } if ( !hasInbox && !ns.isEmpty() ) { // the namespaces includes no listing for the root so start a special // listing for the INBOX to make sure we get it mPrefixList += "/INBOX/"; } mPrefixList += map[ImapAccountBase::PersonalNS]; mPrefixList += map[ImapAccountBase::OtherUsersNS]; mPrefixList += map[ImapAccountBase::SharedNS]; } void SubscriptionDialog::slotConnectionResult( int errorCode, const QString& errorMsg ) { Q_UNUSED( errorMsg ); if ( !errorCode ) slotLoadFolders(); } } // namespace #include "subscriptiondialog.moc" <commit_msg>Reset all vars when a new listing is started. Good catch, thanks for the report. BUGS:105979<commit_after>/* -*- c++ -*- subscriptiondialog.cpp This file is part of KMail, the KDE mail client. Copyright (C) 2002 Carsten Burghardt <burghardt@kde.org> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "subscriptiondialog.h" #include "kmmessage.h" #include "folderstorage.h" #include "listjob.h" #include <klocale.h> #include <kdebug.h> namespace KMail { SubscriptionDialog::SubscriptionDialog( QWidget *parent, const QString &caption, KAccount *acct, QString startPath ) : KSubscription( parent, caption, acct, User1, QString::null, false ), mStartPath( startPath ), mSubscribed( false ) { // hide unneeded checkboxes hideTreeCheckbox(); hideNewOnlyCheckbox(); // ok-button connect(this, SIGNAL(okClicked()), SLOT(slotSave())); // reload-list button connect(this, SIGNAL(user1Clicked()), SLOT(slotLoadFolders())); // get the folders slotLoadFolders(); } //------------------------------------------------------------------------------ void SubscriptionDialog::slotListDirectory( const QStringList& subfolderNames, const QStringList& subfolderPaths, const QStringList& subfolderMimeTypes, const QStringList& subfolderAttributes, const ImapAccountBase::jobData& jobData ) { mFolderNames = subfolderNames; mFolderPaths = subfolderPaths; mFolderMimeTypes = subfolderMimeTypes; mFolderAttributes = subfolderAttributes; mJobData = jobData; mCount = 0; createItems(); } //------------------------------------------------------------------------------ void SubscriptionDialog::createItems() { bool onlySubscribed = mJobData.onlySubscribed; GroupItem *parent = 0; uint done = 0; // kdDebug(5006) << "createItems subscribed=" << onlySubscribed <<",folders=" // << mFolderNames.join(",") << endl; for (uint i = mCount; i < mFolderNames.count(); ++i) { // give the dialog a chance to repaint if (done == 1000) { emit listChanged(); QTimer::singleShot(0, this, SLOT(createItems())); return; } ++mCount; ++done; GroupItem *item = 0; if (!onlySubscribed && mFolderPaths.size() > 0) { // get the parent GroupItem *oldItem = 0; QString parentPath; findParentItem( mFolderNames[i], mFolderPaths[i], parentPath, &parent, &oldItem ); if (!parent && parentPath != "/") { // the parent is not available and it's no root-item // this happens when the folders do not arrive in hierarchical order // so we create each parent in advance QStringList folders = QStringList::split(mDelimiter, parentPath); uint i = 0; for ( QStringList::Iterator it = folders.begin(); it != folders.end(); ++it ) { QString name = *it; if (name.startsWith("/")) name = name.right(name.length()-1); if (name.endsWith("/")) name.truncate(name.length()-1); KGroupInfo info(name); info.subscribed = false; QStringList tmpPath; for ( uint j = 0; j <= i; ++j ) tmpPath << folders[j]; QString path = tmpPath.join(mDelimiter); if (!path.startsWith("/")) path = "/" + path; if (!path.endsWith("/")) path = path + "/"; info.path = path; item = 0; if (folders.count() > 1) { // we have to create more then one level, so better check if this // folder already exists somewhere item = mItemDict[path]; } // as these items are "dummies" we create them non-checkable if (!item) { if (parent) item = new GroupItem(parent, info, this, false); else item = new GroupItem(folderTree(), info, this, false); mItemDict.insert(info.path, item); } parent = item; ++i; } // folders } // parent KGroupInfo info(mFolderNames[i]); info.path = mFolderPaths[i]; if ( info.path == "/INBOX/" ) info.name = i18n("inbox"); // only checkable when the folder is selectable bool checkable = ( mFolderMimeTypes[i] == "inode/directory" ) ? false : true; // create a new item if (parent) item = new GroupItem(parent, info, this, checkable); else item = new GroupItem(folderTree(), info, this, checkable); if (oldItem) // remove old item mItemDict.remove(info.path); mItemDict.insert(info.path, item); if (oldItem) { // move the old childs to the new item QPtrList<QListViewItem> itemsToMove; QListViewItem * myChild = oldItem->firstChild(); while (myChild) { itemsToMove.append(myChild); myChild = myChild->nextSibling(); } QPtrListIterator<QListViewItem> it( itemsToMove ); QListViewItem *cur; while ((cur = it.current())) { oldItem->takeItem(cur); item->insertItem(cur); if ( cur->isSelected() ) // we have new parents so open them folderTree()->ensureItemVisible( cur ); ++it; } delete oldItem; itemsToMove.clear(); } // select the start item if ( mFolderPaths[i] == mStartPath ) { item->setSelected( true ); folderTree()->ensureItemVisible( item ); } } else if (onlySubscribed) { // find the item if ( mItemDict[mFolderPaths[i]] ) { GroupItem* item = mItemDict[mFolderPaths[i]]; item->setOn( true ); } } } processNext(); } //------------------------------------------------------------------------------ void SubscriptionDialog::findParentItem( QString &name, QString &path, QString &parentPath, GroupItem **parent, GroupItem **oldItem ) { // remove the name (and the separator) from the path to get the parent path int start = path.length() - (name.length()+2); int length = name.length()+1; if (start < 0) start = 0; parentPath = path; parentPath.remove(start, length); // find the parent by it's path *parent = mItemDict[parentPath]; // check if the item already exists *oldItem = mItemDict[path]; } //------------------------------------------------------------------------------ void SubscriptionDialog::slotSave() { // subscribe QListViewItemIterator it(subView); for ( ; it.current(); ++it) { static_cast<ImapAccountBase*>(account())->changeSubscription(true, static_cast<GroupItem*>(it.current())->info().path); } // unsubscribe QListViewItemIterator it2(unsubView); for ( ; it2.current(); ++it2) { static_cast<ImapAccountBase*>(account())->changeSubscription(false, static_cast<GroupItem*>(it2.current())->info().path); } } //------------------------------------------------------------------------------ void SubscriptionDialog::slotLoadFolders() { ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); // we need a connection if ( ai->makeConnection() == ImapAccountBase::Error ) { kdWarning(5006) << "SubscriptionDialog - got no connection" << endl; return; } else if ( ai->makeConnection() == ImapAccountBase::Connecting ) { // We'll wait for the connectionResult signal from the account. kdDebug(5006) << "SubscriptionDialog - waiting for connection" << endl; connect( ai, SIGNAL( connectionResult(int, const QString&) ), this, SLOT( slotConnectionResult(int, const QString&) ) ); return; } // clear the views KSubscription::slotLoadFolders(); mItemDict.clear(); mSubscribed = false; mLoading = true; initPrefixList(); processNext(); } //------------------------------------------------------------------------------ void SubscriptionDialog::processNext() { if ( mPrefixList.isEmpty() ) { if ( !mSubscribed ) { mSubscribed = true; initPrefixList(); } else { slotLoadingComplete(); return; } } ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); ImapAccountBase::ListType type = ( mSubscribed ? ImapAccountBase::ListSubscribedNoCheck : ImapAccountBase::List ); bool completeListing = true; mCurrentNamespace = mPrefixList.first(); mDelimiter = ai->delimiterForNamespace( mCurrentNamespace ); mPrefixList.pop_front(); if ( mCurrentNamespace == "/INBOX/" ) { type = mSubscribed ? ImapAccountBase::ListFolderOnlySubscribed : ImapAccountBase::ListFolderOnly; completeListing = false; } // kdDebug(5006) << "process " << mCurrentNamespace << ",subscribed=" << mSubscribed << endl; ListJob* job = new ListJob( ai, type, 0, ai->addPathToNamespace( mCurrentNamespace ), completeListing ); connect( job, SIGNAL(receivedFolders(const QStringList&, const QStringList&, const QStringList&, const QStringList&, const ImapAccountBase::jobData&)), this, SLOT(slotListDirectory(const QStringList&, const QStringList&, const QStringList&, const QStringList&, const ImapAccountBase::jobData&))); job->start(); } //------------------------------------------------------------------------------ void SubscriptionDialog::initPrefixList() { ImapAccountBase* ai = static_cast<ImapAccountBase*>(account()); ImapAccountBase::nsMap map = ai->namespaces(); mPrefixList.clear(); bool hasInbox = false; const QStringList ns = map[ImapAccountBase::PersonalNS]; for ( QStringList::ConstIterator it = ns.begin(); it != ns.end(); ++it ) { if ( (*it).isEmpty() ) hasInbox = true; } if ( !hasInbox && !ns.isEmpty() ) { // the namespaces includes no listing for the root so start a special // listing for the INBOX to make sure we get it mPrefixList += "/INBOX/"; } mPrefixList += map[ImapAccountBase::PersonalNS]; mPrefixList += map[ImapAccountBase::OtherUsersNS]; mPrefixList += map[ImapAccountBase::SharedNS]; } void SubscriptionDialog::slotConnectionResult( int errorCode, const QString& errorMsg ) { Q_UNUSED( errorMsg ); if ( !errorCode ) slotLoadFolders(); } } // namespace #include "subscriptiondialog.moc" <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/io.hpp" #include <cstring> #include <boost/bind.hpp> #include <iostream> using namespace libtorrent; int read_message(stream_socket& s, char* buffer) { using namespace libtorrent::detail; error_code ec; libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 4) , libtorrent::asio::transfer_all(), ec); if (ec) { std::cout << time_now_string() << ": " << ec.message() << std::endl; exit(1); } char* ptr = buffer; int length = read_int32(ptr); libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, length) , libtorrent::asio::transfer_all(), ec); if (ec) { std::cout << time_now_string() << ": " << ec.message() << std::endl; exit(1); } return length; } void print_message(char const* buffer, int len) { char const* message_name[] = {"choke", "unchoke", "interested", "not_interested" , "have", "bitfield", "request", "piece", "cancel", "dht_port", "", "", "" , "suggest_piece", "have_all", "have_none", "reject_request", "allowed_fast"}; char message[50]; char extra[300]; extra[0] = 0; if (len == 0) { strcpy(message, "keepalive"); } else { int msg = buffer[0]; if (msg >= 0 && msg < int(sizeof(message_name)/sizeof(message_name[0]))) strcpy(message, message_name[msg]); else snprintf(message, sizeof(message), "unknown[%d]", msg); if (msg == 0x6 && len == 13) { peer_request r; const char* ptr = buffer + 1; r.piece = detail::read_int32(ptr); r.start = detail::read_int32(ptr); r.length = detail::read_int32(ptr); snprintf(extra, sizeof(extra), "p: %d s: %d l: %d", r.piece, r.start, r.length); } else if (msg == 0x11 && len == 5) { const char* ptr = buffer + 1; int index = detail::read_int32(ptr); snprintf(extra, sizeof(extra), "p: %d", index); } } fprintf(stderr, "%s <== %s %s\n", time_now_string(), message, extra); } void send_allow_fast(stream_socket& s, int piece) { std::cout << time_now_string() << " ==> allow fast: " << piece << std::endl; using namespace libtorrent::detail; char msg[] = "\0\0\0\x05\x11\0\0\0\0"; char* ptr = msg + 5; write_int32(piece, ptr); error_code ec; libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 9) , libtorrent::asio::transfer_all(), ec); } void send_suggest_piece(stream_socket& s, int piece) { std::cout << time_now_string() << " ==> suggest piece: " << piece << std::endl; using namespace libtorrent::detail; char msg[] = "\0\0\0\x05\x0d\0\0\0\0"; char* ptr = msg + 5; write_int32(piece, ptr); error_code ec; libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 9) , libtorrent::asio::transfer_all(), ec); } void send_keepalive(stream_socket& s) { std::cout << time_now_string() << " ==> keepalive" << std::endl; char msg[] = "\0\0\0\0"; error_code ec; libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 4) , libtorrent::asio::transfer_all(), ec); } void send_unchoke(stream_socket& s) { std::cout << time_now_string() << " ==> unchoke" << std::endl; char msg[] = "\0\0\0\x01\x01"; error_code ec; libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 5) , libtorrent::asio::transfer_all(), ec); } void do_handshake(stream_socket& s, sha1_hash const& ih, char* buffer) { char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04" " " // space for info-hash "aaaaaaaaaaaaaaaaaaaa" // peer-id "\0\0\0\x01\x0e"; // have_all std::cout << time_now_string() << " ==> handshake" << std::endl; std::cout << time_now_string() << " ==> have_all" << std::endl; error_code ec; std::memcpy(handshake + 28, ih.begin(), 20); libtorrent::asio::write(s, libtorrent::asio::buffer(handshake, sizeof(handshake) - 1) , libtorrent::asio::transfer_all(), ec); // read handshake libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 68) , libtorrent::asio::transfer_all(), ec); if (ec) { std::cout << time_now_string() << ": " << ec.message() << std::endl; exit(1); } std::cout << time_now_string() << " <== handshake" << std::endl; TEST_CHECK(buffer[0] == 19); TEST_CHECK(std::memcmp(buffer + 1, "BitTorrent protocol", 19) == 0); char* extensions = buffer + 20; // check for fast extension support TEST_CHECK(extensions[7] & 0x4); #ifndef TORRENT_DISABLE_EXTENSIONS // check for extension protocol support TEST_CHECK(extensions[5] & 0x10); #endif #ifndef TORRENT_DISABLE_DHT // check for DHT support TEST_CHECK(extensions[7] & 0x1); #endif TEST_CHECK(std::memcmp(buffer + 28, ih.begin(), 20) == 0); } // makes sure that pieces that are allowed and then // rejected aren't requested again void test_reject_fast() { std::cerr << " === test reject ===" << std::endl; boost::intrusive_ptr<torrent_info> t = ::create_torrent(); sha1_hash ih = t->info_hash(); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48900, 49000), "0.0.0.0", 0); error_code ec; add_torrent_params p; p.ti = t; p.save_path = "./tmp1_fast"; ses1.add_torrent(p, ec); test_sleep(2000); io_service ios; stream_socket s(ios); s.connect(tcp::endpoint(address::from_string("127.0.0.1", ec), ses1.listen_port()), ec); char recv_buffer[1000]; do_handshake(s, ih, recv_buffer); std::vector<int> allowed_fast; allowed_fast.push_back(0); allowed_fast.push_back(1); allowed_fast.push_back(2); allowed_fast.push_back(3); std::for_each(allowed_fast.begin(), allowed_fast.end() , boost::bind(&send_allow_fast, boost::ref(s), _1)); while (!allowed_fast.empty()) { int len = read_message(s, recv_buffer); print_message(recv_buffer, len); int msg = recv_buffer[0]; if (msg != 0x6) continue; using namespace libtorrent::detail; char* ptr = recv_buffer + 1; int piece = read_int32(ptr); std::vector<int>::iterator i = std::find(allowed_fast.begin() , allowed_fast.end(), piece); TEST_CHECK(i != allowed_fast.end()); if (i != allowed_fast.end()) allowed_fast.erase(i); // send reject request recv_buffer[0] = 0x10; error_code ec; std::cerr << time_now_string() << " ==> reject" << std::endl; libtorrent::asio::write(s, libtorrent::asio::buffer("\0\0\0\x0d", 4) , libtorrent::asio::transfer_all(), ec); libtorrent::asio::write(s, libtorrent::asio::buffer(recv_buffer, 13) , libtorrent::asio::transfer_all(), ec); } } void test_respect_suggest() { std::cerr << " === test suggest ===" << std::endl; boost::intrusive_ptr<torrent_info> t = ::create_torrent(); sha1_hash ih = t->info_hash(); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48900, 49000), "0.0.0.0", 0); error_code ec; add_torrent_params p; p.ti = t; p.save_path = "./tmp1_fast"; ses1.add_torrent(p, ec); test_sleep(2000); io_service ios; stream_socket s(ios); s.connect(tcp::endpoint(address::from_string("127.0.0.1", ec), ses1.listen_port()), ec); char recv_buffer[1000]; do_handshake(s, ih, recv_buffer); std::vector<int> suggested; suggested.push_back(0); suggested.push_back(1); suggested.push_back(2); suggested.push_back(3); std::for_each(suggested.begin(), suggested.end() , boost::bind(&send_suggest_piece, boost::ref(s), _1)); send_unchoke(s); send_keepalive(s); int fail_counter = 100; while (!suggested.empty() && fail_counter > 0) { int len = read_message(s, recv_buffer); print_message(recv_buffer, len); int msg = recv_buffer[0]; fail_counter--; if (msg != 0x6) continue; using namespace libtorrent::detail; char* ptr = recv_buffer + 1; int piece = read_int32(ptr); std::vector<int>::iterator i = std::find(suggested.begin() , suggested.end(), piece); TEST_CHECK(i != suggested.end()); if (i != suggested.end()) suggested.erase(i); // send reject request recv_buffer[0] = 0x10; error_code ec; std::cerr << time_now_string() << " ==> reject" << std::endl; libtorrent::asio::write(s, libtorrent::asio::buffer("\0\0\0\x0d", 4) , libtorrent::asio::transfer_all(), ec); libtorrent::asio::write(s, libtorrent::asio::buffer(recv_buffer, 13) , libtorrent::asio::transfer_all(), ec); } TEST_CHECK(fail_counter > 0); } int test_main() { test_reject_fast(); test_respect_suggest(); return 0; } <commit_msg>fix test_fast_extension<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/io.hpp" #include <cstring> #include <boost/bind.hpp> #include <iostream> using namespace libtorrent; int read_message(stream_socket& s, char* buffer) { using namespace libtorrent::detail; error_code ec; libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 4) , libtorrent::asio::transfer_all(), ec); if (ec) { std::cout << time_now_string() << ": " << ec.message() << std::endl; exit(1); } char* ptr = buffer; int length = read_int32(ptr); libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, length) , libtorrent::asio::transfer_all(), ec); if (ec) { std::cout << time_now_string() << ": " << ec.message() << std::endl; exit(1); } return length; } void print_message(char const* buffer, int len) { char const* message_name[] = {"choke", "unchoke", "interested", "not_interested" , "have", "bitfield", "request", "piece", "cancel", "dht_port", "", "", "" , "suggest_piece", "have_all", "have_none", "reject_request", "allowed_fast"}; char message[50]; char extra[300]; extra[0] = 0; if (len == 0) { strcpy(message, "keepalive"); } else { int msg = buffer[0]; if (msg >= 0 && msg < int(sizeof(message_name)/sizeof(message_name[0]))) strcpy(message, message_name[msg]); else snprintf(message, sizeof(message), "unknown[%d]", msg); if (msg == 0x6 && len == 13) { peer_request r; const char* ptr = buffer + 1; r.piece = detail::read_int32(ptr); r.start = detail::read_int32(ptr); r.length = detail::read_int32(ptr); snprintf(extra, sizeof(extra), "p: %d s: %d l: %d", r.piece, r.start, r.length); } else if (msg == 0x11 && len == 5) { const char* ptr = buffer + 1; int index = detail::read_int32(ptr); snprintf(extra, sizeof(extra), "p: %d", index); } } fprintf(stderr, "%s <== %s %s\n", time_now_string(), message, extra); } void send_allow_fast(stream_socket& s, int piece) { std::cout << time_now_string() << " ==> allow fast: " << piece << std::endl; using namespace libtorrent::detail; char msg[] = "\0\0\0\x05\x11\0\0\0\0"; char* ptr = msg + 5; write_int32(piece, ptr); error_code ec; libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 9) , libtorrent::asio::transfer_all(), ec); } void send_suggest_piece(stream_socket& s, int piece) { std::cout << time_now_string() << " ==> suggest piece: " << piece << std::endl; using namespace libtorrent::detail; char msg[] = "\0\0\0\x05\x0d\0\0\0\0"; char* ptr = msg + 5; write_int32(piece, ptr); error_code ec; libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 9) , libtorrent::asio::transfer_all(), ec); } void send_keepalive(stream_socket& s) { std::cout << time_now_string() << " ==> keepalive" << std::endl; char msg[] = "\0\0\0\0"; error_code ec; libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 4) , libtorrent::asio::transfer_all(), ec); } void send_unchoke(stream_socket& s) { std::cout << time_now_string() << " ==> unchoke" << std::endl; char msg[] = "\0\0\0\x01\x01"; error_code ec; libtorrent::asio::write(s, libtorrent::asio::buffer(msg, 5) , libtorrent::asio::transfer_all(), ec); } void do_handshake(stream_socket& s, sha1_hash const& ih, char* buffer) { char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04" " " // space for info-hash "aaaaaaaaaaaaaaaaaaaa" // peer-id "\0\0\0\x01\x0e"; // have_all std::cout << time_now_string() << " ==> handshake" << std::endl; std::cout << time_now_string() << " ==> have_all" << std::endl; error_code ec; std::memcpy(handshake + 28, ih.begin(), 20); libtorrent::asio::write(s, libtorrent::asio::buffer(handshake, sizeof(handshake) - 1) , libtorrent::asio::transfer_all(), ec); // read handshake libtorrent::asio::read(s, libtorrent::asio::buffer(buffer, 68) , libtorrent::asio::transfer_all(), ec); if (ec) { std::cout << time_now_string() << ": " << ec.message() << std::endl; exit(1); } std::cout << time_now_string() << " <== handshake" << std::endl; TEST_CHECK(buffer[0] == 19); TEST_CHECK(std::memcmp(buffer + 1, "BitTorrent protocol", 19) == 0); char* extensions = buffer + 20; // check for fast extension support TEST_CHECK(extensions[7] & 0x4); #ifndef TORRENT_DISABLE_EXTENSIONS // check for extension protocol support TEST_CHECK(extensions[5] & 0x10); #endif #ifndef TORRENT_DISABLE_DHT // check for DHT support TEST_CHECK(extensions[7] & 0x1); #endif TEST_CHECK(std::memcmp(buffer + 28, ih.begin(), 20) == 0); } // makes sure that pieces that are allowed and then // rejected aren't requested again void test_reject_fast() { std::cerr << " === test reject ===" << std::endl; boost::intrusive_ptr<torrent_info> t = ::create_torrent(); sha1_hash ih = t->info_hash(); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48900, 49000), "0.0.0.0", 0); error_code ec; add_torrent_params p; p.ti = t; p.save_path = "./tmp1_fast"; remove("./tmp1_fast/temporary", ec); if (ec) fprintf(stderr, "remove(): %s\n", ec.message().c_str()); ec.clear(); ses1.add_torrent(p, ec); test_sleep(2000); io_service ios; stream_socket s(ios); s.connect(tcp::endpoint(address::from_string("127.0.0.1", ec), ses1.listen_port()), ec); char recv_buffer[1000]; do_handshake(s, ih, recv_buffer); std::vector<int> allowed_fast; allowed_fast.push_back(0); allowed_fast.push_back(1); allowed_fast.push_back(2); allowed_fast.push_back(3); std::for_each(allowed_fast.begin(), allowed_fast.end() , boost::bind(&send_allow_fast, boost::ref(s), _1)); while (!allowed_fast.empty()) { int len = read_message(s, recv_buffer); print_message(recv_buffer, len); int msg = recv_buffer[0]; if (msg != 0x6) continue; using namespace libtorrent::detail; char* ptr = recv_buffer + 1; int piece = read_int32(ptr); std::vector<int>::iterator i = std::find(allowed_fast.begin() , allowed_fast.end(), piece); TEST_CHECK(i != allowed_fast.end()); if (i != allowed_fast.end()) allowed_fast.erase(i); // send reject request recv_buffer[0] = 0x10; error_code ec; std::cerr << time_now_string() << " ==> reject" << std::endl; libtorrent::asio::write(s, libtorrent::asio::buffer("\0\0\0\x0d", 4) , libtorrent::asio::transfer_all(), ec); libtorrent::asio::write(s, libtorrent::asio::buffer(recv_buffer, 13) , libtorrent::asio::transfer_all(), ec); } } void test_respect_suggest() { std::cerr << " === test suggest ===" << std::endl; boost::intrusive_ptr<torrent_info> t = ::create_torrent(); sha1_hash ih = t->info_hash(); session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48900, 49000), "0.0.0.0", 0); error_code ec; add_torrent_params p; p.ti = t; p.save_path = "./tmp1_fast"; remove("./tmp1_fast/temporary", ec); if (ec) fprintf(stderr, "remove(): %s\n", ec.message().c_str()); ec.clear(); ses1.add_torrent(p, ec); test_sleep(2000); io_service ios; stream_socket s(ios); s.connect(tcp::endpoint(address::from_string("127.0.0.1", ec), ses1.listen_port()), ec); char recv_buffer[1000]; do_handshake(s, ih, recv_buffer); std::vector<int> suggested; suggested.push_back(0); suggested.push_back(1); suggested.push_back(2); suggested.push_back(3); std::for_each(suggested.begin(), suggested.end() , boost::bind(&send_suggest_piece, boost::ref(s), _1)); send_unchoke(s); send_keepalive(s); int fail_counter = 100; while (!suggested.empty() && fail_counter > 0) { int len = read_message(s, recv_buffer); print_message(recv_buffer, len); int msg = recv_buffer[0]; fail_counter--; if (msg != 0x6) continue; using namespace libtorrent::detail; char* ptr = recv_buffer + 1; int piece = read_int32(ptr); std::vector<int>::iterator i = std::find(suggested.begin() , suggested.end(), piece); TEST_CHECK(i != suggested.end()); if (i != suggested.end()) suggested.erase(i); // send reject request recv_buffer[0] = 0x10; error_code ec; std::cerr << time_now_string() << " ==> reject" << std::endl; libtorrent::asio::write(s, libtorrent::asio::buffer("\0\0\0\x0d", 4) , libtorrent::asio::transfer_all(), ec); libtorrent::asio::write(s, libtorrent::asio::buffer(recv_buffer, 13) , libtorrent::asio::transfer_all(), ec); } TEST_CHECK(fail_counter > 0); } int test_main() { test_reject_fast(); test_respect_suggest(); return 0; } <|endoftext|>
<commit_before> #include <cstdio> #include <string> #include <iostream> #include <array> #include <vector> #include <unistd.h> #include <lo/lo.h> #include <lo/lo_cpp.h> int test1(const char *path, const char *types, lo_arg **argv, int argc, lo_message m, void *data) { printf("path: %s\n", path); printf("types: %s\n", types); printf("i: %d\n", argv[0]->i); return 0; } int test2(lo_arg **argv, int argc) { printf("in test2: %d\n", argv[0]->i); return 0; } int test3(lo_arg **argv, int argc, lo_message msg) { printf("in test3\n"); return 0; } void init(lo::Server &s) { int j = 234; std::cout << "URL: " << s.url() << std::endl; class test3 { public: test3(int j, std::string s) : _s(s), _j(j) {}; int operator () (lo_arg **argv, int argc, lo_message msg) { std::cout << _s << ": " << _j << ", " << argv[0]->i << std::endl; return 0; } private: std::string _s; int _j; }; s.add_method("test0", "i", test3(j,"test0")); s.del_method("test0", "i"); s.add_method("test1", "i", test1, 0); s.add_method("test2", "i", test2); s.add_method("test3", "i", test3(j, "test3")); s.add_method("test4", "i", [j](lo_arg **argv, int argc) { printf("test4: %d, %d\n", j, argv[0]->i); return 0; }); j *= 2; s.add_method("test5", "i", [j](lo_arg **argv, int argc, lo_message msg) { printf("test5: %d, %d -- ", j, argv[0]->i); lo_message_pp(msg); return 0; }); j *= 2; s.add_method("test6", "i", [j](lo_message msg) { printf("test6: %d -- ", j); lo_message_pp(msg); return 0; }); j *= 2; s.add_method("test7", "i", [j](){printf("test7: %d\n", j); return 0;}); j *= 2; s.add_method("test8", "i", [j](){printf("test8a: %d\n", j);}); j *= 2; s.add_method("test8", "i", [j](){printf("test8b: %d\n", j);}); j*=2; s.add_method("test9", "i", [j](const char *path, const char *types, lo_arg **argv, int argc) {printf("test9.1: %d, %s, %s, %d\n", j, path, types, argv[0]->i); return 1;}); j*=2; s.add_method("test10", "i", [j](const char *types, lo_arg **argv, int argc) {printf("test10.1: %d, %s, %d\n", j, types, argv[0]->i); return 1;}); j*=2; s.add_method("test11", "is", [j](const char *types, lo_arg **argv, int argc, lo_message msg) {printf("test11.1: %d, %s, %d, %s -- ", j, types, argv[0]->i, &argv[1]->s); lo_message_pp(msg); return 1;}); j*=2; s.add_method("test9", "i", [j](const char *path, const char *types, lo_arg **argv, int argc) {printf("test9.2: %d, %s, %s, %d\n", j, path, types, argv[0]->i);}); j*=2; s.add_method("test10", "i", [j](const char *types, lo_arg **argv, int argc) {printf("test10.2: %d, %s, %d\n", j, types, argv[0]->i);}); j*=2; s.add_method("test11", "is", [j](const char *types, lo_arg **argv, int argc, lo_message msg) {printf("test11.2: %d, %s, %d, %s -- ", j, types, argv[0]->i, &argv[1]->s); lo_message_pp(msg);}); j*=2; s.add_method("test12", "i", [j](const lo::Message m) {printf("test12 source: %s\n", m.source().url().c_str());}); s.add_method(0, 0, [](const char *path, lo_message m){printf("generic: %s ", path); lo_message_pp(m);}); j*=2; s.add_bundle_handlers( [j](lo_timetag time){ printf("Bundle start handler! (j=%d)\n", j); }, [j](){ printf("Bundle end handler! (j=%d)\n", j); } ); } int main() { int context = 999; lo::ServerThread st(9000, [=](int num, const char *msg, const char *where) {printf("error handler: %d\n", context);}); if (!st.is_valid()) { printf("Nope.\n"); return 1; } std::cout << "URL: " << st.url() << std::endl; init(st); st.start(); lo::Address a("localhost", "9000"); printf("address host %s, port %s\n", a.hostname().c_str(), a.port().c_str()); printf("iface: %s\n", a.iface().c_str()); a.set_iface(std::string(), std::string("127.0.0.1")); a.set_iface(0, "127.0.0.1"); printf("iface: %s\n", a.iface().c_str()); a.send_from(st, "test1", "i", 20); a.send("test2", "i", 40); a.send("test3", "i", 60); a.send("test4", "i", 80); a.send("test5", "i", 100); a.send("test6", "i", 120); a.send("test7", "i", 140); a.send("test8", "i", 160); a.send("test9", "i", 180); a.send("test10", "i", 200); lo::Message m; m.add("i", 220); m.add_string(std::string("blah")); a.send("test11", m); m.add(lo::Blob(4,"asdf")); m.add(lo::Blob(std::vector<char>(5, 'a'))); m.add(lo::Blob(std::array<char,5>{"asdf"})); a.send("blobtest", m); a.send( lo::Bundle({ {"test11", lo::Message("is",20,"first in bundle")}, {"test11", lo::Message("is",30,"second in bundle")} }) ); lo::Bundle b({{"ok1", lo::Message("is",20,"first in bundle")}, lo::Bundle({"ok2", lo::Message("is",30,"second in bundle")}) }, LO_TT_IMMEDIATE); printf("Bundle:\n"); b.print(); lo::Bundle::Element e(b.get_element(0)); printf("Bundle Message: %s ", e.pm.path.c_str()); e.pm.msg.print(); e = b.get_element(1); printf("Bundle Bundle:\n"); e.bundle.print(); printf("Bundle timestamp: %u.%u\n", e.bundle.timestamp().sec, e.bundle.timestamp().frac); a.send("test12", "i", 240); char oscmsg[] = {'/','o','k',0,',','i',0,0,0,0,0,4}; lo::Message::maybe m2 = lo::Message::deserialise(oscmsg, sizeof(oscmsg)); if (m2.first == 0) { printf("deserialise: %s", oscmsg); m2.second.print(); } else { printf("Unexpected failure in deserialise(): %d\n", m2.first); exit(1); } // Memory for lo_message not copied lo::Message m3(m2.second); // Memory for lo_message is copied lo::Message m4 = m2.second.clone(); sleep(1); printf("%s: %d\n", a.errstr().c_str(), a.get_errno()); } <commit_msg>Make cpp_test exit with an error code if any lo_address errors were encountered.<commit_after> #include <cstdio> #include <string> #include <iostream> #include <array> #include <vector> #include <unistd.h> #include <lo/lo.h> #include <lo/lo_cpp.h> int test1(const char *path, const char *types, lo_arg **argv, int argc, lo_message m, void *data) { printf("path: %s\n", path); printf("types: %s\n", types); printf("i: %d\n", argv[0]->i); return 0; } int test2(lo_arg **argv, int argc) { printf("in test2: %d\n", argv[0]->i); return 0; } int test3(lo_arg **argv, int argc, lo_message msg) { printf("in test3\n"); return 0; } void init(lo::Server &s) { int j = 234; std::cout << "URL: " << s.url() << std::endl; class test3 { public: test3(int j, std::string s) : _s(s), _j(j) {}; int operator () (lo_arg **argv, int argc, lo_message msg) { std::cout << _s << ": " << _j << ", " << argv[0]->i << std::endl; return 0; } private: std::string _s; int _j; }; s.add_method("test0", "i", test3(j,"test0")); s.del_method("test0", "i"); s.add_method("test1", "i", test1, 0); s.add_method("test2", "i", test2); s.add_method("test3", "i", test3(j, "test3")); s.add_method("test4", "i", [j](lo_arg **argv, int argc) { printf("test4: %d, %d\n", j, argv[0]->i); return 0; }); j *= 2; s.add_method("test5", "i", [j](lo_arg **argv, int argc, lo_message msg) { printf("test5: %d, %d -- ", j, argv[0]->i); lo_message_pp(msg); return 0; }); j *= 2; s.add_method("test6", "i", [j](lo_message msg) { printf("test6: %d -- ", j); lo_message_pp(msg); return 0; }); j *= 2; s.add_method("test7", "i", [j](){printf("test7: %d\n", j); return 0;}); j *= 2; s.add_method("test8", "i", [j](){printf("test8a: %d\n", j);}); j *= 2; s.add_method("test8", "i", [j](){printf("test8b: %d\n", j);}); j*=2; s.add_method("test9", "i", [j](const char *path, const char *types, lo_arg **argv, int argc) {printf("test9.1: %d, %s, %s, %d\n", j, path, types, argv[0]->i); return 1;}); j*=2; s.add_method("test10", "i", [j](const char *types, lo_arg **argv, int argc) {printf("test10.1: %d, %s, %d\n", j, types, argv[0]->i); return 1;}); j*=2; s.add_method("test11", "is", [j](const char *types, lo_arg **argv, int argc, lo_message msg) {printf("test11.1: %d, %s, %d, %s -- ", j, types, argv[0]->i, &argv[1]->s); lo_message_pp(msg); return 1;}); j*=2; s.add_method("test9", "i", [j](const char *path, const char *types, lo_arg **argv, int argc) {printf("test9.2: %d, %s, %s, %d\n", j, path, types, argv[0]->i);}); j*=2; s.add_method("test10", "i", [j](const char *types, lo_arg **argv, int argc) {printf("test10.2: %d, %s, %d\n", j, types, argv[0]->i);}); j*=2; s.add_method("test11", "is", [j](const char *types, lo_arg **argv, int argc, lo_message msg) {printf("test11.2: %d, %s, %d, %s -- ", j, types, argv[0]->i, &argv[1]->s); lo_message_pp(msg);}); j*=2; s.add_method("test12", "i", [j](const lo::Message m) {printf("test12 source: %s\n", m.source().url().c_str());}); s.add_method(0, 0, [](const char *path, lo_message m){printf("generic: %s ", path); lo_message_pp(m);}); j*=2; s.add_bundle_handlers( [j](lo_timetag time){ printf("Bundle start handler! (j=%d)\n", j); }, [j](){ printf("Bundle end handler! (j=%d)\n", j); } ); } int main() { int context = 999; lo::ServerThread st(9000, [=](int num, const char *msg, const char *where) {printf("error handler: %d\n", context);}); if (!st.is_valid()) { printf("Nope.\n"); return 1; } std::cout << "URL: " << st.url() << std::endl; init(st); st.start(); lo::Address a("localhost", "9000"); printf("address host %s, port %s\n", a.hostname().c_str(), a.port().c_str()); printf("iface: %s\n", a.iface().c_str()); a.set_iface(std::string(), std::string("127.0.0.1")); a.set_iface(0, "127.0.0.1"); printf("iface: %s\n", a.iface().c_str()); a.send_from(st, "test1", "i", 20); a.send("test2", "i", 40); a.send("test3", "i", 60); a.send("test4", "i", 80); a.send("test5", "i", 100); a.send("test6", "i", 120); a.send("test7", "i", 140); a.send("test8", "i", 160); a.send("test9", "i", 180); a.send("test10", "i", 200); lo::Message m; m.add("i", 220); m.add_string(std::string("blah")); a.send("test11", m); m.add(lo::Blob(4,"asdf")); m.add(lo::Blob(std::vector<char>(5, 'a'))); m.add(lo::Blob(std::array<char,5>{"asdf"})); a.send("blobtest", m); a.send( lo::Bundle({ {"test11", lo::Message("is",20,"first in bundle")}, {"test11", lo::Message("is",30,"second in bundle")} }) ); lo::Bundle b({{"ok1", lo::Message("is",20,"first in bundle")}, lo::Bundle({"ok2", lo::Message("is",30,"second in bundle")}) }, LO_TT_IMMEDIATE); printf("Bundle:\n"); b.print(); lo::Bundle::Element e(b.get_element(0)); printf("Bundle Message: %s ", e.pm.path.c_str()); e.pm.msg.print(); e = b.get_element(1); printf("Bundle Bundle:\n"); e.bundle.print(); printf("Bundle timestamp: %u.%u\n", e.bundle.timestamp().sec, e.bundle.timestamp().frac); a.send("test12", "i", 240); char oscmsg[] = {'/','o','k',0,',','i',0,0,0,0,0,4}; lo::Message::maybe m2 = lo::Message::deserialise(oscmsg, sizeof(oscmsg)); if (m2.first == 0) { printf("deserialise: %s", oscmsg); m2.second.print(); } else { printf("Unexpected failure in deserialise(): %d\n", m2.first); exit(1); } // Memory for lo_message not copied lo::Message m3(m2.second); // Memory for lo_message is copied lo::Message m4 = m2.second.clone(); sleep(1); printf("%s: %d\n", a.errstr().c_str(), a.get_errno()); return a.get_errno(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: galobj.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:49:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_GALOBJ_HXX_ #define _SVX_GALOBJ_HXX_ #include <tools/urlobj.hxx> #include <vcl/graph.hxx> // ----------- // - Defines - // ----------- #define S_THUMB 80 // ----------------------------------------------------------------------------- #define SGA_FORMAT_NONE 0x00000000L #define SGA_FORMAT_STRING 0x00000001L #define SGA_FORMAT_GRAPHIC 0x00000010L #define SGA_FORMAT_SOUND 0x00000100L #define SGA_FORMAT_OLE 0x00001000L #define SGA_FORMAT_SVDRAW 0x00010000L #define SGA_FORMAT_ALL 0xFFFFFFFFL // -------------- // - SgaObjKind - // -------------- enum SgaObjKind { SGA_OBJ_NONE = 0, // Abstraktes Objekt SGA_OBJ_BMP = 1, // Bitmap-Objekt SGA_OBJ_SOUND = 2, // Sound-Objekt SGA_OBJ_VIDEO = 3, // Video-Objekt SGA_OBJ_ANIM = 4, // Animations-Objekt SGA_OBJ_SVDRAW = 5, // Svdraw-Objekt SGA_OBJ_INET = 6 // Grafik aus dem Internet }; // ---------------- // - GalSoundType - // ---------------- enum GalSoundType { SOUND_STANDARD = 0, SOUND_COMPUTER = 1, SOUND_MISC = 2, SOUND_MUSIC = 3, SOUND_NATURE = 4, SOUND_SPEECH = 5, SOUND_TECHNIC = 6, SOUND_ANIMAL = 7 }; // ------------- // - SgaObject - // ------------- class SgaObject { friend class GalleryTheme; private: void ImplUpdateURL( const INetURLObject& rNewURL ) { aURL = rNewURL; } protected: Bitmap aThumbBmp; GDIMetaFile aThumbMtf; INetURLObject aURL; String aUserName; String aTitle; BOOL bIsValid; BOOL bIsThumbBmp; virtual void WriteData( SvStream& rOut ) const; virtual void ReadData( SvStream& rIn, UINT16& rReadVersion ); BOOL CreateThumb( const Graphic& rGraphic ); public: SgaObject(); virtual ~SgaObject() {}; virtual SgaObjKind GetObjKind() const = 0; virtual UINT16 GetVersion() const = 0; virtual Bitmap GetThumbBmp() const { return aThumbBmp; } const GDIMetaFile& GetThumbMtf() const { return aThumbMtf; } const INetURLObject& GetURL() const { return aURL; } BOOL IsValid() const { return bIsValid; } BOOL IsThumbBitmap() const { return bIsThumbBmp; } const String GetTitle() const; void SetTitle( const String& rTitle ); friend SvStream& operator<<( SvStream& rOut, const SgaObject& rObj ); friend SvStream& operator>>( SvStream& rIn, SgaObject& rObj ); }; // ------------------ // - SgaObjectSound - // ------------------ class SgaObjectSound : public SgaObject { private: GalSoundType eSoundType; virtual void WriteData( SvStream& rOut ) const; virtual void ReadData( SvStream& rIn, UINT16& rReadVersion ); virtual UINT16 GetVersion() const { return 6; } public: SgaObjectSound(); SgaObjectSound( const INetURLObject& rURL ); virtual ~SgaObjectSound(); virtual SgaObjKind GetObjKind() const { return SGA_OBJ_SOUND; } virtual Bitmap GetThumbBmp() const; GalSoundType GetSoundType() const { return eSoundType; } }; // ------------------- // - SgaObjectSvDraw - // ------------------- class FmFormModel; class SgaObjectSvDraw : public SgaObject { private: BOOL CreateThumb( const FmFormModel& rModel ); virtual void WriteData( SvStream& rOut ) const; virtual void ReadData( SvStream& rIn, UINT16& rReadVersion ); virtual UINT16 GetVersion() const { return 5; } public: SgaObjectSvDraw(); SgaObjectSvDraw( const FmFormModel& rModel, const INetURLObject& rURL ); SgaObjectSvDraw( SvStream& rIStm, const INetURLObject& rURL ); virtual ~SgaObjectSvDraw() {}; virtual SgaObjKind GetObjKind() const { return SGA_OBJ_SVDRAW; } public: static BOOL DrawCentered( OutputDevice* pOut, const FmFormModel& rModel ); }; // ---------------- // - SgaObjectBmp - // ---------------- class SgaObjectBmp: public SgaObject { private: void Init( const Graphic& rGraphic, const INetURLObject& rURL ); virtual void WriteData( SvStream& rOut ) const; virtual void ReadData( SvStream& rIn, UINT16& rReadVersion ); virtual UINT16 GetVersion() const { return 5; } public: SgaObjectBmp(); SgaObjectBmp( const INetURLObject& rURL ); SgaObjectBmp( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormat ); virtual ~SgaObjectBmp() {}; virtual SgaObjKind GetObjKind() const { return SGA_OBJ_BMP; } }; // ----------------- // - SgaObjectAnim - // ----------------- class SgaObjectAnim : public SgaObjectBmp { private: SgaObjectAnim( const INetURLObject& rURL ) {}; public: SgaObjectAnim(); SgaObjectAnim( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormatName ); virtual ~SgaObjectAnim() {}; virtual SgaObjKind GetObjKind() const { return SGA_OBJ_ANIM; } }; // ----------------- // - SgaObjectINet - // ----------------- class SgaObjectINet : public SgaObjectAnim { private: SgaObjectINet( const INetURLObject& rURL ) {}; public: SgaObjectINet(); SgaObjectINet( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormatName ); virtual ~SgaObjectINet() {}; virtual SgaObjKind GetObjKind() const { return SGA_OBJ_INET; } }; #endif <commit_msg>INTEGRATION: CWS cov2src (1.3.84); FILE MERGED 2005/10/18 14:14:08 rt 1.3.84.1: #126234# Join MWS COV680 m4 into SRC680<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: galobj.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-10-19 12:07:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_GALOBJ_HXX_ #define _SVX_GALOBJ_HXX_ #include <tools/urlobj.hxx> #include <vcl/graph.hxx> // ----------- // - Defines - // ----------- #define S_THUMB 80 // ----------------------------------------------------------------------------- #define SGA_FORMAT_NONE 0x00000000L #define SGA_FORMAT_STRING 0x00000001L #define SGA_FORMAT_GRAPHIC 0x00000010L #define SGA_FORMAT_SOUND 0x00000100L #define SGA_FORMAT_OLE 0x00001000L #define SGA_FORMAT_SVDRAW 0x00010000L #define SGA_FORMAT_ALL 0xFFFFFFFFL // -------------- // - SgaObjKind - // -------------- enum SgaObjKind { SGA_OBJ_NONE = 0, // Abstraktes Objekt SGA_OBJ_BMP = 1, // Bitmap-Objekt SGA_OBJ_SOUND = 2, // Sound-Objekt SGA_OBJ_VIDEO = 3, // Video-Objekt SGA_OBJ_ANIM = 4, // Animations-Objekt SGA_OBJ_SVDRAW = 5, // Svdraw-Objekt SGA_OBJ_INET = 6 // Grafik aus dem Internet }; // ---------------- // - GalSoundType - // ---------------- enum GalSoundType { SOUND_STANDARD = 0, SOUND_COMPUTER = 1, SOUND_MISC = 2, SOUND_MUSIC = 3, SOUND_NATURE = 4, SOUND_SPEECH = 5, SOUND_TECHNIC = 6, SOUND_ANIMAL = 7 }; // ------------- // - SgaObject - // ------------- class SgaObject { friend class GalleryTheme; private: void ImplUpdateURL( const INetURLObject& rNewURL ) { aURL = rNewURL; } protected: Bitmap aThumbBmp; GDIMetaFile aThumbMtf; INetURLObject aURL; String aUserName; String aTitle; BOOL bIsValid; BOOL bIsThumbBmp; virtual void WriteData( SvStream& rOut, const String& rDestDir ) const; virtual void ReadData( SvStream& rIn, UINT16& rReadVersion ); BOOL CreateThumb( const Graphic& rGraphic ); public: SgaObject(); virtual ~SgaObject() {}; virtual SgaObjKind GetObjKind() const = 0; virtual UINT16 GetVersion() const = 0; virtual Bitmap GetThumbBmp() const { return aThumbBmp; } const GDIMetaFile& GetThumbMtf() const { return aThumbMtf; } const INetURLObject& GetURL() const { return aURL; } BOOL IsValid() const { return bIsValid; } BOOL IsThumbBitmap() const { return bIsThumbBmp; } const String GetTitle() const; void SetTitle( const String& rTitle ); friend SvStream& operator<<( SvStream& rOut, const SgaObject& rObj ); friend SvStream& operator>>( SvStream& rIn, SgaObject& rObj ); }; // ------------------ // - SgaObjectSound - // ------------------ class SgaObjectSound : public SgaObject { private: GalSoundType eSoundType; virtual void WriteData( SvStream& rOut, const String& rDestDir ) const; virtual void ReadData( SvStream& rIn, UINT16& rReadVersion ); virtual UINT16 GetVersion() const { return 6; } public: SgaObjectSound(); SgaObjectSound( const INetURLObject& rURL ); virtual ~SgaObjectSound(); virtual SgaObjKind GetObjKind() const { return SGA_OBJ_SOUND; } virtual Bitmap GetThumbBmp() const; GalSoundType GetSoundType() const { return eSoundType; } }; // ------------------- // - SgaObjectSvDraw - // ------------------- class FmFormModel; class SgaObjectSvDraw : public SgaObject { private: BOOL CreateThumb( const FmFormModel& rModel ); virtual void WriteData( SvStream& rOut, const String& rDestDir ) const; virtual void ReadData( SvStream& rIn, UINT16& rReadVersion ); virtual UINT16 GetVersion() const { return 5; } public: SgaObjectSvDraw(); SgaObjectSvDraw( const FmFormModel& rModel, const INetURLObject& rURL ); SgaObjectSvDraw( SvStream& rIStm, const INetURLObject& rURL ); virtual ~SgaObjectSvDraw() {}; virtual SgaObjKind GetObjKind() const { return SGA_OBJ_SVDRAW; } public: static BOOL DrawCentered( OutputDevice* pOut, const FmFormModel& rModel ); }; // ---------------- // - SgaObjectBmp - // ---------------- class SgaObjectBmp: public SgaObject { private: void Init( const Graphic& rGraphic, const INetURLObject& rURL ); virtual void WriteData( SvStream& rOut, const String& rDestDir ) const; virtual void ReadData( SvStream& rIn, UINT16& rReadVersion ); virtual UINT16 GetVersion() const { return 5; } public: SgaObjectBmp(); SgaObjectBmp( const INetURLObject& rURL ); SgaObjectBmp( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormat ); virtual ~SgaObjectBmp() {}; virtual SgaObjKind GetObjKind() const { return SGA_OBJ_BMP; } }; // ----------------- // - SgaObjectAnim - // ----------------- class SgaObjectAnim : public SgaObjectBmp { private: SgaObjectAnim( const INetURLObject& rURL ) {}; public: SgaObjectAnim(); SgaObjectAnim( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormatName ); virtual ~SgaObjectAnim() {}; virtual SgaObjKind GetObjKind() const { return SGA_OBJ_ANIM; } }; // ----------------- // - SgaObjectINet - // ----------------- class SgaObjectINet : public SgaObjectAnim { private: SgaObjectINet( const INetURLObject& rURL ) {}; public: SgaObjectINet(); SgaObjectINet( const Graphic& rGraphic, const INetURLObject& rURL, const String& rFormatName ); virtual ~SgaObjectINet() {}; virtual SgaObjKind GetObjKind() const { return SGA_OBJ_INET; } }; #endif <|endoftext|>