text
stringlengths
54
60.6k
<commit_before>#include "Halide.h" #include <stdio.h> #include <math.h> using std::vector; using namespace Halide; using namespace Halide::Internal; class CountInterleaves : public IRVisitor { public: int result; CountInterleaves() : result(0) {} using IRVisitor::visit; void visit(const Call *op) { if (op->is_intrinsic(Call::interleave_vectors)) { result++; } IRVisitor::visit(op); } }; int count_interleaves(Func f) { Target t = get_jit_target_from_environment(); t.set_feature(Target::NoBoundsQuery); t.set_feature(Target::NoAsserts); f.compute_root(); Stmt s = Internal::lower({f.function()}, f.name(), t); CountInterleaves i; s.accept(&i); return i.result; } void check_interleave_count(Func f, int correct) { int c = count_interleaves(f); if (c < correct) { printf("Func %s should have interleaved >= %d times but interleaved %d times instead.\n", f.name().c_str(), correct, c); exit(-1); } } template <typename FuncRefVarOrExpr> void define(FuncRefVarOrExpr f, std::vector<Expr> values) { if (values.size() == 1) { f = values[0]; } else { f = Tuple(values); } } template <typename FuncRefVarOrExpr> void define(FuncRefVarOrExpr f, Expr value, int count) { std::vector<Expr> values; for (int i = 0; i < count; i++) { values.push_back(value); } define(f, values); } template <typename FuncRefVarOrExpr> Expr element(FuncRefVarOrExpr f, int i) { if (f.size() == 1) { assert(i == 0); return f; } else { return f[i]; } } // Make sure the interleave pattern generates good vector code int main(int argc, char **argv) { Var x, y, c; for (int elements = 1; elements <= 5; elements++) { Func f, g, h; std::vector<Expr> f_def, g_def; for (int i = 0; i < elements; i++) { f_def.push_back(sin(x + i)); g_def.push_back(cos(x + i)); } define(f(x), f_def); define(g(x), g_def); std::vector<Expr> h_def; for (int i = 0; i < elements; i++) { h_def.push_back(select(x % 2 == 0, 1.0f/element(f(x/2), i), element(g(x/2), i)*17.0f)); g_def.push_back(cos(x + i)); } define(h(x), h_def); f.compute_root(); g.compute_root(); h.vectorize(x, 8); check_interleave_count(h, 1); Realization results = h.realize(16); for (int i = 0; i < elements; i++) { Image<float> result = results[i]; for (int x = 0; x < 16; x++) { float correct = ((x % 2) == 0) ? (1.0f/(sinf(x/2 + i))) : (cosf(x/2 + i)*17.0f); float delta = result(x) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result(x), correct); return -1; } } } } { // Test interleave 3 vectors: Func planar, interleaved; planar(x, y) = Halide::cast<float>( 3 * x + y ); interleaved(x, y) = planar(x, y); Var xy("xy"); planar .compute_at(interleaved, xy) .vectorize(x, 4); interleaved .reorder(y, x) .bound(y, 0, 3) .bound(x, 0, 16) .fuse(y, x, xy) .vectorize(xy, 12); interleaved .output_buffer() .set_min(1, 0) .set_stride(0, 3) .set_stride(1, 1) .set_extent(1, 3); Buffer buff3; buff3 = Buffer(Float(32), 16, 3, 0, 0, (uint8_t *)0); buff3.raw_buffer()->stride[0] = 3; buff3.raw_buffer()->stride[1] = 1; Realization r3({buff3}); interleaved.realize(r3); check_interleave_count(interleaved, 1); Image<float> result3 = r3[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 3; y++) { float correct = 3*x + y; float delta = result3(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result3(x,y), correct); return -1; } } } } { // Test interleave 4 vectors: Func f1, f2, f3, f4, f5; f1(x) = sin(x); f2(x) = sin(2*x); f3(x) = sin(3*x); f4(x) = sin(4*x); f5(x) = sin(5*x); Func output4; output4(x, y) = select(y == 0, f1(x), y == 1, f2(x), y == 2, f3(x), f4(x)); output4 .reorder(y, x) .bound(y, 0, 4) .unroll(y) .vectorize(x, 4); output4.output_buffer() .set_min(1, 0) .set_stride(0, 4) .set_stride(1, 1) .set_extent(1, 4); check_interleave_count(output4, 1); Buffer buff4; buff4 = Buffer(Float(32), 16, 4, 0, 0, (uint8_t *)0); buff4.raw_buffer()->stride[0] = 4; buff4.raw_buffer()->stride[1] = 1; Realization r4({buff4}); output4.realize(r4); Image<float> result4 = r4[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 4; y++) { float correct = sin((y+1)*x); float delta = result4(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result4(x,y), correct); return -1; } } } // Test interleave 5 vectors: Func output5; output5(x, y) = select(y == 0, f1(x), y == 1, f2(x), y == 2, f3(x), y == 3, f4(x), f5(x)); output5 .reorder(y, x) .bound(y, 0, 5) .unroll(y) .vectorize(x, 4); output5.output_buffer() .set_min(1, 0) .set_stride(0, 5) .set_stride(1, 1) .set_extent(1, 5); check_interleave_count(output5, 1); Buffer buff5; buff5 = Buffer(Float(32), 16, 5, 0, 0, (uint8_t *)0); buff5.raw_buffer()->stride[0] = 5; buff5.raw_buffer()->stride[1] = 1; Realization r5({buff5}); output5.realize(r5); Image<float> result5 = r5[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 5; y++) { float correct = sin((y+1)*x); float delta = result5(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result5(x,y), correct); return -1; } } } } { // Test interleaving inside of nested blocks Func f1, f2, f3, f4, f5; f1(x) = sin(x); f1.compute_root(); f2(x) = sin(2*x); f2.compute_root(); Func unrolled; unrolled(x, y) = select(x % 2 == 0, f1(x), f2(x)) + y; Var xi, yi; unrolled.tile(x, y, xi, yi, 16, 2).unroll(xi, 2).vectorize(xi, 4).unroll(xi).unroll(yi); check_interleave_count(unrolled, 4); } for (int elements = 1; elements <= 5; elements++) { // Make sure we don't interleave when the reordering would change the meaning. Realization* refs = nullptr; for (int i = 0; i < 2; i++) { Func output6; define(output6(x, y), cast<uint8_t>(x), elements); RDom r(0, 16); // A not-safe-to-merge pair of updates define(output6(2*r, 0), cast<uint8_t>(3), elements); define(output6(2*r+1, 0), cast<uint8_t>(4), elements); // A safe-to-merge pair of updates define(output6(2*r, 1), cast<uint8_t>(3), elements); define(output6(2*r+1, 1), cast<uint8_t>(4), elements); // A safe-to-merge-but-not-complete triple of updates: define(output6(3*r, 3), cast<uint8_t>(3), elements); define(output6(3*r+1, 3), cast<uint8_t>(4), elements); // A safe-to-merge-but-we-don't pair of updates, because they // load recursively, so we conservatively bail out. std::vector<Expr> rdef0, rdef1; for (int i = 0; i < elements; i++) { rdef0.push_back(element(output6(2*r, 2), i) + 1); rdef1.push_back(element(output6(2*r+1, 2), i) + 1); } define(output6(2*r, 2), rdef0); define(output6(2*r+1, 2), rdef1); // A safe-to-merge triple of updates: define(output6(3*r, 3), cast<uint8_t>(7), elements); define(output6(3*r+2, 3), cast<uint8_t>(9), elements); define(output6(3*r+1, 3), cast<uint8_t>(8), elements); if (i == 0) { // Making the reference output. refs = new Realization(output6.realize(50, 4)); } else { // Vectorize and compare to the reference. for (int j = 0; j < 11; j++) { output6.update(j).vectorize(r); } check_interleave_count(output6, 2*elements); Realization outs = output6.realize(50, 4); for (int e = 0; e < elements; e++) { Image<uint8_t> ref = (*refs)[e]; Image<uint8_t> out = outs[e]; for (int y = 0; y < ref.height(); y++) { for (int x = 0; x < ref.width(); x++) { if (out(x, y) != ref(x, y)) { printf("result(%d, %d) = %d instead of %d\n", x, y, out(x, y), ref(x, y)); return -1; } } } } } } delete refs; } { // Test that transposition works when vectorizing either dimension: Func square("square"); square(x, y) = cast(UInt(16), 5*x + y); Func trans1("trans1"); trans1(x, y) = square(y, x); Func trans2("trans2"); trans2(x, y) = square(y, x); square.compute_root() .bound(x, 0, 8) .bound(y, 0, 8); trans1.compute_root() .bound(x, 0, 8) .bound(y, 0, 8) .vectorize(x) .unroll(y); trans2.compute_root() .bound(x, 0, 8) .bound(y, 0, 8) .unroll(x) .vectorize(y); trans1.output_buffer() .set_min(0,0).set_min(1,0) .set_stride(0,1).set_stride(1,8) .set_extent(0,8).set_extent(1,8); trans2.output_buffer() .set_min(0,0).set_min(1,0) .set_stride(0,1).set_stride(1,8) .set_extent(0,8).set_extent(1,8); Image<uint16_t> result6(8,8); Image<uint16_t> result7(8,8); trans1.realize(result6); trans2.realize(result7); for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { int correct = 5*y + x; if (result6(x,y) != correct) { printf("result(%d) = %d instead of %d\n", x, result6(x,y), correct); return -1; } if (result7(x,y) != correct) { printf("result(%d) = %d instead of %d\n", x, result7(x,y), correct); return -1; } } } check_interleave_count(trans1, 1); check_interleave_count(trans2, 1); } printf("Success!\n"); return 0; } <commit_msg>Disable test that triggers possible llvm jit bug<commit_after>#include "Halide.h" #include <stdio.h> #include <math.h> using std::vector; using namespace Halide; using namespace Halide::Internal; class CountInterleaves : public IRVisitor { public: int result; CountInterleaves() : result(0) {} using IRVisitor::visit; void visit(const Call *op) { if (op->is_intrinsic(Call::interleave_vectors)) { result++; } IRVisitor::visit(op); } }; int count_interleaves(Func f) { Target t = get_jit_target_from_environment(); t.set_feature(Target::NoBoundsQuery); t.set_feature(Target::NoAsserts); f.compute_root(); Stmt s = Internal::lower({f.function()}, f.name(), t); CountInterleaves i; s.accept(&i); return i.result; } void check_interleave_count(Func f, int correct) { int c = count_interleaves(f); if (c < correct) { printf("Func %s should have interleaved >= %d times but interleaved %d times instead.\n", f.name().c_str(), correct, c); exit(-1); } } template <typename FuncRefVarOrExpr> void define(FuncRefVarOrExpr f, std::vector<Expr> values) { if (values.size() == 1) { f = values[0]; } else { f = Tuple(values); } } template <typename FuncRefVarOrExpr> void define(FuncRefVarOrExpr f, Expr value, int count) { std::vector<Expr> values; for (int i = 0; i < count; i++) { values.push_back(value); } define(f, values); } template <typename FuncRefVarOrExpr> Expr element(FuncRefVarOrExpr f, int i) { if (f.size() == 1) { assert(i == 0); return f; } else { return f[i]; } } // Make sure the interleave pattern generates good vector code int main(int argc, char **argv) { Var x, y, c; // As of May 26 2016, this test causes a segfault due to // permissions failure on ARM-32 trying to execute a // non-executable page when jitting. Started happening between // llvm commits 270148 and 270159, but there's no obvious // culprit. Just disabling it for now. { Target t = get_host_target(); if (t.arch == Target::ARM && t.bits == 32) { printf("Skipping test on arm-32 (see the source for why)\n"); return 0; } } for (int elements = 1; elements <= 5; elements++) { Func f, g, h; std::vector<Expr> f_def, g_def; for (int i = 0; i < elements; i++) { f_def.push_back(sin(x + i)); g_def.push_back(cos(x + i)); } define(f(x), f_def); define(g(x), g_def); std::vector<Expr> h_def; for (int i = 0; i < elements; i++) { h_def.push_back(select(x % 2 == 0, 1.0f/element(f(x/2), i), element(g(x/2), i)*17.0f)); g_def.push_back(cos(x + i)); } define(h(x), h_def); f.compute_root(); g.compute_root(); h.vectorize(x, 8); check_interleave_count(h, 1); Realization results = h.realize(16); for (int i = 0; i < elements; i++) { Image<float> result = results[i]; for (int x = 0; x < 16; x++) { float correct = ((x % 2) == 0) ? (1.0f/(sinf(x/2 + i))) : (cosf(x/2 + i)*17.0f); float delta = result(x) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result(x), correct); return -1; } } } } { // Test interleave 3 vectors: Func planar, interleaved; planar(x, y) = Halide::cast<float>( 3 * x + y ); interleaved(x, y) = planar(x, y); Var xy("xy"); planar .compute_at(interleaved, xy) .vectorize(x, 4); interleaved .reorder(y, x) .bound(y, 0, 3) .bound(x, 0, 16) .fuse(y, x, xy) .vectorize(xy, 12); interleaved .output_buffer() .set_min(1, 0) .set_stride(0, 3) .set_stride(1, 1) .set_extent(1, 3); Buffer buff3; buff3 = Buffer(Float(32), 16, 3, 0, 0, (uint8_t *)0); buff3.raw_buffer()->stride[0] = 3; buff3.raw_buffer()->stride[1] = 1; Realization r3({buff3}); interleaved.realize(r3); check_interleave_count(interleaved, 1); Image<float> result3 = r3[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 3; y++) { float correct = 3*x + y; float delta = result3(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result3(x,y), correct); return -1; } } } } { // Test interleave 4 vectors: Func f1, f2, f3, f4, f5; f1(x) = sin(x); f2(x) = sin(2*x); f3(x) = sin(3*x); f4(x) = sin(4*x); f5(x) = sin(5*x); Func output4; output4(x, y) = select(y == 0, f1(x), y == 1, f2(x), y == 2, f3(x), f4(x)); output4 .reorder(y, x) .bound(y, 0, 4) .unroll(y) .vectorize(x, 4); output4.output_buffer() .set_min(1, 0) .set_stride(0, 4) .set_stride(1, 1) .set_extent(1, 4); check_interleave_count(output4, 1); Buffer buff4; buff4 = Buffer(Float(32), 16, 4, 0, 0, (uint8_t *)0); buff4.raw_buffer()->stride[0] = 4; buff4.raw_buffer()->stride[1] = 1; Realization r4({buff4}); output4.realize(r4); Image<float> result4 = r4[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 4; y++) { float correct = sin((y+1)*x); float delta = result4(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result4(x,y), correct); return -1; } } } // Test interleave 5 vectors: Func output5; output5(x, y) = select(y == 0, f1(x), y == 1, f2(x), y == 2, f3(x), y == 3, f4(x), f5(x)); output5 .reorder(y, x) .bound(y, 0, 5) .unroll(y) .vectorize(x, 4); output5.output_buffer() .set_min(1, 0) .set_stride(0, 5) .set_stride(1, 1) .set_extent(1, 5); check_interleave_count(output5, 1); Buffer buff5; buff5 = Buffer(Float(32), 16, 5, 0, 0, (uint8_t *)0); buff5.raw_buffer()->stride[0] = 5; buff5.raw_buffer()->stride[1] = 1; Realization r5({buff5}); output5.realize(r5); Image<float> result5 = r5[0]; for (int x = 0; x < 16; x++) { for (int y = 0; y < 5; y++) { float correct = sin((y+1)*x); float delta = result5(x,y) - correct; if (delta > 0.01 || delta < -0.01) { printf("result(%d) = %f instead of %f\n", x, result5(x,y), correct); return -1; } } } } { // Test interleaving inside of nested blocks Func f1, f2, f3, f4, f5; f1(x) = sin(x); f1.compute_root(); f2(x) = sin(2*x); f2.compute_root(); Func unrolled; unrolled(x, y) = select(x % 2 == 0, f1(x), f2(x)) + y; Var xi, yi; unrolled.tile(x, y, xi, yi, 16, 2).unroll(xi, 2).vectorize(xi, 4).unroll(xi).unroll(yi); check_interleave_count(unrolled, 4); } for (int elements = 1; elements <= 5; elements++) { // Make sure we don't interleave when the reordering would change the meaning. Realization* refs = nullptr; for (int i = 0; i < 2; i++) { Func output6; define(output6(x, y), cast<uint8_t>(x), elements); RDom r(0, 16); // A not-safe-to-merge pair of updates define(output6(2*r, 0), cast<uint8_t>(3), elements); define(output6(2*r+1, 0), cast<uint8_t>(4), elements); // A safe-to-merge pair of updates define(output6(2*r, 1), cast<uint8_t>(3), elements); define(output6(2*r+1, 1), cast<uint8_t>(4), elements); // A safe-to-merge-but-not-complete triple of updates: define(output6(3*r, 3), cast<uint8_t>(3), elements); define(output6(3*r+1, 3), cast<uint8_t>(4), elements); // A safe-to-merge-but-we-don't pair of updates, because they // load recursively, so we conservatively bail out. std::vector<Expr> rdef0, rdef1; for (int i = 0; i < elements; i++) { rdef0.push_back(element(output6(2*r, 2), i) + 1); rdef1.push_back(element(output6(2*r+1, 2), i) + 1); } define(output6(2*r, 2), rdef0); define(output6(2*r+1, 2), rdef1); // A safe-to-merge triple of updates: define(output6(3*r, 3), cast<uint8_t>(7), elements); define(output6(3*r+2, 3), cast<uint8_t>(9), elements); define(output6(3*r+1, 3), cast<uint8_t>(8), elements); if (i == 0) { // Making the reference output. refs = new Realization(output6.realize(50, 4)); } else { // Vectorize and compare to the reference. for (int j = 0; j < 11; j++) { output6.update(j).vectorize(r); } check_interleave_count(output6, 2*elements); Realization outs = output6.realize(50, 4); for (int e = 0; e < elements; e++) { Image<uint8_t> ref = (*refs)[e]; Image<uint8_t> out = outs[e]; for (int y = 0; y < ref.height(); y++) { for (int x = 0; x < ref.width(); x++) { if (out(x, y) != ref(x, y)) { printf("result(%d, %d) = %d instead of %d\n", x, y, out(x, y), ref(x, y)); return -1; } } } } } } delete refs; } { // Test that transposition works when vectorizing either dimension: Func square("square"); square(x, y) = cast(UInt(16), 5*x + y); Func trans1("trans1"); trans1(x, y) = square(y, x); Func trans2("trans2"); trans2(x, y) = square(y, x); square.compute_root() .bound(x, 0, 8) .bound(y, 0, 8); trans1.compute_root() .bound(x, 0, 8) .bound(y, 0, 8) .vectorize(x) .unroll(y); trans2.compute_root() .bound(x, 0, 8) .bound(y, 0, 8) .unroll(x) .vectorize(y); trans1.output_buffer() .set_min(0,0).set_min(1,0) .set_stride(0,1).set_stride(1,8) .set_extent(0,8).set_extent(1,8); trans2.output_buffer() .set_min(0,0).set_min(1,0) .set_stride(0,1).set_stride(1,8) .set_extent(0,8).set_extent(1,8); Image<uint16_t> result6(8,8); Image<uint16_t> result7(8,8); trans1.realize(result6); trans2.realize(result7); for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { int correct = 5*y + x; if (result6(x,y) != correct) { printf("result(%d) = %d instead of %d\n", x, result6(x,y), correct); return -1; } if (result7(x,y) != correct) { printf("result(%d) = %d instead of %d\n", x, result7(x,y), correct); return -1; } } } check_interleave_count(trans1, 1); check_interleave_count(trans2, 1); } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>//===- ConstantProp.cpp - Code to perform Constant Propogation ------------===// // // This file implements constant propogation and merging: // // Specifically, this: // * Folds multiple identical constants in the constant pool together // Note that if one is named and the other is not, that the result gets the // original name. // * Converts instructions like "add int %1, %2" into a direct def of %3 in // the constant pool // * Converts conditional branches on a constant boolean value into direct // branches. // * Converts phi nodes with one incoming def to the incoming def directly // . Converts switch statements with one entry into a test & conditional // branch // . Converts switches on constant values into an unconditional branch. // // Notice that: // * This pass has a habit of making definitions be dead. It is a good idea // to to run a DCE pass sometime after running this pass. // //===----------------------------------------------------------------------===// #include "llvm/Optimizations/ConstantProp.h" #include "llvm/Optimizations/ConstantHandling.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/ConstPoolVals.h" #include "llvm/ConstantPool.h" // Merge identical constant values in the constant pool. // // TODO: We can do better than this simplistic N^2 algorithm... // bool opt::DoConstantPoolMerging(Method *M) { return DoConstantPoolMerging(M->getConstantPool()); } bool opt::DoConstantPoolMerging(ConstantPool &CP) { bool Modified = false; for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) { for (ConstantPool::PlaneType::iterator I = (*PI)->begin(); I != (*PI)->end(); ++I) { ConstPoolVal *C = *I; ConstantPool::PlaneType::iterator J = I; for (++J; J != (*PI)->end(); ++J) { if (C->equals(*J)) { Modified = true; // Okay we know that *I == *J. So now we need to make all uses of *I // point to *J. // C->replaceAllUsesWith(*J); (*PI)->remove(I); // Remove C from constant pool... if (C->hasName() && !(*J)->hasName()) // The merged constant inherits (*J)->setName(C->getName()); // the old name... delete C; // Delete the constant itself. break; // Break out of inner for loop } } } } return Modified; } inline static bool ConstantFoldUnaryInst(Method *M, Method::inst_iterator &DI, UnaryOperator *Op, ConstPoolVal *D) { ConstPoolVal *ReplaceWith = opt::ConstantFoldUnaryInstruction(Op->getOpcode(), D); if (!ReplaceWith) return false; // Nothing new to change... // Add the new value to the constant pool... M->getConstantPool().insert(ReplaceWith); // Replaces all of the uses of a variable with uses of the constant. Op->replaceAllUsesWith(ReplaceWith); // Remove the operator from the list of definitions... Op->getParent()->getInstList().remove(DI.getInstructionIterator()); // The new constant inherits the old name of the operator... if (Op->hasName()) ReplaceWith->setName(Op->getName()); // Delete the operator now... delete Op; return true; } inline static bool ConstantFoldBinaryInst(Method *M, Method::inst_iterator &DI, BinaryOperator *Op, ConstPoolVal *D1, ConstPoolVal *D2) { ConstPoolVal *ReplaceWith = opt::ConstantFoldBinaryInstruction(Op->getOpcode(), D1, D2); if (!ReplaceWith) return false; // Nothing new to change... // Add the new value to the constant pool... M->getConstantPool().insert(ReplaceWith); // Replaces all of the uses of a variable with uses of the constant. Op->replaceAllUsesWith(ReplaceWith); // Remove the operator from the list of definitions... Op->getParent()->getInstList().remove(DI.getInstructionIterator()); // The new constant inherits the old name of the operator... if (Op->hasName()) ReplaceWith->setName(Op->getName()); // Delete the operator now... delete Op; return true; } // ConstantFoldTerminator - If a terminator instruction is predicated on a // constant value, convert it into an unconditional branch to the constant // destination. // bool opt::ConstantFoldTerminator(TerminatorInst *T) { // Branch - See if we are conditional jumping on constant if (T->getOpcode() == Instruction::Br) { BranchInst *BI = (BranchInst*)T; if (BI->isUnconditional()) return false; // Can't optimize uncond branch BasicBlock *Dest1 = BI->getOperand(0)->castBasicBlockAsserting(); BasicBlock *Dest2 = BI->getOperand(1)->castBasicBlockAsserting(); if (BI->getCondition()->isConstant()) { // Are we branching on constant? // YES. Change to unconditional branch... ConstPoolBool *Cond = (ConstPoolBool*)BI->getCondition(); BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; //cerr << "Method: " << T->getParent()->getParent() // << "\nRemoving branch from " << T->getParent() // << "\n\nTo: " << OldDest << endl; // Let the basic block know that we are letting go of it. Based on this, // it will adjust it's PHI nodes. assert(BI->getParent() && "Terminator not inserted in block!"); OldDest->removePredecessor(BI->getParent()); // Set the unconditional destination, and change the insn to be an // unconditional branch. BI->setUnconditionalDest(Destination); return true; } else if (Dest2 == Dest1) { // Conditional branch to same location? // This branch matches something like this: // br bool %cond, label %Dest, label %Dest // and changes it into: br label %Dest // Let the basic block know that we are letting go of one copy of it. assert(BI->getParent() && "Terminator not inserted in block!"); Dest1->removePredecessor(BI->getParent()); // Change a conditional branch to unconditional. BI->setUnconditionalDest(Dest1); return true; } } return false; } // ConstantFoldInstruction - If an instruction references constants, try to fold // them together... // inline static bool ConstantFoldInstruction(Method *M, Method::inst_iterator &II) { Instruction *Inst = *II; if (Inst->isBinaryOp()) { ConstPoolVal *D1 = Inst->getOperand(0)->castConstant(); ConstPoolVal *D2 = Inst->getOperand(1)->castConstant(); if (D1 && D2) return ConstantFoldBinaryInst(M, II, (BinaryOperator*)Inst, D1, D2); } else if (Inst->isUnaryOp()) { ConstPoolVal *D = Inst->getOperand(0)->castConstant(); if (D) return ConstantFoldUnaryInst(M, II, (UnaryOperator*)Inst, D); } else if (Inst->isTerminator()) { return opt::ConstantFoldTerminator((TerminatorInst*)Inst); } else if (Inst->isPHINode()) { PHINode *PN = (PHINode*)Inst; // If it's a PHI node and only has one operand // Then replace it directly with that operand. assert(PN->getOperand(0) && "PHI Node must have at least one operand!"); if (PN->getNumOperands() == 1) { // If the PHI Node has exactly 1 operand Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace all uses of this PHI // Unlink from basic block PN->getParent()->getInstList().remove(II.getInstructionIterator()); if (PN->hasName()) V->setName(PN->getName()); // Inherit PHINode name delete PN; // Finally, delete the node... return true; } } return false; } // DoConstPropPass - Propogate constants and do constant folding on instructions // this returns true if something was changed, false if nothing was changed. // static bool DoConstPropPass(Method *M) { bool SomethingChanged = false; #if 1 Method::inst_iterator It = M->inst_begin(); while (It != M->inst_end()) if (ConstantFoldInstruction(M, It)) { SomethingChanged = true; // If returned true, iter is already incremented // Incrementing the iterator in an unchecked manner could mess up the // internals of 'It'. To make sure everything is happy, tell it we might // have broken it. It.resyncInstructionIterator(); } else { ++It; } #else for (Method::iterator BBIt = M->begin(); BBIt != M->end(); ++BBIt) { BasicBlock *BB = *BBIt; reduce_apply_bool(BB->begin(), BB->end(), bind1st(ConstantFoldInstruction, M)); } #endif return SomethingChanged; } // returns true on failure, false on success... // bool opt::DoConstantPropogation(Method *M) { bool Modified = false; // Fold constants until we make no progress... while (DoConstPropPass(M)) Modified = true; // Merge identical constants last: this is important because we may have just // introduced constants that already exist! // Modified |= DoConstantPoolMerging(M->getConstantPool()); return Modified; } <commit_msg>* Supoprt global constants * Remove support for local constant pools * Eliminate constant pool merging method, which is no longer neccesary * Disable invalid optimization (todo: fix it)<commit_after>//===- ConstantProp.cpp - Code to perform Constant Propogation ------------===// // // This file implements constant propogation and merging: // // Specifically, this: // * Folds multiple identical constants in the constant pool together // Note that if one is named and the other is not, that the result gets the // original name. // * Converts instructions like "add int %1, %2" into a direct def of %3 in // the constant pool // * Converts conditional branches on a constant boolean value into direct // branches. // * Converts phi nodes with one incoming def to the incoming def directly // . Converts switch statements with one entry into a test & conditional // branch // . Converts switches on constant values into an unconditional branch. // // Notice that: // * This pass has a habit of making definitions be dead. It is a good idea // to to run a DCE pass sometime after running this pass. // //===----------------------------------------------------------------------===// #include "llvm/Optimizations/ConstantProp.h" #include "llvm/Optimizations/ConstantHandling.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/ConstPoolVals.h" inline static bool ConstantFoldUnaryInst(Method *M, Method::inst_iterator &DI, UnaryOperator *Op, ConstPoolVal *D) { ConstPoolVal *ReplaceWith = opt::ConstantFoldUnaryInstruction(Op->getOpcode(), D); if (!ReplaceWith) return false; // Nothing new to change... // Replaces all of the uses of a variable with uses of the constant. Op->replaceAllUsesWith(ReplaceWith); // Remove the operator from the list of definitions... Op->getParent()->getInstList().remove(DI.getInstructionIterator()); // The new constant inherits the old name of the operator... if (Op->hasName()) ReplaceWith->setName(Op->getName(), M->getSymbolTableSure()); // Delete the operator now... delete Op; return true; } inline static bool ConstantFoldBinaryInst(Method *M, Method::inst_iterator &DI, BinaryOperator *Op, ConstPoolVal *D1, ConstPoolVal *D2) { ConstPoolVal *ReplaceWith = opt::ConstantFoldBinaryInstruction(Op->getOpcode(), D1, D2); if (!ReplaceWith) return false; // Nothing new to change... // Replaces all of the uses of a variable with uses of the constant. Op->replaceAllUsesWith(ReplaceWith); // Remove the operator from the list of definitions... Op->getParent()->getInstList().remove(DI.getInstructionIterator()); // The new constant inherits the old name of the operator... if (Op->hasName()) ReplaceWith->setName(Op->getName(), M->getSymbolTableSure()); // Delete the operator now... delete Op; return true; } // ConstantFoldTerminator - If a terminator instruction is predicated on a // constant value, convert it into an unconditional branch to the constant // destination. // bool opt::ConstantFoldTerminator(TerminatorInst *T) { // Branch - See if we are conditional jumping on constant if (T->getOpcode() == Instruction::Br) { BranchInst *BI = (BranchInst*)T; if (BI->isUnconditional()) return false; // Can't optimize uncond branch BasicBlock *Dest1 = BI->getOperand(0)->castBasicBlockAsserting(); BasicBlock *Dest2 = BI->getOperand(1)->castBasicBlockAsserting(); if (BI->getCondition()->isConstant()) { // Are we branching on constant? // YES. Change to unconditional branch... ConstPoolBool *Cond = (ConstPoolBool*)BI->getCondition(); BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; //cerr << "Method: " << T->getParent()->getParent() // << "\nRemoving branch from " << T->getParent() // << "\n\nTo: " << OldDest << endl; // Let the basic block know that we are letting go of it. Based on this, // it will adjust it's PHI nodes. assert(BI->getParent() && "Terminator not inserted in block!"); OldDest->removePredecessor(BI->getParent()); // Set the unconditional destination, and change the insn to be an // unconditional branch. BI->setUnconditionalDest(Destination); return true; } #if 0 // FIXME: TODO: This doesn't work if the destination has PHI nodes with // different incoming values on each branch! // else if (Dest2 == Dest1) { // Conditional branch to same location? // This branch matches something like this: // br bool %cond, label %Dest, label %Dest // and changes it into: br label %Dest // Let the basic block know that we are letting go of one copy of it. assert(BI->getParent() && "Terminator not inserted in block!"); Dest1->removePredecessor(BI->getParent()); // Change a conditional branch to unconditional. BI->setUnconditionalDest(Dest1); return true; } #endif } return false; } // ConstantFoldInstruction - If an instruction references constants, try to fold // them together... // inline static bool ConstantFoldInstruction(Method *M, Method::inst_iterator &II) { Instruction *Inst = *II; if (Inst->isBinaryOp()) { ConstPoolVal *D1 = Inst->getOperand(0)->castConstant(); ConstPoolVal *D2 = Inst->getOperand(1)->castConstant(); if (D1 && D2) return ConstantFoldBinaryInst(M, II, (BinaryOperator*)Inst, D1, D2); } else if (Inst->isUnaryOp()) { ConstPoolVal *D = Inst->getOperand(0)->castConstant(); if (D) return ConstantFoldUnaryInst(M, II, (UnaryOperator*)Inst, D); } else if (Inst->isTerminator()) { return opt::ConstantFoldTerminator((TerminatorInst*)Inst); } else if (Inst->isPHINode()) { PHINode *PN = (PHINode*)Inst; // If it's a PHI node and only has one operand // Then replace it directly with that operand. assert(PN->getOperand(0) && "PHI Node must have at least one operand!"); if (PN->getNumOperands() == 1) { // If the PHI Node has exactly 1 operand Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace all uses of this PHI // Unlink from basic block PN->getParent()->getInstList().remove(II.getInstructionIterator()); if (PN->hasName()) // Inherit PHINode name V->setName(PN->getName(), M->getSymbolTableSure()); delete PN; // Finally, delete the node... return true; } } return false; } // DoConstPropPass - Propogate constants and do constant folding on instructions // this returns true if something was changed, false if nothing was changed. // static bool DoConstPropPass(Method *M) { bool SomethingChanged = false; #if 1 Method::inst_iterator It = M->inst_begin(); while (It != M->inst_end()) if (ConstantFoldInstruction(M, It)) { SomethingChanged = true; // If returned true, iter is already incremented // Incrementing the iterator in an unchecked manner could mess up the // internals of 'It'. To make sure everything is happy, tell it we might // have broken it. It.resyncInstructionIterator(); } else { ++It; } #else for (Method::iterator BBIt = M->begin(); BBIt != M->end(); ++BBIt) { BasicBlock *BB = *BBIt; reduce_apply_bool(BB->begin(), BB->end(), bind1st(ConstantFoldInstruction, M)); } #endif return SomethingChanged; } // returns true on failure, false on success... // bool opt::DoConstantPropogation(Method *M) { bool Modified = false; // Fold constants until we make no progress... while (DoConstPropPass(M)) Modified = true; return Modified; } <|endoftext|>
<commit_before>//===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Dead Loop Deletion Pass. This pass is responsible // for eliminating loops with non-infinite computable trip counts that have no // side effects or volatile instructions, and do not contribute to the // computation of the function's return value. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "loop-delete" #include "llvm/Transforms/Scalar.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/SmallVector.h" using namespace llvm; STATISTIC(NumDeleted, "Number of loops deleted"); namespace { class VISIBILITY_HIDDEN LoopDeletion : public LoopPass { public: static char ID; // Pass ID, replacement for typeid LoopDeletion() : LoopPass(&ID) {} // Possibly eliminate loop L if it is dead. bool runOnLoop(Loop* L, LPPassManager& LPM); bool SingleDominatingExit(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks); bool IsLoopDead(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks, SmallVector<BasicBlock*, 4>& exitBlocks); bool IsLoopInvariantInst(Instruction *I, Loop* L); virtual void getAnalysisUsage(AnalysisUsage& AU) const { AU.addRequired<ScalarEvolution>(); AU.addRequired<DominatorTree>(); AU.addRequired<LoopInfo>(); AU.addRequiredID(LoopSimplifyID); AU.addRequiredID(LCSSAID); AU.addPreserved<ScalarEvolution>(); AU.addPreserved<DominatorTree>(); AU.addPreserved<LoopInfo>(); AU.addPreservedID(LoopSimplifyID); AU.addPreservedID(LCSSAID); AU.addPreserved<DominanceFrontier>(); } }; } char LoopDeletion::ID = 0; static RegisterPass<LoopDeletion> X("loop-deletion", "Delete dead loops"); Pass* llvm::createLoopDeletionPass() { return new LoopDeletion(); } /// SingleDominatingExit - Checks that there is only a single blocks that /// branches out of the loop, and that it also g the latch block. Loops /// with multiple or non-latch-dominating exiting blocks could be dead, but we'd /// have to do more extensive analysis to make sure, for instance, that the /// control flow logic involved was or could be made loop-invariant. bool LoopDeletion::SingleDominatingExit(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks) { if (exitingBlocks.size() != 1) return false; BasicBlock* latch = L->getLoopLatch(); if (!latch) return false; DominatorTree& DT = getAnalysis<DominatorTree>(); return DT.dominates(exitingBlocks[0], latch); } /// IsLoopInvariantInst - Checks if an instruction is invariant with respect to /// a loop, which is defined as being true if all of its operands are defined /// outside of the loop. These instructions can be hoisted out of the loop /// if their results are needed. This could be made more aggressive by /// recursively checking the operands for invariance, but it's not clear that /// it's worth it. bool LoopDeletion::IsLoopInvariantInst(Instruction *I, Loop* L) { // PHI nodes are not loop invariant if defined in the loop. if (isa<PHINode>(I) && L->contains(I->getParent())) return false; // The instruction is loop invariant if all of its operands are loop-invariant for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) if (!L->isLoopInvariant(I->getOperand(i))) return false; // If we got this far, the instruction is loop invariant! return true; } /// IsLoopDead - Determined if a loop is dead. This assumes that we've already /// checked for unique exit and exiting blocks, and that the code is in LCSSA /// form. bool LoopDeletion::IsLoopDead(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks, SmallVector<BasicBlock*, 4>& exitBlocks) { BasicBlock* exitingBlock = exitingBlocks[0]; BasicBlock* exitBlock = exitBlocks[0]; // Make sure that all PHI entries coming from the loop are loop invariant. // Because the code is in LCSSA form, any values used outside of the loop // must pass through a PHI in the exit block, meaning that this check is // sufficient to guarantee that no loop-variant values are used outside // of the loop. BasicBlock::iterator BI = exitBlock->begin(); while (PHINode* P = dyn_cast<PHINode>(BI)) { Value* incoming = P->getIncomingValueForBlock(exitingBlock); if (Instruction* I = dyn_cast<Instruction>(incoming)) if (!IsLoopInvariantInst(I, L)) return false; BI++; } // Make sure that no instructions in the block have potential side-effects. // This includes instructions that could write to memory, and loads that are // marked volatile. This could be made more aggressive by using aliasing // information to identify readonly and readnone calls. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) { for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE; ++BI) { if (BI->mayHaveSideEffects()) return false; } } return true; } /// runOnLoop - Remove dead loops, by which we mean loops that do not impact the /// observable behavior of the program other than finite running time. Note /// we do ensure that this never remove a loop that might be infinite, as doing /// so could change the halting/non-halting nature of a program. /// NOTE: This entire process relies pretty heavily on LoopSimplify and LCSSA /// in order to make various safety checks work. bool LoopDeletion::runOnLoop(Loop* L, LPPassManager& LPM) { // We can only remove the loop if there is a preheader that we can // branch from after removing it. BasicBlock* preheader = L->getLoopPreheader(); if (!preheader) return false; // We can't remove loops that contain subloops. If the subloops were dead, // they would already have been removed in earlier executions of this pass. if (L->begin() != L->end()) return false; SmallVector<BasicBlock*, 4> exitingBlocks; L->getExitingBlocks(exitingBlocks); SmallVector<BasicBlock*, 4> exitBlocks; L->getUniqueExitBlocks(exitBlocks); // We require that the loop only have a single exit block. Otherwise, we'd // be in the situation of needing to be able to solve statically which exit // block will be branched to, or trying to preserve the branching logic in // a loop invariant manner. if (exitBlocks.size() != 1) return false; // Loops with multiple exits or exits that don't dominate the latch // are too complicated to handle correctly. if (!SingleDominatingExit(L, exitingBlocks)) return false; // Finally, we have to check that the loop really is dead. if (!IsLoopDead(L, exitingBlocks, exitBlocks)) return false; // Don't remove loops for which we can't solve the trip count. // They could be infinite, in which case we'd be changing program behavior. ScalarEvolution& SE = getAnalysis<ScalarEvolution>(); const SCEV *S = SE.getBackedgeTakenCount(L); if (isa<SCEVCouldNotCompute>(S)) return false; // Now that we know the removal is safe, remove the loop by changing the // branch from the preheader to go to the single exit block. BasicBlock* exitBlock = exitBlocks[0]; BasicBlock* exitingBlock = exitingBlocks[0]; // Because we're deleting a large chunk of code at once, the sequence in which // we remove things is very important to avoid invalidation issues. Don't // mess with this unless you have good reason and know what you're doing. // Move simple loop-invariant expressions out of the loop, since they // might be needed by the exit phis. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE; ) { Instruction* I = BI++; if (!I->use_empty() && IsLoopInvariantInst(I, L)) I->moveBefore(preheader->getTerminator()); } // Connect the preheader directly to the exit block. TerminatorInst* TI = preheader->getTerminator(); TI->replaceUsesOfWith(L->getHeader(), exitBlock); // Rewrite phis in the exit block to get their inputs from // the preheader instead of the exiting block. BasicBlock::iterator BI = exitBlock->begin(); while (PHINode* P = dyn_cast<PHINode>(BI)) { P->replaceUsesOfWith(exitingBlock, preheader); BI++; } // Update the dominator tree and remove the instructions and blocks that will // be deleted from the reference counting scheme. DominatorTree& DT = getAnalysis<DominatorTree>(); DominanceFrontier* DF = getAnalysisIfAvailable<DominanceFrontier>(); SmallPtrSet<DomTreeNode*, 8> ChildNodes; for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) { // Move all of the block's children to be children of the preheader, which // allows us to remove the domtree entry for the block. ChildNodes.insert(DT[*LI]->begin(), DT[*LI]->end()); for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = ChildNodes.begin(), DE = ChildNodes.end(); DI != DE; ++DI) { DT.changeImmediateDominator(*DI, DT[preheader]); if (DF) DF->changeImmediateDominator((*DI)->getBlock(), preheader, &DT); } ChildNodes.clear(); DT.eraseNode(*LI); if (DF) DF->removeBlock(*LI); // Remove the block from the reference counting scheme, so that we can // delete it freely later. (*LI)->dropAllReferences(); } // Tell ScalarEvolution that the loop is deleted. Do this before // deleting the loop so that ScalarEvolution can look at the loop // to determine what it needs to clean up. SE.forgetLoopBackedgeTakenCount(L); // Erase the instructions and the blocks without having to worry // about ordering because we already dropped the references. // NOTE: This iteration is safe because erasing the block does not remove its // entry from the loop's block list. We do that in the next section. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) (*LI)->eraseFromParent(); // Finally, the blocks from loopinfo. This has to happen late because // otherwise our loop iterators won't work. LoopInfo& loopInfo = getAnalysis<LoopInfo>(); SmallPtrSet<BasicBlock*, 8> blocks; blocks.insert(L->block_begin(), L->block_end()); for (SmallPtrSet<BasicBlock*,8>::iterator I = blocks.begin(), E = blocks.end(); I != E; ++I) loopInfo.removeBlock(*I); // The last step is to inform the loop pass manager that we've // eliminated this loop. LPM.deleteLoopFromQueue(L); NumDeleted++; return true; } <commit_msg>Tell ScalarEvolution to forget a loop before starting to delete it. This way ScalarEvolution can examine the loop to determine what state it needs to update, if it chooses.<commit_after>//===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Dead Loop Deletion Pass. This pass is responsible // for eliminating loops with non-infinite computable trip counts that have no // side effects or volatile instructions, and do not contribute to the // computation of the function's return value. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "loop-delete" #include "llvm/Transforms/Scalar.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/SmallVector.h" using namespace llvm; STATISTIC(NumDeleted, "Number of loops deleted"); namespace { class VISIBILITY_HIDDEN LoopDeletion : public LoopPass { public: static char ID; // Pass ID, replacement for typeid LoopDeletion() : LoopPass(&ID) {} // Possibly eliminate loop L if it is dead. bool runOnLoop(Loop* L, LPPassManager& LPM); bool SingleDominatingExit(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks); bool IsLoopDead(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks, SmallVector<BasicBlock*, 4>& exitBlocks); bool IsLoopInvariantInst(Instruction *I, Loop* L); virtual void getAnalysisUsage(AnalysisUsage& AU) const { AU.addRequired<ScalarEvolution>(); AU.addRequired<DominatorTree>(); AU.addRequired<LoopInfo>(); AU.addRequiredID(LoopSimplifyID); AU.addRequiredID(LCSSAID); AU.addPreserved<ScalarEvolution>(); AU.addPreserved<DominatorTree>(); AU.addPreserved<LoopInfo>(); AU.addPreservedID(LoopSimplifyID); AU.addPreservedID(LCSSAID); AU.addPreserved<DominanceFrontier>(); } }; } char LoopDeletion::ID = 0; static RegisterPass<LoopDeletion> X("loop-deletion", "Delete dead loops"); Pass* llvm::createLoopDeletionPass() { return new LoopDeletion(); } /// SingleDominatingExit - Checks that there is only a single blocks that /// branches out of the loop, and that it also g the latch block. Loops /// with multiple or non-latch-dominating exiting blocks could be dead, but we'd /// have to do more extensive analysis to make sure, for instance, that the /// control flow logic involved was or could be made loop-invariant. bool LoopDeletion::SingleDominatingExit(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks) { if (exitingBlocks.size() != 1) return false; BasicBlock* latch = L->getLoopLatch(); if (!latch) return false; DominatorTree& DT = getAnalysis<DominatorTree>(); return DT.dominates(exitingBlocks[0], latch); } /// IsLoopInvariantInst - Checks if an instruction is invariant with respect to /// a loop, which is defined as being true if all of its operands are defined /// outside of the loop. These instructions can be hoisted out of the loop /// if their results are needed. This could be made more aggressive by /// recursively checking the operands for invariance, but it's not clear that /// it's worth it. bool LoopDeletion::IsLoopInvariantInst(Instruction *I, Loop* L) { // PHI nodes are not loop invariant if defined in the loop. if (isa<PHINode>(I) && L->contains(I->getParent())) return false; // The instruction is loop invariant if all of its operands are loop-invariant for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) if (!L->isLoopInvariant(I->getOperand(i))) return false; // If we got this far, the instruction is loop invariant! return true; } /// IsLoopDead - Determined if a loop is dead. This assumes that we've already /// checked for unique exit and exiting blocks, and that the code is in LCSSA /// form. bool LoopDeletion::IsLoopDead(Loop* L, SmallVector<BasicBlock*, 4>& exitingBlocks, SmallVector<BasicBlock*, 4>& exitBlocks) { BasicBlock* exitingBlock = exitingBlocks[0]; BasicBlock* exitBlock = exitBlocks[0]; // Make sure that all PHI entries coming from the loop are loop invariant. // Because the code is in LCSSA form, any values used outside of the loop // must pass through a PHI in the exit block, meaning that this check is // sufficient to guarantee that no loop-variant values are used outside // of the loop. BasicBlock::iterator BI = exitBlock->begin(); while (PHINode* P = dyn_cast<PHINode>(BI)) { Value* incoming = P->getIncomingValueForBlock(exitingBlock); if (Instruction* I = dyn_cast<Instruction>(incoming)) if (!IsLoopInvariantInst(I, L)) return false; BI++; } // Make sure that no instructions in the block have potential side-effects. // This includes instructions that could write to memory, and loads that are // marked volatile. This could be made more aggressive by using aliasing // information to identify readonly and readnone calls. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) { for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE; ++BI) { if (BI->mayHaveSideEffects()) return false; } } return true; } /// runOnLoop - Remove dead loops, by which we mean loops that do not impact the /// observable behavior of the program other than finite running time. Note /// we do ensure that this never remove a loop that might be infinite, as doing /// so could change the halting/non-halting nature of a program. /// NOTE: This entire process relies pretty heavily on LoopSimplify and LCSSA /// in order to make various safety checks work. bool LoopDeletion::runOnLoop(Loop* L, LPPassManager& LPM) { // We can only remove the loop if there is a preheader that we can // branch from after removing it. BasicBlock* preheader = L->getLoopPreheader(); if (!preheader) return false; // We can't remove loops that contain subloops. If the subloops were dead, // they would already have been removed in earlier executions of this pass. if (L->begin() != L->end()) return false; SmallVector<BasicBlock*, 4> exitingBlocks; L->getExitingBlocks(exitingBlocks); SmallVector<BasicBlock*, 4> exitBlocks; L->getUniqueExitBlocks(exitBlocks); // We require that the loop only have a single exit block. Otherwise, we'd // be in the situation of needing to be able to solve statically which exit // block will be branched to, or trying to preserve the branching logic in // a loop invariant manner. if (exitBlocks.size() != 1) return false; // Loops with multiple exits or exits that don't dominate the latch // are too complicated to handle correctly. if (!SingleDominatingExit(L, exitingBlocks)) return false; // Finally, we have to check that the loop really is dead. if (!IsLoopDead(L, exitingBlocks, exitBlocks)) return false; // Don't remove loops for which we can't solve the trip count. // They could be infinite, in which case we'd be changing program behavior. ScalarEvolution& SE = getAnalysis<ScalarEvolution>(); const SCEV *S = SE.getBackedgeTakenCount(L); if (isa<SCEVCouldNotCompute>(S)) return false; // Now that we know the removal is safe, remove the loop by changing the // branch from the preheader to go to the single exit block. BasicBlock* exitBlock = exitBlocks[0]; BasicBlock* exitingBlock = exitingBlocks[0]; // Because we're deleting a large chunk of code at once, the sequence in which // we remove things is very important to avoid invalidation issues. Don't // mess with this unless you have good reason and know what you're doing. // Tell ScalarEvolution that the loop is deleted. Do this before // deleting the loop so that ScalarEvolution can look at the loop // to determine what it needs to clean up. SE.forgetLoopBackedgeTakenCount(L); // Move simple loop-invariant expressions out of the loop, since they // might be needed by the exit phis. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE; ) { Instruction* I = BI++; if (!I->use_empty() && IsLoopInvariantInst(I, L)) I->moveBefore(preheader->getTerminator()); } // Connect the preheader directly to the exit block. TerminatorInst* TI = preheader->getTerminator(); TI->replaceUsesOfWith(L->getHeader(), exitBlock); // Rewrite phis in the exit block to get their inputs from // the preheader instead of the exiting block. BasicBlock::iterator BI = exitBlock->begin(); while (PHINode* P = dyn_cast<PHINode>(BI)) { P->replaceUsesOfWith(exitingBlock, preheader); BI++; } // Update the dominator tree and remove the instructions and blocks that will // be deleted from the reference counting scheme. DominatorTree& DT = getAnalysis<DominatorTree>(); DominanceFrontier* DF = getAnalysisIfAvailable<DominanceFrontier>(); SmallPtrSet<DomTreeNode*, 8> ChildNodes; for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) { // Move all of the block's children to be children of the preheader, which // allows us to remove the domtree entry for the block. ChildNodes.insert(DT[*LI]->begin(), DT[*LI]->end()); for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = ChildNodes.begin(), DE = ChildNodes.end(); DI != DE; ++DI) { DT.changeImmediateDominator(*DI, DT[preheader]); if (DF) DF->changeImmediateDominator((*DI)->getBlock(), preheader, &DT); } ChildNodes.clear(); DT.eraseNode(*LI); if (DF) DF->removeBlock(*LI); // Remove the block from the reference counting scheme, so that we can // delete it freely later. (*LI)->dropAllReferences(); } // Erase the instructions and the blocks without having to worry // about ordering because we already dropped the references. // NOTE: This iteration is safe because erasing the block does not remove its // entry from the loop's block list. We do that in the next section. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) (*LI)->eraseFromParent(); // Finally, the blocks from loopinfo. This has to happen late because // otherwise our loop iterators won't work. LoopInfo& loopInfo = getAnalysis<LoopInfo>(); SmallPtrSet<BasicBlock*, 8> blocks; blocks.insert(L->block_begin(), L->block_end()); for (SmallPtrSet<BasicBlock*,8>::iterator I = blocks.begin(), E = blocks.end(); I != E; ++I) loopInfo.removeBlock(*I); // The last step is to inform the loop pass manager that we've // eliminated this loop. LPM.deleteLoopFromQueue(L); NumDeleted++; return true; } <|endoftext|>
<commit_before>//===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Dead Loop Deletion Pass. This pass is responsible // for eliminating loops with non-infinite computable trip counts that have no // side effects or volatile instructions, and do not contribute to the // computation of the function's return value. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/LoopDeletion.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/PatternMatch.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar/LoopPassManager.h" #include "llvm/Transforms/Utils/LoopUtils.h" using namespace llvm; #define DEBUG_TYPE "loop-delete" STATISTIC(NumDeleted, "Number of loops deleted"); /// This function deletes dead loops. The caller of this function needs to /// guarantee that the loop is infact dead. Here we handle two kinds of dead /// loop. The first kind (\p isLoopDead) is where only invariant values from /// within the loop are used outside of it. The second kind (\p /// isLoopNeverExecuted) is where the loop is provably never executed. We can /// always remove never executed loops since they will not cause any difference /// to program behaviour. /// /// This also updates the relevant analysis information in \p DT, \p SE, and \p /// LI. It also updates the loop PM if an updater struct is provided. // TODO: This function will be used by loop-simplifyCFG as well. So, move this // to LoopUtils.cpp static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, LPMUpdater *Updater = nullptr); /// Determines if a loop is dead. /// /// This assumes that we've already checked for unique exit and exiting blocks, /// and that the code is in LCSSA form. static bool isLoopDead(Loop *L, ScalarEvolution &SE, SmallVectorImpl<BasicBlock *> &ExitingBlocks, BasicBlock *ExitBlock, bool &Changed, BasicBlock *Preheader) { // Make sure that all PHI entries coming from the loop are loop invariant. // Because the code is in LCSSA form, any values used outside of the loop // must pass through a PHI in the exit block, meaning that this check is // sufficient to guarantee that no loop-variant values are used outside // of the loop. BasicBlock::iterator BI = ExitBlock->begin(); bool AllEntriesInvariant = true; bool AllOutgoingValuesSame = true; while (PHINode *P = dyn_cast<PHINode>(BI)) { Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); // Make sure all exiting blocks produce the same incoming value for the exit // block. If there are different incoming values for different exiting // blocks, then it is impossible to statically determine which value should // be used. AllOutgoingValuesSame = all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) { return incoming == P->getIncomingValueForBlock(BB); }); if (!AllOutgoingValuesSame) break; if (Instruction *I = dyn_cast<Instruction>(incoming)) if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) { AllEntriesInvariant = false; break; } ++BI; } if (Changed) SE.forgetLoopDispositions(L); if (!AllEntriesInvariant || !AllOutgoingValuesSame) return false; // Make sure that no instructions in the block have potential side-effects. // This includes instructions that could write to memory, and loads that are // marked volatile. for (auto &I : L->blocks()) if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); })) return false; return true; } /// This function returns true if there is no viable path from the /// entry block to the header of \p L. Right now, it only does /// a local search to save compile time. static bool isLoopNeverExecuted(Loop *L) { using namespace PatternMatch; auto *Preheader = L->getLoopPreheader(); // TODO: We can relax this constraint, since we just need a loop // predecessor. assert(Preheader && "Needs preheader!"); if (Preheader == &Preheader->getParent()->getEntryBlock()) return false; // All predecessors of the preheader should have a constant conditional // branch, with the loop's preheader as not-taken. for (auto *Pred: predecessors(Preheader)) { BasicBlock *Taken, *NotTaken; ConstantInt *Cond; if (!match(Pred->getTerminator(), m_Br(m_ConstantInt(Cond), Taken, NotTaken))) return false; if (!Cond->getZExtValue()) std::swap(Taken, NotTaken); if (Taken == Preheader) return false; } assert(!pred_empty(Preheader) && "Preheader should have predecessors at this point!"); // All the predecessors have the loop preheader as not-taken target. return true; } /// Remove a loop if it is dead. /// /// A loop is considered dead if it does not impact the observable behavior of /// the program other than finite running time. This never removes a loop that /// might be infinite (unless it is never executed), as doing so could change /// the halting/non-halting nature of a program. /// /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in /// order to make various safety checks work. /// /// \returns true if any changes were made. This may mutate the loop even if it /// is unable to delete it due to hoisting trivially loop invariant /// instructions out of the loop. static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, LPMUpdater *Updater = nullptr) { assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); // We can only remove the loop if there is a preheader that we can branch from // after removing it. Also, if LoopSimplify form is not available, stay out // of trouble. BasicBlock *Preheader = L->getLoopPreheader(); if (!Preheader || !L->hasDedicatedExits()) { DEBUG(dbgs() << "Deletion requires Loop with preheader and dedicated exits.\n"); return false; } // We can't remove loops that contain subloops. If the subloops were dead, // they would already have been removed in earlier executions of this pass. if (L->begin() != L->end()) { DEBUG(dbgs() << "Loop contains subloops.\n"); return false; } BasicBlock *ExitBlock = L->getUniqueExitBlock(); if (ExitBlock && isLoopNeverExecuted(L)) { DEBUG(dbgs() << "Loop is proven to never execute, delete it!"); // Set incoming value to undef for phi nodes in the exit block. BasicBlock::iterator BI = ExitBlock->begin(); while (PHINode *P = dyn_cast<PHINode>(BI)) { for (unsigned i = 0; i < P->getNumIncomingValues(); i++) P->setIncomingValue(i, UndefValue::get(P->getType())); BI++; } deleteDeadLoop(L, DT, SE, LI, Updater); ++NumDeleted; return true; } // The remaining checks below are for a loop being dead because all statements // in the loop are invariant. SmallVector<BasicBlock *, 4> ExitingBlocks; L->getExitingBlocks(ExitingBlocks); // We require that the loop only have a single exit block. Otherwise, we'd // be in the situation of needing to be able to solve statically which exit // block will be branched to, or trying to preserve the branching logic in // a loop invariant manner. if (!ExitBlock) { DEBUG(dbgs() << "Deletion requires single exit block\n"); return false; } // Finally, we have to check that the loop really is dead. bool Changed = false; if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) { DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n"); return Changed; } // Don't remove loops for which we can't solve the trip count. // They could be infinite, in which case we'd be changing program behavior. const SCEV *S = SE.getMaxBackedgeTakenCount(L); if (isa<SCEVCouldNotCompute>(S)) { DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n"); return Changed; } DEBUG(dbgs() << "Loop is invariant, delete it!"); deleteDeadLoop(L, DT, SE, LI, Updater); ++NumDeleted; return true; } static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, LPMUpdater *Updater) { assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); auto *Preheader = L->getLoopPreheader(); assert(Preheader && "Preheader should exist!"); // Now that we know the removal is safe, remove the loop by changing the // branch from the preheader to go to the single exit block. // // Because we're deleting a large chunk of code at once, the sequence in which // we remove things is very important to avoid invalidation issues. // If we have an LPM updater, tell it about the loop being removed. if (Updater) Updater->markLoopAsDeleted(*L); // Tell ScalarEvolution that the loop is deleted. Do this before // deleting the loop so that ScalarEvolution can look at the loop // to determine what it needs to clean up. SE.forgetLoop(L); auto *ExitBlock = L->getUniqueExitBlock(); assert(ExitBlock && "Should have a unique exit block!"); assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); // Connect the preheader directly to the exit block. // Even when the loop is never executed, we cannot remove the edge from the // source block to the exit block. Consider the case where the unexecuted loop // branches back to an outer loop. If we deleted the loop and removed the edge // coming to this inner loop, this will break the outer loop structure (by // deleting the backedge of the outer loop). If the outer loop is indeed a // non-loop, it will be deleted in a future iteration of loop deletion pass. Preheader->getTerminator()->replaceUsesOfWith(L->getHeader(), ExitBlock); // Rewrite phis in the exit block to get their inputs from the Preheader // instead of the exiting block. BasicBlock::iterator BI = ExitBlock->begin(); while (PHINode *P = dyn_cast<PHINode>(BI)) { // Set the zero'th element of Phi to be from the preheader and remove all // other incoming values. Given the loop has dedicated exits, all other // incoming values must be from the exiting blocks. int PredIndex = 0; P->setIncomingBlock(PredIndex, Preheader); // Removes all incoming values from all other exiting blocks (including // duplicate values from an exiting block). // Nuke all entries except the zero'th entry which is the preheader entry. // NOTE! We need to remove Incoming Values in the reverse order as done // below, to keep the indices valid for deletion (removeIncomingValues // updates getNumIncomingValues and shifts all values down into the operand // being deleted). for (unsigned i = 0, e = P->getNumIncomingValues() - 1; i != e; ++i) P->removeIncomingValue(e-i, false); assert((P->getNumIncomingValues() == 1 && P->getIncomingBlock(PredIndex) == Preheader) && "Should have exactly one value and that's from the preheader!"); ++BI; } // Update the dominator tree and remove the instructions and blocks that will // be deleted from the reference counting scheme. SmallVector<DomTreeNode*, 8> ChildNodes; for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) { // Move all of the block's children to be children of the Preheader, which // allows us to remove the domtree entry for the block. ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end()); for (DomTreeNode *ChildNode : ChildNodes) { DT.changeImmediateDominator(ChildNode, DT[Preheader]); } ChildNodes.clear(); DT.eraseNode(*LI); // Remove the block from the reference counting scheme, so that we can // delete it freely later. (*LI)->dropAllReferences(); } // Erase the instructions and the blocks without having to worry // about ordering because we already dropped the references. // NOTE: This iteration is safe because erasing the block does not remove its // entry from the loop's block list. We do that in the next section. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) (*LI)->eraseFromParent(); // Finally, the blocks from loopinfo. This has to happen late because // otherwise our loop iterators won't work. SmallPtrSet<BasicBlock *, 8> blocks; blocks.insert(L->block_begin(), L->block_end()); for (BasicBlock *BB : blocks) LI.removeBlock(BB); // The last step is to update LoopInfo now that we've eliminated this loop. LI.markAsRemoved(L); } PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &Updater) { DEBUG(dbgs() << "Analyzing Loop for deletion: "); DEBUG(L.dump()); if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater)) return PreservedAnalyses::all(); return getLoopPassPreservedAnalyses(); } namespace { class LoopDeletionLegacyPass : public LoopPass { public: static char ID; // Pass ID, replacement for typeid LoopDeletionLegacyPass() : LoopPass(ID) { initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry()); } // Possibly eliminate loop L if it is dead. bool runOnLoop(Loop *L, LPPassManager &) override; void getAnalysisUsage(AnalysisUsage &AU) const override { getLoopAnalysisUsage(AU); } }; } char LoopDeletionLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion", "Delete dead loops", false, false) INITIALIZE_PASS_DEPENDENCY(LoopPass) INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion", "Delete dead loops", false, false) Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); } bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) { if (skipLoop(L)) return false; DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); return deleteLoopIfDead(L, DT, SE, LI); } <commit_msg>[LoopDeletion] NFC: Add loop being analyzed debug statement<commit_after>//===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Dead Loop Deletion Pass. This pass is responsible // for eliminating loops with non-infinite computable trip counts that have no // side effects or volatile instructions, and do not contribute to the // computation of the function's return value. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/LoopDeletion.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/PatternMatch.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar/LoopPassManager.h" #include "llvm/Transforms/Utils/LoopUtils.h" using namespace llvm; #define DEBUG_TYPE "loop-delete" STATISTIC(NumDeleted, "Number of loops deleted"); /// This function deletes dead loops. The caller of this function needs to /// guarantee that the loop is infact dead. Here we handle two kinds of dead /// loop. The first kind (\p isLoopDead) is where only invariant values from /// within the loop are used outside of it. The second kind (\p /// isLoopNeverExecuted) is where the loop is provably never executed. We can /// always remove never executed loops since they will not cause any difference /// to program behaviour. /// /// This also updates the relevant analysis information in \p DT, \p SE, and \p /// LI. It also updates the loop PM if an updater struct is provided. // TODO: This function will be used by loop-simplifyCFG as well. So, move this // to LoopUtils.cpp static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, LPMUpdater *Updater = nullptr); /// Determines if a loop is dead. /// /// This assumes that we've already checked for unique exit and exiting blocks, /// and that the code is in LCSSA form. static bool isLoopDead(Loop *L, ScalarEvolution &SE, SmallVectorImpl<BasicBlock *> &ExitingBlocks, BasicBlock *ExitBlock, bool &Changed, BasicBlock *Preheader) { // Make sure that all PHI entries coming from the loop are loop invariant. // Because the code is in LCSSA form, any values used outside of the loop // must pass through a PHI in the exit block, meaning that this check is // sufficient to guarantee that no loop-variant values are used outside // of the loop. BasicBlock::iterator BI = ExitBlock->begin(); bool AllEntriesInvariant = true; bool AllOutgoingValuesSame = true; while (PHINode *P = dyn_cast<PHINode>(BI)) { Value *incoming = P->getIncomingValueForBlock(ExitingBlocks[0]); // Make sure all exiting blocks produce the same incoming value for the exit // block. If there are different incoming values for different exiting // blocks, then it is impossible to statically determine which value should // be used. AllOutgoingValuesSame = all_of(makeArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) { return incoming == P->getIncomingValueForBlock(BB); }); if (!AllOutgoingValuesSame) break; if (Instruction *I = dyn_cast<Instruction>(incoming)) if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator())) { AllEntriesInvariant = false; break; } ++BI; } if (Changed) SE.forgetLoopDispositions(L); if (!AllEntriesInvariant || !AllOutgoingValuesSame) return false; // Make sure that no instructions in the block have potential side-effects. // This includes instructions that could write to memory, and loads that are // marked volatile. for (auto &I : L->blocks()) if (any_of(*I, [](Instruction &I) { return I.mayHaveSideEffects(); })) return false; return true; } /// This function returns true if there is no viable path from the /// entry block to the header of \p L. Right now, it only does /// a local search to save compile time. static bool isLoopNeverExecuted(Loop *L) { using namespace PatternMatch; auto *Preheader = L->getLoopPreheader(); // TODO: We can relax this constraint, since we just need a loop // predecessor. assert(Preheader && "Needs preheader!"); if (Preheader == &Preheader->getParent()->getEntryBlock()) return false; // All predecessors of the preheader should have a constant conditional // branch, with the loop's preheader as not-taken. for (auto *Pred: predecessors(Preheader)) { BasicBlock *Taken, *NotTaken; ConstantInt *Cond; if (!match(Pred->getTerminator(), m_Br(m_ConstantInt(Cond), Taken, NotTaken))) return false; if (!Cond->getZExtValue()) std::swap(Taken, NotTaken); if (Taken == Preheader) return false; } assert(!pred_empty(Preheader) && "Preheader should have predecessors at this point!"); // All the predecessors have the loop preheader as not-taken target. return true; } /// Remove a loop if it is dead. /// /// A loop is considered dead if it does not impact the observable behavior of /// the program other than finite running time. This never removes a loop that /// might be infinite (unless it is never executed), as doing so could change /// the halting/non-halting nature of a program. /// /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in /// order to make various safety checks work. /// /// \returns true if any changes were made. This may mutate the loop even if it /// is unable to delete it due to hoisting trivially loop invariant /// instructions out of the loop. static bool deleteLoopIfDead(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, LPMUpdater *Updater = nullptr) { assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); // We can only remove the loop if there is a preheader that we can branch from // after removing it. Also, if LoopSimplify form is not available, stay out // of trouble. BasicBlock *Preheader = L->getLoopPreheader(); if (!Preheader || !L->hasDedicatedExits()) { DEBUG(dbgs() << "Deletion requires Loop with preheader and dedicated exits.\n"); return false; } // We can't remove loops that contain subloops. If the subloops were dead, // they would already have been removed in earlier executions of this pass. if (L->begin() != L->end()) { DEBUG(dbgs() << "Loop contains subloops.\n"); return false; } BasicBlock *ExitBlock = L->getUniqueExitBlock(); if (ExitBlock && isLoopNeverExecuted(L)) { DEBUG(dbgs() << "Loop is proven to never execute, delete it!"); // Set incoming value to undef for phi nodes in the exit block. BasicBlock::iterator BI = ExitBlock->begin(); while (PHINode *P = dyn_cast<PHINode>(BI)) { for (unsigned i = 0; i < P->getNumIncomingValues(); i++) P->setIncomingValue(i, UndefValue::get(P->getType())); BI++; } deleteDeadLoop(L, DT, SE, LI, Updater); ++NumDeleted; return true; } // The remaining checks below are for a loop being dead because all statements // in the loop are invariant. SmallVector<BasicBlock *, 4> ExitingBlocks; L->getExitingBlocks(ExitingBlocks); // We require that the loop only have a single exit block. Otherwise, we'd // be in the situation of needing to be able to solve statically which exit // block will be branched to, or trying to preserve the branching logic in // a loop invariant manner. if (!ExitBlock) { DEBUG(dbgs() << "Deletion requires single exit block\n"); return false; } // Finally, we have to check that the loop really is dead. bool Changed = false; if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader)) { DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n"); return Changed; } // Don't remove loops for which we can't solve the trip count. // They could be infinite, in which case we'd be changing program behavior. const SCEV *S = SE.getMaxBackedgeTakenCount(L); if (isa<SCEVCouldNotCompute>(S)) { DEBUG(dbgs() << "Could not compute SCEV MaxBackedgeTakenCount.\n"); return Changed; } DEBUG(dbgs() << "Loop is invariant, delete it!"); deleteDeadLoop(L, DT, SE, LI, Updater); ++NumDeleted; return true; } static void deleteDeadLoop(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, LPMUpdater *Updater) { assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); auto *Preheader = L->getLoopPreheader(); assert(Preheader && "Preheader should exist!"); // Now that we know the removal is safe, remove the loop by changing the // branch from the preheader to go to the single exit block. // // Because we're deleting a large chunk of code at once, the sequence in which // we remove things is very important to avoid invalidation issues. // If we have an LPM updater, tell it about the loop being removed. if (Updater) Updater->markLoopAsDeleted(*L); // Tell ScalarEvolution that the loop is deleted. Do this before // deleting the loop so that ScalarEvolution can look at the loop // to determine what it needs to clean up. SE.forgetLoop(L); auto *ExitBlock = L->getUniqueExitBlock(); assert(ExitBlock && "Should have a unique exit block!"); assert(L->hasDedicatedExits() && "Loop should have dedicated exits!"); // Connect the preheader directly to the exit block. // Even when the loop is never executed, we cannot remove the edge from the // source block to the exit block. Consider the case where the unexecuted loop // branches back to an outer loop. If we deleted the loop and removed the edge // coming to this inner loop, this will break the outer loop structure (by // deleting the backedge of the outer loop). If the outer loop is indeed a // non-loop, it will be deleted in a future iteration of loop deletion pass. Preheader->getTerminator()->replaceUsesOfWith(L->getHeader(), ExitBlock); // Rewrite phis in the exit block to get their inputs from the Preheader // instead of the exiting block. BasicBlock::iterator BI = ExitBlock->begin(); while (PHINode *P = dyn_cast<PHINode>(BI)) { // Set the zero'th element of Phi to be from the preheader and remove all // other incoming values. Given the loop has dedicated exits, all other // incoming values must be from the exiting blocks. int PredIndex = 0; P->setIncomingBlock(PredIndex, Preheader); // Removes all incoming values from all other exiting blocks (including // duplicate values from an exiting block). // Nuke all entries except the zero'th entry which is the preheader entry. // NOTE! We need to remove Incoming Values in the reverse order as done // below, to keep the indices valid for deletion (removeIncomingValues // updates getNumIncomingValues and shifts all values down into the operand // being deleted). for (unsigned i = 0, e = P->getNumIncomingValues() - 1; i != e; ++i) P->removeIncomingValue(e-i, false); assert((P->getNumIncomingValues() == 1 && P->getIncomingBlock(PredIndex) == Preheader) && "Should have exactly one value and that's from the preheader!"); ++BI; } // Update the dominator tree and remove the instructions and blocks that will // be deleted from the reference counting scheme. SmallVector<DomTreeNode*, 8> ChildNodes; for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) { // Move all of the block's children to be children of the Preheader, which // allows us to remove the domtree entry for the block. ChildNodes.insert(ChildNodes.begin(), DT[*LI]->begin(), DT[*LI]->end()); for (DomTreeNode *ChildNode : ChildNodes) { DT.changeImmediateDominator(ChildNode, DT[Preheader]); } ChildNodes.clear(); DT.eraseNode(*LI); // Remove the block from the reference counting scheme, so that we can // delete it freely later. (*LI)->dropAllReferences(); } // Erase the instructions and the blocks without having to worry // about ordering because we already dropped the references. // NOTE: This iteration is safe because erasing the block does not remove its // entry from the loop's block list. We do that in the next section. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end(); LI != LE; ++LI) (*LI)->eraseFromParent(); // Finally, the blocks from loopinfo. This has to happen late because // otherwise our loop iterators won't work. SmallPtrSet<BasicBlock *, 8> blocks; blocks.insert(L->block_begin(), L->block_end()); for (BasicBlock *BB : blocks) LI.removeBlock(BB); // The last step is to update LoopInfo now that we've eliminated this loop. LI.markAsRemoved(L); } PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &Updater) { DEBUG(dbgs() << "Analyzing Loop for deletion: "); DEBUG(L.dump()); if (!deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, &Updater)) return PreservedAnalyses::all(); return getLoopPassPreservedAnalyses(); } namespace { class LoopDeletionLegacyPass : public LoopPass { public: static char ID; // Pass ID, replacement for typeid LoopDeletionLegacyPass() : LoopPass(ID) { initializeLoopDeletionLegacyPassPass(*PassRegistry::getPassRegistry()); } // Possibly eliminate loop L if it is dead. bool runOnLoop(Loop *L, LPPassManager &) override; void getAnalysisUsage(AnalysisUsage &AU) const override { getLoopAnalysisUsage(AU); } }; } char LoopDeletionLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(LoopDeletionLegacyPass, "loop-deletion", "Delete dead loops", false, false) INITIALIZE_PASS_DEPENDENCY(LoopPass) INITIALIZE_PASS_END(LoopDeletionLegacyPass, "loop-deletion", "Delete dead loops", false, false) Pass *llvm::createLoopDeletionPass() { return new LoopDeletionLegacyPass(); } bool LoopDeletionLegacyPass::runOnLoop(Loop *L, LPPassManager &) { if (skipLoop(L)) return false; DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); DEBUG(dbgs() << "Analyzing Loop for deletion: "); DEBUG(L->dump()); return deleteLoopIfDead(L, DT, SE, LI); } <|endoftext|>
<commit_before>#include "netlink.hpp" #define mnl_attr_for_each_cpp(attr, nlh, offset) \ for ((attr) = (struct nlattr*) mnl_nlmsg_get_payload_offset((nlh), (offset)); \ mnl_attr_ok((attr), (char *)mnl_nlmsg_get_payload_tail(nlh) - (char *)(attr)); \ (attr) = mnl_attr_next(attr)) using namespace std; // Adapted from: // https://git.netfilter.org/libmnl/plain/examples/rtnl/rtnl-link-dump3.c static int data_cb_ip(const struct nlmsghdr *nlh, void *data) { struct ifaddrmsg *ifm = (struct ifaddrmsg *) mnl_nlmsg_get_payload(nlh); struct nlattr *attr; vector<interface>* interfaces = static_cast<vector<interface>*>(data); uint32_t index = ifm->ifa_index; auto it = find_if(interfaces->begin(), interfaces->end(), [index](interface& i){ return i == index; }); interface& interface = (it == interfaces->end()) ? *interfaces->emplace(interfaces->end()) : *it; interface.netlinkIndex = index; mnl_attr_for_each_cpp(attr, nlh, sizeof(*ifm)) { int type = mnl_attr_get_type(attr); /* skip unsupported attribute in user-space */ if (mnl_attr_type_valid(attr, IFLA_MAX) < 0) continue; switch(type) { case IFA_ADDRESS: if (mnl_attr_validate(attr, MNL_TYPE_BINARY) < 0) { logErr("mnl_attr_validate() failed"); return MNL_CB_ERROR; } interface.IPs.push_back(htonl(mnl_attr_get_u32(attr))); break; case IFA_LABEL: if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0) { logErr("mnl_attr_validate() failed"); return MNL_CB_ERROR; } interface.name = mnl_attr_get_str(attr); break; } } return MNL_CB_OK; } // Adapted from: // https://git.netfilter.org/libmnl/plain/examples/rtnl/rtnl-link-dump3.c static int data_cb_link(const struct nlmsghdr *nlh, void *data) { struct ifinfomsg *ifm = (struct ifinfomsg*) mnl_nlmsg_get_payload(nlh); struct nlattr *attr; vector<interface>* interfaces = static_cast<vector<interface>*>(data); uint32_t index = ifm->ifi_index; auto it = find_if(interfaces->begin(), interfaces->end(), [index](interface& i){ return i == index; }); interface& interface = (it == interfaces->end()) ? *interfaces->emplace(interfaces->end()) : *it; interface.netlinkIndex = index; mnl_attr_for_each_cpp(attr, nlh, sizeof(*ifm)) { int type = mnl_attr_get_type(attr); /* skip unsupported attribute in user-space */ if (mnl_attr_type_valid(attr, IFLA_MAX) < 0) continue; switch(type) { case IFLA_ADDRESS: memcpy(&interface.mac, RTA_DATA(attr), 6); break; } } return MNL_CB_OK; } // Adapted from: // https://git.netfilter.org/libmnl/plain/examples/rtnl/rtnl-link-dump3.c shared_ptr<vector<interface>> Netlink::getAllInterfaces() { struct mnl_socket *nl; char buf[MNL_SOCKET_BUFFER_SIZE]; struct nlmsghdr *nlh; struct rtgenmsg *rt; int ret; unsigned int seq, portid; shared_ptr<vector<interface>> interfaces = make_shared<vector<interface>>(); // Open NL socket nl = mnl_socket_open(NETLINK_ROUTE); if (nl == NULL) { fatal("mnl_socket_open() failed"); } if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) { fatal("mnl_socket_bind() failed"); } portid = mnl_socket_get_portid(nl); // do "ip a" nlh = mnl_nlmsg_put_header(buf); nlh->nlmsg_type = RTM_GETADDR; nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; nlh->nlmsg_seq = seq = time(NULL); rt = (struct rtgenmsg *) mnl_nlmsg_put_extra_header(nlh, sizeof(struct rtgenmsg)); rt->rtgen_family = AF_PACKET; if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) { fatal("mnl_socket_sendto() failed"); } ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); while (ret > 0) { ret = mnl_cb_run(buf, ret, seq, portid, data_cb_ip, interfaces.get()); if (ret <= MNL_CB_STOP) break; ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); } if (ret == -1) { fatal("mnl_socket_recvfrom() failed"); } // do "ip l" nlh = mnl_nlmsg_put_header(buf); nlh->nlmsg_type = RTM_GETLINK; nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; nlh->nlmsg_seq = seq = time(NULL); rt = (struct rtgenmsg *) mnl_nlmsg_put_extra_header(nlh, sizeof(struct rtgenmsg)); rt->rtgen_family = AF_PACKET; if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) { fatal("mnl_socket_sendto"); } ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); while (ret > 0) { ret = mnl_cb_run(buf, ret, seq, portid, data_cb_link, interfaces.get()); if (ret <= MNL_CB_STOP) break; ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); } if (ret == -1) { fatal("mnl_socket_recvfrom() failed"); } mnl_socket_close(nl); stringstream sstream; sstream << "Interfaces:" << endl; for(auto i : *interfaces){ sstream << "\tName: " << i.name << endl; sstream << "\tMAC address: " << mac_to_str(i.mac) << endl; sstream << "\tNetlink Index: " << i.netmapIndex << endl; sstream << "\tIP addresses:" << endl; for(auto ip : i.IPs) { sstream << "\t\t" << ip_to_str(ip) << endl; } } logInfo(sstream.str()); return interfaces; } <commit_msg>fix Netlink class<commit_after>#include "netlink.hpp" #define mnl_attr_for_each_cpp(attr, nlh, offset) \ for ((attr) = (struct nlattr*) mnl_nlmsg_get_payload_offset((nlh), (offset)); \ mnl_attr_ok((attr), (char *)mnl_nlmsg_get_payload_tail(nlh) - (char *)(attr)); \ (attr) = mnl_attr_next(attr)) using namespace std; // Adapted from: // https://git.netfilter.org/libmnl/plain/examples/rtnl/rtnl-link-dump3.c static int data_cb_ip(const struct nlmsghdr *nlh, void *data) { struct ifaddrmsg *ifa = (struct ifaddrmsg *) mnl_nlmsg_get_payload(nlh); struct nlattr *attr; vector<interface>* interfaces = static_cast<vector<interface>*>(data); uint32_t index = ifa->ifa_index; auto it = find_if(interfaces->begin(), interfaces->end(), [index](interface& i){ return i.netlinkIndex == index; }); interface& interface = (it == interfaces->end()) ? *interfaces->emplace(interfaces->end()) : *it; interface.netlinkIndex = index; mnl_attr_for_each_cpp(attr, nlh, sizeof(*ifa)) { int type = mnl_attr_get_type(attr); /* skip unsupported attribute in user-space */ if (mnl_attr_type_valid(attr, IFLA_MAX) < 0) continue; switch(type) { case IFA_ADDRESS: if (mnl_attr_validate(attr, MNL_TYPE_BINARY) < 0) { logErr("mnl_attr_validate() failed"); return MNL_CB_ERROR; } interface.IPs.push_back(htonl(mnl_attr_get_u32(attr))); break; case IFA_LABEL: if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0) { logErr("mnl_attr_validate() failed"); return MNL_CB_ERROR; } interface.name = mnl_attr_get_str(attr); break; } } return MNL_CB_OK; } // Adapted from: // https://git.netfilter.org/libmnl/plain/examples/rtnl/rtnl-link-dump3.c static int data_cb_link(const struct nlmsghdr *nlh, void *data) { struct ifinfomsg *ifm = (struct ifinfomsg*) mnl_nlmsg_get_payload(nlh); struct nlattr *attr; vector<interface>* interfaces = static_cast<vector<interface>*>(data); uint32_t index = ifm->ifi_index; auto it = find_if(interfaces->begin(), interfaces->end(), [index](interface& i){ return i.netlinkIndex == index; }); interface& interface = (it == interfaces->end()) ? *interfaces->emplace(interfaces->end()) : *it; interface.netlinkIndex = index; mnl_attr_for_each_cpp(attr, nlh, sizeof(*ifm)) { int type = mnl_attr_get_type(attr); /* skip unsupported attribute in user-space */ if (mnl_attr_type_valid(attr, IFLA_MAX) < 0) continue; switch(type) { case IFLA_ADDRESS: memcpy(&interface.mac, RTA_DATA(attr), 6); break; case IFA_LABEL: if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0) { logErr("mnl_attr_validate() failed"); return MNL_CB_ERROR; } interface.name = mnl_attr_get_str(attr); break; } } return MNL_CB_OK; } // Adapted from: // https://git.netfilter.org/libmnl/plain/examples/rtnl/rtnl-link-dump3.c shared_ptr<vector<interface>> Netlink::getAllInterfaces() { struct mnl_socket *nl; char buf[MNL_SOCKET_BUFFER_SIZE]; struct nlmsghdr *nlh; struct rtgenmsg *rt; int ret; unsigned int seq, portid; shared_ptr<vector<interface>> interfaces = make_shared<vector<interface>>(); // Open NL socket nl = mnl_socket_open(NETLINK_ROUTE); if (nl == NULL) { fatal("mnl_socket_open() failed"); } if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) { fatal("mnl_socket_bind() failed"); } portid = mnl_socket_get_portid(nl); // do "ip a" nlh = mnl_nlmsg_put_header(buf); nlh->nlmsg_type = RTM_GETADDR; nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; nlh->nlmsg_seq = seq = time(NULL); rt = (struct rtgenmsg *) mnl_nlmsg_put_extra_header(nlh, sizeof(struct rtgenmsg)); rt->rtgen_family = AF_INET; if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) { fatal("mnl_socket_sendto() failed"); } ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); while (ret > 0) { ret = mnl_cb_run(buf, ret, seq, portid, data_cb_ip, interfaces.get()); if (ret <= MNL_CB_STOP) break; ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); } if (ret == -1) { fatal("mnl_socket_recvfrom() failed"); } // do "ip l" nlh = mnl_nlmsg_put_header(buf); nlh->nlmsg_type = RTM_GETLINK; nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; nlh->nlmsg_seq = seq = time(NULL); rt = (struct rtgenmsg *) mnl_nlmsg_put_extra_header(nlh, sizeof(struct rtgenmsg)); rt->rtgen_family = AF_PACKET; if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) { fatal("mnl_socket_sendto"); } ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); while (ret > 0) { ret = mnl_cb_run(buf, ret, seq, portid, data_cb_link, interfaces.get()); if (ret <= MNL_CB_STOP) break; ret = mnl_socket_recvfrom(nl, buf, sizeof(buf)); } if (ret == -1) { fatal("mnl_socket_recvfrom() failed"); } mnl_socket_close(nl); stringstream sstream; sstream << "Interfaces:" << endl; for(auto i : *interfaces){ sstream << "\tName: " << i.name << endl; sstream << "\tMAC address: " << mac_to_str(i.mac) << endl; sstream << "\tNetlink Index: " << i.netlinkIndex << endl; sstream << "\tIP addresses: "; for(auto ip : i.IPs) { sstream << ip_to_str(ip) << endl << "\t "; } sstream << endl; } logInfo(sstream.str()); return interfaces; } <|endoftext|>
<commit_before>/* This file is part of kdepim. Copyright (c) 2004 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. */ #include "webdavhandler.h" #include <libkdepim/kpimprefs.h> #include <kdebug.h> #include <kconfig.h> #include <qfile.h> SloxItem::SloxItem() : status( Invalid ) { } WebdavHandler::WebdavHandler() : mLogCount( 0 ) { KConfig cfg( "sloxrc" ); cfg.setGroup( "General" ); mLogFile = cfg.readEntry( "LogFile" ); kdDebug() << "LOG FILE: " << mLogFile << endl; } void WebdavHandler::log( const QString &text ) { if ( mLogFile.isEmpty() ) return; QString filename = mLogFile + "-" + QString::number( mLogCount ); QFile file( filename ); if ( !file.open( IO_WriteOnly ) ) { kdWarning() << "Unable to open log file '" << filename << "'" << endl; return; } QCString textUtf8 = text.utf8(); file.writeBlock( textUtf8.data(), textUtf8.size() - 1 ); if ( ++mLogCount > 5 ) mLogCount = 0; } QValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc ) { kdDebug() << "getSloxItems" << endl; QValueList<SloxItem> items; QDomElement docElement = doc.documentElement(); QDomNode responseNode; for( responseNode = docElement.firstChild(); !responseNode.isNull(); responseNode = responseNode.nextSibling() ) { QDomElement responseElement = responseNode.toElement(); if ( responseElement.tagName() == "response" ) { QDomNode propstat = responseElement.namedItem( "propstat" ); if ( propstat.isNull() ) { kdError() << "Unable to find propstat tag." << endl; continue; } QDomNode prop = propstat.namedItem( "prop" ); if ( prop.isNull() ) { kdError() << "Unable to find WebDAV property" << endl; continue; } QDomNode sloxIdNode = prop.namedItem( "sloxid" ); if ( sloxIdNode.isNull() ) { kdError() << "Unable to find SLOX id." << endl; continue; } QDomElement sloxIdElement = sloxIdNode.toElement(); QString sloxId = sloxIdElement.text(); QDomNode sloxStatus = prop.namedItem( "sloxstatus" ); if ( sloxStatus.isNull() ) { kdError() << "Unable to find SLOX status." << endl; continue; } SloxItem item; item.sloxId = sloxId; item.domNode = prop; QDomElement sloxStatusElement = sloxStatus.toElement(); if ( sloxStatusElement.text() == "DELETE" ) { item.status = SloxItem::Delete; } else if ( sloxStatusElement.text() == "CREATE" ) { item.status = SloxItem::Create; } items.append( item ); } } return items; } QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt ) { uint ticks = -dt.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) ); return QString::number( ticks ) + "000"; } QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt, const QString &timeZoneId ) { QDateTime utc = KPimPrefs::localTimeToUtc( dt, timeZoneId ); uint ticks = -utc.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) ); return QString::number( ticks ) + "000"; } QDateTime WebdavHandler::sloxToQDateTime( const QString &str ) { QString s = str.mid( 0, str.length() - 3 ); unsigned long ticks = s.toULong(); QDateTime dt; dt.setTime_t( ticks, Qt::UTC ); return dt; } QDateTime WebdavHandler::sloxToQDateTime( const QString &str, const QString &timeZoneId ) { QString s = str.mid( 0, str.length() - 3 ); unsigned long ticks = s.toULong(); QDateTime dt; dt.setTime_t( ticks, Qt::UTC ); return KPimPrefs::utcToLocalTime( dt, timeZoneId ); } QDomElement WebdavHandler::addElement( QDomDocument &doc, QDomNode &node, const QString &tag ) { QDomElement el = doc.createElement( tag ); node.appendChild( el ); return el; } QDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node, const QString &tag ) { QDomElement el = doc.createElementNS( "DAV", tag ); node.appendChild( el ); return el; } QDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node, const QString &tag, const QString &text ) { QDomElement el = doc.createElementNS( "SLOX", tag ); if ( !text.isEmpty() ) { QDomText textnode = doc.createTextNode( text ); el.appendChild( textnode ); } node.appendChild( el ); return el; } <commit_msg>Handle dates before 1970 as well<commit_after>/* This file is part of kdepim. Copyright (c) 2004 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. */ #include "webdavhandler.h" #include <values.h> #include <libkdepim/kpimprefs.h> #include <kdebug.h> #include <kconfig.h> #include <qfile.h> SloxItem::SloxItem() : status( Invalid ) { } WebdavHandler::WebdavHandler() : mLogCount( 0 ) { KConfig cfg( "sloxrc" ); cfg.setGroup( "General" ); mLogFile = cfg.readEntry( "LogFile" ); kdDebug() << "LOG FILE: " << mLogFile << endl; } void WebdavHandler::log( const QString &text ) { if ( mLogFile.isEmpty() ) return; QString filename = mLogFile + "-" + QString::number( mLogCount ); QFile file( filename ); if ( !file.open( IO_WriteOnly ) ) { kdWarning() << "Unable to open log file '" << filename << "'" << endl; return; } QCString textUtf8 = text.utf8(); file.writeBlock( textUtf8.data(), textUtf8.size() - 1 ); if ( ++mLogCount > 5 ) mLogCount = 0; } QValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc ) { kdDebug() << "getSloxItems" << endl; QValueList<SloxItem> items; QDomElement docElement = doc.documentElement(); QDomNode responseNode; for( responseNode = docElement.firstChild(); !responseNode.isNull(); responseNode = responseNode.nextSibling() ) { QDomElement responseElement = responseNode.toElement(); if ( responseElement.tagName() == "response" ) { QDomNode propstat = responseElement.namedItem( "propstat" ); if ( propstat.isNull() ) { kdError() << "Unable to find propstat tag." << endl; continue; } QDomNode prop = propstat.namedItem( "prop" ); if ( prop.isNull() ) { kdError() << "Unable to find WebDAV property" << endl; continue; } QDomNode sloxIdNode = prop.namedItem( "sloxid" ); if ( sloxIdNode.isNull() ) { kdError() << "Unable to find SLOX id." << endl; continue; } QDomElement sloxIdElement = sloxIdNode.toElement(); QString sloxId = sloxIdElement.text(); QDomNode sloxStatus = prop.namedItem( "sloxstatus" ); if ( sloxStatus.isNull() ) { kdError() << "Unable to find SLOX status." << endl; continue; } SloxItem item; item.sloxId = sloxId; item.domNode = prop; QDomElement sloxStatusElement = sloxStatus.toElement(); if ( sloxStatusElement.text() == "DELETE" ) { item.status = SloxItem::Delete; } else if ( sloxStatusElement.text() == "CREATE" ) { item.status = SloxItem::Create; } items.append( item ); } } return items; } QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt ) { uint ticks = -dt.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) ); return QString::number( ticks ) + "000"; } QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt, const QString &timeZoneId ) { QDateTime utc = KPimPrefs::localTimeToUtc( dt, timeZoneId ); uint ticks = -utc.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) ); return QString::number( ticks ) + "000"; } QDateTime WebdavHandler::sloxToQDateTime( const QString &str ) { QString s = str.mid( 0, str.length() - 3 ); bool preEpoch = s.startsWith("-"); if (preEpoch) s = s.mid(1); unsigned long ticks = s.toULong(); QDateTime dt; if (preEpoch) { dt.setTime_t( 0, Qt::UTC ); if (ticks > MAXINT) { dt = dt.addSecs(-MAXINT); ticks -= MAXINT; } dt = dt.addSecs(-((long) ticks)); } else { dt.setTime_t( ticks, Qt::UTC ); } return dt; } QDateTime WebdavHandler::sloxToQDateTime( const QString &str, const QString &timeZoneId ) { return KPimPrefs::utcToLocalTime( sloxToQDateTime(str), timeZoneId ); } QDomElement WebdavHandler::addElement( QDomDocument &doc, QDomNode &node, const QString &tag ) { QDomElement el = doc.createElement( tag ); node.appendChild( el ); return el; } QDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node, const QString &tag ) { QDomElement el = doc.createElementNS( "DAV", tag ); node.appendChild( el ); return el; } QDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node, const QString &tag, const QString &text ) { QDomElement el = doc.createElementNS( "SLOX", tag ); if ( !text.isEmpty() ) { QDomText textnode = doc.createTextNode( text ); el.appendChild( textnode ); } node.appendChild( el ); return el; } <|endoftext|>
<commit_before>#include "command.hh" #include "hash.hh" #include "legacy.hh" #include "shared.hh" #include "references.hh" #include "archive.hh" using namespace nix; struct CmdHash : Command { enum Mode { mFile, mPath }; Mode mode; Base base = SRI; bool truncate = false; HashType ht = htSHA256; std::vector<std::string> paths; std::experimental::optional<std::string> modulus; CmdHash(Mode mode) : mode(mode) { mkFlag(0, "sri", "print hash in SRI format", &base, SRI); mkFlag(0, "base64", "print hash in base-64", &base, Base64); mkFlag(0, "base32", "print hash in base-32 (Nix-specific)", &base, Base32); mkFlag(0, "base16", "print hash in base-16", &base, Base16); mkFlag() .longName("type") .mkHashTypeFlag(&ht); mkFlag() .longName("modulo") .description("compute hash modulo specified string") .labels({"modulus"}) .dest(&modulus); expectArgs("paths", &paths); } std::string name() override { return mode == mFile ? "hash-file" : "hash-path"; } std::string description() override { return mode == mFile ? "print cryptographic hash of a regular file" : "print cryptographic hash of the NAR serialisation of a path"; } void run() override { for (auto path : paths) { std::unique_ptr<AbstractHashSink> hashSink; if (modulus) hashSink = std::make_unique<HashModuloSink>(ht, *modulus); else hashSink = std::make_unique<HashSink>(ht); if (mode == mFile) readFile(path, *hashSink); else dumpPath(path, *hashSink); Hash h = hashSink->finish().first; if (truncate && h.hashSize > 20) h = compressHash(h, 20); std::cout << format("%1%\n") % h.to_string(base, base == SRI); } } }; static RegisterCommand r1(make_ref<CmdHash>(CmdHash::mFile)); static RegisterCommand r2(make_ref<CmdHash>(CmdHash::mPath)); struct CmdToBase : Command { Base base; HashType ht = htUnknown; std::vector<std::string> args; CmdToBase(Base base) : base(base) { mkFlag() .longName("type") .mkHashTypeFlag(&ht); expectArgs("strings", &args); } std::string name() override { return base == Base16 ? "to-base16" : base == Base32 ? "to-base32" : base == Base64 ? "to-base64" : "to-sri"; } std::string description() override { return fmt("convert a hash to %s representation", base == Base16 ? "base-16" : base == Base32 ? "base-32" : base == Base64 ? "base-64" : "SRI"); } void run() override { for (auto s : args) std::cout << fmt("%s\n", Hash(s, ht).to_string(base, base == SRI)); } }; static RegisterCommand r3(make_ref<CmdToBase>(Base16)); static RegisterCommand r4(make_ref<CmdToBase>(Base32)); static RegisterCommand r5(make_ref<CmdToBase>(Base64)); static RegisterCommand r6(make_ref<CmdToBase>(SRI)); /* Legacy nix-hash command. */ static int compatNixHash(int argc, char * * argv) { HashType ht = htMD5; bool flat = false; bool base32 = false; bool truncate = false; enum { opHash, opTo32, opTo16 } op = opHash; std::vector<std::string> ss; parseCmdLine(argc, argv, [&](Strings::iterator & arg, const Strings::iterator & end) { if (*arg == "--help") showManPage("nix-hash"); else if (*arg == "--version") printVersion("nix-hash"); else if (*arg == "--flat") flat = true; else if (*arg == "--base32") base32 = true; else if (*arg == "--truncate") truncate = true; else if (*arg == "--type") { string s = getArg(*arg, arg, end); ht = parseHashType(s); if (ht == htUnknown) throw UsageError(format("unknown hash type '%1%'") % s); } else if (*arg == "--to-base16") op = opTo16; else if (*arg == "--to-base32") op = opTo32; else if (*arg != "" && arg->at(0) == '-') return false; else ss.push_back(*arg); return true; }); if (op == opHash) { CmdHash cmd(flat ? CmdHash::mFile : CmdHash::mPath); cmd.ht = ht; cmd.base = base32 ? Base32 : Base16; cmd.truncate = truncate; cmd.paths = ss; cmd.run(); } else { CmdToBase cmd(op == opTo32 ? Base32 : Base16); cmd.args = ss; cmd.ht = ht; cmd.run(); } return 0; } static RegisterLegacyCommand s1("nix-hash", compatNixHash); <commit_msg>Revert "Revert "Fix build""<commit_after>#include "command.hh" #include "hash.hh" #include "legacy.hh" #include "shared.hh" #include "references.hh" #include "archive.hh" using namespace nix; struct CmdHash : Command { enum Mode { mFile, mPath }; Mode mode; Base base = SRI; bool truncate = false; HashType ht = htSHA256; std::vector<std::string> paths; std::optional<std::string> modulus; CmdHash(Mode mode) : mode(mode) { mkFlag(0, "sri", "print hash in SRI format", &base, SRI); mkFlag(0, "base64", "print hash in base-64", &base, Base64); mkFlag(0, "base32", "print hash in base-32 (Nix-specific)", &base, Base32); mkFlag(0, "base16", "print hash in base-16", &base, Base16); mkFlag() .longName("type") .mkHashTypeFlag(&ht); mkFlag() .longName("modulo") .description("compute hash modulo specified string") .labels({"modulus"}) .dest(&modulus); expectArgs("paths", &paths); } std::string name() override { return mode == mFile ? "hash-file" : "hash-path"; } std::string description() override { return mode == mFile ? "print cryptographic hash of a regular file" : "print cryptographic hash of the NAR serialisation of a path"; } void run() override { for (auto path : paths) { std::unique_ptr<AbstractHashSink> hashSink; if (modulus) hashSink = std::make_unique<HashModuloSink>(ht, *modulus); else hashSink = std::make_unique<HashSink>(ht); if (mode == mFile) readFile(path, *hashSink); else dumpPath(path, *hashSink); Hash h = hashSink->finish().first; if (truncate && h.hashSize > 20) h = compressHash(h, 20); std::cout << format("%1%\n") % h.to_string(base, base == SRI); } } }; static RegisterCommand r1(make_ref<CmdHash>(CmdHash::mFile)); static RegisterCommand r2(make_ref<CmdHash>(CmdHash::mPath)); struct CmdToBase : Command { Base base; HashType ht = htUnknown; std::vector<std::string> args; CmdToBase(Base base) : base(base) { mkFlag() .longName("type") .mkHashTypeFlag(&ht); expectArgs("strings", &args); } std::string name() override { return base == Base16 ? "to-base16" : base == Base32 ? "to-base32" : base == Base64 ? "to-base64" : "to-sri"; } std::string description() override { return fmt("convert a hash to %s representation", base == Base16 ? "base-16" : base == Base32 ? "base-32" : base == Base64 ? "base-64" : "SRI"); } void run() override { for (auto s : args) std::cout << fmt("%s\n", Hash(s, ht).to_string(base, base == SRI)); } }; static RegisterCommand r3(make_ref<CmdToBase>(Base16)); static RegisterCommand r4(make_ref<CmdToBase>(Base32)); static RegisterCommand r5(make_ref<CmdToBase>(Base64)); static RegisterCommand r6(make_ref<CmdToBase>(SRI)); /* Legacy nix-hash command. */ static int compatNixHash(int argc, char * * argv) { HashType ht = htMD5; bool flat = false; bool base32 = false; bool truncate = false; enum { opHash, opTo32, opTo16 } op = opHash; std::vector<std::string> ss; parseCmdLine(argc, argv, [&](Strings::iterator & arg, const Strings::iterator & end) { if (*arg == "--help") showManPage("nix-hash"); else if (*arg == "--version") printVersion("nix-hash"); else if (*arg == "--flat") flat = true; else if (*arg == "--base32") base32 = true; else if (*arg == "--truncate") truncate = true; else if (*arg == "--type") { string s = getArg(*arg, arg, end); ht = parseHashType(s); if (ht == htUnknown) throw UsageError(format("unknown hash type '%1%'") % s); } else if (*arg == "--to-base16") op = opTo16; else if (*arg == "--to-base32") op = opTo32; else if (*arg != "" && arg->at(0) == '-') return false; else ss.push_back(*arg); return true; }); if (op == opHash) { CmdHash cmd(flat ? CmdHash::mFile : CmdHash::mPath); cmd.ht = ht; cmd.base = base32 ? Base32 : Base16; cmd.truncate = truncate; cmd.paths = ss; cmd.run(); } else { CmdToBase cmd(op == opTo32 ? Base32 : Base16); cmd.args = ss; cmd.ht = ht; cmd.run(); } return 0; } static RegisterLegacyCommand s1("nix-hash", compatNixHash); <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/command_buffer/service/memory_program_cache.h" #include "base/command_line.h" #include "base/metrics/histogram.h" #include "base/sha1.h" #include "base/string_number_conversions.h" #include "gpu/command_buffer/service/gl_utils.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "ui/gl/gl_bindings.h" namespace { size_t GetCacheSize() { size_t size; const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kGpuProgramCacheSizeKb) && base::StringToSizeT(command_line->GetSwitchValueNative( switches::kGpuProgramCacheSizeKb), &size)) { return size; } return gpu::gles2::MemoryProgramCache::kDefaultMaxProgramCacheMemoryBytes; } } // anonymous namespace namespace gpu { namespace gles2 { MemoryProgramCache::MemoryProgramCache() : max_size_bytes_(GetCacheSize()), curr_size_bytes_(0) { } MemoryProgramCache::MemoryProgramCache(const size_t max_cache_size_bytes) : max_size_bytes_(max_cache_size_bytes), curr_size_bytes_(0) {} MemoryProgramCache::~MemoryProgramCache() {} void MemoryProgramCache::ClearBackend() { curr_size_bytes_ = 0; store_.clear(); eviction_helper_.Clear(); } ProgramCache::ProgramLoadResult MemoryProgramCache::LoadLinkedProgram( GLuint program, ShaderManager::ShaderInfo* shader_a, ShaderManager::ShaderInfo* shader_b, const LocationMap* bind_attrib_location_map) const { char a_sha[kHashLength]; char b_sha[kHashLength]; ComputeShaderHash(*shader_a->deferred_compilation_source(), a_sha); ComputeShaderHash(*shader_b->deferred_compilation_source(), b_sha); char sha[kHashLength]; ComputeProgramHash(a_sha, b_sha, bind_attrib_location_map, sha); const std::string sha_string(sha, kHashLength); StoreMap::const_iterator found = store_.find(sha_string); if (found == store_.end()) { return PROGRAM_LOAD_FAILURE; } const scoped_refptr<ProgramCacheValue> value = found->second; glProgramBinary(program, value->format, static_cast<const GLvoid*>(value->data.get()), value->length); GLint success = 0; glGetProgramiv(program, GL_LINK_STATUS, &success); if (success == GL_FALSE) { return PROGRAM_LOAD_FAILURE; } shader_a->set_attrib_map(value->attrib_map_0); shader_a->set_uniform_map(value->uniform_map_0); shader_b->set_attrib_map(value->attrib_map_1); shader_b->set_uniform_map(value->uniform_map_1); return PROGRAM_LOAD_SUCCESS; } void MemoryProgramCache::SaveLinkedProgram( GLuint program, const ShaderManager::ShaderInfo* shader_a, const ShaderManager::ShaderInfo* shader_b, const LocationMap* bind_attrib_location_map) { GLenum format; GLsizei length = 0; glGetProgramiv(program, GL_PROGRAM_BINARY_LENGTH_OES, &length); if (length == 0 || static_cast<unsigned int>(length) > max_size_bytes_) { return; } scoped_array<char> binary(new char[length]); glGetProgramBinary(program, length, NULL, &format, binary.get()); UMA_HISTOGRAM_COUNTS("GPU.ProgramCache.ProgramBinarySizeBytes", length); char a_sha[kHashLength]; char b_sha[kHashLength]; ComputeShaderHash(*shader_a->deferred_compilation_source(), a_sha); ComputeShaderHash(*shader_b->deferred_compilation_source(), b_sha); char sha[kHashLength]; ComputeProgramHash(a_sha, b_sha, bind_attrib_location_map, sha); const std::string sha_string(sha, sizeof(sha)); UMA_HISTOGRAM_COUNTS("GPU.ProgramCache.MemorySizeBeforeKb", curr_size_bytes_ / 1024); if (store_.find(sha_string) != store_.end()) { const StoreMap::iterator found = store_.find(sha_string); const ProgramCacheValue* evicting = found->second; curr_size_bytes_ -= evicting->length; Evict(sha_string, evicting->shader_0_hash, evicting->shader_1_hash); store_.erase(found); } while (curr_size_bytes_ + length > max_size_bytes_) { DCHECK(!eviction_helper_.IsEmpty()); const std::string* program = eviction_helper_.PeekKey(); const StoreMap::iterator found = store_.find(*program); const ProgramCacheValue* evicting = found->second.get(); curr_size_bytes_ -= evicting->length; Evict(*program, evicting->shader_0_hash, evicting->shader_1_hash); store_.erase(found); eviction_helper_.PopKey(); } store_[sha_string] = new ProgramCacheValue(length, format, binary.release(), a_sha, shader_a->attrib_map(), shader_a->uniform_map(), b_sha, shader_b->attrib_map(), shader_b->uniform_map()); curr_size_bytes_ += length; eviction_helper_.KeyUsed(sha_string); UMA_HISTOGRAM_COUNTS("GPU.ProgramCache.MemorySizeAfterKb", curr_size_bytes_ / 1024); LinkedProgramCacheSuccess(sha_string, std::string(a_sha, kHashLength), std::string(b_sha, kHashLength)); } MemoryProgramCache::ProgramCacheValue::ProgramCacheValue( GLsizei _length, GLenum _format, const char* _data, const char* _shader_0_hash, const ShaderTranslator::VariableMap& _attrib_map_0, const ShaderTranslator::VariableMap& _uniform_map_0, const char* _shader_1_hash, const ShaderTranslator::VariableMap& _attrib_map_1, const ShaderTranslator::VariableMap& _uniform_map_1) : length(_length), format(_format), data(_data), shader_0_hash(_shader_0_hash, kHashLength), attrib_map_0(_attrib_map_0), uniform_map_0(_uniform_map_0), shader_1_hash(_shader_1_hash, kHashLength), attrib_map_1(_attrib_map_1), uniform_map_1(_uniform_map_1) {} MemoryProgramCache::ProgramCacheValue::~ProgramCacheValue() {} } // namespace gles2 } // namespace gpu <commit_msg>Fixed in-memory gpu program cache size flag interpretation<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/command_buffer/service/memory_program_cache.h" #include "base/command_line.h" #include "base/metrics/histogram.h" #include "base/sha1.h" #include "base/string_number_conversions.h" #include "gpu/command_buffer/service/gl_utils.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "ui/gl/gl_bindings.h" namespace { size_t GetCacheSizeBytes() { size_t size; const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kGpuProgramCacheSizeKb) && base::StringToSizeT(command_line->GetSwitchValueNative( switches::kGpuProgramCacheSizeKb), &size)) { return size * 1024; } return gpu::gles2::MemoryProgramCache::kDefaultMaxProgramCacheMemoryBytes; } } // anonymous namespace namespace gpu { namespace gles2 { MemoryProgramCache::MemoryProgramCache() : max_size_bytes_(GetCacheSizeBytes()), curr_size_bytes_(0) { } MemoryProgramCache::MemoryProgramCache(const size_t max_cache_size_bytes) : max_size_bytes_(max_cache_size_bytes), curr_size_bytes_(0) {} MemoryProgramCache::~MemoryProgramCache() {} void MemoryProgramCache::ClearBackend() { curr_size_bytes_ = 0; store_.clear(); eviction_helper_.Clear(); } ProgramCache::ProgramLoadResult MemoryProgramCache::LoadLinkedProgram( GLuint program, ShaderManager::ShaderInfo* shader_a, ShaderManager::ShaderInfo* shader_b, const LocationMap* bind_attrib_location_map) const { char a_sha[kHashLength]; char b_sha[kHashLength]; ComputeShaderHash(*shader_a->deferred_compilation_source(), a_sha); ComputeShaderHash(*shader_b->deferred_compilation_source(), b_sha); char sha[kHashLength]; ComputeProgramHash(a_sha, b_sha, bind_attrib_location_map, sha); const std::string sha_string(sha, kHashLength); StoreMap::const_iterator found = store_.find(sha_string); if (found == store_.end()) { return PROGRAM_LOAD_FAILURE; } const scoped_refptr<ProgramCacheValue> value = found->second; glProgramBinary(program, value->format, static_cast<const GLvoid*>(value->data.get()), value->length); GLint success = 0; glGetProgramiv(program, GL_LINK_STATUS, &success); if (success == GL_FALSE) { return PROGRAM_LOAD_FAILURE; } shader_a->set_attrib_map(value->attrib_map_0); shader_a->set_uniform_map(value->uniform_map_0); shader_b->set_attrib_map(value->attrib_map_1); shader_b->set_uniform_map(value->uniform_map_1); return PROGRAM_LOAD_SUCCESS; } void MemoryProgramCache::SaveLinkedProgram( GLuint program, const ShaderManager::ShaderInfo* shader_a, const ShaderManager::ShaderInfo* shader_b, const LocationMap* bind_attrib_location_map) { GLenum format; GLsizei length = 0; glGetProgramiv(program, GL_PROGRAM_BINARY_LENGTH_OES, &length); if (length == 0 || static_cast<unsigned int>(length) > max_size_bytes_) { return; } scoped_array<char> binary(new char[length]); glGetProgramBinary(program, length, NULL, &format, binary.get()); UMA_HISTOGRAM_COUNTS("GPU.ProgramCache.ProgramBinarySizeBytes", length); char a_sha[kHashLength]; char b_sha[kHashLength]; ComputeShaderHash(*shader_a->deferred_compilation_source(), a_sha); ComputeShaderHash(*shader_b->deferred_compilation_source(), b_sha); char sha[kHashLength]; ComputeProgramHash(a_sha, b_sha, bind_attrib_location_map, sha); const std::string sha_string(sha, sizeof(sha)); UMA_HISTOGRAM_COUNTS("GPU.ProgramCache.MemorySizeBeforeKb", curr_size_bytes_ / 1024); if (store_.find(sha_string) != store_.end()) { const StoreMap::iterator found = store_.find(sha_string); const ProgramCacheValue* evicting = found->second; curr_size_bytes_ -= evicting->length; Evict(sha_string, evicting->shader_0_hash, evicting->shader_1_hash); store_.erase(found); } while (curr_size_bytes_ + length > max_size_bytes_) { DCHECK(!eviction_helper_.IsEmpty()); const std::string* program = eviction_helper_.PeekKey(); const StoreMap::iterator found = store_.find(*program); const ProgramCacheValue* evicting = found->second.get(); curr_size_bytes_ -= evicting->length; Evict(*program, evicting->shader_0_hash, evicting->shader_1_hash); store_.erase(found); eviction_helper_.PopKey(); } store_[sha_string] = new ProgramCacheValue(length, format, binary.release(), a_sha, shader_a->attrib_map(), shader_a->uniform_map(), b_sha, shader_b->attrib_map(), shader_b->uniform_map()); curr_size_bytes_ += length; eviction_helper_.KeyUsed(sha_string); UMA_HISTOGRAM_COUNTS("GPU.ProgramCache.MemorySizeAfterKb", curr_size_bytes_ / 1024); LinkedProgramCacheSuccess(sha_string, std::string(a_sha, kHashLength), std::string(b_sha, kHashLength)); } MemoryProgramCache::ProgramCacheValue::ProgramCacheValue( GLsizei _length, GLenum _format, const char* _data, const char* _shader_0_hash, const ShaderTranslator::VariableMap& _attrib_map_0, const ShaderTranslator::VariableMap& _uniform_map_0, const char* _shader_1_hash, const ShaderTranslator::VariableMap& _attrib_map_1, const ShaderTranslator::VariableMap& _uniform_map_1) : length(_length), format(_format), data(_data), shader_0_hash(_shader_0_hash, kHashLength), attrib_map_0(_attrib_map_0), uniform_map_0(_uniform_map_0), shader_1_hash(_shader_1_hash, kHashLength), attrib_map_1(_attrib_map_1), uniform_map_1(_uniform_map_1) {} MemoryProgramCache::ProgramCacheValue::~ProgramCacheValue() {} } // namespace gles2 } // namespace gpu <|endoftext|>
<commit_before>#include "MuAffineTransform.h" #include <cmath> namespace mural { MuAffineTransform MuAffineTransformMake(float a, float b, float c, float d, float tx, float ty) { MuAffineTransform t; t.a = a; t.b = b; t.c = c; t.d = d; t.tx = tx; t.ty = ty; return t; } MuPoint MuPointApplyAffineTransform(const MuPoint& point, const MuAffineTransform& t) { MuPoint p( t.a * point.x + t.c * point.y + t.tx, t.b * point.x + t.d * point.y + t.ty ); return p; } MuSize MuSizeApplyAffineTransform(const MuSize& size, const MuAffineTransform& t) { MuSize s( t.a * size.width + t.c * size.height, t.b * size.width + t.d * size.height ); return s; } MuAffineTransform MuAffineTransformMakeIdentity() { return MuAffineTransformMake(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); } MuRect MuRectApplyAffineTransform(const MuRect& rect, const MuAffineTransform& anAffineTransform) { float top = rect.getMinY(); float left = rect.getMinX(); float right = rect.getMaxX(); float bottom = rect.getMaxY(); MuPoint topLeft = MuPointApplyAffineTransform(MuPointMake(left, top), anAffineTransform); MuPoint topRight = MuPointApplyAffineTransform(MuPointMake(right, top), anAffineTransform); MuPoint bottomLeft = MuPointApplyAffineTransform(MuPointMake(left, bottom), anAffineTransform); MuPoint bottomRight = MuPointApplyAffineTransform(MuPointMake(right, bottom), anAffineTransform); float minX = fmin(fmin(topLeft.x, topRight.x), fmin(bottomLeft.x, bottomRight.x)); float maxX = fmax(fmax(topLeft.x, topRight.x), fmax(bottomLeft.x, bottomRight.x)); float minY = fmin(fmin(topLeft.y, topRight.y), fmin(bottomLeft.y, bottomRight.y)); float maxY = fmax(fmax(topLeft.y, topRight.y), fmax(bottomLeft.y, bottomRight.y)); return MuRectMake(minX, minY, (maxX - minX), (maxY - minY)); } MuAffineTransform MuAffineTransformTranslate(const MuAffineTransform& t, float tx, float ty) { return MuAffineTransformMake(t.a, t.b, t.c, t.d, t.tx + t.a * tx + t.c * ty, t.ty + t.b * tx + t.d * ty); } MuAffineTransform MuAffineTransformRotate(const MuAffineTransform& aTransform, float anAngle) { float fSin = sin(anAngle); float fCos = cos(anAngle); return MuAffineTransformMake( aTransform.a * fCos + aTransform.c * fSin, aTransform.b * fCos + aTransform.d * fSin, aTransform.c * fCos - aTransform.a * fSin, aTransform.d * fCos - aTransform.b * fSin, aTransform.tx, aTransform.ty ); } MuAffineTransform MuAffineTransformScale(const MuAffineTransform& t, float sx, float sy) { return MuAffineTransformMake(t.a * sx, t.b * sx, t.c * sy, t.d * sy, t.tx, t.ty); } MuAffineTransform MuAffineTransformConcat(const MuAffineTransform& t1, const MuAffineTransform& t2) { return MuAffineTransformMake( t1.a * t2.a + t1.b * t2.c, t1.a * t2.b + t1.b * t2.d, // a, b t1.c * t2.a + t1.d * t2.c, t1.c * t2.b + t1.d * t2.d, // c, d t1.tx * t2.a + t1.ty * t2.c + t2.tx, // tx t1.tx * t2.b + t1.ty * t2.d + t2.ty // ty ); } bool MuAffineTransformEqualToTransform(const MuAffineTransform& t1, const MuAffineTransform& t2) { return (t1.a == t2.a && t1.b == t2.b && t1.c == t2.c && t1.d == t2.d && t1.tx == t2.tx && t1.ty == t2.ty); } bool MuAffineTransformIsIdentity(const MuAffineTransform& t) { return MuAffineTransformEqualToTransform(MuAffineTransformIdentity, t); } MuAffineTransform MuAffineTransformInvert(const MuAffineTransform& t) { float determinant = 1 / (t.a * t.d - t.b * t.c); return MuAffineTransformMake( determinant * t.d, -determinant * t.b, -determinant * t.c, determinant * t.a, determinant * (t.c * t.ty - t.d * t.tx), determinant * (t.b * t.tx - t.a * t.ty) ); } } <commit_msg>Fix MuAffineTransform identity object not initialised issue<commit_after>#include "MuAffineTransform.h" #include <cmath> namespace mural { extern const MuAffineTransform MuAffineTransformIdentity = MuAffineTransformMakeIdentity(); MuAffineTransform MuAffineTransformMake(float a, float b, float c, float d, float tx, float ty) { MuAffineTransform t; t.a = a; t.b = b; t.c = c; t.d = d; t.tx = tx; t.ty = ty; return t; } MuPoint MuPointApplyAffineTransform(const MuPoint& point, const MuAffineTransform& t) { MuPoint p( t.a * point.x + t.c * point.y + t.tx, t.b * point.x + t.d * point.y + t.ty ); return p; } MuSize MuSizeApplyAffineTransform(const MuSize& size, const MuAffineTransform& t) { MuSize s( t.a * size.width + t.c * size.height, t.b * size.width + t.d * size.height ); return s; } MuAffineTransform MuAffineTransformMakeIdentity() { return MuAffineTransformMake(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); } MuRect MuRectApplyAffineTransform(const MuRect& rect, const MuAffineTransform& anAffineTransform) { float top = rect.getMinY(); float left = rect.getMinX(); float right = rect.getMaxX(); float bottom = rect.getMaxY(); MuPoint topLeft = MuPointApplyAffineTransform(MuPointMake(left, top), anAffineTransform); MuPoint topRight = MuPointApplyAffineTransform(MuPointMake(right, top), anAffineTransform); MuPoint bottomLeft = MuPointApplyAffineTransform(MuPointMake(left, bottom), anAffineTransform); MuPoint bottomRight = MuPointApplyAffineTransform(MuPointMake(right, bottom), anAffineTransform); float minX = fmin(fmin(topLeft.x, topRight.x), fmin(bottomLeft.x, bottomRight.x)); float maxX = fmax(fmax(topLeft.x, topRight.x), fmax(bottomLeft.x, bottomRight.x)); float minY = fmin(fmin(topLeft.y, topRight.y), fmin(bottomLeft.y, bottomRight.y)); float maxY = fmax(fmax(topLeft.y, topRight.y), fmax(bottomLeft.y, bottomRight.y)); return MuRectMake(minX, minY, (maxX - minX), (maxY - minY)); } MuAffineTransform MuAffineTransformTranslate(const MuAffineTransform& t, float tx, float ty) { return MuAffineTransformMake(t.a, t.b, t.c, t.d, t.tx + t.a * tx + t.c * ty, t.ty + t.b * tx + t.d * ty); } MuAffineTransform MuAffineTransformRotate(const MuAffineTransform& aTransform, float anAngle) { float fSin = sin(anAngle); float fCos = cos(anAngle); return MuAffineTransformMake( aTransform.a * fCos + aTransform.c * fSin, aTransform.b * fCos + aTransform.d * fSin, aTransform.c * fCos - aTransform.a * fSin, aTransform.d * fCos - aTransform.b * fSin, aTransform.tx, aTransform.ty ); } MuAffineTransform MuAffineTransformScale(const MuAffineTransform& t, float sx, float sy) { return MuAffineTransformMake(t.a * sx, t.b * sx, t.c * sy, t.d * sy, t.tx, t.ty); } MuAffineTransform MuAffineTransformConcat(const MuAffineTransform& t1, const MuAffineTransform& t2) { return MuAffineTransformMake( t1.a * t2.a + t1.b * t2.c, t1.a * t2.b + t1.b * t2.d, // a, b t1.c * t2.a + t1.d * t2.c, t1.c * t2.b + t1.d * t2.d, // c, d t1.tx * t2.a + t1.ty * t2.c + t2.tx, // tx t1.tx * t2.b + t1.ty * t2.d + t2.ty // ty ); } bool MuAffineTransformEqualToTransform(const MuAffineTransform& t1, const MuAffineTransform& t2) { return (t1.a == t2.a && t1.b == t2.b && t1.c == t2.c && t1.d == t2.d && t1.tx == t2.tx && t1.ty == t2.ty); } bool MuAffineTransformIsIdentity(const MuAffineTransform& t) { return MuAffineTransformEqualToTransform(MuAffineTransformIdentity, t); } MuAffineTransform MuAffineTransformInvert(const MuAffineTransform& t) { float determinant = 1 / (t.a * t.d - t.b * t.c); return MuAffineTransformMake( determinant * t.d, -determinant * t.b, -determinant * t.c, determinant * t.a, determinant * (t.c * t.ty - t.d * t.tx), determinant * (t.b * t.tx - t.a * t.ty) ); } } <|endoftext|>
<commit_before>// Copyright (c) 2017 The Khronos Group Inc. // Copyright (c) 2017 Valve Corporation // Copyright (c) 2017 LunarG, Inc. // // 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. // // Authors: Mark Young <marky@lunarg.com> // Nat Brown <natb@valvesoftware.com> // #include <cstring> #include "xr_dependencies.h" // If the C++ macro is set to the version containing C++17, it must support // the final C++17 package #if __cplusplus >= 201703L #define USE_EXPERIMENTAL_FS 0 #define USE_FINAL_FS 1 #elif defined(_MSC_VER) && _MSC_VER >= 1900 #if defined(_HAS_CXX17) && _HAS_CXX17 // When MSC supports c++17 use <filesystem> package. #define USE_EXPERIMENTAL_FS 0 #define USE_FINAL_FS 1 #else // MSC before c++17 need to use <experimental/filesystem> package. #define USE_EXPERIMENTAL_FS 1 #define USE_FINAL_FS 0 #endif // !_HAS_CXX17 // Right now, GCC still only supports the experimental filesystem items starting in GCC 6 #elif (__GNUC__ >= 6) #define USE_EXPERIMENTAL_FS 1 #define USE_FINAL_FS 0 // If Clang, check for feature support #elif defined(__clang__) && (__cpp_lib_filesystem || __cpp_lib_experimental_filesystem) #if __cpp_lib_filesystem #define USE_EXPERIMENTAL_FS 0 #define USE_FINAL_FS 1 #else #define USE_EXPERIMENTAL_FS 1 #define USE_FINAL_FS 0 #endif // If all above fails, fall back to standard C++ and OS-specific items #else #define USE_EXPERIMENTAL_FS 0 #define USE_FINAL_FS 0 #endif #if USE_FINAL_FS == 1 #include <filesystem> #define FS_PREFIX std::filesystem #elif USE_EXPERIMENTAL_FS == 1 #if (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP) #error "Windows universal application doesn't support system::experimental::filesystem" #endif #include <experimental/filesystem> #define FS_PREFIX std::experimental::filesystem #elif defined(XR_USE_PLATFORM_WIN32) // Windows fallback includes #include <stdint.h> #include <direct.h> #else // Linux/Apple fallback includes #include <sys/stat.h> #include <sys/param.h> #include <unistd.h> #include <limits.h> #include <stdlib.h> #include <dirent.h> #endif #include "filesystem_utils.hpp" #if defined(XR_USE_PLATFORM_WIN32) #define PATH_SEPARATOR ';' #define DIRECTORY_SYMBOL '\\' #else #define PATH_SEPARATOR ':' #define DIRECTORY_SYMBOL '/' #endif #if (USE_FINAL_FS == 1) || (USE_EXPERIMENTAL_FS == 1) // We can use one of the C++ filesystem packages bool FileSysUtilsIsRegularFile(const std::string& path) { try { return FS_PREFIX::is_regular_file(path); } catch (...) { return false; } } bool FileSysUtilsIsDirectory(const std::string& path) { try { return FS_PREFIX::is_directory(path); } catch (...) { return false; } } bool FileSysUtilsPathExists(const std::string& path) { try { return FS_PREFIX::exists(path); } catch (...) { return false; } } bool FileSysUtilsIsAbsolutePath(const std::string& path) { try { FS_PREFIX::path file_path(path); return file_path.is_absolute(); } catch (...) { return false; } } bool FileSysUtilsGetCurrentPath(std::string& path) { try { FS_PREFIX::path cur_path = FS_PREFIX::current_path(); path = cur_path.string(); return true; } catch (...) { } return false; } bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) { try { FS_PREFIX::path path_var(file_path); parent_path = path_var.parent_path().string(); return true; } catch (...) { } return false; } bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) { try { absolute = FS_PREFIX::absolute(path).string(); return true; } catch (...) { } return false; } bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) { try { FS_PREFIX::path parent_path(parent); FS_PREFIX::path child_path(child); FS_PREFIX::path full_path = parent_path / child_path; combined = full_path.string(); return true; } catch (...) { } return false; } bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) { try { std::string::size_type start = 0; std::string::size_type location = path_list.find(PATH_SEPARATOR); while (location != std::string::npos) { paths.push_back(path_list.substr(start, location)); start = location + 1; location = path_list.find(PATH_SEPARATOR, start); } paths.push_back(path_list.substr(start, location)); return true; } catch (...) { } return false; } bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) { try { for (auto& dir_iter : FS_PREFIX::directory_iterator(path)) { files.push_back(dir_iter.path().filename().string()); } return true; } catch (...) { } return false; } #elif defined(XR_OS_WINDOWS) // Workaround for MS VS 2010/2013 don't support the experimental filesystem bool FileSysUtilsIsRegularFile(const std::string& path) { try { return (1 != PathIsDirectory(path.c_str())); } catch (...) { return false; } } bool FileSysUtilsIsDirectory(const std::string& path) { try { return (1 == PathIsDirectory(path.c_str())); } catch (...) { return false; } } bool FileSysUtilsPathExists(const std::string& path) { try { return (1 == PathFileExists(path.c_str())); } catch (...) { return false; } } bool FileSysUtilsIsAbsolutePath(const std::string& path) { try { if ((path[0] == '\\') || (path[1] == ':' && (path[2] == '\\' || path[2] == '/'))) { return true; } } catch (...) { } return false; } bool FileSysUtilsGetCurrentPath(std::string& path) { try { char tmp_path[MAX_PATH]; if (nullptr != _getcwd(tmp_path, MAX_PATH - 1)) { path = tmp_path; return true; } } catch (...) { } return false; } bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) { try { std::string full_path; if (FileSysUtilsGetAbsolutePath(file_path, full_path)) { std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL); parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1); return true; } } catch (...) { } return false; } bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) { try { char tmp_path[MAX_PATH]; if (0 != GetFullPathName(path.c_str(), MAX_PATH, tmp_path, NULL)) { absolute = tmp_path; return true; } } catch (...) { } return false; } bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) { try { std::string::size_type parent_len = parent.length(); if (0 == parent_len || "." == parent || ".\\" == parent || "./" == parent) { combined = child; return true; } char last_char = parent[parent_len - 1]; if (last_char == DIRECTORY_SYMBOL) { parent_len--; } combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child; return true; } catch (...) { } return false; } bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) { try { std::string::size_type start = 0; std::string::size_type location = path_list.find(PATH_SEPARATOR); while (location != std::string::npos) { paths.push_back(path_list.substr(start, location)); start = location + 1; location = path_list.find(PATH_SEPARATOR, start); } paths.push_back(path_list.substr(start, location)); return true; } catch (...) { } return false; } bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) { try { WIN32_FIND_DATA file_data; HANDLE file_handle = FindFirstFile(path.c_str(), &file_data); if (file_handle != INVALID_HANDLE_VALUE) { do { if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { files.push_back(file_data.cFileName); } } while (FindNextFile(file_handle, &file_data)); return true; } } catch (...) { } return false; } #else // XR_OS_LINUX/XR_OS_APPLE fallback #include <sys/stat.h> #include <sys/param.h> #include <unistd.h> #include <stdlib.h> #include <dirent.h> // simple POSIX-compatible implementation of the <filesystem> pieces used by OpenXR bool FileSysUtilsIsRegularFile(const std::string& path) { try { struct stat path_stat; stat(path.c_str(), &path_stat); return S_ISREG(path_stat.st_mode); } catch (...) { } return false; } bool FileSysUtilsIsDirectory(const std::string& path) { try { struct stat path_stat; stat(path.c_str(), &path_stat); return S_ISDIR(path_stat.st_mode); } catch (...) { } return false; } bool FileSysUtilsPathExists(const std::string& path) { try { return (access(path.c_str(), F_OK) != -1); } catch (...) { } return false; } bool FileSysUtilsIsAbsolutePath(const std::string& path) { try { return (path[0] == DIRECTORY_SYMBOL); } catch (...) { } return false; } bool FileSysUtilsGetCurrentPath(std::string& path) { try { char tmp_path[PATH_MAX]; if (nullptr != getcwd(tmp_path, PATH_MAX - 1)) { path = tmp_path; return true; } } catch (...) { } return false; } bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) { try { std::string full_path; if (FileSysUtilsGetAbsolutePath(file_path, full_path)) { std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL); parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1); return true; } } catch (...) { } return false; } bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) { try { char buf[PATH_MAX]; if (nullptr != realpath(path.c_str(), buf)) { absolute = buf; return true; } } catch (...) { } return false; } bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) { try { std::string::size_type parent_len = parent.length(); if (0 == parent_len || "." == parent || "./" == parent) { combined = child; return true; } char last_char = parent[parent_len - 1]; if (last_char == DIRECTORY_SYMBOL) { parent_len--; } combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child; return true; } catch (...) { } return false; } bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) { try { std::string::size_type start = 0; std::string::size_type location = path_list.find(PATH_SEPARATOR); while (location != std::string::npos) { paths.push_back(path_list.substr(start, location)); start = location + 1; location = path_list.find(PATH_SEPARATOR, start); } paths.push_back(path_list.substr(start, location)); return true; } catch (...) { } return false; } bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) { try { DIR* dir; struct dirent* entry; dir = opendir(path.c_str()); while (dir && (entry = readdir(dir))) { files.push_back(entry->d_name); } closedir(dir); return true; } catch (...) { } return false; } #endif <commit_msg>make filesystem_util unicode compatible when USE_EXPERIMENTAL_FS=0 and USE_FINAL_FS=0<commit_after>// Copyright (c) 2017 The Khronos Group Inc. // Copyright (c) 2017 Valve Corporation // Copyright (c) 2017 LunarG, Inc. // // 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. // // Authors: Mark Young <marky@lunarg.com> // Nat Brown <natb@valvesoftware.com> // #include <cstring> #include "xr_dependencies.h" // If the C++ macro is set to the version containing C++17, it must support // the final C++17 package #if __cplusplus >= 201703L #define USE_EXPERIMENTAL_FS 0 #define USE_FINAL_FS 1 #elif defined(_MSC_VER) && _MSC_VER >= 1900 #if defined(_HAS_CXX17) && _HAS_CXX17 // When MSC supports c++17 use <filesystem> package. #define USE_EXPERIMENTAL_FS 0 #define USE_FINAL_FS 1 #else // MSC before c++17 need to use <experimental/filesystem> package. #define USE_EXPERIMENTAL_FS 1 #define USE_FINAL_FS 0 #endif // !_HAS_CXX17 // Right now, GCC still only supports the experimental filesystem items starting in GCC 6 #elif (__GNUC__ >= 6) #define USE_EXPERIMENTAL_FS 1 #define USE_FINAL_FS 0 // If Clang, check for feature support #elif defined(__clang__) && (__cpp_lib_filesystem || __cpp_lib_experimental_filesystem) #if __cpp_lib_filesystem #define USE_EXPERIMENTAL_FS 0 #define USE_FINAL_FS 1 #else #define USE_EXPERIMENTAL_FS 1 #define USE_FINAL_FS 0 #endif // If all above fails, fall back to standard C++ and OS-specific items #else #define USE_EXPERIMENTAL_FS 0 #define USE_FINAL_FS 0 #endif #if USE_FINAL_FS == 1 #include <filesystem> #define FS_PREFIX std::filesystem #elif USE_EXPERIMENTAL_FS == 1 #if (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP) #error "Windows universal application doesn't support system::experimental::filesystem" #endif #include <experimental/filesystem> #define FS_PREFIX std::experimental::filesystem #elif defined(XR_USE_PLATFORM_WIN32) // Windows fallback includes #include <stdint.h> #include <direct.h> #include <shlwapi.h> #include <cwchar> #else // Linux/Apple fallback includes #include <sys/stat.h> #include <sys/param.h> #include <unistd.h> #include <limits.h> #include <stdlib.h> #include <dirent.h> #endif #include "filesystem_utils.hpp" #if defined(XR_USE_PLATFORM_WIN32) #define PATH_SEPARATOR ';' #define DIRECTORY_SYMBOL '\\' #else #define PATH_SEPARATOR ':' #define DIRECTORY_SYMBOL '/' #endif #if (USE_FINAL_FS == 1) || (USE_EXPERIMENTAL_FS == 1) // We can use one of the C++ filesystem packages bool FileSysUtilsIsRegularFile(const std::string& path) { try { return FS_PREFIX::is_regular_file(path); } catch (...) { return false; } } bool FileSysUtilsIsDirectory(const std::string& path) { try { return FS_PREFIX::is_directory(path); } catch (...) { return false; } } bool FileSysUtilsPathExists(const std::string& path) { try { return FS_PREFIX::exists(path); } catch (...) { return false; } } bool FileSysUtilsIsAbsolutePath(const std::string& path) { try { FS_PREFIX::path file_path(path); return file_path.is_absolute(); } catch (...) { return false; } } bool FileSysUtilsGetCurrentPath(std::string& path) { try { FS_PREFIX::path cur_path = FS_PREFIX::current_path(); path = cur_path.string(); return true; } catch (...) { } return false; } bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) { try { FS_PREFIX::path path_var(file_path); parent_path = path_var.parent_path().string(); return true; } catch (...) { } return false; } bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) { try { absolute = FS_PREFIX::absolute(path).string(); return true; } catch (...) { } return false; } bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) { try { FS_PREFIX::path parent_path(parent); FS_PREFIX::path child_path(child); FS_PREFIX::path full_path = parent_path / child_path; combined = full_path.string(); return true; } catch (...) { } return false; } bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) { try { std::string::size_type start = 0; std::string::size_type location = path_list.find(PATH_SEPARATOR); while (location != std::string::npos) { paths.push_back(path_list.substr(start, location)); start = location + 1; location = path_list.find(PATH_SEPARATOR, start); } paths.push_back(path_list.substr(start, location)); return true; } catch (...) { } return false; } bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) { try { for (auto& dir_iter : FS_PREFIX::directory_iterator(path)) { files.push_back(dir_iter.path().filename().string()); } return true; } catch (...) { } return false; } #elif defined(XR_OS_WINDOWS) // Workaround for MS VS 2010/2013 don't support the experimental filesystem std::vector<wchar_t> MultibyteToWChar(std::string str) { const char* mbstr = str.c_str(); std::mbstate_t state = std::mbstate_t(); std::size_t len = 1 + std::mbsrtowcs(NULL, &mbstr, 0, &state); std::vector<wchar_t> wstr(len); std::mbsrtowcs(&wstr[0], &mbstr, wstr.size(), &state); return wstr; } bool FileSysUtilsIsRegularFile(const std::string& path) { try { return (1 != PathIsDirectoryW(MultibyteToWChar(path).data())); } catch (...) { return false; } } bool FileSysUtilsIsDirectory(const std::string& path) { try { return (1 == PathIsDirectoryW(MultibyteToWChar(path).data())); } catch (...) { return false; } } bool FileSysUtilsPathExists(const std::string& path) { try { return (1 == PathFileExistsW(MultibyteToWChar(path).data())); } catch (...) { return false; } } bool FileSysUtilsIsAbsolutePath(const std::string& path) { try { if ((path[0] == '\\') || (path[1] == ':' && (path[2] == '\\' || path[2] == '/'))) { return true; } } catch (...) { } return false; } bool FileSysUtilsGetCurrentPath(std::string& path) { try { char tmp_path[MAX_PATH]; if (nullptr != _getcwd(tmp_path, MAX_PATH - 1)) { path = tmp_path; return true; } } catch (...) { } return false; } bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) { try { std::string full_path; if (FileSysUtilsGetAbsolutePath(file_path, full_path)) { std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL); parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1); return true; } } catch (...) { } return false; } bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) { try { char tmp_path[MAX_PATH]; if (0 != GetFullPathNameW(MultibyteToWChar(path).data(), MAX_PATH, MultibyteToWChar(tmp_path).data(), NULL)) { absolute = tmp_path; return true; } } catch (...) { } return false; } bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) { try { std::string::size_type parent_len = parent.length(); if (0 == parent_len || "." == parent || ".\\" == parent || "./" == parent) { combined = child; return true; } char last_char = parent[parent_len - 1]; if (last_char == DIRECTORY_SYMBOL) { parent_len--; } combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child; return true; } catch (...) { } return false; } bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) { try { std::string::size_type start = 0; std::string::size_type location = path_list.find(PATH_SEPARATOR); while (location != std::string::npos) { paths.push_back(path_list.substr(start, location)); start = location + 1; location = path_list.find(PATH_SEPARATOR, start); } paths.push_back(path_list.substr(start, location)); return true; } catch (...) { } return false; } bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) { try { WIN32_FIND_DATA file_data; HANDLE file_handle = FindFirstFileW(MultibyteToWChar(path).data(), &file_data); if (file_handle != INVALID_HANDLE_VALUE) { do { if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { const wchar_t* wstr = file_data.cFileName; std::mbstate_t state = std::mbstate_t(); std::size_t len = 1 + std::wcsrtombs(nullptr, &wstr, 0, &state); std::vector<char> mbstr(len); std::wcsrtombs(&mbstr[0], &wstr, mbstr.size(), &state); files.push_back(mbstr.data()); } } while (FindNextFile(file_handle, &file_data)); return true; } } catch (...) { } return false; } #else // XR_OS_LINUX/XR_OS_APPLE fallback #include <sys/stat.h> #include <sys/param.h> #include <unistd.h> #include <stdlib.h> #include <dirent.h> // simple POSIX-compatible implementation of the <filesystem> pieces used by OpenXR bool FileSysUtilsIsRegularFile(const std::string& path) { try { struct stat path_stat; stat(path.c_str(), &path_stat); return S_ISREG(path_stat.st_mode); } catch (...) { } return false; } bool FileSysUtilsIsDirectory(const std::string& path) { try { struct stat path_stat; stat(path.c_str(), &path_stat); return S_ISDIR(path_stat.st_mode); } catch (...) { } return false; } bool FileSysUtilsPathExists(const std::string& path) { try { return (access(path.c_str(), F_OK) != -1); } catch (...) { } return false; } bool FileSysUtilsIsAbsolutePath(const std::string& path) { try { return (path[0] == DIRECTORY_SYMBOL); } catch (...) { } return false; } bool FileSysUtilsGetCurrentPath(std::string& path) { try { char tmp_path[PATH_MAX]; if (nullptr != getcwd(tmp_path, PATH_MAX - 1)) { path = tmp_path; return true; } } catch (...) { } return false; } bool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) { try { std::string full_path; if (FileSysUtilsGetAbsolutePath(file_path, full_path)) { std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL); parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1); return true; } } catch (...) { } return false; } bool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) { try { char buf[PATH_MAX]; if (nullptr != realpath(path.c_str(), buf)) { absolute = buf; return true; } } catch (...) { } return false; } bool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) { try { std::string::size_type parent_len = parent.length(); if (0 == parent_len || "." == parent || "./" == parent) { combined = child; return true; } char last_char = parent[parent_len - 1]; if (last_char == DIRECTORY_SYMBOL) { parent_len--; } combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child; return true; } catch (...) { } return false; } bool FileSysUtilsParsePathList(std::string& path_list, std::vector<std::string>& paths) { try { std::string::size_type start = 0; std::string::size_type location = path_list.find(PATH_SEPARATOR); while (location != std::string::npos) { paths.push_back(path_list.substr(start, location)); start = location + 1; location = path_list.find(PATH_SEPARATOR, start); } paths.push_back(path_list.substr(start, location)); return true; } catch (...) { } return false; } bool FileSysUtilsFindFilesInPath(const std::string& path, std::vector<std::string>& files) { try { DIR* dir; struct dirent* entry; dir = opendir(path.c_str()); while (dir && (entry = readdir(dir))) { files.push_back(entry->d_name); } closedir(dir); return true; } catch (...) { } return false; } #endif <|endoftext|>
<commit_before>/*************************************************************************** jabbercontact.cpp - description ------------------- begin : Fri Apr 12 2002 copyright : (C) 2002 by Daniel Stone email : daniel@raging.dropbear.id.au ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include <kdebug.h> #include <klocale.h> #include <qfont.h> #include "kopetestdaction.h" #include "jabbercontact.h" #include "jabbermessagedialog.h" // Constructor for no-groups JabberContact::JabberContact(QString userid, QString name, QString group, JabberProtocol * protocol) : KopeteContact(protocol) { mProtocol = protocol; mName = name; mGroup = group; mUserID = userid; hasLocalGroup = false; msgDialog = new JabberMessageDialog(this, mProtocol); connect(this, SIGNAL(msgRecieved (QString, QString, QString, QString, QFont, QColor)), msgDialog, SLOT(slotMessageRecieved (QString, QString, QString, QString, QFont, QColor))); connect(msgDialog, SIGNAL(closing()), this, SLOT(slotMWClosing())); connect(protocol, SIGNAL(contactUpdated(QString, QString, QString, QString)), this, SLOT(slotUpdateContact(QString, QString, QString, QString))); connect(protocol, SIGNAL(nukeContacts(bool)), this, SLOT(slotDeleteMySelf(bool))); connect(protocol, SIGNAL(newMessage(QString, QString)), this, SLOT(slotNewMessage(QString, QString))); initContact(userid, name); } void JabberContact::setResource(QString resource) { mResource = resource; } void JabberContact::initContact(QString, QString name) { setName(name); initActions(); slotUpdateContact(mUserID, "", "Offline", ""); } void JabberContact::initActions() { actionChat = KopeteStdAction::sendMessage(this, SLOT(slotChatThisUser()), this, "actionChat"); actionRemoveFromGroup = new KAction(i18n("Remove From Group"), "edittrash", 0, this, SLOT(slotRemoveFromGroup()), this, "actionRemove"); actionRemove = KopeteStdAction::deleteContact(this, SLOT(slotRemoveThisUser()), this, "actionDelete"); actionContactMove = KopeteStdAction::moveContact(this, SLOT(slotMoveThisUser()), this, "actionMove"); actionHistory = KopeteStdAction::viewHistory(this, SLOT(slotViewHistory()), this, "actionHistory"); actionRename = new KAction(i18n("Rename Contact"), "editrename", 0, this, SLOT(slotRenameContact()), this, "actionRename"); } void JabberContact::showContextMenu(QPoint point, QString /*group */ ) { popup = new KPopupMenu(); popup->insertTitle(mUserID + " (" + mResource + ")"); actionChat->plug(popup); popup->insertSeparator(); actionHistory->plug(popup); popup->insertSeparator(); actionRename->plug(popup); actionContactMove->plug(popup); actionRemoveFromGroup->plug(popup); actionRemove->plug(popup); popup->popup(QCursor::pos()); } void JabberContact::slotUpdateContact(QString handle, QString resource, QString status, QString reason) { if (handle != mUserID) return; kdDebug() << "Jabber plugin: Contact - updating " << handle << " to " << status << "." << endl; if (status != QString("")) { mStatus = status; kdDebug() << "Jabber plugin: Updating status." << endl; } if (resource != QString("")) { mResource = resource; } if (reason != QString("")) { mReason = reason; } emit statusChanged(); } void JabberContact::slotRenameContact() { kdDebug() << "Jabber plugin: Renaming contact." << endl; dlgRename = new dlgJabberRename; dlgRename->lblUserID->setText(mUserID); dlgRename->leNickname->setText(mName); connect(dlgRename->btnRename, SIGNAL(clicked()), this, SLOT(slotDoRenameContact())); dlgRename->show(); } void JabberContact::slotDoRenameContact() { mName = dlgRename->leNickname->text(); setName(mName); delete dlgRename; mProtocol->renameContact(mUserID, mName); } void JabberContact::slotDeleteMySelf(bool connected) { delete this; } JabberContact::ContactStatus JabberContact::status() const { if (mStatus == QString("online")) { return Online; } if (mStatus == QString("away") || mStatus == QString("xa") || mStatus == QString("dnd")) { return Away; } else { return Offline; } } QString JabberContact::statusText() const { return mStatus + " (" + mReason + ")"; } QString JabberContact::statusIcon() const { if (mStatus == QString("online")) { return "jabber_online"; } if (mStatus == QString("away") || mStatus == QString("xa")) { return "jabber_away"; } if (mStatus == QString("dnd")) { return "jabber_na"; } return "jabber_offline"; } void JabberContact::slotRemoveThisUser() { mProtocol->removeUser(mUserID); delete this; } void JabberContact::slotMoveThisUser() { mProtocol->moveUser(mUserID, actionContactMove->currentText(), mName, this); mGroup = actionContactMove->currentText(); } int JabberContact::importance() const { if (mStatus == QString("online")) { return 20; } if (mStatus == QString("away")) { return 15; } if (mStatus == QString("xa")) { return 10; } if (mStatus == QString("dnd")) { return 12; } return 0; } void JabberContact::slotChatThisUser() { kdDebug() << "Jabber plugin: Opening chat with user " << mUserID << endl; msgDialog->show(); } void JabberContact::execute() { slotChatThisUser(); } QString JabberContact::userID() { return mUserID; } QString JabberContact::nickname() { return mName; } void JabberContact::slotNewMessage(QString userID, QString message) { kdDebug() << "Jabber contact: Message recieved for " << userID << endl; if (userID != mUserID) { return; } kdDebug() << "Jabber contact: It's for us! *swoon*" << endl; msgDialog->show(); emit msgRecieved(userID, mName, mName, message, QFont(), QColor()); kdDebug() << "Jabber contact: end slotNewMessage" << endl; } void JabberContact::slotMWClosing() { delete msgDialog; msgDialog = new JabberMessageDialog(this, mProtocol); connect(this, SIGNAL(msgRecieved (QString, QString, QString, QString, QFont, QColor)), msgDialog, SLOT(slotMessageRecieved (QString, QString, QString, QString, QFont, QColor))); connect(msgDialog, SIGNAL(closing(void)), this, SLOT(slotMWClosing(void))); } void JabberContact::slotViewHistory() { if (!historyDialog) { historyDialog = new KopeteHistoryDialog(QString("kopete/jabber_logs/%1.log"). arg(mUserID), name(), true, 50, 0, "JabberHistoryDialog"); connect(historyDialog, SIGNAL(closing()), this, SLOT(slotCloseHistoryDialog())); } } void JabberContact::slotCloseHistoryDialog() { delete historyDialog; } #include "jabbercontact.moc" // vim: noet ts=4 sts=4 sw=4: <commit_msg>Sanity! Fix random broken stuff, but some contact handling still needs a minor cleanup, especially around adding recently authorized contacts, triggered by difficulties I had in speaking with the Psi maintainer.<commit_after>/*************************************************************************** jabbercontact.cpp - description ------------------- begin : Fri Apr 12 2002 copyright : (C) 2002 by Daniel Stone email : daniel@raging.dropbear.id.au ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include <kdebug.h> #include <klocale.h> #include <qfont.h> #include "kopetestdaction.h" #include "jabbercontact.h" #include "jabbermessagedialog.h" // Constructor for no-groups JabberContact::JabberContact(QString userid, QString name, QString group, JabberProtocol * protocol) : KopeteContact(protocol) { mProtocol = protocol; mName = name; mGroup = group; mUserID = userid; hasLocalGroup = false; msgDialog = new JabberMessageDialog(this, mProtocol); connect(this, SIGNAL(msgRecieved (QString, QString, QString, QString, QFont, QColor)), msgDialog, SLOT(slotMessageRecieved (QString, QString, QString, QString, QFont, QColor))); connect(msgDialog, SIGNAL(closing()), this, SLOT(slotMWClosing())); connect(protocol, SIGNAL(contactUpdated(QString, QString, QString, QString)), this, SLOT(slotUpdateContact(QString, QString, QString, QString))); connect(protocol, SIGNAL(nukeContacts(bool)), this, SLOT(slotDeleteMySelf(bool))); connect(protocol, SIGNAL(newMessage(QString, QString)), this, SLOT(slotNewMessage(QString, QString))); historyDialog = 0L; initContact(userid, name); } void JabberContact::setResource(QString resource) { mResource = resource; } void JabberContact::initContact(QString, QString name) { setName(name); initActions(); slotUpdateContact(mUserID, "", "Offline", ""); } void JabberContact::initActions() { actionChat = KopeteStdAction::sendMessage(this, SLOT(slotChatThisUser()), this, "actionChat"); actionRemoveFromGroup = new KAction(i18n("Remove From Group"), "edittrash", 0, this, SLOT(slotRemoveFromGroup()), this, "actionRemove"); actionRemove = KopeteStdAction::deleteContact(this, SLOT(slotRemoveThisUser()), this, "actionDelete"); actionContactMove = KopeteStdAction::moveContact(this, SLOT(slotMoveThisUser()), this, "actionMove"); actionHistory = KopeteStdAction::viewHistory(this, SLOT(slotViewHistory()), this, "actionHistory"); actionRename = new KAction(i18n("Rename Contact"), "editrename", 0, this, SLOT(slotRenameContact()), this, "actionRename"); } void JabberContact::showContextMenu(QPoint point, QString /*group */ ) { popup = new KPopupMenu(); popup->insertTitle(mUserID + " (" + mResource + ")"); actionChat->plug(popup); popup->insertSeparator(); actionHistory->plug(popup); popup->insertSeparator(); actionRename->plug(popup); actionContactMove->plug(popup); actionRemoveFromGroup->plug(popup); actionRemove->plug(popup); popup->popup(QCursor::pos()); } void JabberContact::slotUpdateContact(QString handle, QString resource, QString status, QString reason) { if (handle != mUserID) return; kdDebug() << "Jabber plugin: Contact - updating " << handle << " to " << status << "." << endl; if (status != QString("")) { mStatus = status; kdDebug() << "Jabber plugin: Updating status." << endl; } if (resource != QString("")) { mResource = resource; } if (reason != QString("")) { mReason = reason; } emit statusChanged(); } void JabberContact::slotRenameContact() { kdDebug() << "Jabber plugin: Renaming contact." << endl; dlgRename = new dlgJabberRename; dlgRename->lblUserID->setText(mUserID); dlgRename->leNickname->setText(mName); connect(dlgRename->btnRename, SIGNAL(clicked()), this, SLOT(slotDoRenameContact())); dlgRename->show(); } void JabberContact::slotDoRenameContact() { mName = dlgRename->leNickname->text(); setName(mName); delete dlgRename; mProtocol->renameContact(mUserID, mName); } void JabberContact::slotDeleteMySelf(bool connected) { delete this; } JabberContact::ContactStatus JabberContact::status() const { if (mStatus == QString("online")) { return Online; } if (mStatus == QString("away") || mStatus == QString("xa") || mStatus == QString("dnd")) { return Away; } else { return Offline; } } QString JabberContact::statusText() const { return mStatus + " (" + mReason + ")"; } QString JabberContact::statusIcon() const { if (mStatus == QString("online")) { return "jabber_online"; } if (mStatus == QString("away") || mStatus == QString("xa")) { return "jabber_away"; } if (mStatus == QString("dnd")) { return "jabber_na"; } return "jabber_offline"; } void JabberContact::slotRemoveThisUser() { mProtocol->removeUser(mUserID); delete this; } void JabberContact::slotMoveThisUser() { mProtocol->moveUser(mUserID, actionContactMove->currentText(), mName, this); mGroup = actionContactMove->currentText(); } int JabberContact::importance() const { if (mStatus == QString("online")) { return 20; } if (mStatus == QString("away")) { return 15; } if (mStatus == QString("xa")) { return 10; } if (mStatus == QString("dnd")) { return 12; } return 0; } void JabberContact::slotChatThisUser() { kdDebug() << "Jabber plugin: Opening chat with user " << mUserID << endl; msgDialog->show(); } void JabberContact::execute() { slotChatThisUser(); } QString JabberContact::userID() { return mUserID; } QString JabberContact::nickname() { return mName; } void JabberContact::slotNewMessage(QString userID, QString message) { kdDebug() << "Jabber contact: Message recieved for " << userID << endl; if (userID != mUserID) { return; } kdDebug() << "Jabber contact: It's for us! *swoon*" << endl; msgDialog->show(); emit msgRecieved(userID, mName, mName, message, QFont(), QColor()); kdDebug() << "Jabber contact: end slotNewMessage" << endl; } void JabberContact::slotMWClosing() { delete msgDialog; msgDialog = new JabberMessageDialog(this, mProtocol); connect(this, SIGNAL(msgRecieved (QString, QString, QString, QString, QFont, QColor)), msgDialog, SLOT(slotMessageRecieved (QString, QString, QString, QString, QFont, QColor))); connect(msgDialog, SIGNAL(closing(void)), this, SLOT(slotMWClosing(void))); } void JabberContact::slotViewHistory() { if (historyDialog == 0L) { historyDialog = new KopeteHistoryDialog(QString("kopete/jabber_logs/%1.log"). arg(mUserID), name(), true, 50, 0, "JabberHistoryDialog"); connect(historyDialog, SIGNAL(closing()), this, SLOT(slotCloseHistoryDialog())); } } void JabberContact::slotCloseHistoryDialog() { delete historyDialog; historyDialog = 0L; } #include "jabbercontact.moc" // vim: noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* * $Id$ * * Copyright(C) 1998-2006 Satoshi Nakamura * All rights reserved. * */ #include <qmaccount.h> #include <qmmacro.h> #include <qmmessageholder.h> #include <qmrecents.h> #include <qsthread.h> #include <boost/bind.hpp> #include "uri.h" using namespace qm; using namespace qs; /**************************************************************************** * * RecentsImpl * */ struct qm::RecentsImpl { typedef std::vector<std::pair<URI*, Time> > URIList; typedef std::vector<RecentsHandler*> HandlerList; void fireRecentsChanged(RecentsEvent::Type type); Recents* pThis_; const AccountManager* pAccountManager_; Profile* pProfile_; unsigned int nMax_; std::auto_ptr<Macro> pFilter_; std::auto_ptr<qs::RegexPattern> pURLFilter_; URIList list_; CriticalSection cs_; #ifndef NDEBUG unsigned int nLock_; #endif HandlerList listHandler_; }; void qm::RecentsImpl::fireRecentsChanged(RecentsEvent::Type type) { RecentsEvent event(pThis_, type); std::for_each(listHandler_.begin(), listHandler_.end(), boost::bind(&RecentsHandler::recentsChanged, _1, boost::cref(event))); } /**************************************************************************** * * Recents * */ qm::Recents::Recents(const AccountManager* pAccountManager, Profile* pProfile) : pImpl_(0) { std::auto_ptr<Macro> pFilter; wstring_ptr wstrFilter(pProfile->getString(L"Recents", L"MacroFilter")); if (*wstrFilter.get()) pFilter = MacroParser().parse(wstrFilter.get()); std::auto_ptr<RegexPattern> pURLFilter; wstring_ptr wstrPattern(pProfile->getString(L"Recents", L"Filter")); if (*wstrPattern.get()) pURLFilter = RegexCompiler().compile(wstrPattern.get()); pImpl_ = new RecentsImpl(); pImpl_->pThis_ = this; pImpl_->pAccountManager_ = pAccountManager; pImpl_->pProfile_ = pProfile; pImpl_->nMax_ = pProfile->getInt(L"Recents", L"Max"); pImpl_->pFilter_ = pFilter; pImpl_->pURLFilter_ = pURLFilter; #ifndef NDEBUG pImpl_->nLock_ = 0; #endif } qm::Recents::~Recents() { if (pImpl_) { clear(); delete pImpl_; } } unsigned int qm::Recents::getMax() const { return pImpl_->nMax_; } void qm::Recents::setMax(unsigned int nMax) { pImpl_->nMax_ = nMax; } const Macro* qm::Recents::getFilter() const { return pImpl_->pFilter_.get(); } void qm::Recents::setFilter(std::auto_ptr<Macro> pFilter) { pImpl_->pFilter_ = pFilter; } unsigned int qm::Recents::getCount() const { assert(isLocked()); return static_cast<unsigned int>(pImpl_->list_.size()); } const std::pair<URI*, qs::Time>& qm::Recents::get(unsigned int n) const { assert(isLocked()); assert(n < pImpl_->list_.size()); return pImpl_->list_[n]; } void qm::Recents::add(std::auto_ptr<URI> pURI) { assert(pURI.get()); if (pImpl_->nMax_ == 0) return; if (pImpl_->pURLFilter_.get()) { wstring_ptr wstrURI(pURI->toString()); const WCHAR* pStart = 0; const WCHAR* pEnd = 0; pImpl_->pURLFilter_->search(wstrURI.get(), -1, wstrURI.get(), false, &pStart, &pEnd, 0); if (!pStart) return; } Lock<Recents> lock(*this); RecentsImpl::URIList& l = pImpl_->list_; l.push_back(std::make_pair(pURI.get(), Time::getCurrentTime())); pURI.release(); while (l.size() > pImpl_->nMax_) { delete l.front().first; l.erase(l.begin()); } pImpl_->fireRecentsChanged(RecentsEvent::TYPE_ADDED); } void qm::Recents::remove(const URI* pURI) { assert(pURI); Lock<Recents> lock(*this); RecentsImpl::URIList::iterator it = pImpl_->list_.begin(); while (it != pImpl_->list_.end() && *(*it).first != *pURI) ++it; if (it != pImpl_->list_.end()) { delete (*it).first; pImpl_->list_.erase(it); } pImpl_->fireRecentsChanged(RecentsEvent::TYPE_REMOVED); } void qm::Recents::clear() { Lock<Recents> lock(*this); if (pImpl_->list_.empty()) return; std::for_each(pImpl_->list_.begin(), pImpl_->list_.end(), unary_compose_f_gx( qs::deleter<URI>(), std::select1st<RecentsImpl::URIList::value_type>())); pImpl_->list_.clear(); pImpl_->fireRecentsChanged(RecentsEvent::TYPE_REMOVED); } void qm::Recents::removeSeens() { Lock<Recents> lock(*this); bool bChanged = false; for (RecentsImpl::URIList::iterator it = pImpl_->list_.begin(); it != pImpl_->list_.end(); ) { MessagePtrLock mpl(pImpl_->pAccountManager_->getMessage(*(*it).first)); if (!mpl || mpl->isSeen()) { delete (*it).first; it = pImpl_->list_.erase(it); bChanged = true; } else { ++it; } } if (bChanged) pImpl_->fireRecentsChanged(RecentsEvent::TYPE_REMOVED); } void qm::Recents::save() const { pImpl_->pProfile_->setInt(L"Recents", L"Max", pImpl_->nMax_); } void qm::Recents::lock() const { pImpl_->cs_.lock(); #ifndef NDEBUG ++pImpl_->nLock_; #endif } void qm::Recents::unlock() const { #ifndef NDEBUG --pImpl_->nLock_; #endif pImpl_->cs_.unlock(); } #ifndef NDEBUG bool qm::Recents::isLocked() const { return pImpl_->nLock_ != 0; } #endif void qm::Recents::addRecentsHandler(RecentsHandler* pHandler) { pImpl_->listHandler_.push_back(pHandler); } void qm::Recents::removeRecentsHandler(RecentsHandler* pHandler) { RecentsImpl::HandlerList::iterator it = std::remove( pImpl_->listHandler_.begin(), pImpl_->listHandler_.end(), pHandler); pImpl_->listHandler_.erase(it, pImpl_->listHandler_.end()); } /**************************************************************************** * * RecentsHandler * */ qm::RecentsHandler::~RecentsHandler() { } /**************************************************************************** * * RecentsEvent * */ qm::RecentsEvent::RecentsEvent(Recents* pRecents, Type type) : pRecents_(pRecents), type_(type) { } qm::RecentsEvent::~RecentsEvent() { } Recents* qm::RecentsEvent::getRecents() const { return pRecents_; } RecentsEvent::Type qm::RecentsEvent::getType() const { return type_; } <commit_msg>Fix Recents/MacroFilter is not saved.<commit_after>/* * $Id$ * * Copyright(C) 1998-2006 Satoshi Nakamura * All rights reserved. * */ #include <qmaccount.h> #include <qmmacro.h> #include <qmmessageholder.h> #include <qmrecents.h> #include <qsthread.h> #include <boost/bind.hpp> #include "uri.h" using namespace qm; using namespace qs; /**************************************************************************** * * RecentsImpl * */ struct qm::RecentsImpl { typedef std::vector<std::pair<URI*, Time> > URIList; typedef std::vector<RecentsHandler*> HandlerList; void fireRecentsChanged(RecentsEvent::Type type); Recents* pThis_; const AccountManager* pAccountManager_; Profile* pProfile_; unsigned int nMax_; std::auto_ptr<Macro> pFilter_; std::auto_ptr<qs::RegexPattern> pURLFilter_; URIList list_; CriticalSection cs_; #ifndef NDEBUG unsigned int nLock_; #endif HandlerList listHandler_; }; void qm::RecentsImpl::fireRecentsChanged(RecentsEvent::Type type) { RecentsEvent event(pThis_, type); std::for_each(listHandler_.begin(), listHandler_.end(), boost::bind(&RecentsHandler::recentsChanged, _1, boost::cref(event))); } /**************************************************************************** * * Recents * */ qm::Recents::Recents(const AccountManager* pAccountManager, Profile* pProfile) : pImpl_(0) { std::auto_ptr<Macro> pFilter; wstring_ptr wstrFilter(pProfile->getString(L"Recents", L"MacroFilter")); if (*wstrFilter.get()) pFilter = MacroParser().parse(wstrFilter.get()); std::auto_ptr<RegexPattern> pURLFilter; wstring_ptr wstrPattern(pProfile->getString(L"Recents", L"Filter")); if (*wstrPattern.get()) pURLFilter = RegexCompiler().compile(wstrPattern.get()); pImpl_ = new RecentsImpl(); pImpl_->pThis_ = this; pImpl_->pAccountManager_ = pAccountManager; pImpl_->pProfile_ = pProfile; pImpl_->nMax_ = pProfile->getInt(L"Recents", L"Max"); pImpl_->pFilter_ = pFilter; pImpl_->pURLFilter_ = pURLFilter; #ifndef NDEBUG pImpl_->nLock_ = 0; #endif } qm::Recents::~Recents() { if (pImpl_) { clear(); delete pImpl_; } } unsigned int qm::Recents::getMax() const { return pImpl_->nMax_; } void qm::Recents::setMax(unsigned int nMax) { pImpl_->nMax_ = nMax; } const Macro* qm::Recents::getFilter() const { return pImpl_->pFilter_.get(); } void qm::Recents::setFilter(std::auto_ptr<Macro> pFilter) { pImpl_->pFilter_ = pFilter; } unsigned int qm::Recents::getCount() const { assert(isLocked()); return static_cast<unsigned int>(pImpl_->list_.size()); } const std::pair<URI*, qs::Time>& qm::Recents::get(unsigned int n) const { assert(isLocked()); assert(n < pImpl_->list_.size()); return pImpl_->list_[n]; } void qm::Recents::add(std::auto_ptr<URI> pURI) { assert(pURI.get()); if (pImpl_->nMax_ == 0) return; if (pImpl_->pURLFilter_.get()) { wstring_ptr wstrURI(pURI->toString()); const WCHAR* pStart = 0; const WCHAR* pEnd = 0; pImpl_->pURLFilter_->search(wstrURI.get(), -1, wstrURI.get(), false, &pStart, &pEnd, 0); if (!pStart) return; } Lock<Recents> lock(*this); RecentsImpl::URIList& l = pImpl_->list_; l.push_back(std::make_pair(pURI.get(), Time::getCurrentTime())); pURI.release(); while (l.size() > pImpl_->nMax_) { delete l.front().first; l.erase(l.begin()); } pImpl_->fireRecentsChanged(RecentsEvent::TYPE_ADDED); } void qm::Recents::remove(const URI* pURI) { assert(pURI); Lock<Recents> lock(*this); RecentsImpl::URIList::iterator it = pImpl_->list_.begin(); while (it != pImpl_->list_.end() && *(*it).first != *pURI) ++it; if (it != pImpl_->list_.end()) { delete (*it).first; pImpl_->list_.erase(it); } pImpl_->fireRecentsChanged(RecentsEvent::TYPE_REMOVED); } void qm::Recents::clear() { Lock<Recents> lock(*this); if (pImpl_->list_.empty()) return; std::for_each(pImpl_->list_.begin(), pImpl_->list_.end(), unary_compose_f_gx( qs::deleter<URI>(), std::select1st<RecentsImpl::URIList::value_type>())); pImpl_->list_.clear(); pImpl_->fireRecentsChanged(RecentsEvent::TYPE_REMOVED); } void qm::Recents::removeSeens() { Lock<Recents> lock(*this); bool bChanged = false; for (RecentsImpl::URIList::iterator it = pImpl_->list_.begin(); it != pImpl_->list_.end(); ) { MessagePtrLock mpl(pImpl_->pAccountManager_->getMessage(*(*it).first)); if (!mpl || mpl->isSeen()) { delete (*it).first; it = pImpl_->list_.erase(it); bChanged = true; } else { ++it; } } if (bChanged) pImpl_->fireRecentsChanged(RecentsEvent::TYPE_REMOVED); } void qm::Recents::save() const { pImpl_->pProfile_->setInt(L"Recents", L"Max", pImpl_->nMax_); wstring_ptr wstrFilter; if (pImpl_->pFilter_.get()) wstrFilter = pImpl_->pFilter_->getString(); pImpl_->pProfile_->setString(L"Recents", L"MacroFilter", wstrFilter.get()); } void qm::Recents::lock() const { pImpl_->cs_.lock(); #ifndef NDEBUG ++pImpl_->nLock_; #endif } void qm::Recents::unlock() const { #ifndef NDEBUG --pImpl_->nLock_; #endif pImpl_->cs_.unlock(); } #ifndef NDEBUG bool qm::Recents::isLocked() const { return pImpl_->nLock_ != 0; } #endif void qm::Recents::addRecentsHandler(RecentsHandler* pHandler) { pImpl_->listHandler_.push_back(pHandler); } void qm::Recents::removeRecentsHandler(RecentsHandler* pHandler) { RecentsImpl::HandlerList::iterator it = std::remove( pImpl_->listHandler_.begin(), pImpl_->listHandler_.end(), pHandler); pImpl_->listHandler_.erase(it, pImpl_->listHandler_.end()); } /**************************************************************************** * * RecentsHandler * */ qm::RecentsHandler::~RecentsHandler() { } /**************************************************************************** * * RecentsEvent * */ qm::RecentsEvent::RecentsEvent(Recents* pRecents, Type type) : pRecents_(pRecents), type_(type) { } qm::RecentsEvent::~RecentsEvent() { } Recents* qm::RecentsEvent::getRecents() const { return pRecents_; } RecentsEvent::Type qm::RecentsEvent::getType() const { return type_; } <|endoftext|>
<commit_before>#include "startd.h" static char *_FileName_ = __FILE__; ResState::ResState( Resource* rip ) { r_load_q = new LoadQueue(60); r_state = owner_state; r_act = idle_act; atime = (int)time(NULL); stime = atime; this->rip = rip; } ResState::~ResState() { delete r_load_q; } void ResState::update( ClassAd* cp ) { char tmp[80]; sprintf( tmp, "%s=\"%s\"", ATTR_STATE, state_to_string(r_state) ); cp->InsertOrUpdate( tmp ); sprintf( tmp, "%s=%d", ATTR_ENTERED_CURRENT_STATE, stime ); cp->InsertOrUpdate( tmp ); sprintf( tmp, "%s=\"%s\"", ATTR_ACTIVITY, activity_to_string(r_act) ); cp->InsertOrUpdate( tmp ); sprintf( tmp, "%s=%d", ATTR_ENTERED_CURRENT_ACTIVITY, atime ); cp->InsertOrUpdate(tmp); } int ResState::change( State new_state, Activity new_act ) { int statechange = FALSE, actchange = FALSE, now; if( new_state != r_state ) { statechange = TRUE; } if( new_act != r_act ) { actchange = TRUE; } if( ! (actchange || statechange) ) { return TRUE; // If we're not changing anything, return } // leave_action and enter_action return TRUE if they result in // a state or activity change. In these cases, we want to // abort the current state change. if( leave_action( r_state, r_act, statechange, actchange ) ) { return TRUE; } if( statechange && !actchange ) { dprintf( D_ALWAYS, "Changing state: %s -> %s\n", state_to_string(r_state), state_to_string(new_state) ); } else if (actchange && !statechange ) { dprintf( D_ALWAYS, "Changing activity: %s -> %s\n", activity_to_string(r_act), activity_to_string(new_act) ); } else { dprintf( D_ALWAYS, "Changing state and activity: %s/%s -> %s/%s\n", state_to_string(r_state), activity_to_string(r_act), state_to_string(new_state), activity_to_string(new_act) ); } now = (int)time( NULL ); if( statechange ) { stime = now; r_state = new_state; } if( actchange ) { load_activity_change(); r_act = new_act; atime = now; } if( enter_action( r_state, r_act, statechange, actchange ) ) { return TRUE; } // Note our current state and activity in the classad this->update( rip->r_classad ); if( statechange ) { rip->update(); // We want to update the CM on every state change } return TRUE; } int ResState::change( Activity new_act ) { return change( r_state, new_act ); } int ResState::change( State new_state ) { if( new_state == preempting_state ) { if( rip->wants_vacate() ) { return change( new_state, vacating_act ); } else { return change( new_state, killing_act ); } } else { return change( new_state, idle_act ); } } int ResState::eval() { // Recompute attributes needed at every timeout and refresh classad rip->timeout_classad(); int want_suspend, want_vacate; switch( r_state ) { case claimed_state: want_suspend = rip->wants_suspend(); want_vacate = rip->wants_vacate(); if( ((r_act == busy_act) && (!want_suspend)) || (r_act == suspended_act) ) { // STATE TRANSITION #15 or #16 if( want_vacate && rip->eval_vacate() ) { return change( preempting_state, vacating_act ); } if( !want_vacate && rip->eval_kill() ) { return change( preempting_state, killing_act ); } } if( (r_act == busy_act) && want_suspend ) { if( rip->eval_suspend() ) { // STATE TRANSITION #12 return change( suspended_act ); } } if( r_act == suspended_act ) { if( rip->eval_continue() ) { // STATE TRANSITION #13 return change( busy_act ); } } if( (r_act == idle_act) && (rip->r_reqexp->eval() == 0) ) { // STATE TRANSITION #14 return change( preempting_state ); } if( (r_act == busy_act) && (rip->wants_pckpt()) ) { rip->periodic_checkpoint(); } break; // case claimed_state: case preempting_state: if( r_act == vacating_act ) { if( rip->eval_kill() ) { // STATE TRANSITION #18 return change( killing_act ); } } break; // case preempting_state: case unclaimed_state: // See if we should be owner or unclaimed if( rip->r_reqexp->eval() == 0 ) { return change( owner_state ); } // Check to see if we should run benchmarks deal_with_benchmarks( rip ); break; case owner_state: if( rip->r_reqexp->eval() != 0 ) { change( unclaimed_state ); } break; case matched_state: if( rip->r_reqexp->eval() == 0 ) { // STATE TRANSITION #8 change( owner_state ); } break; default: EXCEPT( "eval_state: ERROR: unknown state (%d)", (int)rip->r_state ); } dprintf( D_FULLDEBUG, "State: %s\tActivity: %s\n", state_to_string(r_state), activity_to_string(r_act) ); return 0; } int act_to_load( Activity act ) { switch( act ) { case idle_act: case suspended_act: return 0; break; case busy_act: case benchmarking_act: case vacating_act: case killing_act: return 1; break; default: EXCEPT( "Unknown activity in act_to_load" ); } return -1; } // This function is called on every activity change. It's purpose is // to keep the load_q array up to date by pushing a 0 or 1 onto the // queue for every second we've been in the previous activity. void ResState::load_activity_change() { int now = (int) time(NULL); int delta = now - atime; int load = act_to_load( r_act ); if( delta < 1 ) { delta = 1; } if( delta >= 60 ) { r_load_q->setval( (char)load ); } else { r_load_q->push( delta, (char)load ); } } float ResState::condor_load() { int now = (int) time(NULL); int delta = now - atime; int load = act_to_load( r_act ); int val; if( delta >= 60 ) { // Easy: Condor load is just 1 or 0 depending on previous // activity. return (float)load; } if( delta < 1 ) { delta = 1; } // Hard: Need to use the load queue to determine average // over last minute. val = r_load_q->val( 60 - delta ); val += ( load * delta ); return ( (float)val / 60 ); } LoadQueue::LoadQueue( int q_size ) { size = q_size; head = 0; buf = new char[size]; this->setval( (char)0 ); } LoadQueue::~LoadQueue() { delete [] buf; } // Return the average value of the queue float LoadQueue::avg() { int i, val = 0; for( i=0; i<size; i++ ) { val += buf[i]; } return( (float)val/size ); } // Return the sum of the values of the first num elements. int LoadQueue::val( int num ) { int i, j, val = 0, delta = size - num, foo; // delta is how many elements we need to skip over to get to // the values we care about. If we were asked for more // elements than the size of our array, we need to return the // sum of all values, i.e., don't skip anything. if( delta < 0 ) { delta = 0; num = size; } foo = head + delta; for( i=0; i<num; i++ ) { j = (foo + i) % size; val += buf[j]; } return val; } // Push num elements onto the array with the given value. void LoadQueue::push( int num, char val ) { int i, j; if( num > size ) { num = size; } for( i=0; i<num; i++ ) { j = (head + i) % size; buf[j] = val; } head = (head + num) % size; } // Set all elements of the array to have the given value. void LoadQueue::setval( char val ) { memset( (void*)buf, (int)val, (size*sizeof(char)) ); // Reset the head, too. head = 0; } int ResState::leave_action( State s, Activity a, int statechange, int ) { ClassAd* cp; switch( s ) { case preempting_state: cp = rip->r_classad; cp->Delete( ATTR_CLIENT_MACHINE ); cp->Delete( ATTR_REMOTE_USER ); cp->Delete( ATTR_JOB_START ); cp->Delete( ATTR_JOB_ID ); cp->Delete( ATTR_JOB_UNIVERSE ); cp->Delete( ATTR_LAST_PERIODIC_CHECKPOINT ); break; case matched_state: case owner_state: case unclaimed_state: break; case claimed_state: if( a == suspended_act ) { if( rip->r_starter->kill( DC_SIGCONTINUE ) < 0 ) { // If there's an error sending kill, it could only // mean the starter has blown up and we didn't // know about it. Send SIGKILL to the process // group and go to the owner state. rip->r_starter->killpg( DC_SIGKILL ); return change( owner_state ); } } if( statechange ) { rip->r_cur->cancel_claim_timer(); } break; default: EXCEPT("Unknown state in ResState::leave_action"); } return FALSE; } int ResState::enter_action( State s, Activity a, int statechange, int ) { switch( s ) { case owner_state: rip->cancel_poll_timer(); // Always want to create new match objects if( rip->r_cur ) { delete( rip->r_cur ); } rip->r_cur = new Match; if( rip->r_pre ) { delete rip->r_pre; rip->r_pre = NULL; } // See if we should be in owner or unclaimed state if( rip->r_reqexp->eval() != 0 ) { // Really want to be in unclaimed. return change( unclaimed_state ); } rip->r_reqexp->unavail(); break; case claimed_state: rip->r_reqexp->pub(); if( statechange ) { rip->start_poll_timer(); rip->r_cur->start_claim_timer(); } if( a == suspended_act ) { if( rip->r_starter->kill( DC_SIGSUSPEND ) < 0 ) { rip->r_starter->killpg( DC_SIGKILL ); return change( owner_state ); } } break; case unclaimed_state: rip->r_reqexp->pub(); break; case matched_state: rip->r_reqexp->unavail(); break; case preempting_state: rip->r_reqexp->unavail(); switch( a ) { case idle_act: delete rip->r_cur; rip->r_cur = NULL; // In english: "If the owner wants the machine // back, or there's no one waiting..." if( (rip->r_reqexp->eval() == 0) || ( ! (rip->r_pre && rip->r_pre->agentstream()) ) ) { // STATE TRANSITION #21 if( rip->r_pre ) { rip->r_pre->vacate(); delete rip->r_pre; rip->r_pre = NULL; } change( owner_state ); return TRUE; } if( rip->r_pre && rip->r_pre->agentstream() ) { rip->r_cur = rip->r_pre; rip->r_pre = NULL; // STATE TRANSITION #20 accept_request_claim( rip ); return TRUE; } break; // idle_act case killing_act: if( rip->r_starter->active() ) { if( rip->r_starter->kill( DC_SIGHARDKILL ) < 0 ) { rip->r_starter->killpg( DC_SIGKILL ); return change( owner_state ); } } else { return change( idle_act ); } break; case vacating_act: rip->r_cur->vacate(); // Send a vacate to the client if( rip->r_starter->active() ) { if( rip->r_starter->kill( DC_SIGSOFTKILL ) < 0 ) { rip->r_starter->killpg( DC_SIGKILL ); return change( owner_state ); } } else { return change( idle_act ); } break; default: EXCEPT( "Unknown activity in ResState::enter_action" ); } break; // preempting_state default: EXCEPT("Unknown state in ResState::enter_action"); } return FALSE; } <commit_msg>+ The enter_action for the claimed state now puts REMOTE_USER and CLIENT_MACHINE into our classad and generates the new preempting Match object. + Removed preempting/idle activity. Now, Resource::starter_exited() has more brains, checks state, calls leave_preempting state(), etc. + Added leave_preempting_state(), which is called when we're ready to leave the preempting state (whenever there's no starter). It decides if we should enter claimed_state or owner_state, does all the twiddling with Match objects, vacates schedds, etc.<commit_after>#include "startd.h" static char *_FileName_ = __FILE__; ResState::ResState( Resource* rip ) { r_load_q = new LoadQueue(60); r_state = owner_state; r_act = idle_act; atime = (int)time(NULL); stime = atime; this->rip = rip; } ResState::~ResState() { delete r_load_q; } void ResState::update( ClassAd* cp ) { char tmp[80]; sprintf( tmp, "%s=\"%s\"", ATTR_STATE, state_to_string(r_state) ); cp->InsertOrUpdate( tmp ); sprintf( tmp, "%s=%d", ATTR_ENTERED_CURRENT_STATE, stime ); cp->InsertOrUpdate( tmp ); sprintf( tmp, "%s=\"%s\"", ATTR_ACTIVITY, activity_to_string(r_act) ); cp->InsertOrUpdate( tmp ); sprintf( tmp, "%s=%d", ATTR_ENTERED_CURRENT_ACTIVITY, atime ); cp->InsertOrUpdate(tmp); } int ResState::change( State new_state, Activity new_act ) { int statechange = FALSE, actchange = FALSE, now; if( new_state != r_state ) { statechange = TRUE; } if( new_act != r_act ) { actchange = TRUE; } if( ! (actchange || statechange) ) { return TRUE; // If we're not changing anything, return } // leave_action and enter_action return TRUE if they result in // a state or activity change. In these cases, we want to // abort the current state change. if( leave_action( r_state, r_act, statechange, actchange ) ) { return TRUE; } if( statechange && !actchange ) { dprintf( D_ALWAYS, "Changing state: %s -> %s\n", state_to_string(r_state), state_to_string(new_state) ); } else if (actchange && !statechange ) { dprintf( D_ALWAYS, "Changing activity: %s -> %s\n", activity_to_string(r_act), activity_to_string(new_act) ); } else { dprintf( D_ALWAYS, "Changing state and activity: %s/%s -> %s/%s\n", state_to_string(r_state), activity_to_string(r_act), state_to_string(new_state), activity_to_string(new_act) ); } now = (int)time( NULL ); if( statechange ) { stime = now; r_state = new_state; } if( actchange ) { load_activity_change(); r_act = new_act; atime = now; } if( enter_action( r_state, r_act, statechange, actchange ) ) { return TRUE; } // Note our current state and activity in the classad this->update( rip->r_classad ); if( statechange ) { rip->update(); // We want to update the CM on every state change } return TRUE; } int ResState::change( Activity new_act ) { return change( r_state, new_act ); } int ResState::change( State new_state ) { if( new_state == preempting_state ) { if( rip->wants_vacate() ) { return change( new_state, vacating_act ); } else { return change( new_state, killing_act ); } } else { return change( new_state, idle_act ); } } int ResState::eval() { // Recompute attributes needed at every timeout and refresh classad rip->timeout_classad(); int want_suspend, want_vacate; switch( r_state ) { case claimed_state: want_suspend = rip->wants_suspend(); want_vacate = rip->wants_vacate(); if( ((r_act == busy_act) && (!want_suspend)) || (r_act == suspended_act) ) { // STATE TRANSITION #15 or #16 if( want_vacate && rip->eval_vacate() ) { return change( preempting_state, vacating_act ); } if( !want_vacate && rip->eval_kill() ) { return change( preempting_state, killing_act ); } } if( (r_act == busy_act) && want_suspend ) { if( rip->eval_suspend() ) { // STATE TRANSITION #12 return change( suspended_act ); } } if( r_act == suspended_act ) { if( rip->eval_continue() ) { // STATE TRANSITION #13 return change( busy_act ); } } if( (r_act == idle_act) && (rip->r_reqexp->eval() == 0) ) { // STATE TRANSITION #14 return change( preempting_state ); } if( (r_act == busy_act) && (rip->wants_pckpt()) ) { rip->periodic_checkpoint(); } break; // case claimed_state: case preempting_state: if( r_act == vacating_act ) { if( rip->eval_kill() ) { // STATE TRANSITION #18 return change( killing_act ); } } break; // case preempting_state: case unclaimed_state: // See if we should be owner or unclaimed if( rip->r_reqexp->eval() == 0 ) { return change( owner_state ); } // Check to see if we should run benchmarks deal_with_benchmarks( rip ); break; case owner_state: if( rip->r_reqexp->eval() != 0 ) { change( unclaimed_state ); } break; case matched_state: if( rip->r_reqexp->eval() == 0 ) { // STATE TRANSITION #8 change( owner_state ); } break; default: EXCEPT( "eval_state: ERROR: unknown state (%d)", (int)rip->r_state ); } dprintf( D_FULLDEBUG, "State: %s\tActivity: %s\n", state_to_string(r_state), activity_to_string(r_act) ); return 0; } int act_to_load( Activity act ) { switch( act ) { case idle_act: case suspended_act: return 0; break; case busy_act: case benchmarking_act: case vacating_act: case killing_act: return 1; break; default: EXCEPT( "Unknown activity in act_to_load" ); } return -1; } // This function is called on every activity change. It's purpose is // to keep the load_q array up to date by pushing a 0 or 1 onto the // queue for every second we've been in the previous activity. void ResState::load_activity_change() { int now = (int) time(NULL); int delta = now - atime; int load = act_to_load( r_act ); if( delta < 1 ) { delta = 1; } if( delta >= 60 ) { r_load_q->setval( (char)load ); } else { r_load_q->push( delta, (char)load ); } } float ResState::condor_load() { int now = (int) time(NULL); int delta = now - atime; int load = act_to_load( r_act ); int val; if( delta >= 60 ) { // Easy: Condor load is just 1 or 0 depending on previous // activity. return (float)load; } if( delta < 1 ) { delta = 1; } // Hard: Need to use the load queue to determine average // over last minute. val = r_load_q->val( 60 - delta ); val += ( load * delta ); return ( (float)val / 60 ); } LoadQueue::LoadQueue( int q_size ) { size = q_size; head = 0; buf = new char[size]; this->setval( (char)0 ); } LoadQueue::~LoadQueue() { delete [] buf; } // Return the average value of the queue float LoadQueue::avg() { int i, val = 0; for( i=0; i<size; i++ ) { val += buf[i]; } return( (float)val/size ); } // Return the sum of the values of the first num elements. int LoadQueue::val( int num ) { int i, j, val = 0, delta = size - num, foo; // delta is how many elements we need to skip over to get to // the values we care about. If we were asked for more // elements than the size of our array, we need to return the // sum of all values, i.e., don't skip anything. if( delta < 0 ) { delta = 0; num = size; } foo = head + delta; for( i=0; i<num; i++ ) { j = (foo + i) % size; val += buf[j]; } return val; } // Push num elements onto the array with the given value. void LoadQueue::push( int num, char val ) { int i, j; if( num > size ) { num = size; } for( i=0; i<num; i++ ) { j = (head + i) % size; buf[j] = val; } head = (head + num) % size; } // Set all elements of the array to have the given value. void LoadQueue::setval( char val ) { memset( (void*)buf, (int)val, (size*sizeof(char)) ); // Reset the head, too. head = 0; } int ResState::leave_action( State s, Activity a, int statechange, int ) { ClassAd* cp; switch( s ) { case preempting_state: cp = rip->r_classad; cp->Delete( ATTR_CLIENT_MACHINE ); cp->Delete( ATTR_REMOTE_USER ); cp->Delete( ATTR_JOB_START ); cp->Delete( ATTR_JOB_ID ); cp->Delete( ATTR_JOB_UNIVERSE ); cp->Delete( ATTR_LAST_PERIODIC_CHECKPOINT ); break; case matched_state: case owner_state: case unclaimed_state: break; case claimed_state: if( a == suspended_act ) { if( rip->r_starter->kill( DC_SIGCONTINUE ) < 0 ) { // If there's an error sending kill, it could only // mean the starter has blown up and we didn't // know about it. Send SIGKILL to the process // group and go to the owner state. rip->r_starter->killpg( DC_SIGKILL ); return change( owner_state ); } } if( statechange ) { rip->r_cur->cancel_claim_timer(); } break; default: EXCEPT("Unknown state in ResState::leave_action"); } return FALSE; } int ResState::enter_action( State s, Activity a, int statechange, int ) { switch( s ) { case owner_state: rip->cancel_poll_timer(); // Always want to create new match objects if( rip->r_cur ) { delete( rip->r_cur ); } rip->r_cur = new Match; if( rip->r_pre ) { delete rip->r_pre; rip->r_pre = NULL; } // See if we should be in owner or unclaimed state if( rip->r_reqexp->eval() != 0 ) { // Really want to be in unclaimed. return change( unclaimed_state ); } rip->r_reqexp->unavail(); break; case claimed_state: rip->r_reqexp->pub(); if( statechange ) { rip->start_poll_timer(); rip->r_cur->start_claim_timer(); // Put attributes in our classad for this claim { char tmp[1024]; sprintf( tmp, "%s=\"%s\"", ATTR_REMOTE_USER, rip->r_cur->client()->name() ); (rip->r_classad)->Insert( tmp ); sprintf( tmp, "%s=\"%s\"", ATTR_CLIENT_MACHINE, rip->r_cur->client()->host() ); (rip->r_classad)->Insert( tmp ); } // Generate a preempting match object rip->r_pre = new Match; } if( a == suspended_act ) { if( rip->r_starter->kill( DC_SIGSUSPEND ) < 0 ) { rip->r_starter->killpg( DC_SIGKILL ); return change( owner_state ); } } break; case unclaimed_state: rip->r_reqexp->pub(); break; case matched_state: rip->r_reqexp->unavail(); break; case preempting_state: rip->r_reqexp->unavail(); switch( a ) { case killing_act: if( rip->r_starter->active() ) { if( rip->r_starter->kill( DC_SIGHARDKILL ) < 0 ) { rip->r_starter->killpg( DC_SIGKILL ); return change( owner_state ); } } else { rip->leave_preempting_state(); return TRUE; } break; case vacating_act: if( rip->r_starter->active() ) { if( rip->r_starter->kill( DC_SIGSOFTKILL ) < 0 ) { rip->r_starter->killpg( DC_SIGKILL ); return change( owner_state ); } } else { rip->leave_preempting_state(); return TRUE; } break; default: EXCEPT( "Unknown activity in ResState::enter_action" ); } break; // preempting_state default: EXCEPT("Unknown state in ResState::enter_action"); } return FALSE; } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // QUESO - a library to support the Quantification of Uncertainty // for Estimation, Simulation and Optimization // // Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include <string> #include <iomanip> #include <queso/OptimizerMonitor.h> namespace QUESO { OptimizerMonitor::OptimizerMonitor( unsigned int n_iters ) : m_display_conv(false), m_print_xmin(false) { m_minimizer_hist.reserve(n_iters); m_objective_hist.reserve(n_iters); m_norm_hist.reserve(n_iters); } OptimizerMonitor::~OptimizerMonitor() {} void OptimizerMonitor::set_display_output( bool enable_output, bool print_xmin ) { m_display_conv = enable_output; m_print_xmin = print_xmin; } void OptimizerMonitor::append( std::vector<double>& x_min, double objective, double norm ) { m_minimizer_hist.push_back(x_min); m_objective_hist.push_back(objective); m_norm_hist.push_back(norm); // Print out to screen if the user set the option if( m_display_conv ) { // If we are appending the first entry, print a nice header if( m_minimizer_hist.size() == 1 ) { this->print_header(std::cout); } // We're assuming here the size of the array is the current iteration this->print_iteration(m_norm_hist.size(),std::cout); } } void OptimizerMonitor::print_header( std::ostream& output ) const { unsigned int width = 35; output.width(5); output << "i"; output.width(8); output << "f" << std::string(5,' '); output.width(11); output << "norm" << std::endl; output << std::string(width,'-') << std::endl; } void OptimizerMonitor::print_iteration( unsigned int iter, std::ostream& output ) const { output.width(5); output << iter; output.width(2); output << " "; output.width(12); output << std::scientific << m_objective_hist[iter-1]; output.width(2); output << " "; output.width(12); output << m_norm_hist[iter-1] << std::endl; } } // end namespace QUESO <commit_msg>Adding monitor output for minimizer convergence<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // QUESO - a library to support the Quantification of Uncertainty // for Estimation, Simulation and Optimization // // Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include <string> #include <iomanip> #include <queso/OptimizerMonitor.h> namespace QUESO { OptimizerMonitor::OptimizerMonitor( unsigned int n_iters ) : m_display_conv(false), m_print_xmin(false) { m_minimizer_hist.reserve(n_iters); m_objective_hist.reserve(n_iters); m_norm_hist.reserve(n_iters); } OptimizerMonitor::~OptimizerMonitor() {} void OptimizerMonitor::set_display_output( bool enable_output, bool print_xmin ) { m_display_conv = enable_output; m_print_xmin = print_xmin; } void OptimizerMonitor::append( std::vector<double>& x_min, double objective, double norm ) { m_minimizer_hist.push_back(x_min); m_objective_hist.push_back(objective); m_norm_hist.push_back(norm); // Print out to screen if the user set the option if( m_display_conv ) { // If we are appending the first entry, print a nice header if( m_minimizer_hist.size() == 1 ) { this->print_header(std::cout); } // We're assuming here the size of the array is the current iteration this->print_iteration(m_norm_hist.size(),std::cout); } } void OptimizerMonitor::print_header( std::ostream& output ) const { unsigned int width = 35; if( m_print_xmin) width += (m_minimizer_hist[0]).size()*12; output.width(5); output << "i"; if( m_print_xmin) { for( unsigned int i = 0; i < m_minimizer_hist[0].size(); i++ ) { output.width(8); output << "x" << i << std::string(5,' '); } } output.width(8); output << "f" << std::string(5,' '); output.width(11); output << "norm" << std::endl; output << std::string(width,'-') << std::endl; } void OptimizerMonitor::print_iteration( unsigned int iter, std::ostream& output ) const { output.width(5); output << iter; if( m_print_xmin) { for( unsigned int i = 0; i < m_minimizer_hist[iter-1].size(); i++ ) { output.width(2); output << " "; output.width(12); output << std::scientific << m_minimizer_hist[iter-1][i]; } } output.width(2); output << " "; output.width(12); output << std::scientific << m_objective_hist[iter-1]; output.width(2); output << " "; output.width(12); output << m_norm_hist[iter-1] << std::endl; } } // end namespace QUESO <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rdboptions.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:10:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <stdio.h> #include "rdboptions.hxx" using namespace rtl; sal_Bool RdbOptions::initOptions(int ac, char* av[], sal_Bool bCmdFile) throw( IllegalArgument ) { sal_Bool ret = sal_True; sal_uInt16 i=0; if (!bCmdFile) { bCmdFile = sal_True; m_program = av[0]; if (ac < 2) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } i = 1; } else { i = 0; } char *s=NULL; for (; i < ac; i++) { if (av[i][0] == '-') { switch (av[i][1]) { case 'O': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-O', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-O"] = OString(s); break; case 'X': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-X', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-X"] = OString(s); break; case 'R': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-R', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-R"] = OString(s); break; case 'B': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-B', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-B"] = OString(s); break; case 'b': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-b', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-b"] = OString(s); break; case 'T': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-T', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } if (m_options.count("-T") > 0) { OString tmp(m_options["-T"]); tmp = tmp + ";" + s; m_options["-T"] = tmp; } else { m_options["-T"] = OString(s); } break; case 'F': if (av[i][2] == 'T') { if (av[i][3] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-FT', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 3; } if (m_options.count("-FT") > 0) { OString tmp(m_options["-FT"]); tmp = tmp + ";" + s; m_options["-FT"] = tmp; } else { m_options["-FT"] = OString(s); } } else { if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-F', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-F"] = OString(s); } break; case 'L': if (av[i][2] != '\0') { OString tmp("'-L', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } m_options["-L"] = OString(); m_generateTypeList = sal_True; break; default: throw IllegalArgument("the option is unknown" + OString(av[i])); } } else { if (av[i][0] == '@') { FILE* cmdFile = fopen(av[i]+1, "r"); if( cmdFile == NULL ) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } else { int rargc=0; char* rargv[512]; char buffer[512]; while ( fscanf(cmdFile, "%s", buffer) != EOF ) { rargv[rargc]= strdup(buffer); rargc++; } fclose(cmdFile); ret = initOptions(rargc, rargv, bCmdFile); for (long j=0; j < rargc; j++) { free(rargv[j]); } } } else { m_inputFiles.push_back(av[i]); } } } return ret; } OString RdbOptions::prepareHelp() { OString help("\nusing: "); help += m_program + " [-options] (-R<regname> | file_1 [... file_n])\n"; help += "The rdbmaker supports 2 modes:\n"; help += " 1. using the internal UNO type description manager -> use -R<regname>\n" " where regname specifies the type library used by the UNO type description manager\n" " after UNO is bootstrapped. This option disables the use of any other type libraries.\n" " The tpye library must be a valid product type library which means that all types are\n" " stored under the global base node UCR (Uno Core Reflection data).\n"; help += " 2. using one or more type library files -> use file_1 ... file_n\n" " file_1 .. file_n specifies one or more valid type library files which are used to\n" " find the needed type information. The used type libraries have to support the same base\n" " node (-B option).\n"; help += "Options:\n"; help += " -O<filename> = filename specifies the name of the generated registry\n"; help += " or text file.\n"; help += " -L = specifies that only a text file is generated with the\n"; help += " names of the specified types and their dependencies.\n"; help += " Default is that a registry file will be created\n"; // help += " -X<xmlfile> = xmlfile specifies the name of an xml description where\n"; // help += " all types are specified which will be generated.\n"; help += " -T<name> = name specifies a type or a list of types. The output for\n"; help += " [t1;...] this type is generated.\n"; help += " Example: 'com.sun.star.uno.XInterface' is a valid type.\n"; help += " -FT<name> = name specifies a type or a list of types. For this types\n"; help += " [t1;...] nothing will be generated.\n"; help += " |F<file> = file specifies an text file. For the specified types in\n" ; help += " this file nothing will be generated.\n"; help += " -B<name> = name specifies the base node. All types are searched under\n"; help += " this node. Default is the root '/' of the registry files.\n"; help += " This option takes effect using run mode 2 only.\n"; help += " -b<name> = name specifies the base node of the output registry. All\n"; help += " types will be generated under this node. Default is the\n"; help += " root '/' of the registry file.\n"; help += prepareVersion(); return help; } OString RdbOptions::prepareVersion() { OString version("\nSun Microsystems (R) "); version += m_program + " Version 2.0\n\n"; return version; } <commit_msg>INTEGRATION: CWS gcc430two (1.6.30); FILE MERGED 2008/01/28 09:53:09 rene 1.6.30.1: more gcc 4.3.0 things<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rdboptions.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: ihi $ $Date: 2008-02-04 13:45:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <stdio.h> #include <string.h> #include "rdboptions.hxx" using namespace rtl; sal_Bool RdbOptions::initOptions(int ac, char* av[], sal_Bool bCmdFile) throw( IllegalArgument ) { sal_Bool ret = sal_True; sal_uInt16 i=0; if (!bCmdFile) { bCmdFile = sal_True; m_program = av[0]; if (ac < 2) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } i = 1; } else { i = 0; } char *s=NULL; for (; i < ac; i++) { if (av[i][0] == '-') { switch (av[i][1]) { case 'O': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-O', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-O"] = OString(s); break; case 'X': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-X', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-X"] = OString(s); break; case 'R': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-R', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-R"] = OString(s); break; case 'B': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-B', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-B"] = OString(s); break; case 'b': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-b', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-b"] = OString(s); break; case 'T': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-T', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } if (m_options.count("-T") > 0) { OString tmp(m_options["-T"]); tmp = tmp + ";" + s; m_options["-T"] = tmp; } else { m_options["-T"] = OString(s); } break; case 'F': if (av[i][2] == 'T') { if (av[i][3] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-FT', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 3; } if (m_options.count("-FT") > 0) { OString tmp(m_options["-FT"]); tmp = tmp + ";" + s; m_options["-FT"] = tmp; } else { m_options["-FT"] = OString(s); } } else { if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-F', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-F"] = OString(s); } break; case 'L': if (av[i][2] != '\0') { OString tmp("'-L', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } m_options["-L"] = OString(); m_generateTypeList = sal_True; break; default: throw IllegalArgument("the option is unknown" + OString(av[i])); } } else { if (av[i][0] == '@') { FILE* cmdFile = fopen(av[i]+1, "r"); if( cmdFile == NULL ) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } else { int rargc=0; char* rargv[512]; char buffer[512]; while ( fscanf(cmdFile, "%s", buffer) != EOF ) { rargv[rargc]= strdup(buffer); rargc++; } fclose(cmdFile); ret = initOptions(rargc, rargv, bCmdFile); for (long j=0; j < rargc; j++) { free(rargv[j]); } } } else { m_inputFiles.push_back(av[i]); } } } return ret; } OString RdbOptions::prepareHelp() { OString help("\nusing: "); help += m_program + " [-options] (-R<regname> | file_1 [... file_n])\n"; help += "The rdbmaker supports 2 modes:\n"; help += " 1. using the internal UNO type description manager -> use -R<regname>\n" " where regname specifies the type library used by the UNO type description manager\n" " after UNO is bootstrapped. This option disables the use of any other type libraries.\n" " The tpye library must be a valid product type library which means that all types are\n" " stored under the global base node UCR (Uno Core Reflection data).\n"; help += " 2. using one or more type library files -> use file_1 ... file_n\n" " file_1 .. file_n specifies one or more valid type library files which are used to\n" " find the needed type information. The used type libraries have to support the same base\n" " node (-B option).\n"; help += "Options:\n"; help += " -O<filename> = filename specifies the name of the generated registry\n"; help += " or text file.\n"; help += " -L = specifies that only a text file is generated with the\n"; help += " names of the specified types and their dependencies.\n"; help += " Default is that a registry file will be created\n"; // help += " -X<xmlfile> = xmlfile specifies the name of an xml description where\n"; // help += " all types are specified which will be generated.\n"; help += " -T<name> = name specifies a type or a list of types. The output for\n"; help += " [t1;...] this type is generated.\n"; help += " Example: 'com.sun.star.uno.XInterface' is a valid type.\n"; help += " -FT<name> = name specifies a type or a list of types. For this types\n"; help += " [t1;...] nothing will be generated.\n"; help += " |F<file> = file specifies an text file. For the specified types in\n" ; help += " this file nothing will be generated.\n"; help += " -B<name> = name specifies the base node. All types are searched under\n"; help += " this node. Default is the root '/' of the registry files.\n"; help += " This option takes effect using run mode 2 only.\n"; help += " -b<name> = name specifies the base node of the output registry. All\n"; help += " types will be generated under this node. Default is the\n"; help += " root '/' of the registry file.\n"; help += prepareVersion(); return help; } OString RdbOptions::prepareVersion() { OString version("\nSun Microsystems (R) "); version += m_program + " Version 2.0\n\n"; return version; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Raine Makelainen <raine.makelainen@jollamobile.com> ** ****************************************************************************/ #include "declarativewebcontainer.h" #include <QPointer> #include <QMetaObject> #include <QTimerEvent> #include <QQuickWindow> DeclarativeWebContainer::DeclarativeWebContainer(QQuickItem *parent) : QQuickItem(parent) , m_webView(0) , m_foreground(true) , m_background(false) , m_windowVisible(false) , m_backgroundTimer(0) , m_pageActive(false) , m_inputPanelVisible(false) , m_inputPanelHeight(0.0) , m_inputPanelOpenHeight(0.0) , m_toolbarHeight(0.0) { setFlag(QQuickItem::ItemHasContents, true); if (!window()) { connect(this, SIGNAL(windowChanged(QQuickWindow*)), this, SLOT(handleWindowChanged(QQuickWindow*))); } else { connect(window(), SIGNAL(visibleChanged(bool)), this, SLOT(windowVisibleChanged(bool))); } } DeclarativeWebContainer::~DeclarativeWebContainer() { // Disconnect all signal slot connections if (m_webView) { disconnect(m_webView, 0, 0, 0); } } QQuickItem *DeclarativeWebContainer::webView() const { return m_webView; } void DeclarativeWebContainer::setWebView(QQuickItem *webView) { if (m_webView != webView) { m_webView = webView; connect(m_webView, SIGNAL(imeNotification(int,bool,int,int,QString)), this, SLOT(imeNotificationChanged(int,bool,int,int,QString))); connect(m_webView, SIGNAL(contentHeightChanged()), this, SLOT(resetHeight())); connect(m_webView, SIGNAL(scrollableOffsetChanged()), this, SLOT(resetHeight())); emit webViewChanged(); } } bool DeclarativeWebContainer::foreground() const { return m_foreground; } void DeclarativeWebContainer::setForeground(bool active) { if (m_foreground != active) { m_foreground = active; if (!m_foreground) { // Respect content height when browser brought back from home resetHeight(true); } emit foregroundChanged(); } } bool DeclarativeWebContainer::background() const { return m_background; } bool DeclarativeWebContainer::pageActive() const { return m_pageActive; } void DeclarativeWebContainer::setPageActive(bool active) { if (m_pageActive != active) { m_pageActive = active; emit pageActiveChanged(); // If dialog has been opened, we need to verify that input panel is not visible. // This might happen when the user fills in login details to a form and // presses enter to accept the form after which PasswordManagerDialog is pushed to pagestack // on top the BrowserPage. Once PassowordManagerDialog is accepted/rejected // this condition can be met. If pageActive changes to true before keyboard is fully closed, // then the inputPanelVisibleChanged() signal is emitted by setInputPanelHeight. if (m_pageActive && m_inputPanelHeight == 0 && m_inputPanelVisible) { m_inputPanelVisible = false; emit inputPanelVisibleChanged(); } } } bool DeclarativeWebContainer::inputPanelVisible() const { return m_inputPanelVisible; } qreal DeclarativeWebContainer::inputPanelHeight() const { return m_inputPanelHeight; } void DeclarativeWebContainer::setInputPanelHeight(qreal height) { if (m_inputPanelHeight != height) { bool imVisibleChanged = false; m_inputPanelHeight = height; if (m_pageActive) { if (m_inputPanelHeight == 0) { if (m_inputPanelVisible) { m_inputPanelVisible = false; imVisibleChanged = true; } } else if (m_inputPanelHeight == m_inputPanelOpenHeight) { if (!m_inputPanelVisible) { m_inputPanelVisible = true; imVisibleChanged = true; } } } if (imVisibleChanged) { emit inputPanelVisibleChanged(); } emit inputPanelHeightChanged(); } } qreal DeclarativeWebContainer::inputPanelOpenHeight() const { return m_inputPanelOpenHeight; } void DeclarativeWebContainer::setInputPanelOpenHeight(qreal height) { if (m_inputPanelOpenHeight != height) { m_inputPanelOpenHeight = height; emit inputPanelOpenHeightChanged(); } } qreal DeclarativeWebContainer::toolbarHeight() const { return m_toolbarHeight; } void DeclarativeWebContainer::setToolbarHeight(qreal height) { if (m_toolbarHeight != height) { m_toolbarHeight = height; emit toolbarHeightChanged(); } } void DeclarativeWebContainer::resetHeight(bool respectContentHeight) { if (!m_webView || !m_webView->state().isEmpty()) { return; } qreal fullHeight = height(); // Application active if (respectContentHeight) { // Handle webView height over here, BrowserPage.qml loading // reset might be redundant as we have also loaded trigger // reset. However, I'd leave it there for safety reasons. // We need to reset height always back to short height when loading starts // so that after tab change there is always initial short composited height. // Height may expand when content is moved. if (contentHeight() > fullHeight + m_toolbarHeight) { m_webView->setHeight(fullHeight); } else { m_webView->setHeight(fullHeight - m_toolbarHeight); } } else { m_webView->setHeight(fullHeight - m_toolbarHeight); } } void DeclarativeWebContainer::imeNotificationChanged(int state, bool open, int cause, int focusChange, const QString &type) { Q_UNUSED(open) Q_UNUSED(cause) Q_UNUSED(focusChange) Q_UNUSED(type) // QmlMozView's input context open is actually intention (0 closed, 1 opened). // cause 3 equals InputContextAction::CAUSE_MOUSE nsIWidget.h if (state == 1 && cause == 3) { // For safety reset height based on contentHeight before going to "boundHeightControl" state // so that when vkb is closed we get correctly reset height back. resetHeight(true); if (!m_inputPanelVisible) { m_inputPanelVisible = true; emit inputPanelVisibleChanged(); } } } qreal DeclarativeWebContainer::contentHeight() const { static QMetaProperty property; if (m_webView) { if (!property.isValid()) { const QMetaObject *webViewMetaObject = m_webView->metaObject(); int propertyIndex = webViewMetaObject->indexOfProperty("contentHeight"); property = webViewMetaObject->property(propertyIndex); } qreal height = property.read(m_webView).toReal(); return height; } else { return 0.0; } } void DeclarativeWebContainer::timerEvent(QTimerEvent *event) { if (m_backgroundTimer == event->timerId()) { if (window()) { // Guard window visibility change was not cancelled after timer triggered. bool tmpVisible = window()->isVisible(); // m_windowVisible == m_background visibility changed if (tmpVisible == m_windowVisible && m_windowVisible == m_background) { m_background = !m_windowVisible; emit backgroundChanged(); } } killTimer(m_backgroundTimer); } } void DeclarativeWebContainer::windowVisibleChanged(bool visible) { if (window()) { m_windowVisible = window()->isVisible(); m_backgroundTimer = startTimer(1000); } } void DeclarativeWebContainer::handleWindowChanged(QQuickWindow *window) { if (window) { connect(window, SIGNAL(visibleChanged(bool)), this, SLOT(windowVisibleChanged(bool))); } } <commit_msg>[sailfish-browser] Fix broken browser page when rotating in tabs page. Fixes JB#14688<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Raine Makelainen <raine.makelainen@jollamobile.com> ** ****************************************************************************/ #include "declarativewebcontainer.h" #include <QPointer> #include <QMetaObject> #include <QTimerEvent> #include <QQuickWindow> DeclarativeWebContainer::DeclarativeWebContainer(QQuickItem *parent) : QQuickItem(parent) , m_webView(0) , m_foreground(true) , m_background(false) , m_windowVisible(false) , m_backgroundTimer(0) , m_pageActive(false) , m_inputPanelVisible(false) , m_inputPanelHeight(0.0) , m_inputPanelOpenHeight(0.0) , m_toolbarHeight(0.0) { setFlag(QQuickItem::ItemHasContents, true); if (!window()) { connect(this, SIGNAL(windowChanged(QQuickWindow*)), this, SLOT(handleWindowChanged(QQuickWindow*))); } else { connect(window(), SIGNAL(visibleChanged(bool)), this, SLOT(windowVisibleChanged(bool))); } } DeclarativeWebContainer::~DeclarativeWebContainer() { // Disconnect all signal slot connections if (m_webView) { disconnect(m_webView, 0, 0, 0); } } QQuickItem *DeclarativeWebContainer::webView() const { return m_webView; } void DeclarativeWebContainer::setWebView(QQuickItem *webView) { if (m_webView != webView) { m_webView = webView; connect(m_webView, SIGNAL(imeNotification(int,bool,int,int,QString)), this, SLOT(imeNotificationChanged(int,bool,int,int,QString))); connect(m_webView, SIGNAL(contentHeightChanged()), this, SLOT(resetHeight())); connect(m_webView, SIGNAL(scrollableOffsetChanged()), this, SLOT(resetHeight())); connect(this, SIGNAL(heightChanged()), this, SLOT(resetHeight())); emit webViewChanged(); } } bool DeclarativeWebContainer::foreground() const { return m_foreground; } void DeclarativeWebContainer::setForeground(bool active) { if (m_foreground != active) { m_foreground = active; if (!m_foreground) { // Respect content height when browser brought back from home resetHeight(true); } emit foregroundChanged(); } } bool DeclarativeWebContainer::background() const { return m_background; } bool DeclarativeWebContainer::pageActive() const { return m_pageActive; } void DeclarativeWebContainer::setPageActive(bool active) { if (m_pageActive != active) { m_pageActive = active; emit pageActiveChanged(); // If dialog has been opened, we need to verify that input panel is not visible. // This might happen when the user fills in login details to a form and // presses enter to accept the form after which PasswordManagerDialog is pushed to pagestack // on top the BrowserPage. Once PassowordManagerDialog is accepted/rejected // this condition can be met. If pageActive changes to true before keyboard is fully closed, // then the inputPanelVisibleChanged() signal is emitted by setInputPanelHeight. if (m_pageActive && m_inputPanelHeight == 0 && m_inputPanelVisible) { m_inputPanelVisible = false; emit inputPanelVisibleChanged(); } } } bool DeclarativeWebContainer::inputPanelVisible() const { return m_inputPanelVisible; } qreal DeclarativeWebContainer::inputPanelHeight() const { return m_inputPanelHeight; } void DeclarativeWebContainer::setInputPanelHeight(qreal height) { if (m_inputPanelHeight != height) { bool imVisibleChanged = false; m_inputPanelHeight = height; if (m_pageActive) { if (m_inputPanelHeight == 0) { if (m_inputPanelVisible) { m_inputPanelVisible = false; imVisibleChanged = true; } } else if (m_inputPanelHeight == m_inputPanelOpenHeight) { if (!m_inputPanelVisible) { m_inputPanelVisible = true; imVisibleChanged = true; } } } if (imVisibleChanged) { emit inputPanelVisibleChanged(); } emit inputPanelHeightChanged(); } } qreal DeclarativeWebContainer::inputPanelOpenHeight() const { return m_inputPanelOpenHeight; } void DeclarativeWebContainer::setInputPanelOpenHeight(qreal height) { if (m_inputPanelOpenHeight != height) { m_inputPanelOpenHeight = height; emit inputPanelOpenHeightChanged(); } } qreal DeclarativeWebContainer::toolbarHeight() const { return m_toolbarHeight; } void DeclarativeWebContainer::setToolbarHeight(qreal height) { if (m_toolbarHeight != height) { m_toolbarHeight = height; emit toolbarHeightChanged(); } } void DeclarativeWebContainer::resetHeight(bool respectContentHeight) { if (!m_webView || !m_webView->state().isEmpty()) { return; } qreal fullHeight = height(); // Application active if (respectContentHeight) { // Handle webView height over here, BrowserPage.qml loading // reset might be redundant as we have also loaded trigger // reset. However, I'd leave it there for safety reasons. // We need to reset height always back to short height when loading starts // so that after tab change there is always initial short composited height. // Height may expand when content is moved. if (contentHeight() > fullHeight + m_toolbarHeight) { m_webView->setHeight(fullHeight); } else { m_webView->setHeight(fullHeight - m_toolbarHeight); } } else { m_webView->setHeight(fullHeight - m_toolbarHeight); } } void DeclarativeWebContainer::imeNotificationChanged(int state, bool open, int cause, int focusChange, const QString &type) { Q_UNUSED(open) Q_UNUSED(cause) Q_UNUSED(focusChange) Q_UNUSED(type) // QmlMozView's input context open is actually intention (0 closed, 1 opened). // cause 3 equals InputContextAction::CAUSE_MOUSE nsIWidget.h if (state == 1 && cause == 3) { // For safety reset height based on contentHeight before going to "boundHeightControl" state // so that when vkb is closed we get correctly reset height back. resetHeight(true); if (!m_inputPanelVisible) { m_inputPanelVisible = true; emit inputPanelVisibleChanged(); } } } qreal DeclarativeWebContainer::contentHeight() const { static QMetaProperty property; if (m_webView) { if (!property.isValid()) { const QMetaObject *webViewMetaObject = m_webView->metaObject(); int propertyIndex = webViewMetaObject->indexOfProperty("contentHeight"); property = webViewMetaObject->property(propertyIndex); } qreal height = property.read(m_webView).toReal(); return height; } else { return 0.0; } } void DeclarativeWebContainer::timerEvent(QTimerEvent *event) { if (m_backgroundTimer == event->timerId()) { if (window()) { // Guard window visibility change was not cancelled after timer triggered. bool tmpVisible = window()->isVisible(); // m_windowVisible == m_background visibility changed if (tmpVisible == m_windowVisible && m_windowVisible == m_background) { m_background = !m_windowVisible; emit backgroundChanged(); } } killTimer(m_backgroundTimer); } } void DeclarativeWebContainer::windowVisibleChanged(bool visible) { if (window()) { m_windowVisible = window()->isVisible(); m_backgroundTimer = startTimer(1000); } } void DeclarativeWebContainer::handleWindowChanged(QQuickWindow *window) { if (window) { connect(window, SIGNAL(visibleChanged(bool)), this, SLOT(windowVisibleChanged(bool))); } } <|endoftext|>
<commit_before>/// /// @file S2_easy.cpp /// @brief Calculate the contribution of the clustered easy leaves /// and the sparse easy leaves in parallel using OpenMP /// (Deleglise-Rivat algorithm). /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <primecount-internal.hpp> #include <calculator.hpp> #include <fast_div.hpp> #include <generate.hpp> #include <int128_t.hpp> #include <min.hpp> #include <imath.hpp> #include <S2Status.hpp> #include <S2.hpp> #include <json.hpp> #include <stdint.h> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { template <typename T, typename J> void backup(J& json, T x, int64_t y, int64_t z, int64_t pi_x13, int threads, double percent, double time) { json["S2_easy"]["x"] = to_string(x); json["S2_easy"]["y"] = y; json["S2_easy"]["z"] = z; json["S2_easy"]["pi_x13"] = pi_x13; json["S2_easy"]["threads"] = threads; json["S2_easy"]["percent"] = percent; json["S2_easy"]["seconds"] = get_wtime() - time; store_backup(json); } template <typename T, typename J> void backup(J& json, int64_t start, int64_t b, int64_t thread_id, int64_t iters, T s2_easy) { json["S2_easy"]["start"] = start; json["S2_easy"]["thread" + to_string(thread_id)]["b"] = b; json["S2_easy"]["thread" + to_string(thread_id)]["iters"] = iters; json["S2_easy"]["thread" + to_string(thread_id)]["s2_easy"] = to_string(s2_easy); } template <typename T, typename J> void backup(J& json, T x, int64_t y, int64_t z, T s2_easy, double time) { json.erase("S2_easy"); json["S2_easy"]["x"] = to_string(x); json["S2_easy"]["y"] = y; json["S2_easy"]["z"] = z; json["S2_easy"]["s2_easy"] = to_string(s2_easy); json["S2_easy"]["percent"] = 100; json["S2_easy"]["seconds"] = get_wtime() - time; store_backup(json); } template <typename T> void print_resume(T x, int64_t start, int64_t pi_x13, T s2_easy, double seconds, double percent) { if (!print_variables()) print_log(""); print_log("=== Resuming from " + backup_file() + " ==="); print_log("start", start); print_log("pi_x13", pi_x13); print_log("s2_easy", s2_easy); print_log_seconds(seconds); print_status(percent, x); } template <typename T> bool resume(T x, int64_t y, int64_t z, int64_t& start, int64_t& pi_x13, T& s2_easy, double& time) { auto j = load_backup(); if (is_resume(j, "S2_easy", x, y, z)) { double percent = j["S2_easy"]["percent"]; double seconds = j["S2_easy"]["seconds"]; start = j["S2_easy"]["b"]; pi_x13 = j["S2_easy"]["pi_x13"]; s2_easy = calculator::eval<T>(j["S2_easy"]["s2_easy"]); time = get_wtime() - seconds; print_resume(x, start, pi_x13, s2_easy, seconds, percent); return true; } return false; } template <typename T, typename Primes> T S2_easy_thread(T x, int64_t y, int64_t z, int64_t b, int64_t stop, int64_t pi_x13, Primes& primes, PiTable& pi, S2Status& status) { T s2_easy = 0; for (; b < stop; b++) { int64_t prime = primes[b]; T x2 = x / prime; int64_t min_trivial = min(x2 / prime, y); int64_t min_clustered = (int64_t) isqrt(x2); int64_t min_sparse = z / prime; min_clustered = in_between(prime, min_clustered, y); min_sparse = in_between(prime, min_sparse, y); int64_t l = pi[min_trivial]; int64_t pi_min_clustered = pi[min_clustered]; int64_t pi_min_sparse = pi[min_sparse]; // Find all clustered easy leaves: // n = primes[b] * primes[l] // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1) // where phi(x / n, b - 1) = pi(x / n) - b + 2 while (l > pi_min_clustered) { int64_t xn = (int64_t) fast_div(x2, primes[l]); int64_t phi_xn = pi[xn] - b + 2; int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]); int64_t l2 = pi[xm]; s2_easy += phi_xn * (l - l2); l = l2; } // Find all sparse easy leaves: // n = primes[b] * primes[l] // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2 for (; l > pi_min_sparse; l--) { int64_t xn = (int64_t) fast_div(x2, primes[l]); s2_easy += pi[xn] - b + 2; } if (is_print()) status.print(b, pi_x13); } return s2_easy; } /// Calculate the contribution of the clustered easy leaves /// and the sparse easy leaves. /// @param T either int64_t or uint128_t. /// template <typename T, typename Primes> T S2_easy_OpenMP(T x, int64_t y, int64_t z, int64_t c, Primes& primes, int threads, double& time) { T s2 = 0; int64_t start; int64_t pi_x13; bool is_resume = resume(x, y, z, start, pi_x13, s2, time); if (is_resume && start >= pi_x13) return s2; PiTable pi(y); S2Status status(x); int64_t pi_sqrty = pi[isqrt(y)]; int64_t x13 = iroot<3>(x); int64_t thread_threshold = 1000; threads = ideal_num_threads(threads, x13, thread_threshold); if (!is_resume) { start = max(c, pi_sqrty) + 1; pi_x13 = pi[x13]; } auto json = load_backup(); double backup_time = get_wtime(); #pragma omp parallel for reduction(+: s2) for (int thread_id = 0; thread_id < threads; thread_id++) { T s2_easy = 0; int64_t b = 0; int64_t iters = 1; double iter_time = 0; while (b <= pi_x13) { int64_t stop; double curr_time = get_wtime(); #pragma omp critical (s2_easy_backup) { if (start <= pi_x13 && curr_time - iter_time < 10) { iters *= 2; int64_t max_iters = (pi_x13 - start) / threads; max_iters = max(max_iters / 8, 1); iters = min(iters, max_iters); } b = start; start += iters; stop = start; stop = min(stop, pi_x13 + 1); backup(json, start, b, thread_id, iters, s2_easy); if (curr_time - backup_time > 300) { double percent = status.getPercent(start, pi_x13, start, pi_x13); backup(json, x, y, z, pi_x13, threads, percent, time); backup_time = get_wtime(); } } iter_time = get_wtime(); s2_easy += S2_easy_thread(x, y, z, b, stop, pi_x13, primes, pi, status); } s2 += s2_easy; } backup(json, x, y, z, s2, time); return s2; } } // namespace namespace primecount { int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, int threads) { #ifdef HAVE_MPI if (mpi_num_procs() > 1) return S2_easy_mpi(x, y, z, c, threads); #endif print_log(""); print_log("=== S2_easy(x, y) ==="); print_log("Computation of the easy special leaves"); print_log(x, y, c, threads); double time = get_wtime(); auto primes = generate_primes<int32_t>(y); int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time); print_log("S2_easy", s2_easy, time); return s2_easy; } #ifdef HAVE_INT128_T int128_t S2_easy(int128_t x, int64_t y, int64_t z, int64_t c, int threads) { #ifdef HAVE_MPI if (mpi_num_procs() > 1) return S2_easy_mpi(x, y, z, c, threads); #endif print_log(""); print_log("=== S2_easy(x, y) ==="); print_log("Computation of the easy special leaves"); print_log(x, y, c, threads); int128_t s2_easy; double time = get_wtime(); // uses less memory if (y <= numeric_limits<uint32_t>::max()) { auto primes = generate_primes<uint32_t>(y); s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time); } else { auto primes = generate_primes<int64_t>(y); s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time); } print_log("S2_easy", s2_easy, time); return s2_easy; } #endif } // namespace <commit_msg>Resume works<commit_after>/// /// @file S2_easy.cpp /// @brief Calculate the contribution of the clustered easy leaves /// and the sparse easy leaves in parallel using OpenMP /// (Deleglise-Rivat algorithm). /// /// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <primecount-internal.hpp> #include <calculator.hpp> #include <fast_div.hpp> #include <generate.hpp> #include <int128_t.hpp> #include <min.hpp> #include <imath.hpp> #include <S2Status.hpp> #include <S2.hpp> #include <json.hpp> #include <stdint.h> #include <vector> #include <iostream> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { template <typename T, typename J> void backup(J& json, T x, int64_t y, int64_t z, int64_t pi_x13, int threads, double percent, double time) { json["S2_easy"]["x"] = to_string(x); json["S2_easy"]["y"] = y; json["S2_easy"]["z"] = z; json["S2_easy"]["pi_x13"] = pi_x13; json["S2_easy"]["threads"] = threads; json["S2_easy"]["percent"] = percent; json["S2_easy"]["seconds"] = get_wtime() - time; store_backup(json); } template <typename T, typename J> void backup(J& json, int64_t start, int64_t b, int64_t thread_id, int64_t iters, T s2_easy) { string tid = "thread" + to_string(thread_id); json["S2_easy"]["start"] = start; json["S2_easy"][tid]["b"] = b; json["S2_easy"][tid]["iters"] = iters; json["S2_easy"][tid]["s2_easy"] = to_string(s2_easy); } template <typename T, typename J> void backup(J& json, T x, int64_t y, int64_t z, int64_t pi_x13, T s2_easy, double time) { json.erase("S2_easy"); json["S2_easy"]["x"] = to_string(x); json["S2_easy"]["y"] = y; json["S2_easy"]["z"] = z; json["S2_easy"]["pi_x13"] = pi_x13; json["S2_easy"]["s2_easy"] = to_string(s2_easy); json["S2_easy"]["percent"] = 100; json["S2_easy"]["seconds"] = get_wtime() - time; store_backup(json); } template <typename T, typename J> int get_start(J& json, T x, int64_t y, int64_t z, int64_t start) { if (is_resume(json, "S2_easy", x, y, z) && json["S2_easy"].count("start")) { start = json["S2_easy"]["start"]; } return start; } template <typename T, typename J> int get_threads(J& json, T x, int64_t y, int64_t z, int threads) { if (is_resume(json, "S2_easy", x, y, z) && json["S2_easy"].count("threads")) { int threads2 = json["S2_easy"]["threads"]; threads = max(threads, threads2); } return threads; } template <typename T> void print_resume(T x, T s2_easy, double seconds) { if (!print_variables()) print_log(""); print_log("=== Resuming from " + backup_file() + " ==="); print_log("s2_easy", s2_easy); print_log_seconds(seconds); } template <typename T, typename J> bool resume(J& json, T x, int64_t y, int64_t z, T& s2_easy, double& time) { if (is_resume(json, "S2_easy", x, y, z) && json["S2_easy"].count("s2_easy")) { double seconds = json["S2_easy"]["seconds"]; s2_easy = calculator::eval<T>(json["S2_easy"]["s2_easy"]); time = get_wtime() - seconds; print_resume(x, s2_easy, seconds); return true; } return false; } template <typename T, typename J> bool resume(J& json, T x, int64_t y, int64_t z, int64_t& b, int64_t& iters, T& s2_easy, int thread_id) { if (is_resume(json, "S2_easy", x, y, z)) { string tid = "thread" + to_string(thread_id); b = json["S2_easy"][tid]["b"]; iters = json["S2_easy"][tid]["iters"]; s2_easy = calculator::eval<T>(json["S2_easy"][tid]["s2_easy"]); return true; } return false; } template <typename T, typename Primes> T S2_easy_thread(T x, int64_t y, int64_t z, int64_t b, int64_t stop, int64_t pi_x13, Primes& primes, PiTable& pi, S2Status& status) { T s2_easy = 0; for (; b < stop; b++) { int64_t prime = primes[b]; T x2 = x / prime; int64_t min_trivial = min(x2 / prime, y); int64_t min_clustered = (int64_t) isqrt(x2); int64_t min_sparse = z / prime; min_clustered = in_between(prime, min_clustered, y); min_sparse = in_between(prime, min_sparse, y); int64_t l = pi[min_trivial]; int64_t pi_min_clustered = pi[min_clustered]; int64_t pi_min_sparse = pi[min_sparse]; // Find all clustered easy leaves: // n = primes[b] * primes[l] // x / n <= y && phi(x / n, b - 1) == phi(x / m, b - 1) // where phi(x / n, b - 1) = pi(x / n) - b + 2 while (l > pi_min_clustered) { int64_t xn = (int64_t) fast_div(x2, primes[l]); int64_t phi_xn = pi[xn] - b + 2; int64_t xm = (int64_t) fast_div(x2, primes[b + phi_xn - 1]); int64_t l2 = pi[xm]; s2_easy += phi_xn * (l - l2); l = l2; } // Find all sparse easy leaves: // n = primes[b] * primes[l] // x / n <= y && phi(x / n, b - 1) = pi(x / n) - b + 2 for (; l > pi_min_sparse; l--) { int64_t xn = (int64_t) fast_div(x2, primes[l]); s2_easy += pi[xn] - b + 2; } if (is_print()) status.print(b, pi_x13); } return s2_easy; } /// Calculate the contribution of the clustered easy leaves /// and the sparse easy leaves. /// @param T either int64_t or uint128_t. /// template <typename T, typename Primes> T S2_easy_OpenMP(T x, int64_t y, int64_t z, int64_t c, Primes& primes, int threads, double& time) { T s2 = 0; auto json = load_backup(); if (resume(json, x, y, z, s2, time)) return s2; PiTable pi(y); S2Status status(x); int64_t x13 = iroot<3>(x); int64_t pi_x13 = pi[x13]; int64_t pi_sqrty = pi[isqrt(y)]; int64_t start = max(c, pi_sqrty) + 1; start = get_start(json, x, y, z, start); int64_t thread_threshold = 1000; threads = ideal_num_threads(threads, x13, thread_threshold); threads = get_threads(json, x, y, z, threads); double backup_time = get_wtime(); #pragma omp parallel num_threads(threads) reduction(+: s2) { T s2_easy = 0; int64_t stop = 0; int64_t b = 0; int64_t iters = 1; double iter_time = 0; int thread_id = omp_get_thread_num(); if (resume(json, x, y, z, b, iters, s2_easy, thread_id)) { iter_time = get_wtime(); stop = b + iters; stop = min(stop, pi_x13 + 1); s2_easy += S2_easy_thread(x, y, z, b, stop, pi_x13, primes, pi, status); std::cout << "Resume finished!" << std::endl; } #pragma omp barrier while (b <= pi_x13) { double curr_time = get_wtime(); #pragma omp critical (s2_easy_backup) { if (start <= pi_x13 && curr_time - iter_time < 10) { iters *= 2; int64_t max_iters = (pi_x13 - start) / threads; max_iters = max(max_iters / 8, 1); iters = min(iters, max_iters); } b = start; start += iters; stop = start; stop = min(stop, pi_x13 + 1); backup(json, start, b, thread_id, iters, s2_easy); if (curr_time - backup_time > 1) { double percent = status.getPercent(start, pi_x13, start, pi_x13); backup(json, x, y, z, pi_x13, threads, percent, time); backup_time = get_wtime(); std::cout << "Backup!" << std::endl; } } iter_time = get_wtime(); s2_easy += S2_easy_thread(x, y, z, b, stop, pi_x13, primes, pi, status); } s2 += s2_easy; } backup(json, x, y, z, pi_x13, s2, time); return s2; } } // namespace namespace primecount { int64_t S2_easy(int64_t x, int64_t y, int64_t z, int64_t c, int threads) { #ifdef HAVE_MPI if (mpi_num_procs() > 1) return S2_easy_mpi(x, y, z, c, threads); #endif print_log(""); print_log("=== S2_easy(x, y) ==="); print_log("Computation of the easy special leaves"); print_log(x, y, c, threads); double time = get_wtime(); auto primes = generate_primes<int32_t>(y); int64_t s2_easy = S2_easy_OpenMP((intfast64_t) x, y, z, c, primes, threads, time); print_log("S2_easy", s2_easy, time); return s2_easy; } #ifdef HAVE_INT128_T int128_t S2_easy(int128_t x, int64_t y, int64_t z, int64_t c, int threads) { #ifdef HAVE_MPI if (mpi_num_procs() > 1) return S2_easy_mpi(x, y, z, c, threads); #endif print_log(""); print_log("=== S2_easy(x, y) ==="); print_log("Computation of the easy special leaves"); print_log(x, y, c, threads); int128_t s2_easy; double time = get_wtime(); // uses less memory if (y <= numeric_limits<uint32_t>::max()) { auto primes = generate_primes<uint32_t>(y); s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time); } else { auto primes = generate_primes<int64_t>(y); s2_easy = S2_easy_OpenMP((intfast128_t) x, y, z, c, primes, threads, time); } print_log("S2_easy", s2_easy, time); return s2_easy; } #endif } // namespace <|endoftext|>
<commit_before>/// @file AesopPredicates.cpp /// @brief Implementation of Predicatess class as defined in AesopPredicates.h #include "AesopPredicates.h" namespace ae { /// @class Predicates /// /// Predicates::Predicates(const Requirements &reqs, const Types &types) : mRequirements(reqs), mTypes(types) { } Predicates::~Predicates() { } void Predicates::add(Predicate &newpred) { // Check for compliance with requirements. if(!getRequirements().predicateParameters && newpred.getParams().size()) return; if(!getRequirements().typing) { for(Predicate::paramlist::const_iterator it = newpred.getParams().begin(); it != newpred.getParams().end(); it++) if(it->second != "") return; } mPredicates[newpred.getName()] = newpred; } Predicate Predicates::create(std::string name) { return Predicate(name); } bool Predicates::has(std::string name) const { return mPredicates.find(name) != mPredicates.end(); } }; <commit_msg>Updated checks when adding a new Predicate.<commit_after>/// @file AesopPredicates.cpp /// @brief Implementation of Predicatess class as defined in AesopPredicates.h #include "AesopPredicates.h" namespace ae { /// @class Predicates /// /// Predicates::Predicates(const Requirements &reqs, const Types &types) : mRequirements(reqs), mTypes(types) { } Predicates::~Predicates() { } void Predicates::add(Predicate &newpred) { // Check for compliance with requirements. if(!getRequirements().predicateParameters && newpred.getParams().size()) return; for(unsigned int i = 0; i < newpred.getParams().size(); i++) { for(Predicate::paramlist::const_iterator it = newpred.getParams().begin(); it != newpred.getParams().end(); it++) if(it->second != "") return; if(!getRequirements().typing && newpred.getParams()[i].second != "") return; else if(!getTypes().has(newpred.getParams()[i].second)) return; } // Add new predicate mPredicates[newpred.getName()] = newpred; } Predicate Predicates::create(std::string name) { return Predicate(name); } bool Predicates::has(std::string name) const { return mPredicates.find(name) != mPredicates.end(); } }; <|endoftext|>
<commit_before>/* * Copyright (C) 2014 INRA * * 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 "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 __Benchmark_models_hpp__ #define __Benchmark_models_hpp__ #include "linpackc.hpp" #include "defs.hpp" #include <vle/mpi-synchronous.hpp> #include <vle/utils.hpp> #include <fstream> #include <numeric> namespace bench { struct TopPixel : AtomicModel { int m_id; std::string m_name; long int m_duration; TopPixel(const vle::Context& ctx) : AtomicModel(ctx, {}, {"0"}) {} virtual ~TopPixel() {} virtual double init(const vle::Common& common, const double&) override final { try { m_id = boost::any_cast <int>(common.at("id")); m_name = std::string("top-") + boost::any_cast <std::string>(common.at("name")); m_duration = boost::any_cast <long int>(common.at("duration")); } catch (const std::exception &e) { throw std::invalid_argument("TopPixel: failed to find name " "or duration parameters"); } return 0.0; } virtual double delta(const double&) override final { if (m_duration > 0) bench::sleep_and_work(m_duration); return 1.0; } virtual void lambda() const override final { vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str()); y[0] = {m_id}; } }; struct NormalPixel : AtomicModel { enum Phase { WAIT, SEND }; int m_id; std::string m_name; double m_current_time; double m_last_time; long int m_duration; unsigned int m_neighbour_number; unsigned int m_received; unsigned int m_total_received; Phase m_phase; double m_simulation_duration; NormalPixel(const vle::Context& ctx) : AtomicModel(ctx, {"0"}, {"0"}) , m_current_time(Infinity <double>::negative) , m_last_time(Infinity <double>::negative) , m_neighbour_number(0) , m_received(0) , m_total_received(0) , m_phase(WAIT) { try { m_simulation_duration = boost::any_cast <double>(ctx->get_user_data()); } catch (const std::exception &e) { throw std::invalid_argument("Normal pixel can not read the " "simulation duration parameter"); } } virtual ~NormalPixel() { if (m_total_received != (m_simulation_duration * m_neighbour_number)) { vle_dbg(AtomicModel::ctx, "/!\\ [%s] failure: have received %" PRIuMAX " messages (%" PRIuMAX " expected)\n", m_name.c_str(), static_cast <std::uintmax_t>(m_total_received), static_cast <std::uintmax_t>(m_neighbour_number * 10)); } } virtual double init(const vle::Common& common, const double& t) override final { m_current_time = t; m_last_time = Infinity <double>::negative; try { m_id = boost::any_cast <int>(common.at("id")); m_duration = boost::any_cast <long int>(common.at("duration")); m_name = std::string("normal-") + boost::any_cast <std::string>(common.at("name")); m_neighbour_number = boost::any_cast <unsigned int>(common.at("neighbour_number")); } catch (const std::exception &e) { throw std::invalid_argument("NormalPixel: failed to find duration," "name or neighbour_number parameters"); } m_received = 0; m_total_received = 0; m_phase = WAIT; return Infinity <double>::positive; } virtual double delta(const double& time) override final { m_current_time += time; if (x.empty()) dint(m_current_time); else dext(m_current_time); if (m_phase == WAIT) return Infinity <double>::positive; return 0.0; } void dint(const double& time) { vle_dbg(AtomicModel::ctx, "[%s] dint at %f\n", m_name.c_str(), time); if (m_duration > 0) bench::sleep_and_work(m_duration); if (m_phase == SEND) { vle_dbg(AtomicModel::ctx, "[%s] %" PRIuMAX "-%" PRIuMAX " (neighbour_number : %" PRIuMAX " expected)\n", m_name.c_str(), static_cast <std::uintmax_t>(m_received), static_cast <std::uintmax_t>(m_total_received), static_cast <std::uintmax_t>(m_neighbour_number * 10)); m_phase = WAIT; m_total_received += m_received; m_received = 0; m_last_time = time; } } void dext(const double& time) { vle_dbg(AtomicModel::ctx, "[%s] dext at %f (x[0].size: %" PRIuMAX " received: %" PRIuMAX " neighbour_number: %" PRIuMAX ")\n", m_name.c_str(), time, static_cast <std::uintmax_t>(x[0].size()), static_cast <std::uintmax_t>(m_received), static_cast <std::uintmax_t>(m_neighbour_number)); if (m_last_time == time) vle_dbg(AtomicModel::ctx, "/!\\ [%s] oups at %f", m_name.c_str(), time); for (size_t i = 0, e = x[0].size(); i != e; ++i) vle_dbg(AtomicModel::ctx, "value: %d\n", x[0][i]); m_received += x[0].size(); if (m_received == m_neighbour_number) m_phase = SEND; } virtual void lambda() const override final { if (m_phase == SEND) { vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str()); y[0] = {m_id}; } } }; template <typename T> struct Coupled : T { std::string m_name; Coupled(const vle::Context& ctx) : T(ctx) {} Coupled(const vle::Context& ctx, unsigned thread_number) : T(ctx, thread_number) {} virtual ~Coupled() {} virtual void apply_common(const vle::Common& common) override { m_name = vle::common_get <std::string>(common, "name"); } virtual vle::Common update_common(const vle::Common& common, const typename Coupled::vertices& v, const typename Coupled::edges& e, int child) override { auto mdl = v[child].get(); unsigned int nb = std::accumulate( e.cbegin(), e.cend(), 0u, [&mdl](unsigned int x, const typename Coupled::edges::value_type& edge) { return edge.second.first == mdl ? x + 1u : x; }); vle::Common ret(common); vle_dbg(T::ctx, "[%s] init %s (%p) with %" PRIuMAX " neightbour\n", m_name.c_str(), vle::stringf("%s-%d", m_name.c_str(), child).c_str(), mdl, static_cast <std::uintmax_t>(nb)); ret["id"] = child; ret["name"] = vle::stringf("%s-%d", m_name.c_str(), child); ret["neighbour_number"] = nb; return std::move(ret); } }; template <typename T> struct RootMPI : T { boost::mpi::communicator com; RootMPI(const vle::Context& ctx) : T(ctx) , com() {} virtual ~RootMPI() {} virtual vle::Common update_common(const vle::Common& common, const typename RootMPI::vertices& v, const typename RootMPI::edges& e, int child) override { (void)v; (void)e; if (com.size() <= child + 1) throw std::invalid_argument("MPI size < children size"); bench::SynchronousProxyModel* mdl = dynamic_cast <bench::SynchronousProxyModel*>(T::m_children[child].get()); if (!mdl) throw std::invalid_argument("RootMPI without SynchronousProxyModel"); mdl->rank = child + 1; vle_info(T::ctx, "RootMPI assign %d to child %d\n", mdl->rank, child); vle::Common ret(common); return std::move(ret); } }; template <typename T> struct Root : T { Root(const vle::Context& ctx, unsigned thread_number) : T(ctx, thread_number) {} virtual ~Root() {} virtual vle::Common update_common(const vle::Common& common, const typename Root::vertices& v, const typename Root::edges& e, int child) override { vle::Common ret(common); auto mdl = v[child].get(); unsigned int nb = std::accumulate( e.cbegin(), e.cend(), 0u, [&mdl](unsigned int x, const typename Root::edges::value_type& edge) { return edge.second.first == mdl ? x + 1u : x; }); ret["id"] = child; ret["name"] = vle::stringf("S%d", child); ret["neighbour_number"] = nb; ret["tgf-filesource"] = vle::stringf("S%d.tgf", child); ret["tgf-format"] = (int)1; return std::move(ret); } }; using RootThread = Root <GenericCoupledModelThread>; using RootMono = Root <GenericCoupledModelMono>; using RootMPIThread = RootMPI <GenericCoupledModelThread>; using RootMPIMono = RootMPI <GenericCoupledModelMono>; using CoupledThread = Coupled <GenericCoupledModelThread>; using CoupledMono = Coupled <GenericCoupledModelMono>; } #endif <commit_msg>models: adding runtime exception if model is bad<commit_after>/* * Copyright (C) 2014 INRA * * 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 "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 __Benchmark_models_hpp__ #define __Benchmark_models_hpp__ #include "linpackc.hpp" #include "defs.hpp" #include <vle/mpi-synchronous.hpp> #include <vle/utils.hpp> #include <fstream> #include <numeric> namespace bench { struct TopPixel : AtomicModel { int m_id; std::string m_name; long int m_duration; TopPixel(const vle::Context& ctx) : AtomicModel(ctx, {}, {"0"}) {} virtual ~TopPixel() {} virtual double init(const vle::Common& common, const double&) override final { try { m_id = boost::any_cast <int>(common.at("id")); m_name = std::string("top-") + boost::any_cast <std::string>(common.at("name")); m_duration = boost::any_cast <long int>(common.at("duration")); } catch (const std::exception &e) { throw std::invalid_argument("TopPixel: failed to find name " "or duration parameters"); } return 0.0; } virtual double delta(const double&) override final { if (m_duration > 0) bench::sleep_and_work(m_duration); return 1.0; } virtual void lambda() const override final { vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str()); y[0] = {m_id}; } }; struct NormalPixel : AtomicModel { enum Phase { WAIT, SEND }; int m_id; std::string m_name; double m_current_time; double m_last_time; long int m_duration; unsigned int m_neighbour_number; unsigned int m_received; unsigned int m_total_received; Phase m_phase; double m_simulation_duration; NormalPixel(const vle::Context& ctx) : AtomicModel(ctx, {"0"}, {"0"}) , m_current_time(Infinity <double>::negative) , m_last_time(Infinity <double>::negative) , m_neighbour_number(0) , m_received(0) , m_total_received(0) , m_phase(WAIT) { try { m_simulation_duration = boost::any_cast <double>(ctx->get_user_data()); } catch (const std::exception &e) { throw std::invalid_argument("Normal pixel can not read the " "simulation duration parameter"); } } virtual ~NormalPixel() { if (m_total_received != (m_simulation_duration * m_neighbour_number)) { vle_dbg(AtomicModel::ctx, "/!\\ [%s] failure: have received %" PRIuMAX " messages (%" PRIuMAX " expected)\n", m_name.c_str(), static_cast <std::uintmax_t>(m_total_received), static_cast <std::uintmax_t>(m_neighbour_number * 10)); #ifdef NDEBUG throw std::runtime_error("Bad end\n"); #endif } } virtual double init(const vle::Common& common, const double& t) override final { m_current_time = t; m_last_time = Infinity <double>::negative; try { m_id = boost::any_cast <int>(common.at("id")); m_duration = boost::any_cast <long int>(common.at("duration")); m_name = std::string("normal-") + boost::any_cast <std::string>(common.at("name")); m_neighbour_number = boost::any_cast <unsigned int>(common.at("neighbour_number")); } catch (const std::exception &e) { throw std::invalid_argument("NormalPixel: failed to find duration," "name or neighbour_number parameters"); } m_received = 0; m_total_received = 0; m_phase = WAIT; return Infinity <double>::positive; } virtual double delta(const double& time) override final { m_current_time += time; if (x.empty()) dint(m_current_time); else dext(m_current_time); if (m_phase == WAIT) return Infinity <double>::positive; return 0.0; } void dint(const double& time) { vle_dbg(AtomicModel::ctx, "[%s] dint at %f\n", m_name.c_str(), time); if (m_duration > 0) bench::sleep_and_work(m_duration); if (m_phase == SEND) { vle_dbg(AtomicModel::ctx, "[%s] %" PRIuMAX "-%" PRIuMAX " (neighbour_number : %" PRIuMAX " expected)\n", m_name.c_str(), static_cast <std::uintmax_t>(m_received), static_cast <std::uintmax_t>(m_total_received), static_cast <std::uintmax_t>(m_neighbour_number * 10)); m_phase = WAIT; m_total_received += m_received; m_received = 0; m_last_time = time; } } void dext(const double& time) { vle_dbg(AtomicModel::ctx, "[%s] dext at %f (x[0].size: %" PRIuMAX " received: %" PRIuMAX " neighbour_number: %" PRIuMAX ")\n", m_name.c_str(), time, static_cast <std::uintmax_t>(x[0].size()), static_cast <std::uintmax_t>(m_received), static_cast <std::uintmax_t>(m_neighbour_number)); if (m_last_time == time) { vle_dbg(AtomicModel::ctx, "/!\\ [%s] oups at %f", m_name.c_str(), time); throw std::runtime_error("Oups event\n"); } for (size_t i = 0, e = x[0].size(); i != e; ++i) vle_dbg(AtomicModel::ctx, "value: %d\n", x[0][i]); m_received += x[0].size(); if (m_received == m_neighbour_number) m_phase = SEND; } virtual void lambda() const override final { if (m_phase == SEND) { vle_dbg(AtomicModel::ctx, "[%s] lambda\n", m_name.c_str()); y[0] = {m_id}; } } }; template <typename T> struct Coupled : T { std::string m_name; Coupled(const vle::Context& ctx) : T(ctx) {} Coupled(const vle::Context& ctx, unsigned thread_number) : T(ctx, thread_number) {} virtual ~Coupled() {} virtual void apply_common(const vle::Common& common) override { m_name = vle::common_get <std::string>(common, "name"); } virtual vle::Common update_common(const vle::Common& common, const typename Coupled::vertices& v, const typename Coupled::edges& e, int child) override { auto mdl = v[child].get(); unsigned int nb = std::accumulate( e.cbegin(), e.cend(), 0u, [&mdl](unsigned int x, const typename Coupled::edges::value_type& edge) { return edge.second.first == mdl ? x + 1u : x; }); vle::Common ret(common); vle_dbg(T::ctx, "[%s] init %s (%p) with %" PRIuMAX " neightbour\n", m_name.c_str(), vle::stringf("%s-%d", m_name.c_str(), child).c_str(), mdl, static_cast <std::uintmax_t>(nb)); ret["id"] = child; ret["name"] = vle::stringf("%s-%d", m_name.c_str(), child); ret["neighbour_number"] = nb; return std::move(ret); } }; template <typename T> struct RootMPI : T { boost::mpi::communicator com; RootMPI(const vle::Context& ctx) : T(ctx) , com() {} virtual ~RootMPI() {} virtual vle::Common update_common(const vle::Common& common, const typename RootMPI::vertices& v, const typename RootMPI::edges& e, int child) override { (void)v; (void)e; if (com.size() <= child + 1) throw std::invalid_argument("MPI size < children size"); bench::SynchronousProxyModel* mdl = dynamic_cast <bench::SynchronousProxyModel*>(T::m_children[child].get()); if (!mdl) throw std::invalid_argument("RootMPI without SynchronousProxyModel"); mdl->rank = child + 1; vle_info(T::ctx, "RootMPI assign %d to child %d\n", mdl->rank, child); vle::Common ret(common); return std::move(ret); } }; template <typename T> struct Root : T { Root(const vle::Context& ctx, unsigned thread_number) : T(ctx, thread_number) {} virtual ~Root() {} virtual vle::Common update_common(const vle::Common& common, const typename Root::vertices& v, const typename Root::edges& e, int child) override { vle::Common ret(common); auto mdl = v[child].get(); unsigned int nb = std::accumulate( e.cbegin(), e.cend(), 0u, [&mdl](unsigned int x, const typename Root::edges::value_type& edge) { return edge.second.first == mdl ? x + 1u : x; }); ret["id"] = child; ret["name"] = vle::stringf("S%d", child); ret["neighbour_number"] = nb; ret["tgf-filesource"] = vle::stringf("S%d.tgf", child); ret["tgf-format"] = (int)1; return std::move(ret); } }; using RootThread = Root <GenericCoupledModelThread>; using RootMono = Root <GenericCoupledModelMono>; using RootMPIThread = RootMPI <GenericCoupledModelThread>; using RootMPIMono = RootMPI <GenericCoupledModelMono>; using CoupledThread = Coupled <GenericCoupledModelThread>; using CoupledMono = Coupled <GenericCoupledModelMono>; } #endif <|endoftext|>
<commit_before>/* * kPPP: A pppd front end for the KDE project * * * * * Copyright (C) 2004 Simone Gotti * <simone.gotti@email.it> * * based on EzPPP: * Copyright (C) 1997 Jay Painter * * This program 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 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdir.h> #include <stdlib.h> #include <qlayout.h> #include <qtabdialog.h> #include <qwhatsthis.h> #include <qmessagebox.h> #include <kapplication.h> #include <kbuttonbox.h> #include <kmessagebox.h> #include <klocale.h> #include <kglobal.h> #include <kwin.h> #include <kdialogbase.h> #include <qvgroupbox.h> #include "general.h" #include "pppdata.h" #include "modems.h" #include "accounting.h" #include "providerdb.h" #include "edit.h" void parseargs(char* buf, char** args); ModemsWidget::ModemsWidget( QWidget *parent, const char *name ) : QWidget( parent, name ) { int min = 0; QVBoxLayout *l1 = new QVBoxLayout(parent, 10, 10); // add a hbox QHBoxLayout *l11 = new QHBoxLayout; l1->addLayout(l11); modemlist_l = new QListBox(parent); modemlist_l->setMinimumSize(160, 128); connect(modemlist_l, SIGNAL(highlighted(int)), this, SLOT(slotListBoxSelect(int))); connect(modemlist_l, SIGNAL(selected(int)), this, SLOT(editmodem())); l11->addWidget(modemlist_l, 10); QVBoxLayout *l111 = new QVBoxLayout; l11->addLayout(l111, 1); edit_b = new QPushButton(i18n("&Edit..."), parent); connect(edit_b, SIGNAL(clicked()), SLOT(editmodem())); QWhatsThis::add(edit_b, i18n("Allows you to modify the selected account")); min = edit_b->sizeHint().width(); min = QMAX(70,min); edit_b->setMinimumWidth(min); l111->addWidget(edit_b); new_b = new QPushButton(i18n("&New..."), parent); connect(new_b, SIGNAL(clicked()), SLOT(newmodem())); l111->addWidget(new_b); QWhatsThis::add(new_b, i18n("Create a new dialup connection\n" "to the Internet")); copy_b = new QPushButton(i18n("Co&py"), parent); connect(copy_b, SIGNAL(clicked()), SLOT(copymodem())); l111->addWidget(copy_b); QWhatsThis::add(copy_b, i18n("Makes a copy of the selected account. All\n" "settings of the selected account are copied\n" "to a new account that you can modify to fit your\n" "needs")); delete_b = new QPushButton(i18n("De&lete"), parent); connect(delete_b, SIGNAL(clicked()), SLOT(deletemodem())); l111->addWidget(delete_b); QWhatsThis::add(delete_b, i18n("<p>Deletes the selected account\n\n" "<font color=\"red\"><b>Use with care!</b></font>")); //load up account list from gppdata to the list box if(gpppdata.modemCount() > 0) { for(int i=0; i <= gpppdata.modemCount()-1; i++) { gpppdata.setModemByIndex(i); modemlist_l->insertItem(gpppdata.modname()); } } slotListBoxSelect(modemlist_l->currentItem()); l1->activate(); } void ModemsWidget::slotListBoxSelect(int idx) { delete_b->setEnabled((bool)(idx != -1)); edit_b->setEnabled((bool)(idx != -1)); copy_b->setEnabled((bool)(idx != -1)); if(idx!=-1) { QString modem = gpppdata.modname(); gpppdata.setModemByIndex(modemlist_l->currentItem()); gpppdata.setModem(modem); } } void ModemsWidget::editmodem() { gpppdata.setModem(modemlist_l->text(modemlist_l->currentItem())); int result = doTab(); if(result == QDialog::Accepted) { modemlist_l->changeItem(gpppdata.modname(),modemlist_l->currentItem()); emit resetmodems(); gpppdata.save(); } } void ModemsWidget::newmodem() { if(modemlist_l->count() == MAX_MODEMS) { KMessageBox::sorry(this, i18n("Maximum number of modems reached.")); return; } int result; if (gpppdata.newmodem() == -1) return; result = doTab(); if(result == QDialog::Accepted) { modemlist_l->insertItem(gpppdata.modname()); modemlist_l->setSelected(modemlist_l->findItem(gpppdata.modname()), true); emit resetmodems(); gpppdata.save(); } else gpppdata.deleteModem(); } void ModemsWidget::copymodem() { if(modemlist_l->count() == MAX_MODEMS) { KMessageBox::sorry(this, i18n("Maximum number of modems reached.")); return; } if(modemlist_l->currentItem()<0) { KMessageBox::sorry(this, i18n("No modem selected.")); return; } gpppdata.copymodem(modemlist_l->currentItem()); modemlist_l->insertItem(gpppdata.modname()); emit resetmodems(); gpppdata.save(); } void ModemsWidget::deletemodem() { QString s = i18n("Are you sure you want to delete\nthe modem \"%1\"?") .arg(modemlist_l->text(modemlist_l->currentItem())); if(KMessageBox::warningYesNo(this, s, i18n("Confirm")) != KMessageBox::Yes) return; if(gpppdata.deleteModem(modemlist_l->text(modemlist_l->currentItem()))) modemlist_l->removeItem(modemlist_l->currentItem()); emit resetmodems(); gpppdata.save(); slotListBoxSelect(modemlist_l->currentItem()); } int ModemsWidget::doTab(){ tabWindow = new KDialogBase( KDialogBase::Tabbed, QString::null, KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, 0, 0, true); KWin::setIcons(tabWindow->winId(), kapp->icon(), kapp->miniIcon()); bool isnewmodem; if(gpppdata.modname().isEmpty()) { tabWindow->setCaption(i18n("New Modem")); isnewmodem = true; } else { QString tit = i18n("Edit Modem: "); tit += gpppdata.modname(); tabWindow->setCaption(tit); isnewmodem = false; } modem1 = new ModemWidget(tabWindow->addPage( i18n("&Device"), i18n("Serial Device")), isnewmodem ); modem2 = new ModemWidget2(tabWindow->addPage( i18n("&Modem"), i18n("Modem Settings"))); connect ( modem1->connectName(), SIGNAL(textChanged ( const QString & )), this, SLOT(modemNameChanged(const QString & ))); modemNameChanged(modem1->connectName()->text()); int result = 0; bool ok = false; while (!ok){ result = tabWindow->exec(); ok = true; if(result == QDialog::Accepted) { if(modem1->save()) { modem2->save(); } else { KMessageBox::error(this, i18n( "You must enter a unique\n" "modem name")); ok = false; } } } delete tabWindow; return result; } void ModemsWidget::modemNameChanged(const QString & text) { tabWindow->enableButtonOK( !text.isEmpty() ); } QString ModemsWidget::prettyPrintVolume(unsigned int n) { int idx = 0; const QString quant[] = {i18n("Byte"), i18n("KB"), i18n("MB"), i18n("GB"), QString::null}; float n1 = n; while(n >= 1024 && !quant[idx].isNull()) { idx++; n /= 1024; } int i = idx; while(i--) n1 = n1 / 1024.0; QString s = KGlobal::locale()->formatNumber( n1, idx==0 ? 0 : 1 ); s += " " + quant[idx]; return s; } #include "modems.moc" <commit_msg>keep the modem-selection in the combobox and in gpppdata in sync<commit_after>/* * kPPP: A pppd front end for the KDE project * * * * * Copyright (C) 2004 Simone Gotti * <simone.gotti@email.it> * * based on EzPPP: * Copyright (C) 1997 Jay Painter * * This program 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 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdir.h> #include <stdlib.h> #include <qlayout.h> #include <qtabdialog.h> #include <qwhatsthis.h> #include <qmessagebox.h> #include <kapplication.h> #include <kbuttonbox.h> #include <kmessagebox.h> #include <klocale.h> #include <kglobal.h> #include <kwin.h> #include <kdialogbase.h> #include <qvgroupbox.h> #include "general.h" #include "pppdata.h" #include "modems.h" #include "accounting.h" #include "providerdb.h" #include "edit.h" void parseargs(char* buf, char** args); ModemsWidget::ModemsWidget( QWidget *parent, const char *name ) : QWidget( parent, name ) { int min = 0; QVBoxLayout *l1 = new QVBoxLayout(parent, 10, 10); // add a hbox QHBoxLayout *l11 = new QHBoxLayout; l1->addLayout(l11); modemlist_l = new QListBox(parent); modemlist_l->setMinimumSize(160, 128); connect(modemlist_l, SIGNAL(highlighted(int)), this, SLOT(slotListBoxSelect(int))); connect(modemlist_l, SIGNAL(selected(int)), this, SLOT(editmodem())); l11->addWidget(modemlist_l, 10); QVBoxLayout *l111 = new QVBoxLayout; l11->addLayout(l111, 1); edit_b = new QPushButton(i18n("&Edit..."), parent); connect(edit_b, SIGNAL(clicked()), SLOT(editmodem())); QWhatsThis::add(edit_b, i18n("Allows you to modify the selected account")); min = edit_b->sizeHint().width(); min = QMAX(70,min); edit_b->setMinimumWidth(min); l111->addWidget(edit_b); new_b = new QPushButton(i18n("&New..."), parent); connect(new_b, SIGNAL(clicked()), SLOT(newmodem())); l111->addWidget(new_b); QWhatsThis::add(new_b, i18n("Create a new dialup connection\n" "to the Internet")); copy_b = new QPushButton(i18n("Co&py"), parent); connect(copy_b, SIGNAL(clicked()), SLOT(copymodem())); l111->addWidget(copy_b); QWhatsThis::add(copy_b, i18n("Makes a copy of the selected account. All\n" "settings of the selected account are copied\n" "to a new account that you can modify to fit your\n" "needs")); delete_b = new QPushButton(i18n("De&lete"), parent); connect(delete_b, SIGNAL(clicked()), SLOT(deletemodem())); l111->addWidget(delete_b); QWhatsThis::add(delete_b, i18n("<p>Deletes the selected account\n\n" "<font color=\"red\"><b>Use with care!</b></font>")); //load up account list from gppdata to the list box // but keep the current one selected in gpppdata if(gpppdata.modemCount() > 0) { const QString currentmodem = gpppdata.modname(); for(int i=0; i <= gpppdata.modemCount()-1; i++) { gpppdata.setModemByIndex(i); modemlist_l->insertItem(gpppdata.modname()); } gpppdata.setModem(currentmodem); } slotListBoxSelect(modemlist_l->currentItem()); l1->activate(); } void ModemsWidget::slotListBoxSelect(int idx) { delete_b->setEnabled((bool)(idx != -1)); edit_b->setEnabled((bool)(idx != -1)); copy_b->setEnabled((bool)(idx != -1)); if(idx!=-1) { QString modem = gpppdata.modname(); gpppdata.setModemByIndex(modemlist_l->currentItem()); gpppdata.setModem(modem); } } void ModemsWidget::editmodem() { gpppdata.setModem(modemlist_l->text(modemlist_l->currentItem())); int result = doTab(); if(result == QDialog::Accepted) { modemlist_l->changeItem(gpppdata.modname(),modemlist_l->currentItem()); emit resetmodems(); gpppdata.save(); } } void ModemsWidget::newmodem() { if(modemlist_l->count() == MAX_MODEMS) { KMessageBox::sorry(this, i18n("Maximum number of modems reached.")); return; } int result; if (gpppdata.newmodem() == -1) return; result = doTab(); if(result == QDialog::Accepted) { modemlist_l->insertItem(gpppdata.modname()); modemlist_l->setSelected(modemlist_l->findItem(gpppdata.modname()), true); emit resetmodems(); gpppdata.save(); } else gpppdata.deleteModem(); } void ModemsWidget::copymodem() { if(modemlist_l->count() == MAX_MODEMS) { KMessageBox::sorry(this, i18n("Maximum number of modems reached.")); return; } if(modemlist_l->currentItem()<0) { KMessageBox::sorry(this, i18n("No modem selected.")); return; } gpppdata.copymodem(modemlist_l->currentItem()); modemlist_l->insertItem(gpppdata.modname()); emit resetmodems(); gpppdata.save(); } void ModemsWidget::deletemodem() { QString s = i18n("Are you sure you want to delete\nthe modem \"%1\"?") .arg(modemlist_l->text(modemlist_l->currentItem())); if(KMessageBox::warningYesNo(this, s, i18n("Confirm")) != KMessageBox::Yes) return; if(gpppdata.deleteModem(modemlist_l->text(modemlist_l->currentItem()))) modemlist_l->removeItem(modemlist_l->currentItem()); emit resetmodems(); gpppdata.save(); slotListBoxSelect(modemlist_l->currentItem()); } int ModemsWidget::doTab(){ tabWindow = new KDialogBase( KDialogBase::Tabbed, QString::null, KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, 0, 0, true); KWin::setIcons(tabWindow->winId(), kapp->icon(), kapp->miniIcon()); bool isnewmodem; if(gpppdata.modname().isEmpty()) { tabWindow->setCaption(i18n("New Modem")); isnewmodem = true; } else { QString tit = i18n("Edit Modem: "); tit += gpppdata.modname(); tabWindow->setCaption(tit); isnewmodem = false; } modem1 = new ModemWidget(tabWindow->addPage( i18n("&Device"), i18n("Serial Device")), isnewmodem ); modem2 = new ModemWidget2(tabWindow->addPage( i18n("&Modem"), i18n("Modem Settings"))); connect ( modem1->connectName(), SIGNAL(textChanged ( const QString & )), this, SLOT(modemNameChanged(const QString & ))); modemNameChanged(modem1->connectName()->text()); int result = 0; bool ok = false; while (!ok){ result = tabWindow->exec(); ok = true; if(result == QDialog::Accepted) { if(modem1->save()) { modem2->save(); } else { KMessageBox::error(this, i18n( "You must enter a unique\n" "modem name")); ok = false; } } } delete tabWindow; return result; } void ModemsWidget::modemNameChanged(const QString & text) { tabWindow->enableButtonOK( !text.isEmpty() ); } QString ModemsWidget::prettyPrintVolume(unsigned int n) { int idx = 0; const QString quant[] = {i18n("Byte"), i18n("KB"), i18n("MB"), i18n("GB"), QString::null}; float n1 = n; while(n >= 1024 && !quant[idx].isNull()) { idx++; n /= 1024; } int i = idx; while(i--) n1 = n1 / 1024.0; QString s = KGlobal::locale()->formatNumber( n1, idx==0 ? 0 : 1 ); s += " " + quant[idx]; return s; } #include "modems.moc" <|endoftext|>
<commit_before>// // test_janus.cpp // sophos // // Created by Raphael Bost on 14/05/2017. // Copyright © 2017 Raphael Bost. All rights reserved. // #include <iostream> #include <ostream> #include <fstream> #include <sse/crypto/puncturable_enc.hpp> #include <sse/crypto/random.hpp> #include <sse/crypto/utils.hpp> #include <chrono> #include <cassert> #include "janus/janus_client.hpp" #include "janus/janus_server.hpp" using namespace sse::crypto; using namespace sse::janus; using namespace std; void benchmark_sk0_generation(ostream &out) { const size_t bench_count = 100; std::chrono::duration<double, std::milli> keyshare_time(0); for (size_t i = 0; i < bench_count; i++) { punct::master_key_type master_key; auto t_start = std::chrono::high_resolution_clock::now(); PuncturableEncryption cryptor(std::move(master_key)); auto volatile sk0 = cryptor.initial_keyshare(i); auto t_end = std::chrono::high_resolution_clock::now(); keyshare_time = t_end - t_start; out << "SK0 \t" << keyshare_time.count() << endl; } } void benchmark_puncture_generation(ostream &out) { const size_t puncture_count = 20; const size_t bench_count = 20; for (size_t j = 0; j < bench_count; j++) { auto master_key_array = sse::crypto::random_bytes<uint8_t, 32>(); std::chrono::duration<double, std::milli> keyshare_time(0); for (size_t i = 1; i < puncture_count+1; i++) { punct::tag_type tag{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}; tag[0] = i&0xFF; tag[1] = (i>>8)&0xFF; tag[2] = (i>>16)&0xFF; tag[3] = (i>>24)&0xFF; tag[4] = (i>>32)&0xFF; tag[5] = (i>>40)&0xFF; tag[6] = (i>>48)&0xFF; tag[7] = (i>>56)&0xFF; // to do the benchmark, we have to copy the key as it is going to be erased otherwise auto master_key_array_cp = master_key_array; auto t_start = std::chrono::high_resolution_clock::now(); PuncturableEncryption cryptor(master_key_array_cp.data()); auto volatile sk_i = cryptor.inc_puncture(i, tag); auto t_end = std::chrono::high_resolution_clock::now(); keyshare_time = t_end - t_start; out << "Puncture \t" << keyshare_time.count() << endl; } } } void benchmark_encrypt(ostream &out) { const size_t encrypt_count = 20; const size_t bench_count = 20; uint64_t M; for (size_t j = 0; j < bench_count; j++) { auto master_key_array = sse::crypto::random_bytes<uint8_t, 32>(); std::chrono::duration<double, std::milli> time(0); for (size_t i = 0; i < encrypt_count; i++) { punct::tag_type tag{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}; sse::crypto::random_bytes(tag); tag[0] = i&0xFF; tag[1] = (i>>8)&0xFF; tag[2] = (i>>16)&0xFF; tag[3] = (i>>24)&0xFF; tag[4] = (i>>32)&0xFF; tag[5] = (i>>40)&0xFF; tag[6] = (i>>48)&0xFF; tag[7] = (i>>56)&0xFF; sse::crypto::random_bytes(sizeof(uint64_t), (uint8_t*) &M); // to do the benchmark, we have to copy the key as it is going to be erased otherwise auto master_key_array_cp = master_key_array; auto t_start = std::chrono::high_resolution_clock::now(); PuncturableEncryption cryptor(master_key_array_cp.data()); auto sk_i = cryptor.encrypt(M, tag); auto t_end = std::chrono::high_resolution_clock::now(); time = t_end - t_start; out << "Encrypt \t" << time.count() << endl; } } } void benchmark_decrypt(ostream &out) { const size_t decrypt_count = 20; const size_t bench_count = 20; uint64_t M, dec_M; const std::vector<size_t> puncture_count_list = {0, 5, 15, 30, 50, 100}; for (size_t j = 0; j < bench_count; j++) { cout << "Decryption round " << j; punct::master_key_type master_key; std::chrono::duration<double, std::milli> time(0); PuncturableEncryption cryptor(std::move(master_key)); std::vector<punct::key_share_type> keyshares; size_t current_p_count = 0; punct::tag_type punctured_tag{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}; sse::crypto::random_bytes(punctured_tag); keyshares.push_back(cryptor.initial_keyshare(0)); for (size_t p : puncture_count_list) { cout << " " << p << flush; // add new punctures for ( ; current_p_count < p; current_p_count++) { punctured_tag[15] = current_p_count&0xFF; punctured_tag[14] = (current_p_count>>8)&0xFF; punctured_tag[13] = (current_p_count>>16)&0xFF; punctured_tag[12] = (current_p_count>>24)&0xFF; punctured_tag[11] = (current_p_count>>32)&0xFF; punctured_tag[10] = (current_p_count>>40)&0xFF; punctured_tag[9] = (current_p_count>>48)&0xFF; // punctured_tag[8] = (current_p_count>>56)&0xFF; punctured_tag[8] = 0xFF; auto share = cryptor.inc_puncture(current_p_count+1, punctured_tag); keyshares.push_back(share); } keyshares[0] = cryptor.initial_keyshare(current_p_count); PuncturableDecryption decryptor(keyshares); for (size_t i = 0; i < decrypt_count; i++) { punct::tag_type tag{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}; sse::crypto::random_bytes(tag); tag[0] = i&0xFF; tag[1] = (i>>8)&0xFF; tag[2] = (i>>16)&0xFF; tag[3] = (i>>24)&0xFF; tag[4] = (i>>32)&0xFF; tag[5] = (i>>40)&0xFF; tag[6] = (i>>48)&0xFF; tag[7] = (i>>56)&0xFF; sse::crypto::random_bytes(sizeof(uint64_t), (uint8_t*) &M); auto ct = cryptor.encrypt(M, tag); auto t_start = std::chrono::high_resolution_clock::now(); bool success = decryptor.decrypt(ct, dec_M); auto t_end = std::chrono::high_resolution_clock::now(); assert(success); time = t_end - t_start; out << "Decrypt_" << std::to_string(current_p_count) << " \t " << time.count() << endl; out << "Decrypt_per_punct" << " \t " << time.count()/(keyshares.size()) << endl; } } cout << endl; } } void benchmark_puncturable_encryption() { ofstream benchmark_file("bench_janus.out"); assert(benchmark_file.is_open()); cout << "SK0 generation " << endl; benchmark_sk0_generation(benchmark_file); cout << "Puncture generation " << endl; benchmark_puncture_generation(benchmark_file); cout << "Encryption " << endl; benchmark_encrypt(benchmark_file); cout << "Decryption " << endl; benchmark_decrypt(benchmark_file); } void test_client_server() { sse::logger::set_severity(sse::logger::DBG); string client_master_key_path = "janus_master.key"; ifstream client_master_key_in(client_master_key_path.c_str()); typedef uint64_t index_type; unique_ptr<JanusClient> client; unique_ptr<JanusServer> server; if (client_master_key_in.good() == true) { // the files exist cout << "Restart Janus client and server" << endl; stringstream client_master_key_buf; string client_master_key; client_master_key_buf << client_master_key_in.rdbuf(); client_master_key = client_master_key_buf.str(); std::array<uint8_t, 32> client_master_key_array; assert(client_master_key.size() == client_master_key_array.size()); std::copy(client_master_key.begin(), client_master_key.end(), client_master_key_array.begin()); client.reset(new JanusClient("janus_client.search.dat", "janus_client.add.dat", "janus_client.del.dat", client_master_key_array.data())); server.reset(new JanusServer("janus_server.add.dat", "janus_server.del.dat", "janus_server.cache.dat")); SearchRequest s_req; std::string key = "toto"; s_req = client->search_request(key); // auto res = server->search(s_req); auto res = server->search_parallel(s_req,8); cout << "Search " << key << ". Results: ["; for(index_type i : res){ cout << i << ", "; } cout << "]" << endl; DeletionRequest del_req; del_req = client->deletion_request("toto", 2); server->delete_entry(del_req); InsertionRequest add_req; add_req = client->insertion_request("tata", 6); server->insert_entry(add_req); }else{ cout << "Create new Janus client-server instances" << endl; // generate new keys std::array<uint8_t, 32> client_master_key = sse::crypto::random_bytes<uint8_t, 32>(); // write keys to files ofstream client_master_key_out(client_master_key_path.c_str()); client_master_key_out << std::string(client_master_key.begin(), client_master_key.end()); client_master_key_out.close(); client.reset(new JanusClient("janus_client.search.dat", "janus_client.add.dat", "janus_client.del.dat", client_master_key.data())); server.reset(new JanusServer("janus_server.add.dat", "janus_server.del.dat", "janus_server.cache.dat")); InsertionRequest add_req; add_req = client->insertion_request("toto", 0); server->insert_entry(add_req); add_req = client->insertion_request("titi", 0); server->insert_entry(add_req); add_req = client->insertion_request("toto", 1); server->insert_entry(add_req); add_req = client->insertion_request("toto", 2); server->insert_entry(add_req); add_req = client->insertion_request("tata", 0); server->insert_entry(add_req); add_req = client->insertion_request("tata", 3); server->insert_entry(add_req); add_req = client->insertion_request("tata", 5); server->insert_entry(add_req); DeletionRequest del_req; del_req = client->deletion_request("tata", 3); server->delete_entry(del_req); } SearchRequest s_req; std::string key = "toto"; s_req = client->search_request(key); // auto res = server->search(s_req); auto res = server->search_parallel(s_req,8); cout << "Search " << key << ". Results: ["; for(index_type i : res){ cout << i << ", "; } cout << "]" << endl; key = "tata"; s_req = client->search_request(key); // res = server->search(s_req); res = server->search_parallel(s_req,8); cout << "Search " << key << ". Results: ["; for(index_type i : res){ cout << i << ", "; } cout << "]" << endl; client_master_key_in.close(); } int main(int argc, const char * argv[]) { init_crypto_lib(); benchmark_puncturable_encryption(); // test_client_server(); cleanup_crypto_lib(); return 0; } <commit_msg>Fix Janus<commit_after>// // test_janus.cpp // sophos // // Created by Raphael Bost on 14/05/2017. // Copyright © 2017 Raphael Bost. All rights reserved. // #include <iostream> #include <ostream> #include <fstream> #include <sse/crypto/puncturable_enc.hpp> #include <sse/crypto/random.hpp> #include <sse/crypto/utils.hpp> #include <chrono> #include <cassert> #include "janus/janus_client.hpp" #include "janus/janus_server.hpp" using namespace sse::crypto; using namespace sse::janus; using namespace std; using master_key_type = sse::crypto::Key<sse::crypto::punct::kMasterKeySize>; void benchmark_sk0_generation(ostream &out) { const size_t bench_count = 100; std::chrono::duration<double, std::milli> keyshare_time(0); for (size_t i = 0; i < bench_count; i++) { punct::master_key_type master_key; auto t_start = std::chrono::high_resolution_clock::now(); PuncturableEncryption cryptor(std::move(master_key)); auto volatile sk0 = cryptor.initial_keyshare(i); auto t_end = std::chrono::high_resolution_clock::now(); keyshare_time = t_end - t_start; out << "SK0 \t" << keyshare_time.count() << endl; } } void benchmark_puncture_generation(ostream &out) { const size_t puncture_count = 20; const size_t bench_count = 20; for (size_t j = 0; j < bench_count; j++) { auto master_key_array = sse::crypto::random_bytes<uint8_t, 32>(); std::chrono::duration<double, std::milli> keyshare_time(0); for (size_t i = 1; i < puncture_count+1; i++) { punct::tag_type tag{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}; tag[0] = i&0xFF; tag[1] = (i>>8)&0xFF; tag[2] = (i>>16)&0xFF; tag[3] = (i>>24)&0xFF; tag[4] = (i>>32)&0xFF; tag[5] = (i>>40)&0xFF; tag[6] = (i>>48)&0xFF; tag[7] = (i>>56)&0xFF; // to do the benchmark, we have to copy the key as it is going to be erased otherwise auto master_key_array_cp = master_key_array; auto t_start = std::chrono::high_resolution_clock::now(); PuncturableEncryption cryptor(master_key_type(master_key_array_cp.data())); auto volatile sk_i = cryptor.inc_puncture(i, tag); auto t_end = std::chrono::high_resolution_clock::now(); keyshare_time = t_end - t_start; out << "Puncture \t" << keyshare_time.count() << endl; } } } void benchmark_encrypt(ostream &out) { const size_t encrypt_count = 20; const size_t bench_count = 20; uint64_t M; for (size_t j = 0; j < bench_count; j++) { auto master_key_array = sse::crypto::random_bytes<uint8_t, 32>(); std::chrono::duration<double, std::milli> time(0); for (size_t i = 0; i < encrypt_count; i++) { punct::tag_type tag{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}; sse::crypto::random_bytes(tag); tag[0] = i&0xFF; tag[1] = (i>>8)&0xFF; tag[2] = (i>>16)&0xFF; tag[3] = (i>>24)&0xFF; tag[4] = (i>>32)&0xFF; tag[5] = (i>>40)&0xFF; tag[6] = (i>>48)&0xFF; tag[7] = (i>>56)&0xFF; sse::crypto::random_bytes(sizeof(uint64_t), (uint8_t*) &M); // to do the benchmark, we have to copy the key as it is going to be erased otherwise auto master_key_array_cp = master_key_array; auto t_start = std::chrono::high_resolution_clock::now(); PuncturableEncryption cryptor(master_key_type(master_key_array_cp.data())); auto sk_i = cryptor.encrypt(M, tag); auto t_end = std::chrono::high_resolution_clock::now(); time = t_end - t_start; out << "Encrypt \t" << time.count() << endl; } } } void benchmark_decrypt(ostream &out) { const size_t decrypt_count = 20; const size_t bench_count = 20; uint64_t M, dec_M; const std::vector<size_t> puncture_count_list = {0, 5, 15, 30, 50, 100}; for (size_t j = 0; j < bench_count; j++) { cout << "Decryption round " << j; punct::master_key_type master_key; std::chrono::duration<double, std::milli> time(0); PuncturableEncryption cryptor(std::move(master_key)); std::vector<punct::key_share_type> keyshares; size_t current_p_count = 0; punct::tag_type punctured_tag{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}; sse::crypto::random_bytes(punctured_tag); keyshares.push_back(cryptor.initial_keyshare(0)); for (size_t p : puncture_count_list) { cout << " " << p << flush; // add new punctures for ( ; current_p_count < p; current_p_count++) { punctured_tag[15] = current_p_count&0xFF; punctured_tag[14] = (current_p_count>>8)&0xFF; punctured_tag[13] = (current_p_count>>16)&0xFF; punctured_tag[12] = (current_p_count>>24)&0xFF; punctured_tag[11] = (current_p_count>>32)&0xFF; punctured_tag[10] = (current_p_count>>40)&0xFF; punctured_tag[9] = (current_p_count>>48)&0xFF; // punctured_tag[8] = (current_p_count>>56)&0xFF; punctured_tag[8] = 0xFF; auto share = cryptor.inc_puncture(current_p_count+1, punctured_tag); keyshares.push_back(share); } keyshares[0] = cryptor.initial_keyshare(current_p_count); PuncturableDecryption decryptor(keyshares); for (size_t i = 0; i < decrypt_count; i++) { punct::tag_type tag{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}; sse::crypto::random_bytes(tag); tag[0] = i&0xFF; tag[1] = (i>>8)&0xFF; tag[2] = (i>>16)&0xFF; tag[3] = (i>>24)&0xFF; tag[4] = (i>>32)&0xFF; tag[5] = (i>>40)&0xFF; tag[6] = (i>>48)&0xFF; tag[7] = (i>>56)&0xFF; sse::crypto::random_bytes(sizeof(uint64_t), (uint8_t*) &M); auto ct = cryptor.encrypt(M, tag); auto t_start = std::chrono::high_resolution_clock::now(); bool success = decryptor.decrypt(ct, dec_M); auto t_end = std::chrono::high_resolution_clock::now(); assert(success); time = t_end - t_start; out << "Decrypt_" << std::to_string(current_p_count) << " \t " << time.count() << endl; out << "Decrypt_per_punct" << " \t " << time.count()/(keyshares.size()) << endl; } } cout << endl; } } void benchmark_puncturable_encryption() { ofstream benchmark_file("bench_janus.out"); assert(benchmark_file.is_open()); cout << "SK0 generation " << endl; benchmark_sk0_generation(benchmark_file); cout << "Puncture generation " << endl; benchmark_puncture_generation(benchmark_file); cout << "Encryption " << endl; benchmark_encrypt(benchmark_file); cout << "Decryption " << endl; benchmark_decrypt(benchmark_file); } void test_client_server() { sse::logger::set_severity(sse::logger::DBG); string client_master_key_path = "janus_master.key"; ifstream client_master_key_in(client_master_key_path.c_str()); typedef uint64_t index_type; unique_ptr<JanusClient> client; unique_ptr<JanusServer> server; if (client_master_key_in.good() == true) { // the files exist cout << "Restart Janus client and server" << endl; stringstream client_master_key_buf; string client_master_key; client_master_key_buf << client_master_key_in.rdbuf(); client_master_key = client_master_key_buf.str(); std::array<uint8_t, 32> client_master_key_array; assert(client_master_key.size() == client_master_key_array.size()); std::copy(client_master_key.begin(), client_master_key.end(), client_master_key_array.begin()); client.reset(new JanusClient("janus_client.search.dat", "janus_client.add.dat", "janus_client.del.dat", Key<JanusClient::kPRFKeySize>(client_master_key_array.data()))); server.reset(new JanusServer("janus_server.add.dat", "janus_server.del.dat", "janus_server.cache.dat")); SearchRequest s_req; std::string key = "toto"; s_req = client->search_request(key); // auto res = server->search(s_req); auto res = server->search_parallel(s_req,8); cout << "Search " << key << ". Results: ["; for(index_type i : res){ cout << i << ", "; } cout << "]" << endl; DeletionRequest del_req; del_req = client->deletion_request("toto", 2); server->delete_entry(del_req); InsertionRequest add_req; add_req = client->insertion_request("tata", 6); server->insert_entry(add_req); }else{ cout << "Create new Janus client-server instances" << endl; // generate new keys std::array<uint8_t, 32> client_master_key = sse::crypto::random_bytes<uint8_t, 32>(); // write keys to files ofstream client_master_key_out(client_master_key_path.c_str()); client_master_key_out << std::string(client_master_key.begin(), client_master_key.end()); client_master_key_out.close(); client.reset(new JanusClient("janus_client.search.dat", "janus_client.add.dat", "janus_client.del.dat", Key<JanusClient::kPRFKeySize>(client_master_key.data()))); server.reset(new JanusServer("janus_server.add.dat", "janus_server.del.dat", "janus_server.cache.dat")); InsertionRequest add_req; add_req = client->insertion_request("toto", 0); server->insert_entry(add_req); add_req = client->insertion_request("titi", 0); server->insert_entry(add_req); add_req = client->insertion_request("toto", 1); server->insert_entry(add_req); add_req = client->insertion_request("toto", 2); server->insert_entry(add_req); add_req = client->insertion_request("tata", 0); server->insert_entry(add_req); add_req = client->insertion_request("tata", 3); server->insert_entry(add_req); add_req = client->insertion_request("tata", 5); server->insert_entry(add_req); DeletionRequest del_req; del_req = client->deletion_request("tata", 3); server->delete_entry(del_req); } SearchRequest s_req; std::string key = "toto"; s_req = client->search_request(key); // auto res = server->search(s_req); auto res = server->search_parallel(s_req,8); cout << "Search " << key << ". Results: ["; for(index_type i : res){ cout << i << ", "; } cout << "]" << endl; key = "tata"; s_req = client->search_request(key); // res = server->search(s_req); res = server->search_parallel(s_req,8); cout << "Search " << key << ". Results: ["; for(index_type i : res){ cout << i << ", "; } cout << "]" << endl; client_master_key_in.close(); } int main(int argc, const char * argv[]) { init_crypto_lib(); benchmark_puncturable_encryption(); // test_client_server(); cleanup_crypto_lib(); return 0; } <|endoftext|>
<commit_before>#include <matrix.hpp> #include <catch.hpp> SCENARIO("copy constructor") { Matrix matrix; Matrix copy(matrix); REQUIRE(copy.strings_() == 2); REQUIRE(copy.columns_() == 2); } SCENARIO("operator +") { Matrix matrix (2, 2); Matrix matrix1 = Matrix (2, 2); std::ifstream("text.txt") >> matrix1; REQUIRE(matrix1 + matrix == matrix + matrix ); } SCENARIO("operator *") { Matrix matrix (2,2); Matrix matrix3 = Matrix (2,2); REQUIRE(matrix * matrix == matrix3); } SCENARIO("operator =") { Matrix matrix (2,2); Matrix matrix2 = matrix; REQUIRE(matrix == matrix2); } SCENARIO("operator ==") { Matrix matrix (2,2); Matrix matrix2 = Matrix (2,2); REQUIRE(matrix == matrix2); } <commit_msg>Update init.cpp<commit_after>#include <matrix.hpp> #include <catch.hpp> SCENARIO("copy constructor") { Matrix matrix; Matrix copy(matrix); REQUIRE(copy.strings() == 2); REQUIRE(copy.columns() == 2); } SCENARIO("operator +") { Matrix matrix (2, 2); Matrix matrix1 = Matrix (2, 2); REQUIRE(matrix1 + matrix == matrix + matrix ); } SCENARIO("operator *") { Matrix matrix (2,2); Matrix matrix3 = Matrix (2,2); REQUIRE(matrix * matrix == matrix3); } SCENARIO("operator =") { Matrix matrix (2,2); Matrix matrix2 = matrix; REQUIRE(matrix == matrix2); } SCENARIO("operator ==") { Matrix matrix (2,2); Matrix matrix2 = Matrix (2,2); REQUIRE(matrix == matrix2); } <|endoftext|>
<commit_before>#include "stack.hpp" #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); s.pop(); REQUIRE(s.count()==0); } SCENARIO("cop", "[cop]"){ stack<int> s; s.push(1); stack<int> s2=s; REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("top", "[top]"){ stack<int> s; s.push(1); REQUIRE(s.top()==1); } SCENARIO("empty", "[empty]"){ stack<int> s1, s2; s1.push(1); REQUIRE(!s1.empty()); REQUIRE(s2.empty()); } <commit_msg>Update init.cpp<commit_after>#include "stack.hpp" #include <catch.hpp> #include <iostream> #include <thread> using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); s.pop(); REQUIRE(s.count()==0); } SCENARIO("cop", "[cop]"){ stack<int> s; s.push(1); stack<int> s2=s; REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("top", "[top]"){ stack<int> s; s.push(1); REQUIRE(s.top()==1); } SCENARIO("empty", "[empty]"){ stack<int> s1, s2; s1.push(1); REQUIRE(!s1.empty()); REQUIRE(s2.empty()); } SCENARIO("threads", "[threads]"){ stack<int> s; std::thread t1(s.push, 1); std::thread t2(s.pop); t1.join; t2.join; REQUIRE(s.count()==0); } <|endoftext|>
<commit_before>/* This file is part of Anabel Anabel 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. Anabel 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 Anabel; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <anabel/stdafx.h> #include <anabel/anabel.h> using namespace boost::filesystem; using namespace boost::interprocess; using namespace Anabel::Exceptions; using namespace std; using namespace Anabel; using namespace Anabel::Internal; void Anabel::TimeSeries::create(char * rootdirpath, int record_size) { path rootpath(rootdirpath); try { create_directory(rootpath); } catch (...) {} ofstream alock((rootpath / "alock").c_str()); alock.close(); ofstream block((rootpath / "block").c_str()); block.close(); ofstream rsf((rootpath / "record_size").c_str()); rsf << record_size; rsf.close(); make_empty_dataset(rootpath / "0"); } /** * Chooses a timestamp that can be chosen, so it contains needle. * * Haystack must not be empty - other way, it would not make any sense, would it? * Haystack must contain entry that will follow us to needle. */ Timestamp choose(vector<Timestamp> haystack, Timestamp needle) { for (unsigned i=0; i<haystack.size(); i++) { if (haystack[i] <= needle) return haystack[i]; } throw InternalError("needle not found"); } Anabel::ReadQuery * Anabel::TimeSeries::get_query(Anabel::Timestamp from, Anabel::Timestamp to) throw(Anabel::Exceptions::InvalidInvocation) { // Sanity checks if ((this->mode != TSO_READ) && (this->mode != TSO_WRITE)) throw InvalidInvocation("invalid open mode"); if (from>to) throw InvalidInvocation("from>to"); typedef vector<Timestamp> timevector; typedef vector<Timestamp>::iterator timevectoriter; // Init variables path cpath = this->root_path; timevector elements; Timestamp choice; vector<path> files; // Locate UBA cpath = this->root_path; try { while (is_directory(cpath)) { elements = scan_directory(cpath); sort(elements.begin(), elements.end(), greater<Timestamp>()); choice = choose(elements, to); cpath /= timestamp_to_string(choice); } } catch (InternalError e) { // query empty. return new Anabel::ReadQuery(from, to, files, this->record_size); } files.push_back(cpath); if (choice <= from) { return new Anabel::ReadQuery(from, to, files, this->record_size); // response is a single-file wonder } cpath = cpath.parent_path(); // Now we will trace thru the filesystem, finding doodz. First up the tree, and then sharp dive towards 'to' Timestamp previous_choice = choice; while (true) { elements = scan_directory(cpath); sort(elements.begin(), elements.end(), std::greater<Timestamp>()); timevectoriter bound = lower_bound(elements.begin(), elements.end(), from, std::greater<Timestamp>()); if (bound == elements.end()) { // we need to ascend // index files from bound upwards for (timevectoriter start_bound = upper_bound(elements.begin(), elements.end(), to, std::greater<Timestamp>()); start_bound != elements.end(); start_bound++) { if (previous_choice == *start_bound) continue; previous_choice = *start_bound; files.push_back(cpath / timestamp_to_string(*start_bound)); } cpath = cpath.parent_path(); continue; } // Descent to "bound" for (timevectoriter start_bound = upper_bound(elements.begin(), elements.end(), to, std::greater<Timestamp>()); start_bound != bound; start_bound++) { if (previous_choice == *start_bound) continue; previous_choice = *start_bound; files.push_back(cpath / timestamp_to_string(*start_bound)); } cpath = cpath / timestamp_to_string(*bound); if (is_regular_file(cpath)) { files.push_back(cpath); break; } } return new Anabel::ReadQuery(from, to, files, this->record_size); } void Anabel::TimeSeries::truncate(void) throw(Anabel::Exceptions::InvalidInvocation) { if (this->mode != TSO_WRITE) throw InvalidInvocation("invalid open mode"); vector<Timestamp> elements = scan_directory(this->root_path); for (vector<Timestamp>::iterator iter = elements.begin(); iter != elements.end(); iter++) remove_all(this->root_path / Anabel::Internal::timestamp_to_string(*iter)); make_empty_dataset(this->root_path / "0"); } void Anabel::TimeSeries::append(void * value) throw(Anabel::Exceptions::InvalidInvocation) { if ((this->mode != TSO_APPEND) && (this->mode != TSO_WRITE)) throw InvalidInvocation("invalid open mode"); path path(this->root_path); while (!is_regular_file(path)) { vector<Timestamp> elements = scan_directory(path); path /= timestamp_to_string(*max_element(elements.begin(), elements.end())); } ofstream file(path.string().c_str(), std::ios::binary | std::ios::app); file.write((char*)value, 8+this->record_size); file.close(); } void Anabel::TimeSeries::open(TimeSeriesOpenMode open_mode) throw(Anabel::Exceptions::InvalidInvocation) { /* Locking interaction table (whether two types of locks may be acquired if the other is present): READ WRITE REBALANCE APPEND READ YES NO NO YES WRITE NO NO NO NO REBALANCE NO NO NO YES APPEND YES NO YES NO Types of locks acquired (eXclusive, Shareable): READ: S(A) WRITE: X(A)+X(B) APPEND: X(B) REBALANCE: X(A) As you may see, deadlocks will not happen */ switch (open_mode) { case TSO_APPEND: this->block->lock(); break; case TSO_REBALANCE: this->alock->lock(); break; case TSO_READ: this->alock->lock_sharable(); break; case TSO_WRITE: this->alock->lock(); this->block->lock(); break; case TSO_CLOSED: // funnt, not undefined though throw InvalidInvocation("invalid open_mode"); break; default: throw InvalidInvocation("unknown open_mode"); } // Read type of time series, as we don't know it now std::ifstream conf((this->root_path / "record_size").string().c_str()); conf >> this->record_size; conf.close(); this->mode = open_mode; } void Anabel::TimeSeries::indent(void) throw(Anabel::Exceptions::InvalidInvocation) { if ((this->mode != TSO_APPEND) && (this->mode != TSO_WRITE)) throw InvalidInvocation("invalid open mode"); vector<Timestamp> elements = scan_directory(this->root_path); sort(elements.begin(), elements.end()); vector<path> files; for (vector<Timestamp>::iterator iter = elements.begin(); iter != elements.end(); iter++) files.push_back(this->root_path / timestamp_to_string(*iter)); DirectoryIterator diter(files, true); Anabel::Timestamp * timestamp = (Anabel::Timestamp*)malloc(8+this->record_size); while (true) { if (diter.empty) return; IntelligentFileReader ifr(diter.next(), this->record_size); if (ifr.records_remaining > 0) { ifr.seek_record(ifr.records_remaining-1); ifr.get_data(1,(void*)timestamp); make_empty_dataset(this->root_path / timestamp_to_string((*timestamp)+1)); } ifr.close(); } } bool Anabel::TimeSeries::get_last(void * buffer) throw(Anabel::Exceptions::InvalidInvocation) { if ((this->mode != TSO_READ) && (this->mode != TSO_WRITE)) throw InvalidInvocation("invalid open mode"); vector<Timestamp> elements = scan_directory(this->root_path); sort(elements.begin(), elements.end()); vector<path> files; for (vector<Timestamp>::iterator iter = elements.begin(); iter != elements.end(); iter++) files.push_back(this->root_path / timestamp_to_string(*iter)); DirectoryIterator diter(files, true); while (true) { if (diter.empty) return false; IntelligentFileReader ifr(diter.next(), this->record_size); if (ifr.records_remaining > 0) { ifr.seek_record(ifr.records_remaining-1); ifr.get_data(1,buffer); return true; } ifr.close(); } } void Anabel::TimeSeries::close(void) { switch (this->mode) { case TSO_READ: this->alock->unlock_sharable(); break; case TSO_WRITE: this->alock->unlock(); this->block->unlock(); break; case TSO_REBALANCE: this->alock->unlock(); break; case TSO_APPEND: this->block->unlock(); break; case TSO_CLOSED: break; } this->mode = TSO_CLOSED; } Anabel::TimeSeries::TimeSeries(char * rootdirpath) throw(Anabel::Exceptions::InvalidRootDirectory) : mode(TSO_CLOSED), record_size(0) { // Prepare pathes this->root_path = rootdirpath; path rsize_path(this->root_path); rsize_path /= "record_size"; path alock_path(this->root_path); alock_path /= "alock"; path block_path(this->root_path); block_path /= "block"; // Sanity-check pathes if (!exists(this->root_path)) throw InvalidRootDirectory("root directory does not exist"); if (!is_directory(this->root_path)) throw InvalidRootDirectory("root directory is not a directory"); if (!exists(rsize_path)) throw InvalidRootDirectory("rsize_path file not found"); if (!exists(alock_path)) throw InvalidRootDirectory("append lock not found"); if (!exists(block_path)) throw InvalidRootDirectory("rebalance lock not found"); // Create locks this->alock = new boost::interprocess::file_lock(alock_path.string().c_str()); this->block = new boost::interprocess::file_lock(block_path.string().c_str()); } Anabel::TimeSeries::~TimeSeries() { if (this->mode != TSO_CLOSED) this->close(); delete this->alock; delete this->block; } <commit_msg>if a create() is called on existing database, it will be overwritten<commit_after>/* This file is part of Anabel Anabel 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. Anabel 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 Anabel; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <anabel/stdafx.h> #include <anabel/anabel.h> using namespace boost::filesystem; using namespace boost::interprocess; using namespace Anabel::Exceptions; using namespace std; using namespace Anabel; using namespace Anabel::Internal; void Anabel::TimeSeries::create(char * rootdirpath, int record_size) { path rootpath(rootdirpath); try { remove_all(rootpath); } catch(...) {} try { create_directory(rootpath); } catch (...) {} ofstream alock((rootpath / "alock").c_str()); alock.close(); ofstream block((rootpath / "block").c_str()); block.close(); ofstream rsf((rootpath / "record_size").c_str()); rsf << record_size; rsf.close(); make_empty_dataset(rootpath / "0"); } /** * Chooses a timestamp that can be chosen, so it contains needle. * * Haystack must not be empty - other way, it would not make any sense, would it? * Haystack must contain entry that will follow us to needle. */ Timestamp choose(vector<Timestamp> haystack, Timestamp needle) { for (unsigned i=0; i<haystack.size(); i++) { if (haystack[i] <= needle) return haystack[i]; } throw InternalError("needle not found"); } Anabel::ReadQuery * Anabel::TimeSeries::get_query(Anabel::Timestamp from, Anabel::Timestamp to) throw(Anabel::Exceptions::InvalidInvocation) { // Sanity checks if ((this->mode != TSO_READ) && (this->mode != TSO_WRITE)) throw InvalidInvocation("invalid open mode"); if (from>to) throw InvalidInvocation("from>to"); typedef vector<Timestamp> timevector; typedef vector<Timestamp>::iterator timevectoriter; // Init variables path cpath = this->root_path; timevector elements; Timestamp choice; vector<path> files; // Locate UBA cpath = this->root_path; try { while (is_directory(cpath)) { elements = scan_directory(cpath); sort(elements.begin(), elements.end(), greater<Timestamp>()); choice = choose(elements, to); cpath /= timestamp_to_string(choice); } } catch (InternalError e) { // query empty. return new Anabel::ReadQuery(from, to, files, this->record_size); } files.push_back(cpath); if (choice <= from) { return new Anabel::ReadQuery(from, to, files, this->record_size); // response is a single-file wonder } cpath = cpath.parent_path(); // Now we will trace thru the filesystem, finding doodz. First up the tree, and then sharp dive towards 'to' Timestamp previous_choice = choice; while (true) { elements = scan_directory(cpath); sort(elements.begin(), elements.end(), std::greater<Timestamp>()); timevectoriter bound = lower_bound(elements.begin(), elements.end(), from, std::greater<Timestamp>()); if (bound == elements.end()) { // we need to ascend // index files from bound upwards for (timevectoriter start_bound = upper_bound(elements.begin(), elements.end(), to, std::greater<Timestamp>()); start_bound != elements.end(); start_bound++) { if (previous_choice == *start_bound) continue; previous_choice = *start_bound; files.push_back(cpath / timestamp_to_string(*start_bound)); } cpath = cpath.parent_path(); continue; } // Descent to "bound" for (timevectoriter start_bound = upper_bound(elements.begin(), elements.end(), to, std::greater<Timestamp>()); start_bound != bound; start_bound++) { if (previous_choice == *start_bound) continue; previous_choice = *start_bound; files.push_back(cpath / timestamp_to_string(*start_bound)); } cpath = cpath / timestamp_to_string(*bound); if (is_regular_file(cpath)) { files.push_back(cpath); break; } } return new Anabel::ReadQuery(from, to, files, this->record_size); } void Anabel::TimeSeries::truncate(void) throw(Anabel::Exceptions::InvalidInvocation) { if (this->mode != TSO_WRITE) throw InvalidInvocation("invalid open mode"); vector<Timestamp> elements = scan_directory(this->root_path); for (vector<Timestamp>::iterator iter = elements.begin(); iter != elements.end(); iter++) remove_all(this->root_path / Anabel::Internal::timestamp_to_string(*iter)); make_empty_dataset(this->root_path / "0"); } void Anabel::TimeSeries::append(void * value) throw(Anabel::Exceptions::InvalidInvocation) { if ((this->mode != TSO_APPEND) && (this->mode != TSO_WRITE)) throw InvalidInvocation("invalid open mode"); path path(this->root_path); while (!is_regular_file(path)) { vector<Timestamp> elements = scan_directory(path); path /= timestamp_to_string(*max_element(elements.begin(), elements.end())); } ofstream file(path.string().c_str(), std::ios::binary | std::ios::app); file.write((char*)value, 8+this->record_size); file.close(); } void Anabel::TimeSeries::open(TimeSeriesOpenMode open_mode) throw(Anabel::Exceptions::InvalidInvocation) { /* Locking interaction table (whether two types of locks may be acquired if the other is present): READ WRITE REBALANCE APPEND READ YES NO NO YES WRITE NO NO NO NO REBALANCE NO NO NO YES APPEND YES NO YES NO Types of locks acquired (eXclusive, Shareable): READ: S(A) WRITE: X(A)+X(B) APPEND: X(B) REBALANCE: X(A) As you may see, deadlocks will not happen */ switch (open_mode) { case TSO_APPEND: this->block->lock(); break; case TSO_REBALANCE: this->alock->lock(); break; case TSO_READ: this->alock->lock_sharable(); break; case TSO_WRITE: this->alock->lock(); this->block->lock(); break; case TSO_CLOSED: // funnt, not undefined though throw InvalidInvocation("invalid open_mode"); break; default: throw InvalidInvocation("unknown open_mode"); } // Read type of time series, as we don't know it now std::ifstream conf((this->root_path / "record_size").string().c_str()); conf >> this->record_size; conf.close(); this->mode = open_mode; } void Anabel::TimeSeries::indent(void) throw(Anabel::Exceptions::InvalidInvocation) { if ((this->mode != TSO_APPEND) && (this->mode != TSO_WRITE)) throw InvalidInvocation("invalid open mode"); vector<Timestamp> elements = scan_directory(this->root_path); sort(elements.begin(), elements.end()); vector<path> files; for (vector<Timestamp>::iterator iter = elements.begin(); iter != elements.end(); iter++) files.push_back(this->root_path / timestamp_to_string(*iter)); DirectoryIterator diter(files, true); Anabel::Timestamp * timestamp = (Anabel::Timestamp*)malloc(8+this->record_size); while (true) { if (diter.empty) return; IntelligentFileReader ifr(diter.next(), this->record_size); if (ifr.records_remaining > 0) { ifr.seek_record(ifr.records_remaining-1); ifr.get_data(1,(void*)timestamp); make_empty_dataset(this->root_path / timestamp_to_string((*timestamp)+1)); } ifr.close(); } } bool Anabel::TimeSeries::get_last(void * buffer) throw(Anabel::Exceptions::InvalidInvocation) { if ((this->mode != TSO_READ) && (this->mode != TSO_WRITE)) throw InvalidInvocation("invalid open mode"); vector<Timestamp> elements = scan_directory(this->root_path); sort(elements.begin(), elements.end()); vector<path> files; for (vector<Timestamp>::iterator iter = elements.begin(); iter != elements.end(); iter++) files.push_back(this->root_path / timestamp_to_string(*iter)); DirectoryIterator diter(files, true); while (true) { if (diter.empty) return false; IntelligentFileReader ifr(diter.next(), this->record_size); if (ifr.records_remaining > 0) { ifr.seek_record(ifr.records_remaining-1); ifr.get_data(1,buffer); return true; } ifr.close(); } } void Anabel::TimeSeries::close(void) { switch (this->mode) { case TSO_READ: this->alock->unlock_sharable(); break; case TSO_WRITE: this->alock->unlock(); this->block->unlock(); break; case TSO_REBALANCE: this->alock->unlock(); break; case TSO_APPEND: this->block->unlock(); break; case TSO_CLOSED: break; } this->mode = TSO_CLOSED; } Anabel::TimeSeries::TimeSeries(char * rootdirpath) throw(Anabel::Exceptions::InvalidRootDirectory) : mode(TSO_CLOSED), record_size(0) { // Prepare pathes this->root_path = rootdirpath; path rsize_path(this->root_path); rsize_path /= "record_size"; path alock_path(this->root_path); alock_path /= "alock"; path block_path(this->root_path); block_path /= "block"; // Sanity-check pathes if (!exists(this->root_path)) throw InvalidRootDirectory("root directory does not exist"); if (!is_directory(this->root_path)) throw InvalidRootDirectory("root directory is not a directory"); if (!exists(rsize_path)) throw InvalidRootDirectory("rsize_path file not found"); if (!exists(alock_path)) throw InvalidRootDirectory("append lock not found"); if (!exists(block_path)) throw InvalidRootDirectory("rebalance lock not found"); // Create locks this->alock = new boost::interprocess::file_lock(alock_path.string().c_str()); this->block = new boost::interprocess::file_lock(block_path.string().c_str()); } Anabel::TimeSeries::~TimeSeries() { if (this->mode != TSO_CLOSED) this->close(); delete this->alock; delete this->block; } <|endoftext|>
<commit_before>#include <CCeilL.h> #include <COSSignal.h> static void ClLanguageSignalHandler(int sig) { ClSignalMgrInst->handleSignal(sig); } //------------------------ void ClSignalMgr:: init() { signal_command_map_[SIGSYNTAX] = nullptr; signal_command_map_[SIGEXPR ] = nullptr; signal_command_map_[SIGINT ] = nullptr; #ifdef SIGQUIT signal_command_map_[SIGQUIT ] = nullptr; #endif signal_command_map_[SIGABRT ] = nullptr; signal_command_map_[SIGTERM ] = nullptr; #ifdef SIGALRM signal_command_map_[SIGALRM ] = nullptr; #endif #ifdef SIGCHLD signal_command_map_[SIGCHLD ] = nullptr; #endif signal_command_map_[SIGSEGV ] = nullptr; } void ClSignalMgr:: initSignalProcs() { setSignalProc("interrupt", ClLanguageSignalHandler); setSignalProc("quit" , ClLanguageSignalHandler); setSignalProc("abort" , ClLanguageSignalHandler); setSignalProc("terminate", ClLanguageSignalHandler); } void ClSignalMgr:: termSignalProcs() { setSignalProc("interrupt", nullptr); setSignalProc("quit" , nullptr); setSignalProc("abort" , nullptr); setSignalProc("terminate", nullptr); } /*------------------------------------------------------------------* * * setSignalCommand * Set the Command to be Executed when the Named * Signal is raised. * * CALL: * bool flag = setSignalCommand(const std::string &name, const std::string &command); * * INPUT: * name : Signal Name * * command : Command String * * RETURNS: * flag : Whether the routine was successful or not. * *------------------------------------------------------------------*/ bool ClSignalMgr:: setSignalCommand(const std::string &name, const std::string &command) { int type = signalNameToType(name); if (type == -1) return false; ClSignalCommand *signal_command = getSignalCommand(type); if (! signal_command) return false; if (command != "") { if (isUnixSignal(type)) { ClSignalHandler proc = (ClSignalHandler) ClLanguageSignalHandler; if (! signal_command->proc) signal_command->old_proc = COSSignal::getSignalHandler(type); COSSignal::addSignalHandler(type, proc); signal_command->proc = proc; } signal_command->command = command; } else { if (isUnixSignal(type)) { if (signal_command->old_proc) COSSignal::addSignalHandler(type, signal_command->old_proc); else COSSignal::defaultSignal(type); signal_command->proc = nullptr; signal_command->old_proc = nullptr; } signal_command->command = ""; } return true; } /*------------------------------------------------------------------* * * raiseSignal * Raise the Named Signal to invoke is associated * Command or Routine. * * CALL: * bool flag = raiseSignal(const std::string &name, const std::string &data); * * INPUT: * name : Signal Name * * data : Signal Data (message str for "syntax" and "expression"). * * RETURNS: * flag : Whether the routine was successful or not. * *------------------------------------------------------------------*/ bool ClSignalMgr:: raiseSignal(const std::string &name, const std::string &data) { int type = signalNameToType(name); if (type == -1) return false; if (isUnixSignal(type)) COSSignal::sendSignalToProcessGroup(type); else if (type == SIGSYNTAX) { char *message; ClLanguageArgs *args = new ClLanguageArgs; args->startArgs(nullptr); if (args->getStringArgList(data, CLArgType::STRING, &message, CLArgType::NONE) != 1) return false; ClLanguageMgrInst->syntaxError(message); args->termArgs(); delete args; } else if (type == SIGEXPR) { char *message; ClLanguageArgs *args = new ClLanguageArgs; args->startArgs(nullptr); if (args->getStringArgList(data, CLArgType::STRING, &message, CLArgType::NONE) != 1) return false; ClLanguageMgrInst->expressionError(-1, message); args->termArgs(); delete args; } else return false; return true; } /*------------------------------------------------------------------* * * setSignalProc * Set the Routine to be called when the Named Signal is raised. * * CALL: * bool flag = setSignalProc(const std::string &name, ClSignalHandler proc); * * INPUT: * name : Signal Name * * proc : Signal Handling routine to call. * * OUTPUT: * None * * RETURNS: * flag : Whether the routine was successful or not. * * NOTES: * None * *------------------------------------------------------------------*/ bool ClSignalMgr:: setSignalProc(const std::string &name, ClSignalHandler proc) { int type = signalNameToType(name); if (type == -1) return false; ClSignalCommand *signal_command = getSignalCommand(type); if (! signal_command) return false; if (proc) { if (isUnixSignal(type)) { signal_command->old_proc = COSSignal::getSignalHandler(type); COSSignal::addSignalHandler(type, proc); } signal_command->proc = proc; } else { if (isUnixSignal(type)) { if (signal_command->old_proc) COSSignal::addSignalHandler(type, signal_command->old_proc); else COSSignal::defaultSignal(type); } signal_command->proc = nullptr; signal_command->old_proc = nullptr; signal_command->command = ""; } return true; } /*------------------------------------------------------------------* * * checkSignalCommand * Check whether there is a Command associated with * the Signal Type. * * CALL: * bool flag = checkSignalCommand(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * flag : Whether there is a Command associated with the Signal. * * NOTES: * None * *------------------------------------------------------------------*/ bool ClSignalMgr:: checkSignalCommand(int type) { ClSignalCommand *signal_command = getSignalCommand(type); if (! signal_command) return false; return (signal_command->command != ""); } /*------------------------------------------------------------------* * * executeSignalCommand * Run any Command associated with the Signal Type. * * CALL: * bool flag = executeSignalCommand(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * flag : Whether there is a Command associated with the Signal. * * NOTES: * None * *------------------------------------------------------------------*/ bool ClSignalMgr:: executeSignalCommand(int type) { ClSignalCommand *signal_command = getSignalCommand(type); if (! signal_command) return false; if (signal_command->command != "") ClLanguageMgrInst->runCommand(signal_command->command); return true; } /*------------------------------------------------------------------* * * handleSignal * Signal Handler for UNIX signals which runs any * associated Commands/Routines. * * CALL: * handleSignal(int sig); * * INPUT: * sig : Signal Type * * OUTPUT: * None * * RETURNS: * None * * NOTES: * None * *------------------------------------------------------------------*/ void ClSignalMgr:: handleSignal(int sig) { ClSignalCommand *signal_command = getSignalCommand(sig); if (signal_command && signal_command->command != "") ClLanguageMgrInst->runCommand(signal_command->command); else { if (sig == SIGINT || sig == SIGQUIT || sig == SIGABRT || sig == SIGTERM) ClLanguageMgrInst->setAbortSignal(true); if (sig == SIGINT) ClLanguageMgrInst->setInterruptFlag(true); } } /*------------------------------------------------------------------* * * getSignalCommand * Get the Signal Command Structure associated with * the specified Signal Type. * * CALL: * ClSignalCommand *signal_command = getSignalCommand(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * signal_command : Signal Command Structure * : (null if none). * * NOTES: * None * *------------------------------------------------------------------*/ ClSignalCommand * ClSignalMgr:: getSignalCommand(int type) const { SignalCommandMap::const_iterator p = signal_command_map_.find(type); if (p != signal_command_map_.end()) return (*p).second; return nullptr; } /*------------------------------------------------------------------* * * signalNameToType * Get the Type of the specified Signal Name. * * CALL: * int type = signalNameToType(comst std::string &name); * * INPUT: * name : Signal Name * * OUTPUT: * None * * RETURNS: * type : Signal Type * * NOTES: * None * *------------------------------------------------------------------*/ int ClSignalMgr:: signalNameToType(const std::string &name) const { if (CStrUtil::casecmp(name, "syntax") == 0) return SIGSYNTAX; else if (CStrUtil::casecmp(name, "expression") == 0) return SIGEXPR; return COSSignal::string_to_signal(name); } /*------------------------------------------------------------------* * * signalTypeToName * Get the Name of the specified Signal Type. * * CALL: * std::string name = signalTypeToName(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * name : Signal Name * * NOTES: * None * *------------------------------------------------------------------*/ std::string ClSignalMgr:: signalTypeToName(int type) const { switch (type) { case SIGSYNTAX: return "syntax"; break; case SIGEXPR: return "expression"; break; } return COSSignal::strsignal(type); } /*------------------------------------------------------------------* * * isUnixSignal * Check if a Signal Type is a UNIX Signal. * * CALL: * bool flag = isUnixSignal(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * flag : Whether the Signal Type is a UNIX Signal. * * NOTES: * None * *------------------------------------------------------------------*/ bool ClSignalMgr:: isUnixSignal(int type) const { if (type == SIGSYNTAX || type == SIGEXPR) return false; return true; } <commit_msg>new files<commit_after>#include <CCeilL.h> #include <COSSignal.h> static void ClLanguageSignalHandler(int sig) { ClSignalMgrInst->handleSignal(sig); } //------------------------ void ClSignalMgr:: init() { signal_command_map_[SIGSYNTAX] = nullptr; signal_command_map_[SIGEXPR ] = nullptr; signal_command_map_[SIGINT ] = nullptr; #ifdef SIGQUIT signal_command_map_[SIGQUIT ] = nullptr; #endif signal_command_map_[SIGABRT ] = nullptr; signal_command_map_[SIGTERM ] = nullptr; #ifdef SIGALRM signal_command_map_[SIGALRM ] = nullptr; #endif #ifdef SIGCHLD signal_command_map_[SIGCHLD ] = nullptr; #endif signal_command_map_[SIGSEGV ] = nullptr; } void ClSignalMgr:: initSignalProcs() { setSignalProc("interrupt", ClLanguageSignalHandler); setSignalProc("quit" , ClLanguageSignalHandler); setSignalProc("abort" , ClLanguageSignalHandler); setSignalProc("terminate", ClLanguageSignalHandler); } void ClSignalMgr:: termSignalProcs() { setSignalProc("interrupt", nullptr); setSignalProc("quit" , nullptr); setSignalProc("abort" , nullptr); setSignalProc("terminate", nullptr); } /*------------------------------------------------------------------* * * setSignalCommand * Set the Command to be Executed when the Named * Signal is raised. * * CALL: * bool flag = setSignalCommand(const std::string &name, const std::string &command); * * INPUT: * name : Signal Name * * command : Command String * * RETURNS: * flag : Whether the routine was successful or not. * *------------------------------------------------------------------*/ bool ClSignalMgr:: setSignalCommand(const std::string &name, const std::string &command) { int type = signalNameToType(name); if (type == -1) return false; ClSignalCommand *signal_command = getSignalCommand(type); if (! signal_command) return false; if (command != "") { if (isUnixSignal(type)) { ClSignalHandler proc = (ClSignalHandler) ClLanguageSignalHandler; if (! signal_command->proc) signal_command->old_proc = COSSignal::getSignalHandler(type); COSSignal::addSignalHandler(type, proc); signal_command->proc = proc; } signal_command->command = command; } else { if (isUnixSignal(type)) { if (signal_command->old_proc) COSSignal::addSignalHandler(type, signal_command->old_proc); else COSSignal::defaultSignal(type); signal_command->proc = nullptr; signal_command->old_proc = nullptr; } signal_command->command = ""; } return true; } /*------------------------------------------------------------------* * * raiseSignal * Raise the Named Signal to invoke is associated * Command or Routine. * * CALL: * bool flag = raiseSignal(const std::string &name, const std::string &data); * * INPUT: * name : Signal Name * * data : Signal Data (message str for "syntax" and "expression"). * * RETURNS: * flag : Whether the routine was successful or not. * *------------------------------------------------------------------*/ bool ClSignalMgr:: raiseSignal(const std::string &name, const std::string &data) { int type = signalNameToType(name); if (type == -1) return false; if (isUnixSignal(type)) COSSignal::sendSignalToProcessGroup(type); else if (type == SIGSYNTAX) { char *message; ClLanguageArgs *args = new ClLanguageArgs; args->startArgs(nullptr); if (args->getStringArgList(data, CLArgType::STRING, &message, CLArgType::NONE) != 1) return false; ClLanguageMgrInst->syntaxError(message); args->termArgs(); delete args; } else if (type == SIGEXPR) { char *message; ClLanguageArgs *args = new ClLanguageArgs; args->startArgs(nullptr); if (args->getStringArgList(data, CLArgType::STRING, &message, CLArgType::NONE) != 1) return false; ClLanguageMgrInst->expressionError(-1, message); args->termArgs(); delete args; } else return false; return true; } /*------------------------------------------------------------------* * * setSignalProc * Set the Routine to be called when the Named Signal is raised. * * CALL: * bool flag = setSignalProc(const std::string &name, ClSignalHandler proc); * * INPUT: * name : Signal Name * * proc : Signal Handling routine to call. * * OUTPUT: * None * * RETURNS: * flag : Whether the routine was successful or not. * * NOTES: * None * *------------------------------------------------------------------*/ bool ClSignalMgr:: setSignalProc(const std::string &name, ClSignalHandler proc) { int type = signalNameToType(name); if (type == -1) return false; ClSignalCommand *signal_command = getSignalCommand(type); if (! signal_command) return false; if (proc) { if (isUnixSignal(type)) { signal_command->old_proc = COSSignal::getSignalHandler(type); COSSignal::addSignalHandler(type, proc); } signal_command->proc = proc; } else { if (isUnixSignal(type)) { if (signal_command->old_proc) COSSignal::addSignalHandler(type, signal_command->old_proc); else COSSignal::defaultSignal(type); } signal_command->proc = nullptr; signal_command->old_proc = nullptr; signal_command->command = ""; } return true; } /*------------------------------------------------------------------* * * checkSignalCommand * Check whether there is a Command associated with * the Signal Type. * * CALL: * bool flag = checkSignalCommand(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * flag : Whether there is a Command associated with the Signal. * * NOTES: * None * *------------------------------------------------------------------*/ bool ClSignalMgr:: checkSignalCommand(int type) { ClSignalCommand *signal_command = getSignalCommand(type); if (! signal_command) return false; return (signal_command->command != ""); } /*------------------------------------------------------------------* * * executeSignalCommand * Run any Command associated with the Signal Type. * * CALL: * bool flag = executeSignalCommand(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * flag : Whether there is a Command associated with the Signal. * * NOTES: * None * *------------------------------------------------------------------*/ bool ClSignalMgr:: executeSignalCommand(int type) { ClSignalCommand *signal_command = getSignalCommand(type); if (! signal_command) return false; if (signal_command->command != "") ClLanguageMgrInst->runCommand(signal_command->command); return true; } /*------------------------------------------------------------------* * * handleSignal * Signal Handler for UNIX signals which runs any * associated Commands/Routines. * * CALL: * handleSignal(int sig); * * INPUT: * sig : Signal Type * * OUTPUT: * None * * RETURNS: * None * * NOTES: * None * *------------------------------------------------------------------*/ void ClSignalMgr:: handleSignal(int sig) { ClSignalCommand *signal_command = getSignalCommand(sig); if (signal_command && signal_command->command != "") ClLanguageMgrInst->runCommand(signal_command->command); else { if (sig == SIGINT || sig == SIGQUIT || sig == SIGABRT || sig == SIGTERM) ClLanguageMgrInst->setAbortSignal(true); if (sig == SIGINT) ClLanguageMgrInst->setInterruptFlag(true); } } /*------------------------------------------------------------------* * * getSignalCommand * Get the Signal Command Structure associated with * the specified Signal Type. * * CALL: * ClSignalCommand *signal_command = getSignalCommand(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * signal_command : Signal Command Structure * : (null if none). * * NOTES: * None * *------------------------------------------------------------------*/ ClSignalCommand * ClSignalMgr:: getSignalCommand(int type) const { SignalCommandMap::const_iterator p = signal_command_map_.find(type); if (p != signal_command_map_.end()) return (*p).second; return nullptr; } /*------------------------------------------------------------------* * * signalNameToType * Get the Type of the specified Signal Name. * * CALL: * int type = signalNameToType(comst std::string &name); * * INPUT: * name : Signal Name * * OUTPUT: * None * * RETURNS: * type : Signal Type * * NOTES: * None * *------------------------------------------------------------------*/ int ClSignalMgr:: signalNameToType(const std::string &name) const { if (CStrUtil::casecmp(name, "syntax") == 0) return SIGSYNTAX; else if (CStrUtil::casecmp(name, "expression") == 0) return SIGEXPR; return COSSignal::string_to_signal(name); } /*------------------------------------------------------------------* * * signalTypeToName * Get the Name of the specified Signal Type. * * CALL: * std::string name = signalTypeToName(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * name : Signal Name * * NOTES: * None * *------------------------------------------------------------------*/ std::string ClSignalMgr:: signalTypeToName(int type) const { switch (type) { case SIGSYNTAX: return "syntax"; break; case SIGEXPR: return "expression"; break; } return COSSignal::strsignal(type); } /*------------------------------------------------------------------* * * isUnixSignal * Check if a Signal Type is a UNIX Signal. * * CALL: * bool flag = isUnixSignal(int type); * * INPUT: * type : Signal Type * * OUTPUT: * None * * RETURNS: * flag : Whether the Signal Type is a UNIX Signal. * * NOTES: * None * *------------------------------------------------------------------*/ bool ClSignalMgr:: isUnixSignal(int type) const { if (type == SIGSYNTAX || type == SIGEXPR) return false; return true; } <|endoftext|>
<commit_before>#include "ClientHelper.hpp" namespace Network { SocketClientHelper::SocketClientHelper(const std::shared_ptr<Network::ABasicSocket>& sock, size_t readSize) : _readSize(readSize), _connected(true), _socket(sock) { _socket->setReadeableCallback(std::bind(&SocketClientHelper::onReadeable, this)); _socket->setWritableCallback(std::bind(&SocketClientHelper::onWritable, this)); _socket->setEventRequest(Network::ASocket::Event::READ); } SocketClientHelper::SocketClientHelper(size_t readSize) : _readSize(readSize), _connected(false), _socket(nullptr) { } void SocketClientHelper::setSocket(const std::shared_ptr<Network::ABasicSocket>& sock) { _socket = sock; _socket->setReadeableCallback(std::bind(&SocketClientHelper::onReadeable, this)); _socket->setWritableCallback(std::bind(&SocketClientHelper::onWritable, this)); _socket->setEventRequest(Network::ASocket::Event::READ); _connected = true; } void SocketClientHelper::onReadeable() { Buffer buff; size_t size = _readBuff.getLeftWrite(); if (_readSize > size) size = _readSize; try { _socket->read(buff, size); size = buff.size(); _readBuff.writeBuffer(buff); onRead(size); if (_writeBuff.getLeftRead() > 0) _socket->setEventRequest(Network::ASocket::Event::RDWR); else _socket->setEventRequest(Network::ASocket::Event::READ); if (size == 0 && _socket->getSockType() == ASocket::SockType::TCP) _connected = false; } catch (Network::Error& e) { _connected = false; } if (!_connected) { _socket->setEventRequest(Network::ASocket::Event::NONE); _socket->closeSocket(); } } void SocketClientHelper::onWritable() { size_t size = _writeBuff.getLeftRead(); size_t sizeWrite; Buffer buff; _writeBuff.readBuffer(buff, size); try { sizeWrite = _socket->write(buff); _writeBuff.rollbackReadBuffer(size - sizeWrite); onWrite(size); if (_writeBuff.getLeftRead() > 0) _socket->setEventRequest(Network::ASocket::Event::RDWR); else _socket->setEventRequest(Network::ASocket::Event::READ); } catch (Network::Error& e) { _connected = false; _writeBuff.rollbackReadBuffer(size); } if (!_connected) { _socket->setEventRequest(Network::ASocket::Event::NONE); _socket->closeSocket(); } } IdentityClientHelper::IdentityClientHelper(const std::shared_ptr<Network::Identity>& id, const std::weak_ptr<Network::AListenSocket>& listener) : _listener(listener), _id(id) { _id->onRead = std::bind(&IdentityClientHelper::readData, this, std::placeholders::_1); } void IdentityClientHelper::setId(const std::shared_ptr<Network::Identity>& id) { _id = id; _id->onRead = std::bind(&IdentityClientHelper::readData, this, std::placeholders::_1); } void IdentityClientHelper::readData(const Network::Buffer& data) { _readBuff.writeBuffer(data); onRead(); writeData(); } void IdentityClientHelper::writeData() { size_t size = _writeBuff.getLeftRead(); size_t sizeWrite; Buffer buff; std::shared_ptr<Network::AListenSocket> listener = _listener.lock(); if (!listener) throw std::runtime_error("Can't lock listener."); _writeBuff.readBuffer(buff, size); try { sizeWrite = listener->sendTo(*(_id.get()), buff); _writeBuff.rollbackReadBuffer(size - sizeWrite); } catch (Network::Error& e) { _writeBuff.rollbackReadBuffer(size); } } }; <commit_msg>call disconnet<commit_after>#include "ClientHelper.hpp" namespace Network { SocketClientHelper::SocketClientHelper(const std::shared_ptr<Network::ABasicSocket>& sock, size_t readSize) : _readSize(readSize), _connected(true), _socket(sock) { _socket->setReadeableCallback(std::bind(&SocketClientHelper::onReadeable, this)); _socket->setWritableCallback(std::bind(&SocketClientHelper::onWritable, this)); _socket->setEventRequest(Network::ASocket::Event::READ); } SocketClientHelper::SocketClientHelper(size_t readSize) : _readSize(readSize), _connected(false), _socket(nullptr) { } void SocketClientHelper::setSocket(const std::shared_ptr<Network::ABasicSocket>& sock) { _socket = sock; _socket->setReadeableCallback(std::bind(&SocketClientHelper::onReadeable, this)); _socket->setWritableCallback(std::bind(&SocketClientHelper::onWritable, this)); _socket->setEventRequest(Network::ASocket::Event::READ); _connected = true; } void SocketClientHelper::onReadeable() { Buffer buff; size_t size = _readBuff.getLeftWrite(); if (_readSize > size) size = _readSize; try { _socket->read(buff, size); size = buff.size(); _readBuff.writeBuffer(buff); onRead(size); if (_writeBuff.getLeftRead() > 0) _socket->setEventRequest(Network::ASocket::Event::RDWR); else _socket->setEventRequest(Network::ASocket::Event::READ); if (size == 0 && _socket->getSockType() == ASocket::SockType::TCP) _connected = false; } catch (Network::Error& e) { _connected = false; } if (!_connected) { _socket->setEventRequest(Network::ASocket::Event::NONE); _socket->closeSocket(); onDisconnet(); } } void SocketClientHelper::onWritable() { size_t size = _writeBuff.getLeftRead(); size_t sizeWrite; Buffer buff; _writeBuff.readBuffer(buff, size); try { sizeWrite = _socket->write(buff); _writeBuff.rollbackReadBuffer(size - sizeWrite); onWrite(size); if (_writeBuff.getLeftRead() > 0) _socket->setEventRequest(Network::ASocket::Event::RDWR); else _socket->setEventRequest(Network::ASocket::Event::READ); } catch (Network::Error& e) { _connected = false; _writeBuff.rollbackReadBuffer(size); } if (!_connected) { _socket->setEventRequest(Network::ASocket::Event::NONE); _socket->closeSocket(); } } IdentityClientHelper::IdentityClientHelper(const std::shared_ptr<Network::Identity>& id, const std::weak_ptr<Network::AListenSocket>& listener) : _listener(listener), _id(id) { _id->onRead = std::bind(&IdentityClientHelper::readData, this, std::placeholders::_1); } void IdentityClientHelper::setId(const std::shared_ptr<Network::Identity>& id) { _id = id; _id->onRead = std::bind(&IdentityClientHelper::readData, this, std::placeholders::_1); } void IdentityClientHelper::readData(const Network::Buffer& data) { _readBuff.writeBuffer(data); onRead(); writeData(); } void IdentityClientHelper::writeData() { size_t size = _writeBuff.getLeftRead(); size_t sizeWrite; Buffer buff; std::shared_ptr<Network::AListenSocket> listener = _listener.lock(); if (!listener) throw std::runtime_error("Can't lock listener."); _writeBuff.readBuffer(buff, size); try { sizeWrite = listener->sendTo(*(_id.get()), buff); _writeBuff.rollbackReadBuffer(size - sizeWrite); } catch (Network::Error& e) { _writeBuff.rollbackReadBuffer(size); } } }; <|endoftext|>
<commit_before>#include <cassert> #include "CodeGen_Bash.h" using namespace Bish; void CodeGen_Bash::indent() { for (unsigned i = 0; i < indent_level; i++) { stream << " "; } } // Return true if the given node is a statement that should be // emitted. This excludes side-effecting statements like 'import'. bool CodeGen_Bash::should_emit_statement(const IRNode *node) const { return dynamic_cast<const ImportStatement*>(node) == NULL; } void CodeGen_Bash::visit(Module *n) { // Define the functions first. for (std::vector<Function *>::const_iterator I = n->functions.begin(), E = n->functions.end(); I != E; ++I) { (*I)->accept(this); } // Global variables next. for (std::vector<Assignment *>::const_iterator I = n->global_variables.begin(), E = n->global_variables.end(); I != E; ++I) { (*I)->accept(this); stream << ";\n"; } stream << "\n"; // Insert a call to bish_main(). assert(n->main); FunctionCall *call_main = new FunctionCall(n->main); visit(call_main); stream << ";\n"; delete call_main; } void CodeGen_Bash::visit(Block *n) { if (should_print_block_braces()) stream << "{\n"; indent_level++; if (!function_args_insert.empty()) { Function *f = function_args_insert.top(); function_args_insert.pop(); unsigned i = 1; for (std::vector<Variable *>::const_iterator I = f->args.begin(), E = f->args.end(); I != E; ++I, ++i) { indent(); stream << "local " << (*I)->name.str() << "=\"$" << i << "\";\n"; } } for (std::vector<IRNode *>::const_iterator I = n->nodes.begin(), E = n->nodes.end(); I != E; ++I) { if (should_emit_statement(*I)) { indent(); (*I)->accept(this); stream << ";\n"; } } indent_level--; if (should_print_block_braces()) stream << "}\n\n"; } void CodeGen_Bash::visit(Variable *n) { if (should_quote_variable()) stream << "\""; stream << "$" << lookup_name(n); if (should_quote_variable()) stream << "\""; } void CodeGen_Bash::visit(ReturnStatement *n) { bool external = dynamic_cast<ExternCall*>(n->value) != NULL; stream << "echo "; enable_functioncall_wrap(); // Defensively wrap external calls in quotes in case they return // space-separated strings. Not sure how to handle this yet in the // general case. if (external) stream << "\""; n->value->accept(this); if (external) stream << "\""; reset_functioncall_wrap(); stream << "; exit"; } void CodeGen_Bash::visit(LoopControlStatement *n) { switch (n->op) { case LoopControlStatement::Break: stream << "break"; break; case LoopControlStatement::Continue: stream << "continue"; break; } } void CodeGen_Bash::visit(IfStatement *n) { stream << "if [[ "; enable_functioncall_wrap(); n->pblock->condition->accept(this); if (is_equals_op(n->pblock->condition) || !dynamic_cast<BinOp*>(n->pblock->condition)) { stream << " -eq 1"; } reset_functioncall_wrap(); stream << " ]]; then\n"; disable_block_braces(); n->pblock->body->accept(this); for (std::vector<PredicatedBlock *>::const_iterator I = n->elses.begin(), E = n->elses.end(); I != E; ++I) { indent(); stream << "elif [[ "; enable_functioncall_wrap(); (*I)->condition->accept(this); reset_functioncall_wrap(); stream << " ]]; then\n"; (*I)->body->accept(this); } if (n->elseblock) { indent(); stream << "else\n"; n->elseblock->accept(this); } reset_block_braces(); indent(); stream << "fi"; } void CodeGen_Bash::visit(ForLoop *n) { stream << "for " << lookup_name(n->variable) << " in "; if (n->upper) { stream << "$(seq "; n->lower->accept(this); stream << " "; n->upper->accept(this); stream << ")"; } else { disable_quote_variable(); n->lower->accept(this); reset_quote_variable(); } stream << "; do\n"; disable_block_braces(); n->body->accept(this); reset_block_braces(); indent(); stream << "done"; } void CodeGen_Bash::visit(Function *n) { if (n->body == NULL) return; stream << "function " << n->name.str() << " "; stream << "() "; push_function_args_insert(n); if (n->body) n->body->accept(this); } void CodeGen_Bash::visit(FunctionCall *n) { const int nargs = n->args.size(); if (should_functioncall_wrap()) stream << "$("; stream << n->function->name.str(); for (int i = 0; i < nargs; i++) { stream << " "; enable_functioncall_wrap(); if (const FunctionCall *FC = dynamic_cast<const FunctionCall*>(n->args[i])) { if (should_quote_variable()) stream << "\""; n->args[i]->accept(this); if (should_quote_variable()) stream << "\""; } else { n->args[i]->accept(this); } reset_functioncall_wrap(); } if (should_functioncall_wrap()) stream << ")"; } void CodeGen_Bash::visit(ExternCall *n) { if (should_functioncall_wrap()) stream << "$("; disable_quote_variable(); output_interpolated_string(n->body); reset_quote_variable(); if (should_functioncall_wrap()) stream << ")"; } void CodeGen_Bash::output_interpolated_string(InterpolatedString *n) { for (InterpolatedString::const_iterator I = n->begin(), E = n->end(); I != E; ++I) { if ((*I).is_str()) { stream << (*I).str(); } else { assert((*I).is_var()); visit((*I).var()); } } } void CodeGen_Bash::visit(IORedirection *n) { std::string bash_op; switch (n->op) { case IORedirection::Pipe: bash_op = "|"; break; default: assert(false && "Unimplemented redirection."); } disable_functioncall_wrap(); stream << "$("; n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); stream << ")"; reset_functioncall_wrap(); } void CodeGen_Bash::visit(Assignment *n) { if (!n->variable->global) stream << "local "; stream << lookup_name(n->variable) << "="; enable_functioncall_wrap(); n->value->accept(this); reset_functioncall_wrap(); } void CodeGen_Bash::visit(BinOp *n) { std::string bash_op; bool comparison = false, equals = false, string = false; if (n->a->type() == StringTy || n->b->type() == StringTy) { string = true; } switch (n->op) { case BinOp::Eq: bash_op = string ? "==" : "-eq"; equals = true; comparison = true; break; case BinOp::NotEq: bash_op = string ? "!=" : "-ne"; equals = true; comparison = true; break; case BinOp::LT: bash_op = string ? "<" : "-lt"; comparison = true; break; case BinOp::LTE: bash_op = "-le"; comparison = true; break; case BinOp::GT: bash_op = string ? ">" : "-gt"; comparison = true; break; case BinOp::GTE: bash_op = "-ge"; comparison = true; break; case BinOp::And: bash_op = "&&"; comparison = true; break; case BinOp::Or: bash_op = "||"; comparison = true; break; case BinOp::Add: bash_op = "+"; break; case BinOp::Sub: bash_op = "-"; break; case BinOp::Mul: bash_op = "*"; break; case BinOp::Div: bash_op = "/"; break; case BinOp::Mod: bash_op = "%"; break; } bool reset_wrap = false; if (should_comparison_wrap() && (n->op == BinOp::And || n->op == BinOp::Or)) { reset_wrap = true; // Disable wrapping comparisons in [[]] because we need to // wrap them all from the outside for And and Or operations. disable_comparison_wrap(); stream << "$([[ "; } if (equals && should_comparison_wrap()) stream << "$([[ "; if (!comparison) stream << "$(("; if (!string) disable_quote_variable(); n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); if (equals && should_comparison_wrap()) stream << " ]] && echo 1 || echo 0)"; if (!comparison) stream << "))"; if (!string) reset_quote_variable(); if (reset_wrap && (n->op == BinOp::And || n->op == BinOp::Or)) { reset_comparison_wrap(); stream << " ]] && echo 1 || echo 0)"; } } void CodeGen_Bash::visit(UnaryOp *n) { bool negate_binop = dynamic_cast<BinOp*>(n->a); switch (n->op) { case UnaryOp::Negate: stream << "-"; break; case UnaryOp::Not: stream << "$(! [[ "; disable_comparison_wrap(); break; } n->a->accept(this); if (n->op == UnaryOp::Not) { // Don't need the '-eq 1' if the argument is a binary operator (like '=='). if (!negate_binop) stream << " -eq 1"; stream << " ]] && echo 1 || echo 0)"; reset_comparison_wrap(); } } void CodeGen_Bash::visit(Integer *n) { stream << n->value; } void CodeGen_Bash::visit(Fractional *n) { stream << n->value; } void CodeGen_Bash::visit(String *n) { stream << "\""; output_interpolated_string(n->value); stream << "\""; } void CodeGen_Bash::visit(Boolean *n) { stream << n->value; } <commit_msg>Fix codegen issue with empty function bodies.<commit_after>#include <cassert> #include "CodeGen_Bash.h" using namespace Bish; void CodeGen_Bash::indent() { for (unsigned i = 0; i < indent_level; i++) { stream << " "; } } // Return true if the given node is a statement that should be // emitted. This excludes side-effecting statements like 'import'. bool CodeGen_Bash::should_emit_statement(const IRNode *node) const { return dynamic_cast<const ImportStatement*>(node) == NULL; } void CodeGen_Bash::visit(Module *n) { // Define the functions first. for (std::vector<Function *>::const_iterator I = n->functions.begin(), E = n->functions.end(); I != E; ++I) { (*I)->accept(this); } // Global variables next. for (std::vector<Assignment *>::const_iterator I = n->global_variables.begin(), E = n->global_variables.end(); I != E; ++I) { (*I)->accept(this); stream << ";\n"; } // Insert a call to bish_main(). assert(n->main); FunctionCall *call_main = new FunctionCall(n->main); visit(call_main); stream << ";\n"; delete call_main; } void CodeGen_Bash::visit(Block *n) { if (should_print_block_braces()) stream << "{\n"; indent_level++; if (!function_args_insert.empty()) { Function *f = function_args_insert.top(); function_args_insert.pop(); unsigned i = 1; for (std::vector<Variable *>::const_iterator I = f->args.begin(), E = f->args.end(); I != E; ++I, ++i) { indent(); stream << "local " << (*I)->name.str() << "=\"$" << i << "\";\n"; } } for (std::vector<IRNode *>::const_iterator I = n->nodes.begin(), E = n->nodes.end(); I != E; ++I) { if (should_emit_statement(*I)) { indent(); (*I)->accept(this); stream << ";\n"; } } // Bash doesn't allow empty functions: must insert a call to a null command. if (n->nodes.empty()) { indent(); stream << ": # Empty function\n"; } indent_level--; if (should_print_block_braces()) stream << "}\n\n"; } void CodeGen_Bash::visit(Variable *n) { if (should_quote_variable()) stream << "\""; stream << "$" << lookup_name(n); if (should_quote_variable()) stream << "\""; } void CodeGen_Bash::visit(ReturnStatement *n) { bool external = dynamic_cast<ExternCall*>(n->value) != NULL; stream << "echo "; enable_functioncall_wrap(); // Defensively wrap external calls in quotes in case they return // space-separated strings. Not sure how to handle this yet in the // general case. if (external) stream << "\""; n->value->accept(this); if (external) stream << "\""; reset_functioncall_wrap(); stream << "; exit"; } void CodeGen_Bash::visit(LoopControlStatement *n) { switch (n->op) { case LoopControlStatement::Break: stream << "break"; break; case LoopControlStatement::Continue: stream << "continue"; break; } } void CodeGen_Bash::visit(IfStatement *n) { stream << "if [[ "; enable_functioncall_wrap(); n->pblock->condition->accept(this); if (is_equals_op(n->pblock->condition) || !dynamic_cast<BinOp*>(n->pblock->condition)) { stream << " -eq 1"; } reset_functioncall_wrap(); stream << " ]]; then\n"; disable_block_braces(); n->pblock->body->accept(this); for (std::vector<PredicatedBlock *>::const_iterator I = n->elses.begin(), E = n->elses.end(); I != E; ++I) { indent(); stream << "elif [[ "; enable_functioncall_wrap(); (*I)->condition->accept(this); reset_functioncall_wrap(); stream << " ]]; then\n"; (*I)->body->accept(this); } if (n->elseblock) { indent(); stream << "else\n"; n->elseblock->accept(this); } reset_block_braces(); indent(); stream << "fi"; } void CodeGen_Bash::visit(ForLoop *n) { stream << "for " << lookup_name(n->variable) << " in "; if (n->upper) { stream << "$(seq "; n->lower->accept(this); stream << " "; n->upper->accept(this); stream << ")"; } else { disable_quote_variable(); n->lower->accept(this); reset_quote_variable(); } stream << "; do\n"; disable_block_braces(); n->body->accept(this); reset_block_braces(); indent(); stream << "done"; } void CodeGen_Bash::visit(Function *n) { if (n->body == NULL) return; stream << "function " << n->name.str() << " "; stream << "() "; push_function_args_insert(n); if (n->body) n->body->accept(this); } void CodeGen_Bash::visit(FunctionCall *n) { const int nargs = n->args.size(); if (should_functioncall_wrap()) stream << "$("; stream << n->function->name.str(); for (int i = 0; i < nargs; i++) { stream << " "; enable_functioncall_wrap(); if (const FunctionCall *FC = dynamic_cast<const FunctionCall*>(n->args[i])) { if (should_quote_variable()) stream << "\""; n->args[i]->accept(this); if (should_quote_variable()) stream << "\""; } else { n->args[i]->accept(this); } reset_functioncall_wrap(); } if (should_functioncall_wrap()) stream << ")"; } void CodeGen_Bash::visit(ExternCall *n) { if (should_functioncall_wrap()) stream << "$("; disable_quote_variable(); output_interpolated_string(n->body); reset_quote_variable(); if (should_functioncall_wrap()) stream << ")"; } void CodeGen_Bash::output_interpolated_string(InterpolatedString *n) { for (InterpolatedString::const_iterator I = n->begin(), E = n->end(); I != E; ++I) { if ((*I).is_str()) { stream << (*I).str(); } else { assert((*I).is_var()); visit((*I).var()); } } } void CodeGen_Bash::visit(IORedirection *n) { std::string bash_op; switch (n->op) { case IORedirection::Pipe: bash_op = "|"; break; default: assert(false && "Unimplemented redirection."); } disable_functioncall_wrap(); stream << "$("; n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); stream << ")"; reset_functioncall_wrap(); } void CodeGen_Bash::visit(Assignment *n) { if (!n->variable->global) stream << "local "; stream << lookup_name(n->variable) << "="; enable_functioncall_wrap(); n->value->accept(this); reset_functioncall_wrap(); } void CodeGen_Bash::visit(BinOp *n) { std::string bash_op; bool comparison = false, equals = false, string = false; if (n->a->type() == StringTy || n->b->type() == StringTy) { string = true; } switch (n->op) { case BinOp::Eq: bash_op = string ? "==" : "-eq"; equals = true; comparison = true; break; case BinOp::NotEq: bash_op = string ? "!=" : "-ne"; equals = true; comparison = true; break; case BinOp::LT: bash_op = string ? "<" : "-lt"; comparison = true; break; case BinOp::LTE: bash_op = "-le"; comparison = true; break; case BinOp::GT: bash_op = string ? ">" : "-gt"; comparison = true; break; case BinOp::GTE: bash_op = "-ge"; comparison = true; break; case BinOp::And: bash_op = "&&"; comparison = true; break; case BinOp::Or: bash_op = "||"; comparison = true; break; case BinOp::Add: bash_op = "+"; break; case BinOp::Sub: bash_op = "-"; break; case BinOp::Mul: bash_op = "*"; break; case BinOp::Div: bash_op = "/"; break; case BinOp::Mod: bash_op = "%"; break; } bool reset_wrap = false; if (should_comparison_wrap() && (n->op == BinOp::And || n->op == BinOp::Or)) { reset_wrap = true; // Disable wrapping comparisons in [[]] because we need to // wrap them all from the outside for And and Or operations. disable_comparison_wrap(); stream << "$([[ "; } if (equals && should_comparison_wrap()) stream << "$([[ "; if (!comparison) stream << "$(("; if (!string) disable_quote_variable(); n->a->accept(this); stream << " " << bash_op << " "; n->b->accept(this); if (equals && should_comparison_wrap()) stream << " ]] && echo 1 || echo 0)"; if (!comparison) stream << "))"; if (!string) reset_quote_variable(); if (reset_wrap && (n->op == BinOp::And || n->op == BinOp::Or)) { reset_comparison_wrap(); stream << " ]] && echo 1 || echo 0)"; } } void CodeGen_Bash::visit(UnaryOp *n) { bool negate_binop = dynamic_cast<BinOp*>(n->a); switch (n->op) { case UnaryOp::Negate: stream << "-"; break; case UnaryOp::Not: stream << "$(! [[ "; disable_comparison_wrap(); break; } n->a->accept(this); if (n->op == UnaryOp::Not) { // Don't need the '-eq 1' if the argument is a binary operator (like '=='). if (!negate_binop) stream << " -eq 1"; stream << " ]] && echo 1 || echo 0)"; reset_comparison_wrap(); } } void CodeGen_Bash::visit(Integer *n) { stream << n->value; } void CodeGen_Bash::visit(Fractional *n) { stream << n->value; } void CodeGen_Bash::visit(String *n) { stream << "\""; output_interpolated_string(n->value); stream << "\""; } void CodeGen_Bash::visit(Boolean *n) { stream << n->value; } <|endoftext|>
<commit_before>/* OpenSceneGraph example, osgshaders2 * * 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 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. */ /* file: examples/osgshaders2/osgshaders2.cpp * author: Mike Weiblen 2008-01-03 * copyright: (C) 2008 Zebra Imaging * license: OpenSceneGraph Public License (OSGPL) * * A demo of GLSL geometry shaders using OSG * Tested on Dell Precision M4300 w/ NVIDIA Quadro FX 360M */ #include <osg/Notify> #include <osg/ref_ptr> #include <osg/Geode> #include <osg/Geometry> #include <osg/Point> #include <osg/Vec3> #include <osg/Vec4> #include <osg/Program> #include <osg/Shader> #include <osg/Uniform> #include <osgViewer/Viewer> // play with these #defines to see their effect #define ENABLE_GLSL #define ENABLE_GEOMETRY_SHADER /////////////////////////////////////////////////////////////////////////// #ifdef ENABLE_GLSL class SineAnimation: public osg::Uniform::Callback { public: SineAnimation( float rate = 1.0f, float scale = 1.0f, float offset = 0.0f ) : _rate(rate), _scale(scale), _offset(offset) {} void operator()( osg::Uniform* uniform, osg::NodeVisitor* nv ) { float angle = _rate * nv->getFrameStamp()->getSimulationTime(); float value = sinf( angle ) * _scale + _offset; uniform->set( value ); } private: const float _rate; const float _scale; const float _offset; }; /////////////////////////////////////////////////////////////////////////// static const char* vertSource = { "#version 120\n" "#extension GL_EXT_geometry_shader4 : enable\n" "uniform float u_anim1;\n" "varying vec4 v_color;\n" "void main(void)\n" "{\n" " v_color = gl_Vertex;\n" " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n" "}\n" }; static const char* geomSource = { "#version 120\n" "#extension GL_EXT_geometry_shader4 : enable\n" "uniform float u_anim1;\n" "varying in vec4 v_color[];\n" "varying out vec4 v_color_out;\n" "void main(void)\n" "{\n" " vec4 v = gl_PositionIn[0];\n" " v_color_out = v + v_color[0];\n" "\n" " gl_Position = v + vec4(u_anim1,0.,0.,0.); EmitVertex();\n" " gl_Position = v - vec4(u_anim1,0.,0.,0.); EmitVertex();\n" " EndPrimitive();\n" "\n" " gl_Position = v + vec4(0.,1.0-u_anim1,0.,0.); EmitVertex();\n" " gl_Position = v - vec4(0.,1.0-u_anim1,0.,0.); EmitVertex();\n" " EndPrimitive();\n" "}\n" }; static const char* fragSource = { "#version 120\n" "#extension GL_EXT_geometry_shader4 : enable\n" "uniform float u_anim1;\n" "varying vec4 v_color_out;\n" "void main(void)\n" "{\n" " gl_FragColor = v_color_out;\n" "}\n" }; osg::Program* createShader() { osg::Program* pgm = new osg::Program; pgm->setName( "osgshader2 demo" ); pgm->addShader( new osg::Shader( osg::Shader::VERTEX, vertSource ) ); pgm->addShader( new osg::Shader( osg::Shader::FRAGMENT, fragSource ) ); #ifdef ENABLE_GEOMETRY_SHADER pgm->addShader( new osg::Shader( osg::Shader::GEOMETRY, geomSource ) ); pgm->setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, 4 ); pgm->setParameter( GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS ); pgm->setParameter( GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_LINE_STRIP ); #endif return pgm; } #endif /////////////////////////////////////////////////////////////////////////// class SomePoints : public osg::Geometry { public: SomePoints() { osg::Vec4Array* cAry = new osg::Vec4Array; setColorArray( cAry ); setColorBinding( osg::Geometry::BIND_OVERALL ); cAry->push_back( osg::Vec4(1,1,1,1) ); osg::Vec3Array* vAry = new osg::Vec3Array; setVertexArray( vAry ); vAry->push_back( osg::Vec3(0,0,0) ); vAry->push_back( osg::Vec3(0,1,0) ); vAry->push_back( osg::Vec3(1,0,0) ); vAry->push_back( osg::Vec3(1,1,0) ); vAry->push_back( osg::Vec3(0,0,1) ); vAry->push_back( osg::Vec3(0,1,1) ); vAry->push_back( osg::Vec3(1,0,1) ); vAry->push_back( osg::Vec3(1,1,1) ); addPrimitiveSet( new osg::DrawArrays( GL_POINTS, 0, vAry->size() ) ); osg::StateSet* sset = getOrCreateStateSet(); sset->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); // if things go wrong, fall back to big points osg::Point* p = new osg::Point; p->setSize(6); sset->setAttribute( p ); #ifdef ENABLE_GLSL sset->setAttribute( createShader() ); // a generic cyclic animation value osg::Uniform* u_anim1( new osg::Uniform( "u_anim1", 0.0f ) ); u_anim1->setUpdateCallback( new SineAnimation( 4, 0.5, 0.5 ) ); sset->addUniform( u_anim1 ); #endif } }; /////////////////////////////////////////////////////////////////////////// int main( int , char * ) { osg::Geode* root( new osg::Geode ); root->addDrawable( new SomePoints ); osgViewer::Viewer viewer; viewer.setSceneData( root ); return viewer.run(); } // vim: set sw=4 ts=8 et ic ai: <commit_msg>Added missing *.<commit_after>/* OpenSceneGraph example, osgshaders2 * * 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 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. */ /* file: examples/osgshaders2/osgshaders2.cpp * author: Mike Weiblen 2008-01-03 * copyright: (C) 2008 Zebra Imaging * license: OpenSceneGraph Public License (OSGPL) * * A demo of GLSL geometry shaders using OSG * Tested on Dell Precision M4300 w/ NVIDIA Quadro FX 360M */ #include <osg/Notify> #include <osg/ref_ptr> #include <osg/Geode> #include <osg/Geometry> #include <osg/Point> #include <osg/Vec3> #include <osg/Vec4> #include <osg/Program> #include <osg/Shader> #include <osg/Uniform> #include <osgViewer/Viewer> // play with these #defines to see their effect #define ENABLE_GLSL #define ENABLE_GEOMETRY_SHADER /////////////////////////////////////////////////////////////////////////// #ifdef ENABLE_GLSL class SineAnimation: public osg::Uniform::Callback { public: SineAnimation( float rate = 1.0f, float scale = 1.0f, float offset = 0.0f ) : _rate(rate), _scale(scale), _offset(offset) {} void operator()( osg::Uniform* uniform, osg::NodeVisitor* nv ) { float angle = _rate * nv->getFrameStamp()->getSimulationTime(); float value = sinf( angle ) * _scale + _offset; uniform->set( value ); } private: const float _rate; const float _scale; const float _offset; }; /////////////////////////////////////////////////////////////////////////// static const char* vertSource = { "#version 120\n" "#extension GL_EXT_geometry_shader4 : enable\n" "uniform float u_anim1;\n" "varying vec4 v_color;\n" "void main(void)\n" "{\n" " v_color = gl_Vertex;\n" " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n" "}\n" }; static const char* geomSource = { "#version 120\n" "#extension GL_EXT_geometry_shader4 : enable\n" "uniform float u_anim1;\n" "varying in vec4 v_color[];\n" "varying out vec4 v_color_out;\n" "void main(void)\n" "{\n" " vec4 v = gl_PositionIn[0];\n" " v_color_out = v + v_color[0];\n" "\n" " gl_Position = v + vec4(u_anim1,0.,0.,0.); EmitVertex();\n" " gl_Position = v - vec4(u_anim1,0.,0.,0.); EmitVertex();\n" " EndPrimitive();\n" "\n" " gl_Position = v + vec4(0.,1.0-u_anim1,0.,0.); EmitVertex();\n" " gl_Position = v - vec4(0.,1.0-u_anim1,0.,0.); EmitVertex();\n" " EndPrimitive();\n" "}\n" }; static const char* fragSource = { "#version 120\n" "#extension GL_EXT_geometry_shader4 : enable\n" "uniform float u_anim1;\n" "varying vec4 v_color_out;\n" "void main(void)\n" "{\n" " gl_FragColor = v_color_out;\n" "}\n" }; osg::Program* createShader() { osg::Program* pgm = new osg::Program; pgm->setName( "osgshader2 demo" ); pgm->addShader( new osg::Shader( osg::Shader::VERTEX, vertSource ) ); pgm->addShader( new osg::Shader( osg::Shader::FRAGMENT, fragSource ) ); #ifdef ENABLE_GEOMETRY_SHADER pgm->addShader( new osg::Shader( osg::Shader::GEOMETRY, geomSource ) ); pgm->setParameter( GL_GEOMETRY_VERTICES_OUT_EXT, 4 ); pgm->setParameter( GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS ); pgm->setParameter( GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_LINE_STRIP ); #endif return pgm; } #endif /////////////////////////////////////////////////////////////////////////// class SomePoints : public osg::Geometry { public: SomePoints() { osg::Vec4Array* cAry = new osg::Vec4Array; setColorArray( cAry ); setColorBinding( osg::Geometry::BIND_OVERALL ); cAry->push_back( osg::Vec4(1,1,1,1) ); osg::Vec3Array* vAry = new osg::Vec3Array; setVertexArray( vAry ); vAry->push_back( osg::Vec3(0,0,0) ); vAry->push_back( osg::Vec3(0,1,0) ); vAry->push_back( osg::Vec3(1,0,0) ); vAry->push_back( osg::Vec3(1,1,0) ); vAry->push_back( osg::Vec3(0,0,1) ); vAry->push_back( osg::Vec3(0,1,1) ); vAry->push_back( osg::Vec3(1,0,1) ); vAry->push_back( osg::Vec3(1,1,1) ); addPrimitiveSet( new osg::DrawArrays( GL_POINTS, 0, vAry->size() ) ); osg::StateSet* sset = getOrCreateStateSet(); sset->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); // if things go wrong, fall back to big points osg::Point* p = new osg::Point; p->setSize(6); sset->setAttribute( p ); #ifdef ENABLE_GLSL sset->setAttribute( createShader() ); // a generic cyclic animation value osg::Uniform* u_anim1( new osg::Uniform( "u_anim1", 0.0f ) ); u_anim1->setUpdateCallback( new SineAnimation( 4, 0.5, 0.5 ) ); sset->addUniform( u_anim1 ); #endif } }; /////////////////////////////////////////////////////////////////////////// int main( int , char** ) { osg::Geode* root( new osg::Geode ); root->addDrawable( new SomePoints ); osgViewer::Viewer viewer; viewer.setSceneData( root ); return viewer.run(); } // vim: set sw=4 ts=8 et ic ai: <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osg/Material> #include <osg/Geode> #include <osg/BlendFunc> #include <osg/Depth> #include <osg/Projection> #include <osg/PolygonOffset> #include <osg/MatrixTransform> #include <osg/Camera> #include <osg/FrontFace> #include <osgText/Text> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgViewer/CompositeViewer> int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments); if (!scene) return 1; // construct the viewer. osgViewer::CompositeViewer viewer; if (arguments.read("-1")) { #if 1 osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface(); if (!wsi) { osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl; return 1; } unsigned int width, height; wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 0; traits->y = 0; traits->width = width; traits->height = height; traits->windowDecoration = true; traits->doubleBuffer = true; traits->sharedContext = 0; osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get()); if (gc.valid()) { osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<std::endl; // need to ensure that the window is cleared make sure that the complete window is set the correct colour // rather than just the parts of the window that are under the camera's viewports gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f)); gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } else { osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl; } osgViewer::View* view_one = new osgViewer::View; view_one->setSceneData(scene.get()); view_one->getCamera()->setViewport(new osg::Viewport(0,0, width/2, height/2)); view_one->getCamera()->setGraphicsContext(gc.get()); view_one->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view_one); osgViewer::View* view_two = new osgViewer::View; view_two->setSceneData(scene.get()); view_two->getCamera()->setViewport(new osg::Viewport(width/2,0, width/2, height/2)); view_two->getCamera()->setGraphicsContext(gc.get()); view_two->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view_two); #endif osgViewer::View* view_three = new osgViewer::View; view_three->setSceneData(osgDB::readNodeFile("town.ive")); view_three->setUpViewAcrossAllScreens(); #if 0 view_three->getCamera()->setViewport(new osg::Viewport(0, height/2, width, height/2)); view_three->getCamera()->setGraphicsContext(gc.get()); #endif view_three->setCameraManipulator(new osgGA::FlightManipulator); viewer.addView(view_three); } else { osgViewer::View* view_one = new osgViewer::View; view_one->setUpViewOnSingleScreen(0); view_one->setSceneData(scene.get()); view_one->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view_one); osgViewer::View* view_two = new osgViewer::View; view_two->setUpViewOnSingleScreen(1); view_two->setSceneData(scene.get()); view_two->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view_two); } while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::CompositeViewer::SingleThreaded); } while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::CompositeViewer::ThreadPerContext); } while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::CompositeViewer::ThreadPerCamera); } return viewer.run(); } <commit_msg>Added extra view combinations too commandline<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osg/Material> #include <osg/Geode> #include <osg/BlendFunc> #include <osg/Depth> #include <osg/Projection> #include <osg/PolygonOffset> #include <osg/MatrixTransform> #include <osg/Camera> #include <osg/FrontFace> #include <osgText/Text> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/StateSetManipulator> #include <osgViewer/CompositeViewer> int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments); if (!scene) return 1; // construct the viewer. osgViewer::CompositeViewer viewer; if (arguments.read("-1")) { osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface(); if (!wsi) { osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl; return 1; } unsigned int width, height; wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 0; traits->y = 0; traits->width = width; traits->height = height; traits->windowDecoration = true; traits->doubleBuffer = true; traits->sharedContext = 0; osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get()); if (gc.valid()) { osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<std::endl; // need to ensure that the window is cleared make sure that the complete window is set the correct colour // rather than just the parts of the window that are under the camera's viewports gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f)); gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } else { osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl; } // view one { osgViewer::View* view = new osgViewer::View; view->setSceneData(scene.get()); view->getCamera()->setViewport(new osg::Viewport(0,0, width/2, height/2)); view->getCamera()->setGraphicsContext(gc.get()); view->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view); // add the state manipulator osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator; statesetManipulator->setStateSet(view->getCamera()->getOrCreateStateSet()); view->addEventHandler( statesetManipulator.get() ); } // view two { osgViewer::View* view = new osgViewer::View; view->setSceneData(scene.get()); view->getCamera()->setViewport(new osg::Viewport(width/2,0, width/2, height/2)); view->getCamera()->setGraphicsContext(gc.get()); view->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view); } // view three if (false) { osgViewer::View* view = new osgViewer::View; view->setSceneData(osgDB::readNodeFile("town.ive")); view->setUpViewAcrossAllScreens(); viewer.addView(view); } else { osgViewer::View* view = new osgViewer::View; view->setSceneData(osgDB::readNodeFile("town.ive")); view->getCamera()->setProjectionMatrixAsPerspective(30.0, double(width) / double(height/2), 1.0, 1000.0); view->getCamera()->setViewport(new osg::Viewport(0, height/2, width, height/2)); view->getCamera()->setGraphicsContext(gc.get()); view->setCameraManipulator(new osgGA::FlightManipulator); viewer.addView(view); } } if (arguments.read("-2")) { { osgViewer::View* view = new osgViewer::View; view->setSceneData(osgDB::readNodeFile("town.ive")); view->setUpViewAcrossAllScreens(); view->setCameraManipulator(new osgGA::FlightManipulator); viewer.addView(view); } } if (arguments.read("-3") || viewer.getNumViews()==0) { // view one { osgViewer::View* view = new osgViewer::View; viewer.addView(view); view->setUpViewOnSingleScreen(0); view->setSceneData(scene.get()); view->setCameraManipulator(new osgGA::TrackballManipulator); // add the state manipulator osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator; statesetManipulator->setStateSet(view->getCamera()->getOrCreateStateSet()); view->addEventHandler( statesetManipulator.get() ); } // view two { osgViewer::View* view = new osgViewer::View; viewer.addView(view); view->setUpViewOnSingleScreen(1); view->setSceneData(scene.get()); view->setCameraManipulator(new osgGA::TrackballManipulator); } } while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::CompositeViewer::SingleThreaded); } while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::CompositeViewer::ThreadPerContext); } while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::CompositeViewer::ThreadPerCamera); } return viewer.run(); } <|endoftext|>
<commit_before>/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Stamp.h" #define MAX_DELTA_STAMP 1000 #define MAX_CTS 500 #define ABS(x) ((x) > 0 ? (x) : (-x)) namespace mediakit { int64_t DeltaStamp::deltaStamp(int64_t stamp) { if(!_last_stamp){ //第一次计算时间戳增量,时间戳增量为0 if(stamp){ _last_stamp = stamp; } return 0; } int64_t ret = stamp - _last_stamp; if(ret >= 0){ //时间戳增量为正,返回之 _last_stamp = stamp; //在直播情况下,时间戳增量不得大于MAX_DELTA_STAMP return ret < MAX_DELTA_STAMP ? ret : (_playback ? ret : 0); } //时间戳增量为负,说明时间戳回环了或回退了 _last_stamp = stamp; return _playback ? ret : 0; } void DeltaStamp::setPlayBack(bool playback) { _playback = playback; } void Stamp::revise(int64_t dts, int64_t pts, int64_t &dts_out, int64_t &pts_out,bool modifyStamp) { if(!pts){ //没有播放时间戳,使其赋值为解码时间戳 pts = dts; } //pts和dts的差值 int pts_dts_diff = pts - dts; if(_last_dts != dts){ //时间戳发生变更 if(modifyStamp){ _relativeStamp = _ticker.elapsedTime(); }else{ _relativeStamp += deltaStamp(dts); } _last_dts = dts; } dts_out = _relativeStamp; //////////////以下是播放时间戳的计算////////////////// if(ABS(pts_dts_diff) > MAX_CTS){ //如果差值太大,则认为由于回环导致时间戳错乱了 pts_dts_diff = 0; } pts_out = dts_out + pts_dts_diff; if(pts_out < 0){ //时间戳不能小于0 pts_out = 0; } } void Stamp::setRelativeStamp(int64_t relativeStamp) { _relativeStamp = relativeStamp; } int64_t Stamp::getRelativeStamp() const { return _relativeStamp; } bool DtsGenerator::getDts(uint32_t pts, uint32_t &dts){ bool ret = false; if(pts == _last_pts){ //pts未变,返回上次结果 if(_last_dts){ dts = _last_dts; ret = true; } return ret; } ret = getDts_l(pts,dts); if(ret){ //保存本次结果 _last_dts = dts; } //记录上次pts _last_pts = pts; return ret; } bool DtsGenerator::getDts_l(uint32_t pts, uint32_t &dts){ if(pts > _last_max_pts){ if(!_sorter_max_size && _frames_since_last_max_pts && _count_sorter_max_size++ > 0){ _sorter_max_size = _frames_since_last_max_pts; _dts_pts_offset = (pts - _last_max_pts) / 2; InfoL << _sorter_max_size << " " << _dts_pts_offset; } _frames_since_last_max_pts = 0; _last_max_pts = pts; } _pts_sorter.emplace(pts); ++_frames_since_last_max_pts; if(_sorter_max_size && _pts_sorter.size() > _sorter_max_size){ auto it = _pts_sorter.begin(); dts = *it + _dts_pts_offset; if(dts > pts){ //dts不能大于pts(基本不可能到达这个逻辑) dts = pts; } _pts_sorter.erase(it); return true; } return false; } }//namespace mediakit<commit_msg>优化不含B帧时的dts生成性能<commit_after>/* * MIT License * * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com> * * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Stamp.h" #define MAX_DELTA_STAMP 1000 #define MAX_CTS 500 #define ABS(x) ((x) > 0 ? (x) : (-x)) namespace mediakit { int64_t DeltaStamp::deltaStamp(int64_t stamp) { if(!_last_stamp){ //第一次计算时间戳增量,时间戳增量为0 if(stamp){ _last_stamp = stamp; } return 0; } int64_t ret = stamp - _last_stamp; if(ret >= 0){ //时间戳增量为正,返回之 _last_stamp = stamp; //在直播情况下,时间戳增量不得大于MAX_DELTA_STAMP return ret < MAX_DELTA_STAMP ? ret : (_playback ? ret : 0); } //时间戳增量为负,说明时间戳回环了或回退了 _last_stamp = stamp; return _playback ? ret : 0; } void DeltaStamp::setPlayBack(bool playback) { _playback = playback; } void Stamp::revise(int64_t dts, int64_t pts, int64_t &dts_out, int64_t &pts_out,bool modifyStamp) { if(!pts){ //没有播放时间戳,使其赋值为解码时间戳 pts = dts; } //pts和dts的差值 int pts_dts_diff = pts - dts; if(_last_dts != dts){ //时间戳发生变更 if(modifyStamp){ _relativeStamp = _ticker.elapsedTime(); }else{ _relativeStamp += deltaStamp(dts); } _last_dts = dts; } dts_out = _relativeStamp; //////////////以下是播放时间戳的计算////////////////// if(ABS(pts_dts_diff) > MAX_CTS){ //如果差值太大,则认为由于回环导致时间戳错乱了 pts_dts_diff = 0; } pts_out = dts_out + pts_dts_diff; if(pts_out < 0){ //时间戳不能小于0 pts_out = 0; } } void Stamp::setRelativeStamp(int64_t relativeStamp) { _relativeStamp = relativeStamp; } int64_t Stamp::getRelativeStamp() const { return _relativeStamp; } bool DtsGenerator::getDts(uint32_t pts, uint32_t &dts){ bool ret = false; if(pts == _last_pts){ //pts未变,返回上次结果 if(_last_dts){ dts = _last_dts; ret = true; } return ret; } ret = getDts_l(pts,dts); if(ret){ //保存本次结果 _last_dts = dts; } //记录上次pts _last_pts = pts; return ret; } bool DtsGenerator::getDts_l(uint32_t pts, uint32_t &dts){ if(_sorter_max_size == 1){ //没有B帧 dts = pts; return true; } if(pts > _last_max_pts){ if(!_sorter_max_size && _frames_since_last_max_pts && _count_sorter_max_size++ > 0){ _sorter_max_size = _frames_since_last_max_pts; _dts_pts_offset = (pts - _last_max_pts) / 2; } _frames_since_last_max_pts = 0; _last_max_pts = pts; } _pts_sorter.emplace(pts); ++_frames_since_last_max_pts; if(_sorter_max_size && _pts_sorter.size() > _sorter_max_size){ auto it = _pts_sorter.begin(); dts = *it + _dts_pts_offset; if(dts > pts){ //dts不能大于pts(基本不可能到达这个逻辑) dts = pts; } _pts_sorter.erase(it); return true; } return false; } }//namespace mediakit<|endoftext|>
<commit_before>#include "ContextCairo.h" #include <cassert> #include <cmath> #include <iostream> using namespace canvas; using namespace std; CairoSurface::CairoSurface(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, bool _has_alpha) : Surface(_logical_width, _logical_height, _actual_width, _actual_height, _has_alpha) { cairo_format_t format = _has_alpha ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24; surface = cairo_image_surface_create(format, _actual_width, _actual_height); assert(surface); } CairoSurface::CairoSurface(const Image & image) : Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight(), image.hasAlpha()) { cairo_format_t format = image.hasAlpha() ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24; unsigned int stride = cairo_format_stride_for_width(format, getActualWidth()); assert(stride == 4 * getActualWidth()); storage = new unsigned int[getActualWidth() * getActualHeight()]; const unsigned char * data = image.getData(); if (image.hasAlpha()) { for (unsigned int i = 0; i < getActualWidth() * getActualHeight(); i++) { #if 0 storage[i] = (data[4 * i + 0] << 24) + (data[4 * i + 1] << 16) + (data[4 * i + 2] << 8) + data[4 * i + 3]; #else storage[i] = (data[4 * i + 0]) + (data[4 * i + 1] << 8) + (data[4 * i + 2] << 16) + (data[4 * i + 3] << 24); #endif } } else { for (unsigned int i = 0; i < getActualWidth() * getActualHeight(); i++) { storage[i] = data[3 * i + 2] + (data[3 * i + 1] << 8) + (data[3 * i + 0] << 16); } } surface = cairo_image_surface_create_for_data((unsigned char*)storage, format, getActualWidth(), getActualHeight(), stride); assert(surface); } CairoSurface::CairoSurface(const std::string & filename) : Surface(0, 0, 0, 0, true) { surface = cairo_image_surface_create_from_png(filename.c_str()); assert(surface); unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface); bool has_alpha = cairo_image_surface_get_format(surface) == CAIRO_FORMAT_ARGB32; Surface::resize(w, h, w, h, has_alpha); } struct read_buffer_s { size_t offset, size; const unsigned char * data; }; static cairo_status_t read_buffer(void *closure, unsigned char *data, unsigned int length) { read_buffer_s * buf = (read_buffer_s*)closure; if (buf->offset + length > buf->size) { return CAIRO_STATUS_READ_ERROR; } memcpy(data, buf->data + buf->offset, length); buf->offset += length; return CAIRO_STATUS_SUCCESS; } CairoSurface::CairoSurface(const unsigned char * buffer, size_t size) : Surface(16, 16, 16, 16, true) { read_buffer_s buf = { 0, size, buffer }; if (isPNG(buffer, size)) { surface = cairo_image_surface_create_from_png_stream(read_buffer, &buf); unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface); bool has_alpha = cairo_image_surface_get_format(surface) == CAIRO_FORMAT_ARGB32; Surface::resize(w, h, w, h, has_alpha); } else { cerr << "failed to load image from memory\n"; surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, getActualWidth(), getActualHeight()); } assert(surface); } CairoSurface::~CairoSurface() { if (cr) { cairo_destroy(cr); } if (surface) { cairo_surface_destroy(surface); } delete[] storage; } void CairoSurface::flush() { cairo_surface_flush(surface); } void CairoSurface::markDirty() { cairo_surface_mark_dirty(surface); } void CairoSurface::resize(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, bool has_alpha) { Surface::resize(_logical_width, _logical_height, _actual_width, _actual_height, has_alpha); if (cr) { cairo_destroy(cr); cr = 0; } if (surface) cairo_surface_destroy(surface); cairo_format_t format = has_alpha ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24; surface = cairo_image_surface_create(format, _actual_width, _actual_height); assert(surface); } void CairoSurface::sendPath(const Path & path) { initializeContext(); for (auto pc : path.getData()) { switch (pc.type) { case PathComponent::MOVE_TO: cairo_move_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break; case PathComponent::LINE_TO: cairo_line_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break; case PathComponent::CLOSE: cairo_close_path(cr); break; case PathComponent::ARC: if (!pc.anticlockwise) { cairo_arc(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea); } else { cairo_arc_negative(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea); } break; } } } void CairoSurface::clip(const Path & path, float display_scale) { sendPath(path); cairo_clip(cr); } void CairoSurface::renderPath(RenderMode mode, const Path & path, const Style & style, float lineWidth, float display_scale) { initializeContext(); cairo_pattern_t * pat = 0; if (style.getType() == Style::LINEAR_GRADIENT) { pat = cairo_pattern_create_linear(style.x0 * display_scale, style.y0 * display_scale, style.x1 * display_scale, style.y1 * display_scale); for (map<float, Color>::const_iterator it = style.getColors().begin(); it != style.getColors().end(); it++) { cairo_pattern_add_color_stop_rgba(pat, it->first, it->second.red, it->second.green, it->second.blue, it->second.alpha); } cairo_set_source(cr, pat); } else if (style.getType() == Style::FILTER) { double min_x, min_y, max_x, max_y; path.getExtents(min_x, min_y, max_x, max_y); } else { cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha); } sendPath(path); switch (mode) { case STROKE: cairo_set_line_width(cr, lineWidth); // cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); cairo_stroke(cr); break; case FILL: cairo_fill(cr); break; } if (pat) { cairo_pattern_destroy(pat); cairo_set_source_rgb(cr, 0.0, 0.0, 0.0); } } void CairoSurface::renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, double x, double y, float lineWidth, float display_scale) { initializeContext(); cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha); cairo_select_font_face(cr, font.family.c_str(), font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE), font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, font.size * display_scale); x *= display_scale; y *= display_scale; if (textBaseline.getType() == TextBaseline::MIDDLE || textBaseline.getType() == TextBaseline::TOP) { cairo_font_extents_t font_extents; cairo_font_extents(cr, &font_extents); switch (textBaseline.getType()) { // case TextBaseline::MIDDLE: y -= (extents.height/2 + extents.y_bearing); break; case TextBaseline::MIDDLE: y += -font_extents.descent + (font_extents.ascent + font_extents.descent) / 2.0; break; case TextBaseline::TOP: y += font_extents.ascent; break; default: break; } } if (textAlign.getType() != TextAlign::LEFT) { cairo_text_extents_t text_extents; cairo_text_extents(cr, text.c_str(), &text_extents); switch (textAlign.getType()) { case TextAlign::LEFT: break; case TextAlign::CENTER: x -= text_extents.width / 2; break; case TextAlign::RIGHT: x -= text_extents.width; break; default: break; } } cairo_move_to(cr, x + 0.5, y + 0.5); switch (mode) { case STROKE: cairo_set_line_width(cr, lineWidth); cairo_text_path(cr, text.c_str()); cairo_stroke(cr); break; case FILL: cairo_show_text(cr, text.c_str()); break; } } // renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, double x, double y, float lineWidth, float display_scale) { TextMetrics CairoSurface::measureText(const Font & font, const std::string & text, float display_scale) { initializeContext(); cairo_select_font_face(cr, font.family.c_str(), font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE), font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, font.size * display_scale); cairo_text_extents_t te; cairo_text_extents(cr, text.c_str(), &te); return TextMetrics((float)te.width / display_scale); //, (float)te.height); } void CairoSurface::drawNativeSurface(CairoSurface & img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) { initializeContext(); double sx = w / img.getActualWidth(), sy = h / img.getActualHeight(); cairo_save(cr); cairo_scale(cr, sx, sy); cairo_set_source_surface(cr, img.surface, (x / sx) + 0.5, (y / sy) + 0.5); cairo_pattern_set_filter(cairo_get_source(cr), imageSmoothingEnabled ? CAIRO_FILTER_BILINEAR : CAIRO_FILTER_NEAREST); if (alpha < 1.0f) { cairo_paint_with_alpha(cr, alpha); } else { cairo_paint(cr); } cairo_set_source_rgb(cr, 0.0f, 0.0f, 0.0f); // is this needed? cairo_restore(cr); } void CairoSurface::drawImage(Surface & _img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) { CairoSurface * cs = dynamic_cast<CairoSurface*>(&_img); if (cs) { drawNativeSurface(*cs, x, y, w, h, alpha, imageSmoothingEnabled); } else { auto img = _img.createImage(); CairoSurface cs(*img); drawNativeSurface(cs, x, y, w, h, alpha, imageSmoothingEnabled); } } void CairoSurface::drawImage(const Image & _img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) { CairoSurface img(_img); drawNativeSurface(img, x, y, w, h, alpha, imageSmoothingEnabled); } void CairoSurface::save() { initializeContext(); cairo_save(cr); } void CairoSurface::restore() { initializeContext(); cairo_restore(cr); } <commit_msg>do not create backing surface for zero sized surface<commit_after>#include "ContextCairo.h" #include <cassert> #include <cmath> #include <iostream> using namespace canvas; using namespace std; CairoSurface::CairoSurface(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, bool _has_alpha) : Surface(_logical_width, _logical_height, _actual_width, _actual_height, _has_alpha) { if (_actual_width && _actual_height) { cairo_format_t format = _has_alpha ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24; surface = cairo_image_surface_create(format, _actual_width, _actual_height); assert(surface); } else { surface = 0; } } CairoSurface::CairoSurface(const Image & image) : Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight(), image.hasAlpha()) { cairo_format_t format = image.hasAlpha() ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24; unsigned int stride = cairo_format_stride_for_width(format, getActualWidth()); assert(stride == 4 * getActualWidth()); storage = new unsigned int[getActualWidth() * getActualHeight()]; const unsigned char * data = image.getData(); if (image.hasAlpha()) { for (unsigned int i = 0; i < getActualWidth() * getActualHeight(); i++) { #if 0 storage[i] = (data[4 * i + 0] << 24) + (data[4 * i + 1] << 16) + (data[4 * i + 2] << 8) + data[4 * i + 3]; #else storage[i] = (data[4 * i + 0]) + (data[4 * i + 1] << 8) + (data[4 * i + 2] << 16) + (data[4 * i + 3] << 24); #endif } } else { for (unsigned int i = 0; i < getActualWidth() * getActualHeight(); i++) { storage[i] = data[3 * i + 2] + (data[3 * i + 1] << 8) + (data[3 * i + 0] << 16); } } surface = cairo_image_surface_create_for_data((unsigned char*)storage, format, getActualWidth(), getActualHeight(), stride); assert(surface); } CairoSurface::CairoSurface(const std::string & filename) : Surface(0, 0, 0, 0, true) { surface = cairo_image_surface_create_from_png(filename.c_str()); assert(surface); unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface); bool has_alpha = cairo_image_surface_get_format(surface) == CAIRO_FORMAT_ARGB32; Surface::resize(w, h, w, h, has_alpha); } struct read_buffer_s { size_t offset, size; const unsigned char * data; }; static cairo_status_t read_buffer(void *closure, unsigned char *data, unsigned int length) { read_buffer_s * buf = (read_buffer_s*)closure; if (buf->offset + length > buf->size) { return CAIRO_STATUS_READ_ERROR; } memcpy(data, buf->data + buf->offset, length); buf->offset += length; return CAIRO_STATUS_SUCCESS; } CairoSurface::CairoSurface(const unsigned char * buffer, size_t size) : Surface(16, 16, 16, 16, true) { read_buffer_s buf = { 0, size, buffer }; if (isPNG(buffer, size)) { surface = cairo_image_surface_create_from_png_stream(read_buffer, &buf); unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface); bool has_alpha = cairo_image_surface_get_format(surface) == CAIRO_FORMAT_ARGB32; Surface::resize(w, h, w, h, has_alpha); } else { cerr << "failed to load image from memory\n"; surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, getActualWidth(), getActualHeight()); } assert(surface); } CairoSurface::~CairoSurface() { if (cr) { cairo_destroy(cr); } if (surface) { cairo_surface_destroy(surface); } delete[] storage; } void CairoSurface::flush() { cairo_surface_flush(surface); } void CairoSurface::markDirty() { cairo_surface_mark_dirty(surface); } void CairoSurface::resize(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, bool has_alpha) { Surface::resize(_logical_width, _logical_height, _actual_width, _actual_height, has_alpha); if (cr) { cairo_destroy(cr); cr = 0; } if (surface) cairo_surface_destroy(surface); cairo_format_t format = has_alpha ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24; surface = cairo_image_surface_create(format, _actual_width, _actual_height); assert(surface); } void CairoSurface::sendPath(const Path & path) { initializeContext(); for (auto pc : path.getData()) { switch (pc.type) { case PathComponent::MOVE_TO: cairo_move_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break; case PathComponent::LINE_TO: cairo_line_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break; case PathComponent::CLOSE: cairo_close_path(cr); break; case PathComponent::ARC: if (!pc.anticlockwise) { cairo_arc(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea); } else { cairo_arc_negative(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea); } break; } } } void CairoSurface::clip(const Path & path, float display_scale) { sendPath(path); cairo_clip(cr); } void CairoSurface::renderPath(RenderMode mode, const Path & path, const Style & style, float lineWidth, float display_scale) { initializeContext(); cairo_pattern_t * pat = 0; if (style.getType() == Style::LINEAR_GRADIENT) { pat = cairo_pattern_create_linear(style.x0 * display_scale, style.y0 * display_scale, style.x1 * display_scale, style.y1 * display_scale); for (map<float, Color>::const_iterator it = style.getColors().begin(); it != style.getColors().end(); it++) { cairo_pattern_add_color_stop_rgba(pat, it->first, it->second.red, it->second.green, it->second.blue, it->second.alpha); } cairo_set_source(cr, pat); } else if (style.getType() == Style::FILTER) { double min_x, min_y, max_x, max_y; path.getExtents(min_x, min_y, max_x, max_y); } else { cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha); } sendPath(path); switch (mode) { case STROKE: cairo_set_line_width(cr, lineWidth); // cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); cairo_stroke(cr); break; case FILL: cairo_fill(cr); break; } if (pat) { cairo_pattern_destroy(pat); cairo_set_source_rgb(cr, 0.0, 0.0, 0.0); } } void CairoSurface::renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, double x, double y, float lineWidth, float display_scale) { initializeContext(); cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha); cairo_select_font_face(cr, font.family.c_str(), font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE), font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, font.size * display_scale); x *= display_scale; y *= display_scale; if (textBaseline.getType() == TextBaseline::MIDDLE || textBaseline.getType() == TextBaseline::TOP) { cairo_font_extents_t font_extents; cairo_font_extents(cr, &font_extents); switch (textBaseline.getType()) { // case TextBaseline::MIDDLE: y -= (extents.height/2 + extents.y_bearing); break; case TextBaseline::MIDDLE: y += -font_extents.descent + (font_extents.ascent + font_extents.descent) / 2.0; break; case TextBaseline::TOP: y += font_extents.ascent; break; default: break; } } if (textAlign.getType() != TextAlign::LEFT) { cairo_text_extents_t text_extents; cairo_text_extents(cr, text.c_str(), &text_extents); switch (textAlign.getType()) { case TextAlign::LEFT: break; case TextAlign::CENTER: x -= text_extents.width / 2; break; case TextAlign::RIGHT: x -= text_extents.width; break; default: break; } } cairo_move_to(cr, x + 0.5, y + 0.5); switch (mode) { case STROKE: cairo_set_line_width(cr, lineWidth); cairo_text_path(cr, text.c_str()); cairo_stroke(cr); break; case FILL: cairo_show_text(cr, text.c_str()); break; } } // renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, double x, double y, float lineWidth, float display_scale) { TextMetrics CairoSurface::measureText(const Font & font, const std::string & text, float display_scale) { initializeContext(); cairo_select_font_face(cr, font.family.c_str(), font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE), font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size(cr, font.size * display_scale); cairo_text_extents_t te; cairo_text_extents(cr, text.c_str(), &te); return TextMetrics((float)te.width / display_scale); //, (float)te.height); } void CairoSurface::drawNativeSurface(CairoSurface & img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) { initializeContext(); double sx = w / img.getActualWidth(), sy = h / img.getActualHeight(); cairo_save(cr); cairo_scale(cr, sx, sy); cairo_set_source_surface(cr, img.surface, (x / sx) + 0.5, (y / sy) + 0.5); cairo_pattern_set_filter(cairo_get_source(cr), imageSmoothingEnabled ? CAIRO_FILTER_BILINEAR : CAIRO_FILTER_NEAREST); if (alpha < 1.0f) { cairo_paint_with_alpha(cr, alpha); } else { cairo_paint(cr); } cairo_set_source_rgb(cr, 0.0f, 0.0f, 0.0f); // is this needed? cairo_restore(cr); } void CairoSurface::drawImage(Surface & _img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) { CairoSurface * cs = dynamic_cast<CairoSurface*>(&_img); if (cs) { drawNativeSurface(*cs, x, y, w, h, alpha, imageSmoothingEnabled); } else { auto img = _img.createImage(); CairoSurface cs(*img); drawNativeSurface(cs, x, y, w, h, alpha, imageSmoothingEnabled); } } void CairoSurface::drawImage(const Image & _img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) { CairoSurface img(_img); drawNativeSurface(img, x, y, w, h, alpha, imageSmoothingEnabled); } void CairoSurface::save() { initializeContext(); cairo_save(cr); } void CairoSurface::restore() { initializeContext(); cairo_restore(cr); } <|endoftext|>
<commit_before>#include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/DbCorpusReader.hh> #include <AlpinoCorpus/DirectoryCorpusReader.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/IndexedCorpusReader.hh> #include <QString> #include <typeinfo> #include <libxml/parser.h> #include <QDebug> namespace alpinocorpus { CorpusReader *CorpusReader::open(QString const &corpusPath) { try { return new DirectoryCorpusReader(corpusPath); } catch (OpenError const &e) { } try { return new IndexedCorpusReader(corpusPath); } catch (OpenError const &e) { } return new DbCorpusReader(corpusPath); } CorpusReader::EntryIterator CorpusReader::query(CorpusReader::Dialect d, QString const &q) const { switch (d) { case XPATH: return runXPath(q); case XQUERY: return runXQuery(q); default: throw NotImplemented("unknown query language"); } } CorpusReader::EntryIterator CorpusReader::runXPath(QString const &query) const { //throw NotImplemented(typeid(*this).name(), "XQuery functionality"); return EntryIterator(new FilterIter(*this, getBegin(), getEnd(), query)); } CorpusReader::EntryIterator CorpusReader::runXQuery(QString const &) const { throw NotImplemented(typeid(*this).name(), "XQuery functionality"); } CorpusReader::FilterIter::FilterIter(CorpusReader const &corpus, EntryIterator itr, EntryIterator end, QString const &query) : d_corpus(corpus), d_itr(itr), d_end(end), d_query(query.toUtf8()) { next(); } QString CorpusReader::FilterIter::current() const { return d_file; } bool CorpusReader::FilterIter::equals(IterImpl const &itr) const { try { // TODO fix me to be more like isEqual instead of hasNext. return d_itr == d_end && d_buffer.size() == 0; } catch (std::bad_cast const &e) { return false; } } void CorpusReader::FilterIter::next() { if (!d_buffer.isEmpty()) { d_buffer.dequeue(); return; } while (d_buffer.isEmpty() && d_itr != d_end) { d_file = *d_itr; parseFile(d_file); ++d_itr; } } QString CorpusReader::FilterIter::contents(CorpusReader const &rdr) const { return d_buffer.isEmpty() ? QString() : d_buffer.head(); } void CorpusReader::FilterIter::parseFile(QString const &file) { QString xml(d_corpus.read(file)); QByteArray xmlData(xml.toUtf8()); xmlDocPtr doc = xmlParseMemory(xmlData.constData(), xmlData.size()); if (!doc) { qWarning() << "XPathMapper::run: could not parse XML data: " << *d_itr; return; } // Parse XPath query xmlXPathContextPtr ctx = xmlXPathNewContext(doc); if (!ctx) { xmlFreeDoc(doc); qWarning() << "XPathMapper::run: could not construct XPath context from document: " << *d_itr; return; } xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression( reinterpret_cast<xmlChar const *>(d_query.constData()), ctx); if (!xpathObj) { xmlXPathFreeContext(ctx); xmlFreeDoc(doc); throw Error("XPathMapper::run: could not evaluate XPath expression."); } if (xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) { for (int i = 0; i < xpathObj->nodesetval->nodeNr; ++i) { xmlNode *node = xpathObj->nodesetval->nodeTab[i]; QString value; for (xmlNodePtr child = node->children; child; child = child->next) value += QString::fromUtf8(reinterpret_cast<const char *>(child->content)); if (!value.isEmpty()) d_buffer.enqueue(value); } } xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(ctx); xmlFreeDoc(doc); } } <commit_msg>FilterIter::contents: return file contents.<commit_after>#include <AlpinoCorpus/CorpusReader.hh> #include <AlpinoCorpus/DbCorpusReader.hh> #include <AlpinoCorpus/DirectoryCorpusReader.hh> #include <AlpinoCorpus/Error.hh> #include <AlpinoCorpus/IndexedCorpusReader.hh> #include <QString> #include <typeinfo> #include <libxml/parser.h> #include <QDebug> namespace alpinocorpus { CorpusReader *CorpusReader::open(QString const &corpusPath) { try { return new DirectoryCorpusReader(corpusPath); } catch (OpenError const &e) { } try { return new IndexedCorpusReader(corpusPath); } catch (OpenError const &e) { } return new DbCorpusReader(corpusPath); } CorpusReader::EntryIterator CorpusReader::query(CorpusReader::Dialect d, QString const &q) const { switch (d) { case XPATH: return runXPath(q); case XQUERY: return runXQuery(q); default: throw NotImplemented("unknown query language"); } } CorpusReader::EntryIterator CorpusReader::runXPath(QString const &query) const { //throw NotImplemented(typeid(*this).name(), "XQuery functionality"); return EntryIterator(new FilterIter(*this, getBegin(), getEnd(), query)); } CorpusReader::EntryIterator CorpusReader::runXQuery(QString const &) const { throw NotImplemented(typeid(*this).name(), "XQuery functionality"); } CorpusReader::FilterIter::FilterIter(CorpusReader const &corpus, EntryIterator itr, EntryIterator end, QString const &query) : d_corpus(corpus), d_itr(itr), d_end(end), d_query(query.toUtf8()) { next(); } QString CorpusReader::FilterIter::current() const { return d_file; } bool CorpusReader::FilterIter::equals(IterImpl const &itr) const { try { // TODO fix me to be more like isEqual instead of hasNext. return d_itr == d_end && d_buffer.size() == 0; } catch (std::bad_cast const &e) { return false; } } void CorpusReader::FilterIter::next() { if (!d_buffer.isEmpty()) { d_buffer.dequeue(); return; } while (d_buffer.isEmpty() && d_itr != d_end) { d_file = *d_itr; parseFile(d_file); ++d_itr; } } QString CorpusReader::FilterIter::contents(CorpusReader const &rdr) const { return d_buffer.isEmpty() ? QString() : d_buffer.head(); } void CorpusReader::FilterIter::parseFile(QString const &file) { QString xml(d_corpus.read(file)); QByteArray xmlData(xml.toUtf8()); xmlDocPtr doc = xmlParseMemory(xmlData.constData(), xmlData.size()); if (!doc) { qWarning() << "XPathMapper::run: could not parse XML data: " << *d_itr; return; } // Parse XPath query xmlXPathContextPtr ctx = xmlXPathNewContext(doc); if (!ctx) { xmlFreeDoc(doc); qWarning() << "XPathMapper::run: could not construct XPath context from document: " << *d_itr; return; } xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression( reinterpret_cast<xmlChar const *>(d_query.constData()), ctx); if (!xpathObj) { xmlXPathFreeContext(ctx); xmlFreeDoc(doc); throw Error("XPathMapper::run: could not evaluate XPath expression."); } if (xpathObj->nodesetval && xpathObj->nodesetval->nodeNr > 0) d_buffer.enqueue(xml); xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(ctx); xmlFreeDoc(doc); } } <|endoftext|>
<commit_before>#include "DepthSensor.h" #include "OpenNI.h" #include "cinder/app/app.h" #include "cinder/Log.h" #pragma comment (lib, "OpenNI2.lib") using namespace ci; using namespace ci::app; using namespace std; namespace ds { struct DeviceOpenNI : public Device { static const int OpenNiSensorTypeCount = openni::SENSOR_DEPTH; openni::Device device; openni::VideoStream infraredStream, depthStream, colorStream; float depthScale; ivec2 depthSize; ivec2 colorSize; static uint32_t getDeviceCount() { // TODO: return 1; } virtual float getDepthToMmScale() { return depthScale; } ~DeviceOpenNI() { // TODO: ref-count openni::OpenNI::shutdown(); } // TODO: ivec2 getDepthSize() const { return depthSize; } ivec2 getColorSize() const { return colorSize; } bool isValid() const { return device.isValid(); } DeviceOpenNI(Option option) { this->option = option; openni::Status rc = openni::OpenNI::initialize(); if (rc != openni::STATUS_OK) { CI_LOG_E("Initialize failed\n%s\n", openni::OpenNI::getExtendedError()); return; } rc = device.open(openni::ANY_DEVICE); if (rc != openni::STATUS_OK) { CI_LOG_E("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError()); return; } bool streamEnabled[] = { option.enableInfrared, option.enableColor, option.enableDepth }; openni::VideoStream* streams[] = { &infraredStream, &colorStream, &depthStream, }; for (int i = 0; i < OpenNiSensorTypeCount; i++) { if (!streamEnabled[i]) continue; auto type = openni::SensorType(i + 1); if (device.getSensorInfo(type) != NULL) { rc = streams[i]->create(device, type); if (rc != openni::STATUS_OK) { CI_LOG_E("Couldn't create stream %d\n%s\n", i, openni::OpenNI::getExtendedError()); return; } } rc = streams[i]->start(); if (rc != openni::STATUS_OK) { CI_LOG_E("Couldn't start stream %d\n%s\n", i, openni::OpenNI::getExtendedError()); return; } } App::get()->getSignalUpdate().connect(std::bind(&DeviceOpenNI::update, this)); } static const int SAMPLE_READ_WAIT_TIMEOUT = 100; // ms openni::VideoFrameRef grabVideoFrame(openni::VideoStream* pStream) { openni::VideoFrameRef frame; int changedStreamDummy; openni::Status rc = openni::OpenNI::waitForAnyStream(&pStream, 1, &changedStreamDummy, SAMPLE_READ_WAIT_TIMEOUT); if (rc != openni::STATUS_OK) { CI_LOG_E("Wait failed! (timeout is %d ms)\n%s\n", openni::SAMPLE_READ_WAIT_TIMEOUT, openni::OpenNI::getExtendedError()); } rc = pStream->readFrame(&frame); if (rc != openni::STATUS_OK) { CI_LOG_E("Read failed!\n%s\n", OpenNI::getExtendedError()); } return frame; } void update() { if (option.enableDepth) { auto frame = grabVideoFrame(&depthStream); depthSize.x = frame.getWidth(); depthSize.y = frame.getHeight(); auto data = (uint16_t*)frame.getData(); depthChannel = Channel16u(depthSize.x, depthSize.y, sizeof(uint16_t) * depthSize.x, 1, data); signalDepthDirty.emit(); } if (option.enableInfrared) { auto frame = grabVideoFrame(&infraredStream); auto data = (uint16_t*)frame.getData(); int w = frame.getWidth(); int h = frame.getHeight(); infraredChannel = Channel16u(w, h, sizeof(uint16_t) * w, 1, data); signalInfraredDirty.emit(); } if (option.enableColor) { auto frame = grabVideoFrame(&colorStream); auto data = (uint8_t*)frame.getData(); colorSize.x = frame.getWidth(); colorSize.y = frame.getHeight(); colorSurface = Surface8u(data, colorSize.x, colorSize.y, sizeof(uint8_t) * 3 * colorSize.x, SurfaceChannelOrder::RGB); signalColorDirty.emit(); } } }; uint32_t getOpenNICount() { return DeviceOpenNI::getDeviceCount(); } DeviceRef createOpenNI(Option option) { return DeviceRef(new DeviceOpenNI(option)); } } <commit_msg>Remove getDepthToMmScale() form DeviceOpenNI<commit_after>#include "DepthSensor.h" #include "OpenNI.h" #include "cinder/app/app.h" #include "cinder/Log.h" #pragma comment (lib, "OpenNI2.lib") using namespace ci; using namespace ci::app; using namespace std; namespace ds { struct DeviceOpenNI : public Device { static const int OpenNiSensorTypeCount = openni::SENSOR_DEPTH; openni::Device device; openni::VideoStream infraredStream, depthStream, colorStream; ivec2 depthSize; ivec2 colorSize; static uint32_t getDeviceCount() { // TODO: return 1; } ~DeviceOpenNI() { // TODO: ref-count openni::OpenNI::shutdown(); } // TODO: ivec2 getDepthSize() const { return depthSize; } ivec2 getColorSize() const { return colorSize; } bool isValid() const { return device.isValid(); } DeviceOpenNI(Option option) { this->option = option; openni::Status rc = openni::OpenNI::initialize(); if (rc != openni::STATUS_OK) { CI_LOG_E("Initialize failed\n%s\n", openni::OpenNI::getExtendedError()); return; } rc = device.open(openni::ANY_DEVICE); if (rc != openni::STATUS_OK) { CI_LOG_E("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError()); return; } bool streamEnabled[] = { option.enableInfrared, option.enableColor, option.enableDepth }; openni::VideoStream* streams[] = { &infraredStream, &colorStream, &depthStream, }; for (int i = 0; i < OpenNiSensorTypeCount; i++) { if (!streamEnabled[i]) continue; auto type = openni::SensorType(i + 1); if (device.getSensorInfo(type) != NULL) { rc = streams[i]->create(device, type); if (rc != openni::STATUS_OK) { CI_LOG_E("Couldn't create stream %d\n%s\n", i, openni::OpenNI::getExtendedError()); return; } } rc = streams[i]->start(); if (rc != openni::STATUS_OK) { CI_LOG_E("Couldn't start stream %d\n%s\n", i, openni::OpenNI::getExtendedError()); return; } } App::get()->getSignalUpdate().connect(std::bind(&DeviceOpenNI::update, this)); } static const int SAMPLE_READ_WAIT_TIMEOUT = 100; // ms openni::VideoFrameRef grabVideoFrame(openni::VideoStream* pStream) { openni::VideoFrameRef frame; int changedStreamDummy; openni::Status rc = openni::OpenNI::waitForAnyStream(&pStream, 1, &changedStreamDummy, SAMPLE_READ_WAIT_TIMEOUT); if (rc != openni::STATUS_OK) { CI_LOG_E("Wait failed! (timeout is %d ms)\n%s\n", openni::SAMPLE_READ_WAIT_TIMEOUT, openni::OpenNI::getExtendedError()); } rc = pStream->readFrame(&frame); if (rc != openni::STATUS_OK) { CI_LOG_E("Read failed!\n%s\n", OpenNI::getExtendedError()); } return frame; } void update() { if (option.enableDepth) { auto frame = grabVideoFrame(&depthStream); depthSize.x = frame.getWidth(); depthSize.y = frame.getHeight(); auto data = (uint16_t*)frame.getData(); depthChannel = Channel16u(depthSize.x, depthSize.y, sizeof(uint16_t) * depthSize.x, 1, data); signalDepthDirty.emit(); } if (option.enableInfrared) { auto frame = grabVideoFrame(&infraredStream); auto data = (uint16_t*)frame.getData(); int w = frame.getWidth(); int h = frame.getHeight(); infraredChannel = Channel16u(w, h, sizeof(uint16_t) * w, 1, data); signalInfraredDirty.emit(); } if (option.enableColor) { auto frame = grabVideoFrame(&colorStream); auto data = (uint8_t*)frame.getData(); colorSize.x = frame.getWidth(); colorSize.y = frame.getHeight(); colorSurface = Surface8u(data, colorSize.x, colorSize.y, sizeof(uint8_t) * 3 * colorSize.x, SurfaceChannelOrder::RGB); signalColorDirty.emit(); } } }; uint32_t getOpenNICount() { return DeviceOpenNI::getDeviceCount(); } DeviceRef createOpenNI(Option option) { return DeviceRef(new DeviceOpenNI(option)); } } <|endoftext|>
<commit_before> /* * param.cpp for MSIsensor * Copyright (c) 2013 Beifang Niu && Kai Ye WUGSC All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "param.h" #include <iostream> #include <bitset> bit8_t homo_alphabet[256]; void inital_homo_phabet() { // convert char 'A' to 1 for (int i=0; i<256; i++){ homo_alphabet[i] = 0; } homo_alphabet['a'] = homo_alphabet['A'] = 1; } // Aa=0 // Cc=1 // Gg=2 // Tt=3 // N=4 // bit8_t alphabet[256]; void initalphabet() { // convert unknown char as 4 for (int i=0; i<256; i++) { alphabet[i] = 4; } alphabet['a'] = alphabet['A'] = 0; alphabet['c'] = alphabet['C'] = 1; alphabet['g'] = alphabet['G'] = 2; alphabet['t'] = alphabet['T'] = 3; } bit8_t rev_alphabet[256]; void initrevalphabet() { // complementary chain for (int i=0; i<256; i++) { rev_alphabet[i] = 4; } rev_alphabet['c'] = rev_alphabet['A'] = 3; rev_alphabet['c'] = rev_alphabet['C'] = 2; rev_alphabet['g'] = rev_alphabet['G'] = 1; rev_alphabet['t'] = rev_alphabet['T'] = 0; } // for homopolymer char homo_code[5] = {'A', 'C', 'G', 'T', 'N'}; char uhomo_code[5] = {'T', 'G', 'C', 'A', 'N'}; char chain_flag[2] = {'+', '-'}; char nt_code[4] = {'A', 'C', 'G', 'T'}; char revnt_code[4] = {'T', 'G', 'C', 'A'}; Param::Param() : bufSize(500000) , ncpu(1) , chains(0) , max_dbseq_size(300000000) //300Mb , append_dbseq_size(0x1000000) //16Mb , MininalHomoSize(5) , ContextLength(5) , MaxHomoSize(50) , SpanSize(500) , MininalHomoForDis(10) // microsate , MinMicrosate(3) , MinMicrosateForDis(5) , MaxMicrosateForDis(40) , DisSpan(500) , HomoOnly(0) , MicrosateOnly(0) , s_dispots(100) , MaxMicrosate(5) , Repeats(3) , numberThreads(1) , PercentPairs(20) , PercentPairsNumber(2) , HomoCoverage(40) , windowSize(500000) // window size (default 50k) , covCutoff( 20 ) , fdrThreshold( 0.05 ) { inital_homo_phabet(); initalphabet(); initrevalphabet(); }; Param::~Param() { //xxx }; <commit_msg>fix a bug of conversion from uppercase to lowercase<commit_after> /* * param.cpp for MSIsensor * Copyright (c) 2013 Beifang Niu && Kai Ye WUGSC All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "param.h" #include <iostream> #include <bitset> bit8_t homo_alphabet[256]; void inital_homo_phabet() { // convert char 'A' to 1 for (int i=0; i<256; i++){ homo_alphabet[i] = 0; } homo_alphabet['a'] = homo_alphabet['A'] = 1; } // Aa=0 // Cc=1 // Gg=2 // Tt=3 // N=4 // bit8_t alphabet[256]; void initalphabet() { // convert unknown char as 4 for (int i=0; i<256; i++) { alphabet[i] = 4; } alphabet['a'] = alphabet['A'] = 0; alphabet['c'] = alphabet['C'] = 1; alphabet['g'] = alphabet['G'] = 2; alphabet['t'] = alphabet['T'] = 3; } bit8_t rev_alphabet[256]; void initrevalphabet() { // complementary chain for (int i=0; i<256; i++) { rev_alphabet[i] = 4; } rev_alphabet['a'] = rev_alphabet['A'] = 3; rev_alphabet['c'] = rev_alphabet['C'] = 2; rev_alphabet['g'] = rev_alphabet['G'] = 1; rev_alphabet['t'] = rev_alphabet['T'] = 0; } // for homopolymer char homo_code[5] = {'A', 'C', 'G', 'T', 'N'}; char uhomo_code[5] = {'T', 'G', 'C', 'A', 'N'}; char chain_flag[2] = {'+', '-'}; char nt_code[4] = {'A', 'C', 'G', 'T'}; char revnt_code[4] = {'T', 'G', 'C', 'A'}; Param::Param() : bufSize(500000) , ncpu(1) , chains(0) , max_dbseq_size(300000000) //300Mb , append_dbseq_size(0x1000000) //16Mb , MininalHomoSize(5) , ContextLength(5) , MaxHomoSize(50) , SpanSize(500) , MininalHomoForDis(10) // microsate , MinMicrosate(3) , MinMicrosateForDis(5) , MaxMicrosateForDis(40) , DisSpan(500) , HomoOnly(0) , MicrosateOnly(0) , s_dispots(100) , MaxMicrosate(5) , Repeats(3) , numberThreads(1) , PercentPairs(20) , PercentPairsNumber(2) , HomoCoverage(40) , windowSize(500000) // window size (default 50k) , covCutoff( 20 ) , fdrThreshold( 0.05 ) { inital_homo_phabet(); initalphabet(); initrevalphabet(); }; Param::~Param() { //xxx }; <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include "../Global.h" #include "../Options.h" #include "../Data.h" #include "../Scheme.h" #include "../Inputs/Input.h" #include "../Loggers/Logger.h" #include "../Loggers/Default.h" #include "../Location.h" #include "../Member.h" #include <cstring> bool mShowAll; bool mShowStat; bool mShowSpecific; void showLocations(Input* input); void showOffsets(Input* input); void showDates(Input* input); void showMembers(Input* input); void showVariables(Input* input); int getNumValid(Input* input, std::string variable, int locationId, int startDate, int endDate); int main(int argc, const char *argv[]) { Global::setLogger(new LoggerDefault(Logger::message)); if(argc != 2 && argc != 3 && argc != 4) { std::cout << "Show information about a COMPS dataset" << std::endl; std::cout << std::endl; std::cout << "usage: info.exe dataset [--show-all] show information about dataset" << std::endl; std::cout << " or: info.exe dataset date show detailed information for a specific date" << std::endl; std::cout << " or: info.exe dataset startDate endDate show detailed information for a date range" << std::endl; std::cout << std::endl; std::cout << "Arguments:" << std::endl; std::cout << " dataset Tag of dataset from namelist" << std::endl; std::cout << " date Date in YYYYMMDD format" << std::endl; std::cout << " --show-all Do not limit variables/dates/offsets to the first 100" << std::endl; return 0; } mShowAll = false; mShowSpecific = false; int startDate = Global::MV; int endDate = Global::MV; std::string dataset(argv[1]); if(argc >= 3) { for(int i = 2; i < argc; i++) { if(!std::strcmp(argv[i], "--show-all")) { mShowAll = true; } else if(!Global::isValid(startDate)) { std::stringstream ss; ss<< std::string(argv[i]); ss >> startDate; endDate = startDate; } else { std::stringstream ss; ss<< std::string(argv[i]); ss >> endDate; } } } if(Global::isValid(startDate)) { mShowSpecific = true; } InputContainer inputContainer(Options("")); Input* input = inputContainer.getInput(dataset); if(mShowSpecific) { // Show results for one specific date std::vector<float> offsets = input->getOffsets(); std::vector<std::string> variables = input->getVariables(); std::vector<Location> locations = input->getLocations(); std::vector<Member> members = input->getMembers(); std::vector<double> min(variables.size(), Global::INF); std::vector<double> mean(variables.size(), 0); std::vector<double> max(variables.size(), -Global::INF); std::vector<long> num(variables.size(), 0); std::cout << "Variable min mean max count (max " << offsets.size()*locations.size()*members.size() << ")" << std::endl; for(int v = 0; v < variables.size(); v++) { int date = startDate; while(date <= endDate) { for(int i = 0; i < offsets.size(); i++) { for(int k = 0; k < locations.size(); k++) { for(int m = 0; m < members.size(); m++) { float value = input->getValue(date, 0, offsets[i], locations[k].getId(), members[m].getId(), variables[v]); if(Global::isValid(value)) { min[v] = std::min(min[v], value); mean[v] += value; max[v] = std::max(max[v], value); num[v]++; } } } } date = Global::getDate(date, 24); } if(num[v] > 0) mean[v] /= num[v]; else { min[v] = Global::MV; mean[v] = Global::MV; max[v] = Global::MV; } std::cout << std::left << std::setfill(' ') << std::setw(12) << variables[v] << " " << std::setprecision(3) << std::setw(5) << min[v] << " " << std::setprecision(3) << std::setw(5) << mean[v]<< " " << std::setprecision(3) << std::setw(10) << max[v] << " " << num[v] << std::endl; } // Show results for each location std::cout << std::endl; std::cout << "Counts for each location and variable" << std::endl; std::cout << "Id "; for(int v = 0; v < variables.size(); v++) { std::cout << std::setw(12) << variables[v]; } std::cout << std::endl; for(int k = 0; k < locations.size(); k++) { std::cout << std::setw(6) << locations[k].getId(); for(int v = 0; v < variables.size(); v++) { int num = 0; int date = startDate; while(date <= endDate) { for(int i = 0; i < offsets.size(); i++) { for(int m = 0; m < members.size(); m++) { float value = input->getValue(startDate, 0, offsets[i], locations[k].getId(), members[m].getId(), variables[v]); if(Global::isValid(value)) { num++; } } } date = Global::getDate(date, 24); } std::cout << std::setw(12) << num; } std::cout << std::endl; } } else { // Show general statistics showLocations(input); showOffsets(input); showDates(input); showVariables(input); showMembers(input); } } void showLocations(Input* input) { const std::vector<Location>& locations = input->getLocations(); std::cout << "Locations (" << locations.size() << " total):" << std::endl; std::cout << "Id code lat lon elev gradient"; std::cout << std::endl; for(int i = 0; i < locations.size(); i++) { if(mShowAll || locations.size() < 100 || i < 5 || i >= locations.size()-5) { std::cout << std::setw(6) << locations[i].getId() << " " << std::setw(6) << locations[i].getCode() << " " << std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getLat() << " " << std::setw(6) << locations[i].getLon() << " " << std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getElev() << " "; float gradX = locations[i].getGradientX(); float gradY = locations[i].getGradientY(); if(Global::isValid(gradX) && Global::isValid(gradY)) { std::cout << std::setw(6) << std::fixed << std::setprecision(3) << gradX << "," << std::setw(6) << std::fixed << std::setprecision(3) << gradY; } else { std::cout << " "; } std::cout << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } std::cout << std::endl; } void showOffsets(Input* input) { std::vector<float> offsets = input->getOffsets(); std::cout << "Offsets (" << offsets.size() << " total):" << std::endl; std::cout << "Id offset (h)" << std::endl; for(int i = 0; i < offsets.size(); i++) { if(mShowAll || offsets.size() < 100 || i < 5 || i >= offsets.size()-5) { std::cout << std::setw(6) << i << " " << std::setw(6) << offsets[i] << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } std::cout << std::endl; } void showDates(Input* input) { std::vector<int> dates; std::cout << "Dates (" << dates.size() << " total):" << std::endl; input->getDates(dates); std::cout << "Id dates" << std::endl; for(int i = 0; i < dates.size(); i++) { if(mShowAll || dates.size() < 100 || i < 5 || i >= dates.size()-5) { std::cout << std::setw(6) << i << std::setw(9) << dates[i] << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } std::cout << std::endl; } void showVariables(Input* input) { std::vector<std::string> variables = input->getVariables(); std::cout << "Variables (" << variables.size() << " total):" << std::endl; std::cout << " Id variable" << std::endl; for(int i = 0; i < variables.size(); i++) { if(mShowAll || variables.size() < 100 || i < 5 || i >= variables.size()-5) { std::cout << std::setw(6) << i << " " << std::setw(12) << variables[i] << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } } void showMembers(Input* input) { std::vector<Member> members = input->getMembers(); std::cout << "Members (" << members.size() << " total):" << std::endl; std::cout << " Id model resolution" << std::endl; for(int i = 0; i < members.size(); i++) { if(mShowAll || members.size() < 100 || i < 5 || i >= members.size()-5) { float res = members[i].getResolution(); std::cout << std::setw(6) << i << " " << std::setw(12) << members[i].getModel(); if(Global::isValid(res)) std::cout << std::setw(9) << res << "km"; std::cout << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } std::cout << std::endl; } int getNumValid(Input* input, std::string variable, int locationId, int startDate, int endDate) { std::vector<float> offsets = input->getOffsets(); std::vector<Location> locations = input->getLocations(); std::vector<Member> members = input->getMembers(); // float min=0,mean=0,max=0,num=0; float num = 0; int date = startDate; while(date <= endDate) { for(int i = 0; i < offsets.size(); i++) { for(int k = 0; k < locations.size(); k++) { for(int m = 0; m < members.size(); m++) { float value = input->getValue(date, 0, offsets[i], locationId, members[m].getId(), variable); if(Global::isValid(value)) { // min = std::min(min, value); // mean += value; // max = std::max(max, value); num++; } } } } date = Global::getDate(date, 24); } return num; } <commit_msg>Simple compile error in info driver<commit_after>#include <iostream> #include <iomanip> #include "../Global.h" #include "../Options.h" #include "../Data.h" #include "../Scheme.h" #include "../Inputs/Input.h" #include "../Loggers/Logger.h" #include "../Loggers/Default.h" #include "../Location.h" #include "../Member.h" #include <cstring> bool mShowAll; bool mShowStat; bool mShowSpecific; void showLocations(Input* input); void showOffsets(Input* input); void showDates(Input* input); void showMembers(Input* input); void showVariables(Input* input); int getNumValid(Input* input, std::string variable, int locationId, int startDate, int endDate); int main(int argc, const char *argv[]) { Global::setLogger(new LoggerDefault(Logger::message)); if(argc != 2 && argc != 3 && argc != 4) { std::cout << "Show information about a COMPS dataset" << std::endl; std::cout << std::endl; std::cout << "usage: info.exe dataset [--show-all] show information about dataset" << std::endl; std::cout << " or: info.exe dataset date show detailed information for a specific date" << std::endl; std::cout << " or: info.exe dataset startDate endDate show detailed information for a date range" << std::endl; std::cout << std::endl; std::cout << "Arguments:" << std::endl; std::cout << " dataset Tag of dataset from namelist" << std::endl; std::cout << " date Date in YYYYMMDD format" << std::endl; std::cout << " --show-all Do not limit variables/dates/offsets to the first 100" << std::endl; return 0; } mShowAll = false; mShowSpecific = false; int startDate = Global::MV; int endDate = Global::MV; std::string dataset(argv[1]); if(argc >= 3) { for(int i = 2; i < argc; i++) { if(!std::strcmp(argv[i], "--show-all")) { mShowAll = true; } else if(!Global::isValid(startDate)) { std::stringstream ss; ss<< std::string(argv[i]); ss >> startDate; endDate = startDate; } else { std::stringstream ss; ss<< std::string(argv[i]); ss >> endDate; } } } if(Global::isValid(startDate)) { mShowSpecific = true; } InputContainer inputContainer(Options("")); Input* input = inputContainer.getInput(dataset); if(mShowSpecific) { // Show results for one specific date std::vector<float> offsets = input->getOffsets(); std::vector<std::string> variables = input->getVariables(); std::vector<Location> locations = input->getLocations(); std::vector<Member> members = input->getMembers(); std::vector<double> min(variables.size(), Global::INF); std::vector<double> mean(variables.size(), 0); std::vector<double> max(variables.size(), -Global::INF); std::vector<long> num(variables.size(), 0); std::cout << "Variable min mean max count (max " << offsets.size()*locations.size()*members.size() << ")" << std::endl; for(int v = 0; v < variables.size(); v++) { int date = startDate; while(date <= endDate) { for(int i = 0; i < offsets.size(); i++) { for(int k = 0; k < locations.size(); k++) { for(int m = 0; m < members.size(); m++) { double value = input->getValue(date, 0, offsets[i], locations[k].getId(), members[m].getId(), variables[v]); if(Global::isValid(value)) { min[v] = std::min(min[v], value); mean[v] += value; max[v] = std::max(max[v], value); num[v]++; } } } } date = Global::getDate(date, 24); } if(num[v] > 0) mean[v] /= num[v]; else { min[v] = Global::MV; mean[v] = Global::MV; max[v] = Global::MV; } std::cout << std::left << std::setfill(' ') << std::setw(12) << variables[v] << " " << std::setprecision(3) << std::setw(5) << min[v] << " " << std::setprecision(3) << std::setw(5) << mean[v]<< " " << std::setprecision(3) << std::setw(10) << max[v] << " " << num[v] << std::endl; } // Show results for each location std::cout << std::endl; std::cout << "Counts for each location and variable" << std::endl; std::cout << "Id "; for(int v = 0; v < variables.size(); v++) { std::cout << std::setw(12) << variables[v]; } std::cout << std::endl; for(int k = 0; k < locations.size(); k++) { std::cout << std::setw(6) << locations[k].getId(); for(int v = 0; v < variables.size(); v++) { int num = 0; int date = startDate; while(date <= endDate) { for(int i = 0; i < offsets.size(); i++) { for(int m = 0; m < members.size(); m++) { float value = input->getValue(startDate, 0, offsets[i], locations[k].getId(), members[m].getId(), variables[v]); if(Global::isValid(value)) { num++; } } } date = Global::getDate(date, 24); } std::cout << std::setw(12) << num; } std::cout << std::endl; } } else { // Show general statistics showLocations(input); showOffsets(input); showDates(input); showVariables(input); showMembers(input); } } void showLocations(Input* input) { const std::vector<Location>& locations = input->getLocations(); std::cout << "Locations (" << locations.size() << " total):" << std::endl; std::cout << "Id code lat lon elev gradient"; std::cout << std::endl; for(int i = 0; i < locations.size(); i++) { if(mShowAll || locations.size() < 100 || i < 5 || i >= locations.size()-5) { std::cout << std::setw(6) << locations[i].getId() << " " << std::setw(6) << locations[i].getCode() << " " << std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getLat() << " " << std::setw(6) << locations[i].getLon() << " " << std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getElev() << " "; float gradX = locations[i].getGradientX(); float gradY = locations[i].getGradientY(); if(Global::isValid(gradX) && Global::isValid(gradY)) { std::cout << std::setw(6) << std::fixed << std::setprecision(3) << gradX << "," << std::setw(6) << std::fixed << std::setprecision(3) << gradY; } else { std::cout << " "; } std::cout << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } std::cout << std::endl; } void showOffsets(Input* input) { std::vector<float> offsets = input->getOffsets(); std::cout << "Offsets (" << offsets.size() << " total):" << std::endl; std::cout << "Id offset (h)" << std::endl; for(int i = 0; i < offsets.size(); i++) { if(mShowAll || offsets.size() < 100 || i < 5 || i >= offsets.size()-5) { std::cout << std::setw(6) << i << " " << std::setw(6) << offsets[i] << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } std::cout << std::endl; } void showDates(Input* input) { std::vector<int> dates; std::cout << "Dates (" << dates.size() << " total):" << std::endl; input->getDates(dates); std::cout << "Id dates" << std::endl; for(int i = 0; i < dates.size(); i++) { if(mShowAll || dates.size() < 100 || i < 5 || i >= dates.size()-5) { std::cout << std::setw(6) << i << std::setw(9) << dates[i] << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } std::cout << std::endl; } void showVariables(Input* input) { std::vector<std::string> variables = input->getVariables(); std::cout << "Variables (" << variables.size() << " total):" << std::endl; std::cout << " Id variable" << std::endl; for(int i = 0; i < variables.size(); i++) { if(mShowAll || variables.size() < 100 || i < 5 || i >= variables.size()-5) { std::cout << std::setw(6) << i << " " << std::setw(12) << variables[i] << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } } void showMembers(Input* input) { std::vector<Member> members = input->getMembers(); std::cout << "Members (" << members.size() << " total):" << std::endl; std::cout << " Id model resolution" << std::endl; for(int i = 0; i < members.size(); i++) { if(mShowAll || members.size() < 100 || i < 5 || i >= members.size()-5) { float res = members[i].getResolution(); std::cout << std::setw(6) << i << " " << std::setw(12) << members[i].getModel(); if(Global::isValid(res)) std::cout << std::setw(9) << res << "km"; std::cout << std::endl; } else if(i == 5) { std::cout << "..." << std::endl; } } std::cout << std::endl; } int getNumValid(Input* input, std::string variable, int locationId, int startDate, int endDate) { std::vector<float> offsets = input->getOffsets(); std::vector<Location> locations = input->getLocations(); std::vector<Member> members = input->getMembers(); // float min=0,mean=0,max=0,num=0; float num = 0; int date = startDate; while(date <= endDate) { for(int i = 0; i < offsets.size(); i++) { for(int k = 0; k < locations.size(); k++) { for(int m = 0; m < members.size(); m++) { float value = input->getValue(date, 0, offsets[i], locationId, members[m].getId(), variable); if(Global::isValid(value)) { // min = std::min(min, value); // mean += value; // max = std::max(max, value); num++; } } } } date = Global::getDate(date, 24); } return num; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "OnInput.h" #include <cmath> #include <SA2ModLoader.h> #include "Networking.h" #include "AdventurePacketOverloads.h" #include "globals.h" #include "AddressList.h" #include "nop.h" #include "CommonEnums.h" static const ushort ANALOG_THRESHOLD = 16; static const uint ANALOG_FRAMES = 8; static uint analog_timer = 0; static uint angle_timer = 0; static bool send_angle = false; static ControllerData net_input[ControllerPointers_Length]; static PolarCoord net_analog[ControllerPointers_Length]; using namespace nethax; using namespace globals; static void send(MessageID type, Protocol protocol, pnum_t pnum) { auto& pad = ControllerPointers[pnum]; auto& net_pad = net_input[pnum]; switch (type) { default: break; case MessageID::I_Analog: { sws::Packet packet; packet << pad->LeftStickX << pad->LeftStickY; net_pad.LeftStickX = pad->LeftStickX; net_pad.LeftStickY = pad->LeftStickY; broker->append(MessageID::I_Analog, protocol, &packet); break; } case MessageID::I_AnalogAngle: { sws::Packet packet; packet << AnalogThings[pnum]; net_analog[pnum] = AnalogThings[pnum]; broker->append(MessageID::I_AnalogAngle, protocol, &packet); break; } case MessageID::I_Buttons: { sws::Packet packet; packet << pad->HeldButtons; net_pad.HeldButtons = pad->HeldButtons; broker->append(MessageID::I_Buttons, protocol, &packet); break; } } } extern "C" { void __declspec(dllexport) OnInput() { if (!is_connected()) { return; } auto pnum = broker->get_player_number(); for (size_t i = 0; i < 4; i++) { ControllerData* pad = ControllerPointers[i]; ControllerData* net_pad = &net_input[i]; #pragma region Send if (static_cast<pnum_t>(i) == pnum) { bool sent_buttons = false; if (pad->PressedButtons || pad->ReleasedButtons) { send(MessageID::I_Buttons, Protocol::tcp, i); sent_buttons = true; } // TODO: Make less spammy if (pad->LeftStickX != net_pad->LeftStickX || pad->LeftStickY != net_pad->LeftStickY) { ++analog_timer %= (ANALOG_FRAMES / FrameIncrement); if ((abs(net_pad->LeftStickX - pad->LeftStickX) >= ANALOG_THRESHOLD || abs(net_pad->LeftStickY - pad->LeftStickY) >= ANALOG_THRESHOLD) || !analog_timer) { analog_timer = 0; send(MessageID::I_Analog, Protocol::udp, i); send_angle = true; } else if (!pad->LeftStickX && !pad->LeftStickY) { send(MessageID::I_Analog, Protocol::tcp, i); send_angle = true; } } send_angle = send_angle || sent_buttons; broker->finalize(); continue; } #pragma endregion pad->LeftStickX = net_pad->LeftStickX; pad->LeftStickY = net_pad->LeftStickY; pad->RightStickX = net_pad->RightStickX; pad->RightStickY = net_pad->RightStickY; pad->HeldButtons = net_pad->HeldButtons; pad->NotHeldButtons = ~pad->HeldButtons; // Here we're using netPad's "Old" since it can in some cases be overwritten // by the input update with irrelevant data, thus invalidating Released and Pressed. const uint mask = (pad->HeldButtons ^ net_pad->Old); pad->ReleasedButtons = net_pad->Old & mask; pad->PressedButtons = pad->HeldButtons & mask; // Setting pad->Old might not be necessary, but better safe than sorry. net_pad->Old = pad->Old = pad->HeldButtons; // HACK: Fixes camera rotation in non-emerald hunting modes. pad->LTriggerPressure = (pad->HeldButtons & Buttons_L) ? UCHAR_MAX : 0; pad->RTriggerPressure = (pad->HeldButtons & Buttons_R) ? UCHAR_MAX : 0; } } void __declspec(dllexport) OnControl() { if (!is_connected()) { return; } auto pnum = broker->get_player_number(); for (size_t i = 0; i < 4; i++) { const PolarCoord& current = AnalogThings[i]; const PolarCoord& net = net_analog[i]; if (static_cast<pnum_t>(i) == pnum) { RumblePort_A[i] = 0; bool dir_delta = abs(net.angle - current.angle) >= 2048; bool mag_delta = fabs(current.distance - net.distance) >= 0.0625f; send_angle = send_angle || (++angle_timer %= (ANALOG_FRAMES / FrameIncrement)) == 0; if (dir_delta || mag_delta || (send_angle && (current.angle != net.angle || fabs(current.distance - net.distance) >= FLT_EPSILON))) { #ifdef _DEBUG PrintDebug("[%04d]\t\tDIR: %d MAG: %d TIMER: %d", FrameCount, dir_delta, mag_delta, (!dir_delta && !mag_delta)); #endif send(MessageID::I_AnalogAngle, Protocol::udp, i); send_angle = false; } continue; } RumblePort_A[i] = -1; auto& pad = net_input[i]; if (pad.LeftStickX != 0 || pad.LeftStickY != 0) { AnalogThings[i] = net; } } } } static bool MessageHandler(MessageID id, int pnum, sws::Packet& packet) { if (CurrentMenu[0] == Menu::battle || (TwoPlayerMode > 0 && GameState > GameState::Inactive)) { switch (id) { default: return false; case MessageID::I_Buttons: packet >> net_input[pnum].HeldButtons; break; case MessageID::I_Analog: packet >> net_input[pnum].LeftStickX >> net_input[pnum].LeftStickY; break; case MessageID::I_AnalogAngle: packet >> net_analog[pnum]; AnalogThings[pnum] = net_analog[pnum]; break; } return true; } return false; } void InitOnInput() { // Control nop::apply(0x00441BCA, 7); nop::apply(0x00441BFC, 11); nop::apply(0x00441C1C, 10); // Control_b nop::apply(0x00441D7A, 7); nop::apply(0x00441DAC, 11); nop::apply(0x00441DCC, 10); broker->register_message_handler(MessageID::I_Buttons, MessageHandler); broker->register_message_handler(MessageID::I_Analog, MessageHandler); broker->register_message_handler(MessageID::I_AnalogAngle, MessageHandler); for (size_t i = 0; i < 4; i++) { net_input[i] = {}; net_analog[i] = {}; } } void DeinitOnInput() { // Control nop::restore(0x00441BCA); nop::restore(0x00441BFC); nop::restore(0x00441C1C); // Control_b nop::restore(0x00441D7A); nop::restore(0x00441DAC); nop::restore(0x00441DCC); } template<typename T> void swap(T& a, int from, int to) { auto last = a[to]; a[to] = a[from]; a[from] = last; } void SwapInput(pnum_t from, pnum_t to) { swap(ControllerPointers, from, to); swap(net_input, from, to); swap(net_analog, from, to); } <commit_msg>:||||||||||||||<commit_after>#include "stdafx.h" #include "OnInput.h" #include <cmath> #include <SA2ModLoader.h> #include "Networking.h" #include "AdventurePacketOverloads.h" #include "globals.h" #include "AddressList.h" #include "nop.h" #include "CommonEnums.h" static const ushort ANALOG_THRESHOLD = 16; static const uint ANALOG_FRAMES = 8; static uint analog_timer = 0; static uint angle_timer = 0; static bool send_angle = false; static ControllerData net_input[ControllerPointers_Length]; static PolarCoord net_analog[ControllerPointers_Length]; using namespace nethax; using namespace globals; static void send(MessageID type, Protocol protocol, pnum_t pnum) { auto& pad = ControllerPointers[pnum]; auto& net_pad = net_input[pnum]; switch (type) { default: break; case MessageID::I_Analog: { sws::Packet packet; packet << pad->LeftStickX << pad->LeftStickY; net_pad.LeftStickX = pad->LeftStickX; net_pad.LeftStickY = pad->LeftStickY; broker->append(MessageID::I_Analog, protocol, &packet); break; } case MessageID::I_AnalogAngle: { sws::Packet packet; packet << AnalogThings[pnum]; net_analog[pnum] = AnalogThings[pnum]; broker->append(MessageID::I_AnalogAngle, protocol, &packet); break; } case MessageID::I_Buttons: { sws::Packet packet; packet << pad->HeldButtons; net_pad.HeldButtons = pad->HeldButtons; broker->append(MessageID::I_Buttons, protocol, &packet); break; } } } extern "C" { void __declspec(dllexport) OnInput() { if (!is_connected()) { return; } auto pnum = broker->get_player_number(); for (size_t i = 0; i < 4; i++) { ControllerData* pad = ControllerPointers[i]; ControllerData* net_pad = &net_input[i]; #pragma region Send if (static_cast<pnum_t>(i) == pnum) { bool sent_buttons = false; if (pad->PressedButtons || pad->ReleasedButtons) { send(MessageID::I_Buttons, Protocol::tcp, static_cast<pnum_t>(i)); sent_buttons = true; } // TODO: Make less spammy if (pad->LeftStickX != net_pad->LeftStickX || pad->LeftStickY != net_pad->LeftStickY) { ++analog_timer %= (ANALOG_FRAMES / FrameIncrement); if ((abs(net_pad->LeftStickX - pad->LeftStickX) >= ANALOG_THRESHOLD || abs(net_pad->LeftStickY - pad->LeftStickY) >= ANALOG_THRESHOLD) || !analog_timer) { analog_timer = 0; send(MessageID::I_Analog, Protocol::udp, static_cast<pnum_t>(i)); send_angle = true; } else if (!pad->LeftStickX && !pad->LeftStickY) { send(MessageID::I_Analog, Protocol::tcp, static_cast<pnum_t>(i)); send_angle = true; } } send_angle = send_angle || sent_buttons; broker->finalize(); continue; } #pragma endregion pad->LeftStickX = net_pad->LeftStickX; pad->LeftStickY = net_pad->LeftStickY; pad->RightStickX = net_pad->RightStickX; pad->RightStickY = net_pad->RightStickY; pad->HeldButtons = net_pad->HeldButtons; pad->NotHeldButtons = ~pad->HeldButtons; // Here we're using netPad's "Old" since it can in some cases be overwritten // by the input update with irrelevant data, thus invalidating Released and Pressed. const uint mask = (pad->HeldButtons ^ net_pad->Old); pad->ReleasedButtons = net_pad->Old & mask; pad->PressedButtons = pad->HeldButtons & mask; // Setting pad->Old might not be necessary, but better safe than sorry. net_pad->Old = pad->Old = pad->HeldButtons; // HACK: Fixes camera rotation in non-emerald hunting modes. pad->LTriggerPressure = (pad->HeldButtons & Buttons_L) ? UCHAR_MAX : 0; pad->RTriggerPressure = (pad->HeldButtons & Buttons_R) ? UCHAR_MAX : 0; } } void __declspec(dllexport) OnControl() { if (!is_connected()) { return; } auto pnum = broker->get_player_number(); for (size_t i = 0; i < 4; i++) { const PolarCoord& current = AnalogThings[i]; const PolarCoord& net = net_analog[i]; if (static_cast<pnum_t>(i) == pnum) { RumblePort_A[i] = 0; bool dir_delta = abs(net.angle - current.angle) >= 2048; bool mag_delta = fabs(current.distance - net.distance) >= 0.0625f; send_angle = send_angle || (++angle_timer %= (ANALOG_FRAMES / FrameIncrement)) == 0; if (dir_delta || mag_delta || (send_angle && (current.angle != net.angle || fabs(current.distance - net.distance) >= FLT_EPSILON))) { #ifdef _DEBUG PrintDebug("[%04d]\t\tDIR: %d MAG: %d TIMER: %d", FrameCount, dir_delta, mag_delta, (!dir_delta && !mag_delta)); #endif send(MessageID::I_AnalogAngle, Protocol::udp, static_cast<pnum_t>(i)); send_angle = false; } continue; } RumblePort_A[i] = -1; auto& pad = net_input[i]; if (pad.LeftStickX != 0 || pad.LeftStickY != 0) { AnalogThings[i] = net; } } } } static bool MessageHandler(MessageID id, int pnum, sws::Packet& packet) { if (CurrentMenu[0] == Menu::battle || (TwoPlayerMode > 0 && GameState > GameState::Inactive)) { switch (id) { default: return false; case MessageID::I_Buttons: packet >> net_input[pnum].HeldButtons; break; case MessageID::I_Analog: packet >> net_input[pnum].LeftStickX >> net_input[pnum].LeftStickY; break; case MessageID::I_AnalogAngle: packet >> net_analog[pnum]; AnalogThings[pnum] = net_analog[pnum]; break; } return true; } return false; } void InitOnInput() { // Control nop::apply(0x00441BCA, 7); nop::apply(0x00441BFC, 11); nop::apply(0x00441C1C, 10); // Control_b nop::apply(0x00441D7A, 7); nop::apply(0x00441DAC, 11); nop::apply(0x00441DCC, 10); broker->register_message_handler(MessageID::I_Buttons, MessageHandler); broker->register_message_handler(MessageID::I_Analog, MessageHandler); broker->register_message_handler(MessageID::I_AnalogAngle, MessageHandler); for (size_t i = 0; i < 4; i++) { net_input[i] = {}; net_analog[i] = {}; } } void DeinitOnInput() { // Control nop::restore(0x00441BCA); nop::restore(0x00441BFC); nop::restore(0x00441C1C); // Control_b nop::restore(0x00441D7A); nop::restore(0x00441DAC); nop::restore(0x00441DCC); } template<typename T> void swap(T& a, int from, int to) { auto last = a[to]; a[to] = a[from]; a[from] = last; } void SwapInput(pnum_t from, pnum_t to) { swap(ControllerPointers, from, to); swap(net_input, from, to); swap(net_analog, from, to); } <|endoftext|>
<commit_before>// Time: O(logn) // Space: O(1) class Solution { public: /** * @param n: An integers. * @return: An integer which is the first bad version. */ int findFirstBadVersion(int n) { int left = 1, right = n + 1; VersionControl vc; while (left < right) { int mid = left + (right - left) / 2; // Is target if (vc.isBadVersion(mid)) { right = mid; } else { left = mid + 1; } } return left; } }; class Solution2 { public: /** * @param n: An integers. * @return: An integer which is the first bad version. */ int findFirstBadVersion(int n) { int left = 1, right = n; VersionControl vc; while (left < right) { int mid = left + (right - left) / 2; // Is target if (vc.isBadVersion(mid)) { right = mid - 1; } else { left = mid + 1; } } return left; } }; <commit_msg>3 types of binary search<commit_after>// Time: O(logn) // Space: O(1) class Solution { public: /** * @param n: An integers. * @return: An integer which is the first bad version. */ int findFirstBadVersion(int n) { int left = 1 - 1, right = n; VersionControl vc; while (right - left > 1) { int mid = left + (right - left) / 2; // Is target if (vc.isBadVersion(mid)) { right = mid; } else { left = mid; } } return right; } }; class Solution2 { public: /** * @param n: An integers. * @return: An integer which is the first bad version. */ int findFirstBadVersion(int n) { int left = 1, right = n + 1; VersionControl vc; while (left < right) { int mid = left + (right - left) / 2; // Is target if (vc.isBadVersion(mid)) { right = mid; } else { left = mid + 1; } } return left; } }; class Solution3 { public: /** * @param n: An integers. * @return: An integer which is the first bad version. */ int findFirstBadVersion(int n) { int left = 1, right = n; VersionControl vc; while (left < right) { int mid = left + (right - left) / 2; // Is target if (vc.isBadVersion(mid)) { right = mid - 1; } else { left = mid + 1; } } return left; } }; <|endoftext|>
<commit_before>// Time: O(m + n), m is length of pattern, n is length of string // Space: O(1) // Iteration with greedy class Solution { public: /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ bool isMatch(const char *s, const char *p) { int p_pos = 0, s_pos = 0; int last_s_pos = -1, last_p_pos = -1; int s_len = strlen(s), p_len = strlen(p); while (s_pos < s_len) { if (p_pos < p_len && (p[p_pos] == s[s_pos] || p[p_pos] == '?')) { // Matched a char. ++s_pos; ++p_pos; } else if (p_pos < p_len && p[p_pos] == '*') { // Matched '*'. ++p_pos; last_s_pos = s_pos; last_p_pos = p_pos; } else if (last_p_pos != -1) { // Rollback to the last position of '*' plus 1. // And try next position of last matched one. ++last_s_pos; s_pos = last_s_pos; p_pos = last_p_pos; } else { // s_pos < s_len && no matched p, no position to retry. return false; } } // Skip '*' in p. while (p_pos < p_len && p[p_pos] == '*') { ++p_pos; } // Check if pattern is all matched. return p_pos == p_len; } }; // Time: O(m * n), m is length of pattern, n is length of string // Space: O(m) // DP solution with rolling window class Solution2 { public: /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ bool isMatch(const char *s, const char *p) { size_t s_len = strlen(s); size_t p_len = strlen(p); // match[i][j] denotes as: // s[0, i - 1] matches p[0, j - 1] or not. vector<vector<bool>> match(2, vector<bool>(p_len + 1)); match[0][0] = true; for (int i = 1; i <= p_len; ++i) { if (p[i - 1] == '*') { match[0 % 2][i] = match[0 % 2][i - 1]; } } for (int i = 1; i <= s_len; ++i) { match[i % 2][0] = false; for (int j = 1; j <= p_len; ++j) { if (p[j - 1] != '*') { match[i % 2][j] = match[(i - 1) % 2][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?'); } else { match[i % 2][j] = match[i % 2][j - 1] || match[(i - 1) % 2][j]; } } } return match[s_len % 2][p_len]; } }; // Time: O(m * n), m is length of pattern, n is length of string // Space: O(m * n) // DP solution class Solution3 { public: /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ bool isMatch(const char *s, const char *p) { size_t s_len = strlen(s); size_t p_len = strlen(p); // match[i][j] denotes as: // s[0, i - 1] matches p[0, j - 1] or not. vector<vector<bool>> match(s_len + 1, vector<bool>(p_len + 1)); match[0][0] = true; for (int i = 1; i <= p_len; ++i) { if (p[i - 1] == '*') { match[0][i] = match[0][i - 1]; } } for (int i = 1; i <= s_len; ++i) { match[i][0] = false; for (int j = 1; j <= p_len; ++j) { if (p[j - 1] != '*') { match[i][j] = match[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?'); } else { match[i][j] = match[i][j - 1] || match[i - 1][j]; } } } return match[s_len][p_len]; } }; // Time: O(m * n^2) // Space: O(m + n) // Recursion class Solution_TLE { public: /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ bool isMatch(const char *s, const char *p) { if (*s == 0 || *p == 0) { return *s == 0 && *p == 0; } if (p[0] != '*') { if (p[0] == s[0] || p[0] == '?') { // Matched a char. return isMatch(s + 1, p + 1); } else { return false; } } else { // Try all possible matches with '*' in p. while (*s != 0) { if (isMatch(s, p + 1)) { return true; } ++s; } return isMatch(s, p + 1); } } };<commit_msg>update<commit_after>// Time: O(m + n), m is length of pattern, n is length of string // Space: O(1) // Iteration with greedy class Solution { public: /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ bool isMatch(const char *s, const char *p) { int p_pos = 0, s_pos = 0; int last_s_pos = -1, last_p_pos = -1; const int s_len = strlen(s), p_len = strlen(p); while (s_pos < s_len) { if (p_pos < p_len && (p[p_pos] == s[s_pos] || p[p_pos] == '?')) { // Matched a char. ++s_pos; ++p_pos; } else if (p_pos < p_len && p[p_pos] == '*') { // Matched '*'. ++p_pos; last_s_pos = s_pos; last_p_pos = p_pos; } else if (last_p_pos != -1) { // Rollback to the last position of '*' plus 1. // And try next position of last matched one. ++last_s_pos; s_pos = last_s_pos; p_pos = last_p_pos; } else { // s_pos < s_len && no matched p, no position to retry. return false; } } // Skip '*' in p. while (p_pos < p_len && p[p_pos] == '*') { ++p_pos; } // Check if pattern is all matched. return p_pos == p_len; } }; // Time: O(m * n), m is length of pattern, n is length of string // Space: O(m) // DP solution with rolling window class Solution2 { public: /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ bool isMatch(const char *s, const char *p) { const size_t s_len = strlen(s); const size_t p_len = strlen(p); // match[i][j] denotes as: // s[0, i - 1] matches p[0, j - 1] or not. vector<vector<bool>> match(2, vector<bool>(p_len + 1)); match[0][0] = true; for (int i = 1; i <= p_len; ++i) { if (p[i - 1] == '*') { match[0 % 2][i] = match[0 % 2][i - 1]; } } for (int i = 1; i <= s_len; ++i) { match[i % 2][0] = false; for (int j = 1; j <= p_len; ++j) { if (p[j - 1] != '*') { match[i % 2][j] = match[(i - 1) % 2][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?'); } else { match[i % 2][j] = match[i % 2][j - 1] || match[(i - 1) % 2][j]; } } } return match[s_len % 2][p_len]; } }; // Time: O(m * n), m is length of pattern, n is length of string // Space: O(m * n) // DP solution class Solution3 { public: /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ bool isMatch(const char *s, const char *p) { const size_t s_len = strlen(s); const size_t p_len = strlen(p); // match[i][j] denotes as: // s[0, i - 1] matches p[0, j - 1] or not. vector<vector<bool>> match(s_len + 1, vector<bool>(p_len + 1)); match[0][0] = true; for (int i = 1; i <= p_len; ++i) { if (p[i - 1] == '*') { match[0][i] = match[0][i - 1]; } } for (int i = 1; i <= s_len; ++i) { match[i][0] = false; for (int j = 1; j <= p_len; ++j) { if (p[j - 1] != '*') { match[i][j] = match[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '?'); } else { match[i][j] = match[i][j - 1] || match[i - 1][j]; } } } return match[s_len][p_len]; } }; // Time: O(m * n^2) // Space: O(m + n) // Recursion class Solution_TLE { public: /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ bool isMatch(const char *s, const char *p) { if (*s == 0 || *p == 0) { return *s == 0 && *p == 0; } if (p[0] != '*') { if (p[0] == s[0] || p[0] == '?') { // Matched a char. return isMatch(s + 1, p + 1); } else { return false; } } else { // Try all possible matches with '*' in p. while (*s != 0) { if (isMatch(s, p + 1)) { return true; } ++s; } return isMatch(s, p + 1); } } };<|endoftext|>
<commit_before>/* * Copyright (C) 2015 Mario Alviano (mario@alviano.net) * * 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 "FairSatSolver.h" #include <core/Dimacs.h> Glucose::EnumOption option_fairsat_alg("FAIRSAT", "fairsat-alg", "Set search algorithm.", "bb|binary|progression"); Glucose::BoolOption option_fairsat_printmodel("FAIRSAT", "fairsat-print-model", "Print optimal model if found.", true); namespace aspino { template<class B, class Solver> static void readObjFunc(B& in, Solver& S, vec<Lit>& lits, vec<int64_t>& coeffs) { int parsed_lit, var; lits.clear(); coeffs.clear(); int size = parseInt(in); for(int i = 0; i < size; i++) { parsed_lit = parseInt(in); if (parsed_lit == 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); var = abs(parsed_lit)-1; while (var >= S.nVars()) S.newVar(); lits.push( (parsed_lit > 0) ? mkLit(var) : ~mkLit(var) ); } for(int i = 0; i < size; i++) { coeffs.push(parseLong(in)); if (coeffs.last() == 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); } parsed_lit = parseInt(in); if (parsed_lit != 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); } void ObjectFunction::init(vec<Lit>& lits_, vec<int64_t>& coeffs_) { assert(lits_.size() == coeffs_.size()); lits_.moveTo(lits); coeffs_.moveTo(coeffs); } FairSatSolver::FairSatSolver() : PseudoBooleanSolver() { if(strcmp(option_fairsat_alg, "bb") == 0) search_alg = &FairSatSolver::search_alg_bb; else if(strcmp(option_fairsat_alg, "binary") == 0) search_alg = &FairSatSolver::search_alg_binary; else if(strcmp(option_fairsat_alg, "progression") == 0) search_alg = &FairSatSolver::search_alg_progression; else assert(0); } FairSatSolver::~FairSatSolver() { for(int i = 0; i < objectFunctions.size(); i++) delete objectFunctions[i]; objectFunctions.clear(); } void FairSatSolver::parse(gzFile in_) { Glucose::StreamBuffer in(in_); int64_t objFuncs = -1; vec<Lit> lits; vec<int64_t> coeffs; int vars = 0; int count = 0; inClauses = 0; for(;;) { if(inClauses > 0 && count == inClauses) break; skipWhitespace(in); if(*in == EOF) break; if(*in == 'p') { ++in; if(*in != ' ') cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); ++in; if(eagerMatch(in, "fcnf")) { vars = parseInt(in); inClauses = parseInt(in); objFuncs = parseLong(in); nInVars(vars); while(nVars() < nInVars()) newVar(); } else { cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); } } else if(*in == 'c') skipLine(in); else { count++; readClause(in, *this, lits); addClause_(lits); } } if(count != inClauses) cerr << "WARNING! DIMACS header mismatch: wrong number of clauses." << endl, exit(3); count = 0; for(;;) { skipWhitespace(in); if(*in == EOF) break; if(*in == 'c') skipLine(in); else { count++; readObjFunc(in, *this, lits, coeffs); addObjectFunction(lits, coeffs); } } if(count != objFuncs) cerr << "WARNING! DIMACS header mismatch: wrong number of object functions." << endl, exit(3); upperbound = processObjectFunctions(); assert(upperbound >= 0); freeze(); } void FairSatSolver::addObjectFunction(vec<Lit>& lits, vec<int64_t>& coeffs) { ObjectFunction* objF = new ObjectFunction; objF->init(lits, coeffs); objectFunctions.push(objF); } int64_t FairSatSolver::processObjectFunctions() { int64_t min = INT64_MAX; for(int idx = 0; idx < objectFunctions.size(); idx++) { ObjectFunction& objF = *objectFunctions[idx]; WeightConstraint wc; objF.lits.copyTo(wc.lits); objF.coeffs.copyTo(wc.coeffs); for(int i = 0; i < objF.coeffs.size(); i++) wc.bound += objF.coeffs[i]; objF.sumOfInCoeffs = wc.bound; if(wc.bound < min) min = wc.bound; int64_t n = floor(log2(wc.bound)); for(int64_t i = 0, w = 1; i <= n; i++, w *= 2) { newVar(); wc.lits.push(~mkLit(nVars()-1)); wc.coeffs.push(w); objF.selectorVars.push(nVars()-1); } addConstraint(wc); } return min; } void FairSatSolver::setMinObjectFunction(int64_t min) { assumptions.clear(); for(int i = 0; i < objectFunctions.size(); i++) { int64_t mask = objectFunctions[i]->sumOfInCoeffs - min; assert(mask >= 0); for(int j = 0; j < objectFunctions[i]->selectorVars.size(); j++) { assumptions.push(mkLit(objectFunctions[i]->selectorVars[j], (1ll << j) & mask)); } } } void FairSatSolver::updateLowerBound() { copyModel(); int64_t min = INT64_MAX; for(int i = 0; i < objectFunctions.size(); i++) { ObjectFunction& objF = *objectFunctions[i]; objF.modelValue = 0; for(int j = 0; j < objF.lits.size(); j++) { if(value(objF.lits[j]) != l_False) objF.modelValue += objF.coeffs[j]; } if(objF.modelValue < min) min = objF.modelValue; } assert_msg(min > lowerbound, "min = " << min << "; lowerbound = " << lowerbound); lowerbound = min; } lbool FairSatSolver::solve() { lowerbound = -1; cout << "c searching in [" << lowerbound << ".." << upperbound << "]" << endl; (this->*search_alg)(); if(lowerbound == -1) cout << "s UNSATISFIABLE" << endl; else { cout << "s OPTIMUM FOUND" << endl; if(option_fairsat_printmodel) printModel(); } return status; } void FairSatSolver::search_alg_bb() { for(;;) { setMinObjectFunction(lowerbound + 1); PseudoBooleanSolver::solve(); if(status == l_False) break; if(status == l_True) { updateLowerBound(); cout << "o " << lowerbound << endl; // cout << "c object function values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue; // cout << endl; // cout << "c unsatisfied values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue); // cout << endl; } if(lowerbound == upperbound) break; } } void FairSatSolver::search_alg_binary() { for(;;) { assert(lowerbound < upperbound); int64_t mid = (lowerbound + upperbound) / 2; if(mid == lowerbound) mid++; setMinObjectFunction(mid); PseudoBooleanSolver::solve(); if(status == l_False) { upperbound = mid-1; cout << "c ub " << upperbound << endl; } else if(status == l_True) { updateLowerBound(); cout << "o " << lowerbound << endl; // cout << "c object function values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue; // cout << endl; // cout << "c unsatisfied values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue); // cout << endl; } if(lowerbound == upperbound) break; } } void FairSatSolver::search_alg_progression() { int64_t progression = 1; for(;;) { assert(lowerbound < upperbound); if(lowerbound + progression > upperbound) progression = 1; setMinObjectFunction(lowerbound + progression); // cout << progression << endl; // setConfBudget(100); PseudoBooleanSolver::solve(); // budgetOff(); if(status == l_False) { upperbound = lowerbound + progression - 1; cout << "c ub " << upperbound << endl; } else if(status == l_True) { updateLowerBound(); cout << "o " << lowerbound << endl; // cout << "c object function values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue; // cout << endl; // cout << "c unsatisfied values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue); // cout << endl; } // else { progression = 1; continue; } if(lowerbound == upperbound) break; progression *= 2; } } } // namespace aspino <commit_msg>Rise error if reading negative weigths in FairSAT.<commit_after>/* * Copyright (C) 2015 Mario Alviano (mario@alviano.net) * * 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 "FairSatSolver.h" #include <core/Dimacs.h> Glucose::EnumOption option_fairsat_alg("FAIRSAT", "fairsat-alg", "Set search algorithm.", "bb|binary|progression"); Glucose::BoolOption option_fairsat_printmodel("FAIRSAT", "fairsat-print-model", "Print optimal model if found.", true); namespace aspino { template<class B, class Solver> static void readObjFunc(B& in, Solver& S, vec<Lit>& lits, vec<int64_t>& coeffs) { int parsed_lit, var; lits.clear(); coeffs.clear(); int size = parseInt(in); for(int i = 0; i < size; i++) { parsed_lit = parseInt(in); if (parsed_lit == 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); var = abs(parsed_lit)-1; while (var >= S.nVars()) S.newVar(); lits.push( (parsed_lit > 0) ? mkLit(var) : ~mkLit(var) ); } for(int i = 0; i < size; i++) { coeffs.push(parseLong(in)); if(coeffs.last() <= 0) cerr << "PARSE ERROR! The weights must be nonnegative." << endl, exit(3); } parsed_lit = parseInt(in); if (parsed_lit != 0) cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); } void ObjectFunction::init(vec<Lit>& lits_, vec<int64_t>& coeffs_) { assert(lits_.size() == coeffs_.size()); lits_.moveTo(lits); coeffs_.moveTo(coeffs); } FairSatSolver::FairSatSolver() : PseudoBooleanSolver() { if(strcmp(option_fairsat_alg, "bb") == 0) search_alg = &FairSatSolver::search_alg_bb; else if(strcmp(option_fairsat_alg, "binary") == 0) search_alg = &FairSatSolver::search_alg_binary; else if(strcmp(option_fairsat_alg, "progression") == 0) search_alg = &FairSatSolver::search_alg_progression; else assert(0); } FairSatSolver::~FairSatSolver() { for(int i = 0; i < objectFunctions.size(); i++) delete objectFunctions[i]; objectFunctions.clear(); } void FairSatSolver::parse(gzFile in_) { Glucose::StreamBuffer in(in_); int64_t objFuncs = -1; vec<Lit> lits; vec<int64_t> coeffs; int vars = 0; int count = 0; inClauses = 0; for(;;) { if(inClauses > 0 && count == inClauses) break; skipWhitespace(in); if(*in == EOF) break; if(*in == 'p') { ++in; if(*in != ' ') cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); ++in; if(eagerMatch(in, "fcnf")) { vars = parseInt(in); inClauses = parseInt(in); objFuncs = parseLong(in); if(vars <= 0) cerr << "PARSE ERROR! The number of variables must be positive." << endl, exit(3); if(inClauses <= 0) cerr << "PARSE ERROR! The number of clauses must be positive." << endl, exit(3); if(objFuncs <= 0) cerr << "PARSE ERROR! The number of object functions must be positive." << endl, exit(3); nInVars(vars); while(nVars() < nInVars()) newVar(); } else { cerr << "PARSE ERROR! Unexpected char: " << static_cast<char>(*in) << endl, exit(3); } } else if(*in == 'c') skipLine(in); else { count++; readClause(in, *this, lits); addClause_(lits); } } if(count != inClauses) cerr << "WARNING! DIMACS header mismatch: wrong number of clauses." << endl, exit(3); count = 0; for(;;) { skipWhitespace(in); if(*in == EOF) break; if(*in == 'c') skipLine(in); else { count++; readObjFunc(in, *this, lits, coeffs); addObjectFunction(lits, coeffs); } } if(count != objFuncs) cerr << "WARNING! DIMACS header mismatch: wrong number of object functions." << endl, exit(3); upperbound = processObjectFunctions(); assert(upperbound >= 0); freeze(); } void FairSatSolver::addObjectFunction(vec<Lit>& lits, vec<int64_t>& coeffs) { ObjectFunction* objF = new ObjectFunction; objF->init(lits, coeffs); objectFunctions.push(objF); } int64_t FairSatSolver::processObjectFunctions() { int64_t min = INT64_MAX; for(int idx = 0; idx < objectFunctions.size(); idx++) { ObjectFunction& objF = *objectFunctions[idx]; WeightConstraint wc; objF.lits.copyTo(wc.lits); objF.coeffs.copyTo(wc.coeffs); for(int i = 0; i < objF.coeffs.size(); i++) wc.bound += objF.coeffs[i]; objF.sumOfInCoeffs = wc.bound; if(wc.bound < min) min = wc.bound; int64_t n = floor(log2(wc.bound)); for(int64_t i = 0, w = 1; i <= n; i++, w *= 2) { newVar(); wc.lits.push(~mkLit(nVars()-1)); wc.coeffs.push(w); objF.selectorVars.push(nVars()-1); } addConstraint(wc); } return min; } void FairSatSolver::setMinObjectFunction(int64_t min) { assumptions.clear(); for(int i = 0; i < objectFunctions.size(); i++) { int64_t mask = objectFunctions[i]->sumOfInCoeffs - min; assert(mask >= 0); for(int j = 0; j < objectFunctions[i]->selectorVars.size(); j++) { assumptions.push(mkLit(objectFunctions[i]->selectorVars[j], (1ll << j) & mask)); } } } void FairSatSolver::updateLowerBound() { copyModel(); int64_t min = INT64_MAX; for(int i = 0; i < objectFunctions.size(); i++) { ObjectFunction& objF = *objectFunctions[i]; objF.modelValue = 0; for(int j = 0; j < objF.lits.size(); j++) { if(value(objF.lits[j]) != l_False) objF.modelValue += objF.coeffs[j]; } if(objF.modelValue < min) min = objF.modelValue; } assert_msg(min > lowerbound, "min = " << min << "; lowerbound = " << lowerbound); lowerbound = min; } lbool FairSatSolver::solve() { lowerbound = -1; cout << "c searching in [" << lowerbound << ".." << upperbound << "]" << endl; (this->*search_alg)(); if(lowerbound == -1) cout << "s UNSATISFIABLE" << endl; else { cout << "s OPTIMUM FOUND" << endl; if(option_fairsat_printmodel) printModel(); } return status; } void FairSatSolver::search_alg_bb() { for(;;) { setMinObjectFunction(lowerbound + 1); PseudoBooleanSolver::solve(); if(status == l_False) break; if(status == l_True) { updateLowerBound(); cout << "o " << lowerbound << endl; // cout << "c object function values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue; // cout << endl; // cout << "c unsatisfied values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue); // cout << endl; } if(lowerbound == upperbound) break; } } void FairSatSolver::search_alg_binary() { for(;;) { assert(lowerbound < upperbound); int64_t mid = (lowerbound + upperbound) / 2; if(mid == lowerbound) mid++; setMinObjectFunction(mid); PseudoBooleanSolver::solve(); if(status == l_False) { upperbound = mid-1; cout << "c ub " << upperbound << endl; } else if(status == l_True) { updateLowerBound(); cout << "o " << lowerbound << endl; // cout << "c object function values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue; // cout << endl; // cout << "c unsatisfied values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue); // cout << endl; } if(lowerbound == upperbound) break; } } void FairSatSolver::search_alg_progression() { int64_t progression = 1; for(;;) { assert(lowerbound < upperbound); if(lowerbound + progression > upperbound) progression = 1; setMinObjectFunction(lowerbound + progression); // cout << progression << endl; // setConfBudget(100); PseudoBooleanSolver::solve(); // budgetOff(); if(status == l_False) { upperbound = lowerbound + progression - 1; cout << "c ub " << upperbound << endl; } else if(status == l_True) { updateLowerBound(); cout << "o " << lowerbound << endl; // cout << "c object function values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << objectFunctions[i]->modelValue; // cout << endl; // cout << "c unsatisfied values:"; // for(int i = 0; i < objectFunctions.size(); i++) cout << " " << (objectFunctions[i]->sumOfInCoeffs - objectFunctions[i]->modelValue); // cout << endl; } // else { progression = 1; continue; } if(lowerbound == upperbound) break; progression *= 2; } } } // namespace aspino <|endoftext|>
<commit_before>#include "Genes/Genome.h" #include "Game/Board.h" #include "Game/Color.h" #include "Utility.h" #include "Genes/Gene.h" #include "Genes/Total_Force_Gene.h" #include "Genes/Freedom_To_Move_Gene.h" #include "Genes/Pawn_Advancement_Gene.h" #include "Genes/Opponent_Pieces_Targeted_Gene.h" #include "Genes/Sphere_of_Influence_Gene.h" #include "Genes/Look_Ahead_Gene.h" #include "Genes/King_Confinement_Gene.h" #include "Genes/King_Protection_Gene.h" #include "Genes/Branch_Pruning_Gene.h" #include "Genes/Castling_Possible_Gene.h" // Creation ex nihilo Genome::Genome() : piece_strength_gene_index(-1), look_ahead_gene_index(-1), branch_pruning_gene_index(-1) { // Regulator genes genome.emplace_back(std::make_unique<Piece_Strength_Gene>()); piece_strength_gene_index = genome.size() - 1; genome.emplace_back(std::make_unique<Look_Ahead_Gene>()); look_ahead_gene_index = genome.size() - 1; genome.emplace_back(std::make_unique<Branch_Pruning_Gene>()); branch_pruning_gene_index = genome.size() - 1; // Normal genes genome.emplace_back(std::make_unique<Total_Force_Gene>(static_cast<Piece_Strength_Gene*>(genome[piece_strength_gene_index].get()))); genome.emplace_back(std::make_unique<Freedom_To_Move_Gene>()); genome.emplace_back(std::make_unique<Pawn_Advancement_Gene>()); genome.emplace_back(std::make_unique<Opponent_Pieces_Targeted_Gene>(static_cast<Piece_Strength_Gene*>(genome[piece_strength_gene_index].get()))); genome.emplace_back(std::make_unique<Sphere_of_Influence_Gene>()); genome.emplace_back(std::make_unique<King_Confinement_Gene>()); genome.emplace_back(std::make_unique<King_Protection_Gene>()); genome.emplace_back(std::make_unique<Castling_Possible_Gene>()); } // Cloning Genome::Genome(const Genome& other) : genome(), piece_strength_gene_index(other.piece_strength_gene_index), look_ahead_gene_index(other.look_ahead_gene_index), branch_pruning_gene_index(other.branch_pruning_gene_index) { // Copy all other genes for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); } void Genome::reseat_piece_strength_gene() { auto piece_strength_gene = static_cast<Piece_Strength_Gene*>(genome[piece_strength_gene_index].get()); for(auto& gene : genome) { gene->reset_piece_strength_gene(piece_strength_gene); } } // Injection Genome& Genome::operator=(const Genome& other) { if(this == &other) { return *this; } piece_strength_gene_index = other.piece_strength_gene_index; look_ahead_gene_index = other.look_ahead_gene_index; branch_pruning_gene_index = other.branch_pruning_gene_index; genome.clear(); for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); return *this; } // Sexual reproduction Genome::Genome(const Genome& A, const Genome& B) : genome(), piece_strength_gene_index(A.piece_strength_gene_index), look_ahead_gene_index(A.look_ahead_gene_index), branch_pruning_gene_index(A.branch_pruning_gene_index) { // Copy all other genes for(size_t i = 0; i < A.genome.size(); ++i) { auto& donor = (Random::coin_flip() ? A : B); genome.emplace_back(donor.genome[i]->duplicate()); } reseat_piece_strength_gene(); } void Genome::read_from(std::istream& is) { std::string line; while(getline(is, line)) { if(line.empty()) { continue; } if(line == "END") { return; } if(String::starts_with(line, "Name:")) { auto gene_name = String::split(line, ": ")[1]; bool gene_found = false; for(auto& gene : genome) { if(gene->name() == gene_name) { gene->read_from(is); gene_found = true; break; } } if( ! gene_found) { throw std::runtime_error("Unrecognized gene name: " + gene_name + "\nin line: " + line); } } } } double Genome::score_board(const Board& board, Color perspective) const { double score = 0; for(const auto& gene : genome) { score += gene->evaluate(board, perspective); } return score; } double Genome::evaluate(const Board& board, Color perspective) const { if(board.game_has_ended()) { if(board.get_winner() == NONE) // stalemate { return 0; } else if(board.get_winner() == perspective) // checkmate win { return Math::win_score; } else // checkmate loss { return Math::lose_score; } } return score_board(board, perspective) - score_board(board, opposite(perspective)); } void Genome::mutate() { for(auto& gene : genome) { const int mean_number_of_mutations = 2; if(Random::random_integer(1, genome.size()) <= mean_number_of_mutations) { gene->mutate(); } } } void Genome::print(std::ostream& os) const { for(const auto& gene : genome) { gene->print(os); } os << "\n"; } double Genome::time_to_examine(const Board& board, const Clock& clock) const { return static_cast<Look_Ahead_Gene*>(genome[look_ahead_gene_index].get())->time_to_examine(board, clock); } bool Genome::good_enough_to_examine(const Board& before, const Board& after, Color perspective) const { auto score_difference = evaluate(after, perspective) - evaluate(before, perspective); return static_cast<Branch_Pruning_Gene*>(genome[branch_pruning_gene_index].get())->good_enough_to_examine(score_difference); } bool Genome::enough_time_to_recurse(double time_allotted, const Board& board) const { return static_cast<Look_Ahead_Gene*>(genome[look_ahead_gene_index].get())->enough_time_to_recurse(time_allotted, board); } <commit_msg>Delete redundant code and comments<commit_after>#include "Genes/Genome.h" #include "Game/Board.h" #include "Game/Color.h" #include "Utility.h" #include "Genes/Gene.h" #include "Genes/Total_Force_Gene.h" #include "Genes/Freedom_To_Move_Gene.h" #include "Genes/Pawn_Advancement_Gene.h" #include "Genes/Opponent_Pieces_Targeted_Gene.h" #include "Genes/Sphere_of_Influence_Gene.h" #include "Genes/Look_Ahead_Gene.h" #include "Genes/King_Confinement_Gene.h" #include "Genes/King_Protection_Gene.h" #include "Genes/Branch_Pruning_Gene.h" #include "Genes/Castling_Possible_Gene.h" // Creation ex nihilo Genome::Genome() { // Regulator genes genome.emplace_back(std::make_unique<Piece_Strength_Gene>()); piece_strength_gene_index = genome.size() - 1; genome.emplace_back(std::make_unique<Look_Ahead_Gene>()); look_ahead_gene_index = genome.size() - 1; genome.emplace_back(std::make_unique<Branch_Pruning_Gene>()); branch_pruning_gene_index = genome.size() - 1; // Normal genes genome.emplace_back(std::make_unique<Total_Force_Gene>(static_cast<Piece_Strength_Gene*>(genome[piece_strength_gene_index].get()))); genome.emplace_back(std::make_unique<Freedom_To_Move_Gene>()); genome.emplace_back(std::make_unique<Pawn_Advancement_Gene>()); genome.emplace_back(std::make_unique<Opponent_Pieces_Targeted_Gene>(static_cast<Piece_Strength_Gene*>(genome[piece_strength_gene_index].get()))); genome.emplace_back(std::make_unique<Sphere_of_Influence_Gene>()); genome.emplace_back(std::make_unique<King_Confinement_Gene>()); genome.emplace_back(std::make_unique<King_Protection_Gene>()); genome.emplace_back(std::make_unique<Castling_Possible_Gene>()); } // Cloning Genome::Genome(const Genome& other) : genome(), piece_strength_gene_index(other.piece_strength_gene_index), look_ahead_gene_index(other.look_ahead_gene_index), branch_pruning_gene_index(other.branch_pruning_gene_index) { for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); } void Genome::reseat_piece_strength_gene() { auto piece_strength_gene = static_cast<Piece_Strength_Gene*>(genome[piece_strength_gene_index].get()); for(auto& gene : genome) { gene->reset_piece_strength_gene(piece_strength_gene); } } // Injection Genome& Genome::operator=(const Genome& other) { if(this == &other) { return *this; } piece_strength_gene_index = other.piece_strength_gene_index; look_ahead_gene_index = other.look_ahead_gene_index; branch_pruning_gene_index = other.branch_pruning_gene_index; genome.clear(); for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); return *this; } // Sexual reproduction Genome::Genome(const Genome& A, const Genome& B) : genome(), piece_strength_gene_index(A.piece_strength_gene_index), look_ahead_gene_index(A.look_ahead_gene_index), branch_pruning_gene_index(A.branch_pruning_gene_index) { for(size_t i = 0; i < A.genome.size(); ++i) { auto& donor = (Random::coin_flip() ? A : B); genome.emplace_back(donor.genome[i]->duplicate()); } reseat_piece_strength_gene(); } void Genome::read_from(std::istream& is) { std::string line; while(getline(is, line)) { if(line.empty()) { continue; } if(line == "END") { return; } if(String::starts_with(line, "Name:")) { auto gene_name = String::split(line, ": ")[1]; bool gene_found = false; for(auto& gene : genome) { if(gene->name() == gene_name) { gene->read_from(is); gene_found = true; break; } } if( ! gene_found) { throw std::runtime_error("Unrecognized gene name: " + gene_name + "\nin line: " + line); } } } } double Genome::score_board(const Board& board, Color perspective) const { double score = 0; for(const auto& gene : genome) { score += gene->evaluate(board, perspective); } return score; } double Genome::evaluate(const Board& board, Color perspective) const { if(board.game_has_ended()) { if(board.get_winner() == NONE) // stalemate { return 0; } else if(board.get_winner() == perspective) // checkmate win { return Math::win_score; } else // checkmate loss { return Math::lose_score; } } return score_board(board, perspective) - score_board(board, opposite(perspective)); } void Genome::mutate() { for(auto& gene : genome) { const int mean_number_of_mutations = 2; if(Random::random_integer(1, genome.size()) <= mean_number_of_mutations) { gene->mutate(); } } } void Genome::print(std::ostream& os) const { for(const auto& gene : genome) { gene->print(os); } os << "\n"; } double Genome::time_to_examine(const Board& board, const Clock& clock) const { return static_cast<Look_Ahead_Gene*>(genome[look_ahead_gene_index].get())->time_to_examine(board, clock); } bool Genome::good_enough_to_examine(const Board& before, const Board& after, Color perspective) const { auto score_difference = evaluate(after, perspective) - evaluate(before, perspective); return static_cast<Branch_Pruning_Gene*>(genome[branch_pruning_gene_index].get())->good_enough_to_examine(score_difference); } bool Genome::enough_time_to_recurse(double time_allotted, const Board& board) const { return static_cast<Look_Ahead_Gene*>(genome[look_ahead_gene_index].get())->enough_time_to_recurse(time_allotted, board); } <|endoftext|>
<commit_before>#include "Genes/Genome.h" #include <limits> #include "Game/Color.h" #include "Utility.h" #include "Genes/Gene.h" #include "Genes/Total_Force_Gene.h" #include "Genes/Freedom_To_Move_Gene.h" #include "Genes/Pawn_Advancement_Gene.h" #include "Genes/Opponent_Pieces_Targeted_Gene.h" #include "Genes/Sphere_of_Influence_Gene.h" #include "Genes/Look_Ahead_Gene.h" #include "Genes/Last_Minute_Panic_Gene.h" #include "Genes/King_Confinement_Gene.h" #include "Genes/Branch_Pruning_Gene.h" #include "Genes/King_Protection_Gene.h" #include "Exceptions/Generic_Exception.h" // Creation ex nihilo Genome::Genome() : piece_strength_gene_index(-1), look_ahead_gene_index(-1), last_minute_panic_gene_index(-1), branch_pruning_gene_index(-1) { // Regulator genes genome.emplace_back(new Piece_Strength_Gene); piece_strength_gene_index = genome.size() - 1; genome.emplace_back(new Look_Ahead_Gene); look_ahead_gene_index = genome.size() - 1; genome.emplace_back(new Last_Minute_Panic_Gene); last_minute_panic_gene_index = genome.size() - 1; genome.emplace_back(new Branch_Pruning_Gene); branch_pruning_gene_index = genome.size() - 1; // Normal genes if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Total_Force_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Freedom_To_Move_Gene); genome.emplace_back(new Pawn_Advancement_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Opponent_Pieces_Targeted_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); genome.emplace_back(new Sphere_of_Influence_Gene); } genome.emplace_back(new King_Confinement_Gene); genome.emplace_back(new King_Protection_Gene); } // Cloning Genome::Genome(const Genome& other) : genome(), piece_strength_gene_index(other.piece_strength_gene_index), look_ahead_gene_index(other.look_ahead_gene_index), last_minute_panic_gene_index(other.last_minute_panic_gene_index), branch_pruning_gene_index(other.branch_pruning_gene_index) { // Copy all other genes for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); } void Genome::reseat_piece_strength_gene() { if(piece_strength_gene_index < genome.size()) { for(auto& gene : genome) { gene->reset_piece_strength_gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index])); } } } // Injection Genome& Genome::operator=(const Genome& other) { piece_strength_gene_index = other.piece_strength_gene_index; look_ahead_gene_index = other.look_ahead_gene_index; last_minute_panic_gene_index = other.last_minute_panic_gene_index; branch_pruning_gene_index = other.branch_pruning_gene_index; genome.clear(); for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); return *this; } // Sexual reproduction0 Genome::Genome(const Genome& A, const Genome& B) : genome(), piece_strength_gene_index(A.piece_strength_gene_index), look_ahead_gene_index(A.look_ahead_gene_index), last_minute_panic_gene_index(A.last_minute_panic_gene_index), branch_pruning_gene_index(A.branch_pruning_gene_index) { // Copy all other genes for(size_t i = 0; i < A.genome.size(); ++i) { genome.emplace_back(Random::coin_flip() ? A.genome[i]->duplicate() : B.genome[i]->duplicate()); } reseat_piece_strength_gene(); } void Genome::read_from(std::istream& is) { std::string line; while(getline(is, line)) { if(line.empty()) { continue; } if(line == "END") { return; } if(String::starts_with(line, "Name:")) { auto gene_name = String::split(line, ": ")[1]; for(auto& gene : genome) { if(gene->name() == gene_name) { gene->read_from(is); break; } } } } } double Genome::score_board(const Board& board, Color perspective) const { double score = 0; for(const auto& gene : genome) { // To parallelize, replace below with std::async() call // like in gene pool game matchups score += gene->evaluate(board, perspective); } return score; } double Genome::evaluate(const Board& board, Color perspective) const { return score_board(board, perspective) - score_board(board, opposite(perspective)); } void Genome::mutate() { for(auto& gene : genome) { // On average, mutate 2 genes (if condition ends with <= 2) if(Random::random_integer(1, genome.size()) <= 2) { gene->mutate(); } } } void Genome::print(std::ostream& os) const { for(const auto& gene : genome) { gene->print(os); } os << "\n"; } size_t Genome::positions_to_examine(double time) const { if(look_ahead_gene_index < genome.size()) { return std::static_pointer_cast<Look_Ahead_Gene>(genome[look_ahead_gene_index])->positions_to_examine(time); } else { return 0; } } double Genome::time_required() const { if(last_minute_panic_gene_index < genome.size()) { return std::static_pointer_cast<Last_Minute_Panic_Gene>(genome[last_minute_panic_gene_index])->time_required(); } else { return 0; } } double Genome::minimum_score_change() const { if(branch_pruning_gene_index < genome.size()) { return std::static_pointer_cast<Branch_Pruning_Gene>(genome[branch_pruning_gene_index])->minimum_score_change(); } else { return std::numeric_limits<double>::lowest(); } } <commit_msg>Throw exception if unknown gene name in file<commit_after>#include "Genes/Genome.h" #include <limits> #include "Game/Color.h" #include "Utility.h" #include "Genes/Gene.h" #include "Genes/Total_Force_Gene.h" #include "Genes/Freedom_To_Move_Gene.h" #include "Genes/Pawn_Advancement_Gene.h" #include "Genes/Opponent_Pieces_Targeted_Gene.h" #include "Genes/Sphere_of_Influence_Gene.h" #include "Genes/Look_Ahead_Gene.h" #include "Genes/Last_Minute_Panic_Gene.h" #include "Genes/King_Confinement_Gene.h" #include "Genes/Branch_Pruning_Gene.h" #include "Genes/King_Protection_Gene.h" #include "Exceptions/Generic_Exception.h" // Creation ex nihilo Genome::Genome() : piece_strength_gene_index(-1), look_ahead_gene_index(-1), last_minute_panic_gene_index(-1), branch_pruning_gene_index(-1) { // Regulator genes genome.emplace_back(new Piece_Strength_Gene); piece_strength_gene_index = genome.size() - 1; genome.emplace_back(new Look_Ahead_Gene); look_ahead_gene_index = genome.size() - 1; genome.emplace_back(new Last_Minute_Panic_Gene); last_minute_panic_gene_index = genome.size() - 1; genome.emplace_back(new Branch_Pruning_Gene); branch_pruning_gene_index = genome.size() - 1; // Normal genes if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Total_Force_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); } genome.emplace_back(new Freedom_To_Move_Gene); genome.emplace_back(new Pawn_Advancement_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); if(piece_strength_gene_index < genome.size()) { genome.emplace_back(new Opponent_Pieces_Targeted_Gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index]))); genome.emplace_back(new Sphere_of_Influence_Gene); } genome.emplace_back(new King_Confinement_Gene); genome.emplace_back(new King_Protection_Gene); } // Cloning Genome::Genome(const Genome& other) : genome(), piece_strength_gene_index(other.piece_strength_gene_index), look_ahead_gene_index(other.look_ahead_gene_index), last_minute_panic_gene_index(other.last_minute_panic_gene_index), branch_pruning_gene_index(other.branch_pruning_gene_index) { // Copy all other genes for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); } void Genome::reseat_piece_strength_gene() { if(piece_strength_gene_index < genome.size()) { for(auto& gene : genome) { gene->reset_piece_strength_gene(std::static_pointer_cast<Piece_Strength_Gene>(genome[piece_strength_gene_index])); } } } // Injection Genome& Genome::operator=(const Genome& other) { piece_strength_gene_index = other.piece_strength_gene_index; look_ahead_gene_index = other.look_ahead_gene_index; last_minute_panic_gene_index = other.last_minute_panic_gene_index; branch_pruning_gene_index = other.branch_pruning_gene_index; genome.clear(); for(const auto& gene : other.genome) { genome.emplace_back(gene->duplicate()); } reseat_piece_strength_gene(); return *this; } // Sexual reproduction0 Genome::Genome(const Genome& A, const Genome& B) : genome(), piece_strength_gene_index(A.piece_strength_gene_index), look_ahead_gene_index(A.look_ahead_gene_index), last_minute_panic_gene_index(A.last_minute_panic_gene_index), branch_pruning_gene_index(A.branch_pruning_gene_index) { // Copy all other genes for(size_t i = 0; i < A.genome.size(); ++i) { genome.emplace_back(Random::coin_flip() ? A.genome[i]->duplicate() : B.genome[i]->duplicate()); } reseat_piece_strength_gene(); } void Genome::read_from(std::istream& is) { std::string line; while(getline(is, line)) { if(line.empty()) { continue; } if(line == "END") { return; } if(String::starts_with(line, "Name:")) { auto gene_name = String::split(line, ": ")[1]; bool gene_found = false; for(auto& gene : genome) { if(gene->name() == gene_name) { gene->read_from(is); gene_found = true; break; } } if( ! gene_found) { throw Generic_Exception("Unrecognized gene name: " + gene_name + "\nin line: " + line); } } } } double Genome::score_board(const Board& board, Color perspective) const { double score = 0; for(const auto& gene : genome) { // To parallelize, replace below with std::async() call // like in gene pool game matchups score += gene->evaluate(board, perspective); } return score; } double Genome::evaluate(const Board& board, Color perspective) const { return score_board(board, perspective) - score_board(board, opposite(perspective)); } void Genome::mutate() { for(auto& gene : genome) { // On average, mutate 2 genes (if condition ends with <= 2) if(Random::random_integer(1, genome.size()) <= 2) { gene->mutate(); } } } void Genome::print(std::ostream& os) const { for(const auto& gene : genome) { gene->print(os); } os << "\n"; } size_t Genome::positions_to_examine(double time) const { if(look_ahead_gene_index < genome.size()) { return std::static_pointer_cast<Look_Ahead_Gene>(genome[look_ahead_gene_index])->positions_to_examine(time); } else { return 0; } } double Genome::time_required() const { if(last_minute_panic_gene_index < genome.size()) { return std::static_pointer_cast<Last_Minute_Panic_Gene>(genome[last_minute_panic_gene_index])->time_required(); } else { return 0; } } double Genome::minimum_score_change() const { if(branch_pruning_gene_index < genome.size()) { return std::static_pointer_cast<Branch_Pruning_Gene>(genome[branch_pruning_gene_index])->minimum_score_change(); } else { return std::numeric_limits<double>::lowest(); } } <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/GrPathRendererChain.h" #include "include/gpu/GrDirectContext.h" #include "include/gpu/GrRecordingContext.h" #include "src/gpu/GrCaps.h" #include "src/gpu/GrDirectContextPriv.h" #include "src/gpu/GrGpu.h" #include "src/gpu/GrRecordingContextPriv.h" #include "src/gpu/GrShaderCaps.h" #include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h" #include "src/gpu/geometry/GrStyledShape.h" #include "src/gpu/ops/GrAAConvexPathRenderer.h" #include "src/gpu/ops/GrAAHairLinePathRenderer.h" #include "src/gpu/ops/GrAALinearizingConvexPathRenderer.h" #include "src/gpu/ops/GrDashLinePathRenderer.h" #include "src/gpu/ops/GrDefaultPathRenderer.h" #include "src/gpu/ops/GrSmallPathRenderer.h" #include "src/gpu/ops/GrTriangulatingPathRenderer.h" #include "src/gpu/tessellate/GrTessellationPathRenderer.h" GrPathRendererChain::GrPathRendererChain(GrRecordingContext* context, const Options& options) { const GrCaps& caps = *context->priv().caps(); if (options.fGpuPathRenderers & GpuPathRenderers::kDashLine) { fChain.push_back(sk_make_sp<GrDashLinePathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kAAConvex) { fChain.push_back(sk_make_sp<GrAAConvexPathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kCoverageCounting) { fCoverageCountingPathRenderer = GrCoverageCountingPathRenderer::CreateIfSupported(caps); if (fCoverageCountingPathRenderer) { // Don't add to the chain. This is only for clips. // TODO: Remove from here. context->priv().addOnFlushCallbackObject(fCoverageCountingPathRenderer.get()); } } if (options.fGpuPathRenderers & GpuPathRenderers::kAAHairline) { fChain.push_back(sk_make_sp<GrAAHairLinePathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kAALinearizing) { fChain.push_back(sk_make_sp<GrAALinearizingConvexPathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kSmall) { fChain.push_back(sk_make_sp<GrSmallPathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kTriangulating) { fChain.push_back(sk_make_sp<GrTriangulatingPathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kTessellation) { if (GrTessellationPathRenderer::IsSupported(caps)) { auto tess = sk_make_sp<GrTessellationPathRenderer>(context); fTessellationPathRenderer = tess.get(); context->priv().addOnFlushCallbackObject(tess.get()); fChain.push_back(std::move(tess)); } } // We always include the default path renderer (as well as SW), so we can draw any path fChain.push_back(sk_make_sp<GrDefaultPathRenderer>()); } GrPathRenderer* GrPathRendererChain::getPathRenderer( const GrPathRenderer::CanDrawPathArgs& args, DrawType drawType, GrPathRenderer::StencilSupport* stencilSupport) { static_assert(GrPathRenderer::kNoSupport_StencilSupport < GrPathRenderer::kStencilOnly_StencilSupport); static_assert(GrPathRenderer::kStencilOnly_StencilSupport < GrPathRenderer::kNoRestriction_StencilSupport); GrPathRenderer::StencilSupport minStencilSupport; if (DrawType::kStencil == drawType) { minStencilSupport = GrPathRenderer::kStencilOnly_StencilSupport; } else if (DrawType::kStencilAndColor == drawType) { minStencilSupport = GrPathRenderer::kNoRestriction_StencilSupport; } else { minStencilSupport = GrPathRenderer::kNoSupport_StencilSupport; } if (minStencilSupport != GrPathRenderer::kNoSupport_StencilSupport) { // We don't support (and shouldn't need) stenciling of non-fill paths. if (!args.fShape->style().isSimpleFill()) { return nullptr; } } GrPathRenderer* bestPathRenderer = nullptr; for (const sk_sp<GrPathRenderer>& pr : fChain) { GrPathRenderer::StencilSupport support = GrPathRenderer::kNoSupport_StencilSupport; if (GrPathRenderer::kNoSupport_StencilSupport != minStencilSupport) { support = pr->getStencilSupport(*args.fShape); if (support < minStencilSupport) { continue; } } GrPathRenderer::CanDrawPath canDrawPath = pr->canDrawPath(args); if (GrPathRenderer::CanDrawPath::kNo == canDrawPath) { continue; } if (GrPathRenderer::CanDrawPath::kAsBackup == canDrawPath && bestPathRenderer) { continue; } if (stencilSupport) { *stencilSupport = support; } bestPathRenderer = pr.get(); if (GrPathRenderer::CanDrawPath::kYes == canDrawPath) { break; } } return bestPathRenderer; } <commit_msg>Revert "Re-enable CCPR atlasing + reordering"<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/GrPathRendererChain.h" #include "include/gpu/GrDirectContext.h" #include "include/gpu/GrRecordingContext.h" #include "src/gpu/GrCaps.h" #include "src/gpu/GrDirectContextPriv.h" #include "src/gpu/GrGpu.h" #include "src/gpu/GrRecordingContextPriv.h" #include "src/gpu/GrShaderCaps.h" #include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h" #include "src/gpu/geometry/GrStyledShape.h" #include "src/gpu/ops/GrAAConvexPathRenderer.h" #include "src/gpu/ops/GrAAHairLinePathRenderer.h" #include "src/gpu/ops/GrAALinearizingConvexPathRenderer.h" #include "src/gpu/ops/GrDashLinePathRenderer.h" #include "src/gpu/ops/GrDefaultPathRenderer.h" #include "src/gpu/ops/GrSmallPathRenderer.h" #include "src/gpu/ops/GrTriangulatingPathRenderer.h" #include "src/gpu/tessellate/GrTessellationPathRenderer.h" GrPathRendererChain::GrPathRendererChain(GrRecordingContext* context, const Options& options) { const GrCaps& caps = *context->priv().caps(); if (options.fGpuPathRenderers & GpuPathRenderers::kDashLine) { fChain.push_back(sk_make_sp<GrDashLinePathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kAAConvex) { fChain.push_back(sk_make_sp<GrAAConvexPathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kCoverageCounting) { // opsTask IDs for the atlas have an issue with --reduceOpsTaskSplitting: skbug.com/11731 if (context->priv().options().fReduceOpsTaskSplitting != GrContextOptions::Enable::kYes) { fCoverageCountingPathRenderer = GrCoverageCountingPathRenderer::CreateIfSupported(caps); if (fCoverageCountingPathRenderer) { // Don't add to the chain. This is only for clips. // TODO: Remove from here. context->priv().addOnFlushCallbackObject(fCoverageCountingPathRenderer.get()); } } } if (options.fGpuPathRenderers & GpuPathRenderers::kAAHairline) { fChain.push_back(sk_make_sp<GrAAHairLinePathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kAALinearizing) { fChain.push_back(sk_make_sp<GrAALinearizingConvexPathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kSmall) { fChain.push_back(sk_make_sp<GrSmallPathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kTriangulating) { fChain.push_back(sk_make_sp<GrTriangulatingPathRenderer>()); } if (options.fGpuPathRenderers & GpuPathRenderers::kTessellation) { if (GrTessellationPathRenderer::IsSupported(caps)) { auto tess = sk_make_sp<GrTessellationPathRenderer>(context); fTessellationPathRenderer = tess.get(); context->priv().addOnFlushCallbackObject(tess.get()); fChain.push_back(std::move(tess)); } } // We always include the default path renderer (as well as SW), so we can draw any path fChain.push_back(sk_make_sp<GrDefaultPathRenderer>()); } GrPathRenderer* GrPathRendererChain::getPathRenderer( const GrPathRenderer::CanDrawPathArgs& args, DrawType drawType, GrPathRenderer::StencilSupport* stencilSupport) { static_assert(GrPathRenderer::kNoSupport_StencilSupport < GrPathRenderer::kStencilOnly_StencilSupport); static_assert(GrPathRenderer::kStencilOnly_StencilSupport < GrPathRenderer::kNoRestriction_StencilSupport); GrPathRenderer::StencilSupport minStencilSupport; if (DrawType::kStencil == drawType) { minStencilSupport = GrPathRenderer::kStencilOnly_StencilSupport; } else if (DrawType::kStencilAndColor == drawType) { minStencilSupport = GrPathRenderer::kNoRestriction_StencilSupport; } else { minStencilSupport = GrPathRenderer::kNoSupport_StencilSupport; } if (minStencilSupport != GrPathRenderer::kNoSupport_StencilSupport) { // We don't support (and shouldn't need) stenciling of non-fill paths. if (!args.fShape->style().isSimpleFill()) { return nullptr; } } GrPathRenderer* bestPathRenderer = nullptr; for (const sk_sp<GrPathRenderer>& pr : fChain) { GrPathRenderer::StencilSupport support = GrPathRenderer::kNoSupport_StencilSupport; if (GrPathRenderer::kNoSupport_StencilSupport != minStencilSupport) { support = pr->getStencilSupport(*args.fShape); if (support < minStencilSupport) { continue; } } GrPathRenderer::CanDrawPath canDrawPath = pr->canDrawPath(args); if (GrPathRenderer::CanDrawPath::kNo == canDrawPath) { continue; } if (GrPathRenderer::CanDrawPath::kAsBackup == canDrawPath && bestPathRenderer) { continue; } if (stencilSupport) { *stencilSupport = support; } bestPathRenderer = pr.get(); if (GrPathRenderer::CanDrawPath::kYes == canDrawPath) { break; } } return bestPathRenderer; } <|endoftext|>
<commit_before>#include "graph/node_initializers.h" #include "layers/word2vec_reader.h" #include "tensors/tensor_operators.h" #include <stdint.h> #include <algorithm> #include <iterator> #include <random> namespace marian { namespace inits { float xor128() { static uint64_t x = 123456789; static uint64_t y = 362436069; static uint64_t z = 521288629; static uint64_t w = 88675123; uint64_t t; t = (x ^ (x << 11)) % 1000; x = y; y = z; z = w; w = (w ^ (w >> 19) ^ t ^ (t >> 8)) % 1000; return 0.1f * ((w % 1000) / 1000.f) - 0.05f; } void zeros(Tensor t) { t->set(0.f); } void ones(Tensor t) { t->set(1.0f); } NodeInitializer from_value(float v) { return [v](Tensor t) { t->set(v); }; } // diagonal matrix with value val along diagonal NodeInitializer eye(float val) { return [val](Tensor t) { ABORT_IF(t->shape().size() != 2 || t->shape()[-1] != t->shape()[-2], "eye(val) is defined only for quadratic tensors, shape is {}", t->shape()); // @TODO: implement efficient version on the GPU std::vector<float> vec(t->size(), 0); for(int i = 0; i < t->shape()[-1]; ++i) vec[i * t->shape()[0] + i] = val; t->set(vec); }; } NodeInitializer uniform(float a, float b) { return [a, b](Tensor tensor) { tensor->getBackend()->getRandomGenerator()->uniform(tensor, a, b); }; } NodeInitializer normal(float mean, float stddev) { return [mean, stddev](Tensor tensor) { tensor->getBackend()->getRandomGenerator()->normal(tensor, mean, stddev); }; } void glorot_uniform(Tensor tensor) { float scale = sqrtf(6.0f / (tensor->shape()[-2] + tensor->shape()[-1])); uniform(-scale, scale)(tensor); } void glorot_normal(Tensor tensor) { float scale = sqrtf(2.0f / (tensor->shape()[-2] + tensor->shape()[-1])); normal(0.f, scale)(tensor); } void xorshift(Tensor t) { std::vector<float> vals(t->size()); for(auto&& v : vals) v = xor128(); t->set(vals); } NodeInitializer bernoulli(float prob, float scale) { return [prob, scale](Tensor tensor) { Bernoulli(tensor, prob, scale); }; } NodeInitializer dropout(float prob) { return [prob](Tensor t) { Dropout(t, prob); }; } // gumbel noise: // -log(-log(uniform(0.f + eps, 1.f - eps))); void gumbel(Tensor tensor) { using namespace functional; // @TODO: make eps a parameter? Seems to influence amplitude quite heavily float eps = 1e-05; uniform(0.f + eps, 1.f - eps)(tensor); Element(_1 = -log(-log(_1)), tensor); } NodeInitializer from_vector(const std::vector<float>& v) { auto vPtr = New<std::vector<float>>(v.begin(), v.end()); return [vPtr](Tensor t) { t->set(vPtr->data(), vPtr->data() + vPtr->size()); }; } // @TODO: handle this better with proper type support, the NodeInitializer // should be able to inform the calling function about the tensor type it // is expecting. Probably needs to turn into struct with type information. NodeInitializer from_vector(const std::vector<IndexType>& v) { auto vPtr = New<std::vector<IndexType>>(v.begin(), v.end()); return [vPtr](Tensor t) { t->set(vPtr->data(), vPtr->data() + vPtr->size()); }; } NodeInitializer from_sparse_vector( std::pair<std::vector<size_t>, std::vector<float>>& v) { return [v](Tensor t) { t->set(1e-6); t->setSparse(v.first, v.second); }; } // NodeInitializer from_numpy(const cnpy::NpyArrayPtr& np) { // return [np](Tensor t) { // size_t size = 1; // for(size_t dim : np->shape) // size *= dim; // t->set((float*)np->data(), (float*)np->data() + size); // }; //} // move this somewhere else NodeInitializer from_word2vec(const std::string& file, int dimVoc, int dimEmb, bool normalize /*= false*/) { return [file, dimVoc, dimEmb, normalize](Tensor t) { auto embs = Word2VecReader().read(file, dimVoc, dimEmb); if(normalize) { float norm = 0; for(auto e : embs) norm += e * e; norm = std::sqrt(norm); if(norm != 0) for(auto& e : embs) e = e / norm; } t->set(embs); }; } NodeInitializer from_item(const io::Item& item) { if(item.mapped) { return [item](Tensor t) { // @TODO: implement other types, for now croak loudly. ABORT_IF(t->getBackend()->getDeviceId().type != DeviceType::cpu, "Memory mapping only works for CPU tensors"); ABORT_IF(!matchType<float>(t->type()), "Tensor type and type for mapping do not match"); auto mp = New<MemoryPiece>((uint8_t*)item.ptr, t->size() * sizeof(float)); t->reset(mp); }; } else { return [item](Tensor t) { // @TODO: implement other types, for now croak loudly. ABORT_IF(!matchType<float>(t->type()), "Tensor type and type for mapping do not match"); t->set((const float*)item.bytes.data(), (const float*)item.bytes.data() + t->size()); }; } } } // namespace inits } // namespace marian <commit_msg>mark eps as float<commit_after>#include "graph/node_initializers.h" #include "layers/word2vec_reader.h" #include "tensors/tensor_operators.h" #include <stdint.h> #include <algorithm> #include <iterator> #include <random> namespace marian { namespace inits { float xor128() { static uint64_t x = 123456789; static uint64_t y = 362436069; static uint64_t z = 521288629; static uint64_t w = 88675123; uint64_t t; t = (x ^ (x << 11)) % 1000; x = y; y = z; z = w; w = (w ^ (w >> 19) ^ t ^ (t >> 8)) % 1000; return 0.1f * ((w % 1000) / 1000.f) - 0.05f; } void zeros(Tensor t) { t->set(0.f); } void ones(Tensor t) { t->set(1.0f); } NodeInitializer from_value(float v) { return [v](Tensor t) { t->set(v); }; } // diagonal matrix with value val along diagonal NodeInitializer eye(float val) { return [val](Tensor t) { ABORT_IF(t->shape().size() != 2 || t->shape()[-1] != t->shape()[-2], "eye(val) is defined only for quadratic tensors, shape is {}", t->shape()); // @TODO: implement efficient version on the GPU std::vector<float> vec(t->size(), 0); for(int i = 0; i < t->shape()[-1]; ++i) vec[i * t->shape()[0] + i] = val; t->set(vec); }; } NodeInitializer uniform(float a, float b) { return [a, b](Tensor tensor) { tensor->getBackend()->getRandomGenerator()->uniform(tensor, a, b); }; } NodeInitializer normal(float mean, float stddev) { return [mean, stddev](Tensor tensor) { tensor->getBackend()->getRandomGenerator()->normal(tensor, mean, stddev); }; } void glorot_uniform(Tensor tensor) { float scale = sqrtf(6.0f / (tensor->shape()[-2] + tensor->shape()[-1])); uniform(-scale, scale)(tensor); } void glorot_normal(Tensor tensor) { float scale = sqrtf(2.0f / (tensor->shape()[-2] + tensor->shape()[-1])); normal(0.f, scale)(tensor); } void xorshift(Tensor t) { std::vector<float> vals(t->size()); for(auto&& v : vals) v = xor128(); t->set(vals); } NodeInitializer bernoulli(float prob, float scale) { return [prob, scale](Tensor tensor) { Bernoulli(tensor, prob, scale); }; } NodeInitializer dropout(float prob) { return [prob](Tensor t) { Dropout(t, prob); }; } // gumbel noise: // -log(-log(uniform(0.f + eps, 1.f - eps))); void gumbel(Tensor tensor) { using namespace functional; // @TODO: make eps a parameter? Seems to influence amplitude quite heavily float eps = 1e-05f; uniform(0.f + eps, 1.f - eps)(tensor); Element(_1 = -log(-log(_1)), tensor); } NodeInitializer from_vector(const std::vector<float>& v) { auto vPtr = New<std::vector<float>>(v.begin(), v.end()); return [vPtr](Tensor t) { t->set(vPtr->data(), vPtr->data() + vPtr->size()); }; } // @TODO: handle this better with proper type support, the NodeInitializer // should be able to inform the calling function about the tensor type it // is expecting. Probably needs to turn into struct with type information. NodeInitializer from_vector(const std::vector<IndexType>& v) { auto vPtr = New<std::vector<IndexType>>(v.begin(), v.end()); return [vPtr](Tensor t) { t->set(vPtr->data(), vPtr->data() + vPtr->size()); }; } NodeInitializer from_sparse_vector( std::pair<std::vector<size_t>, std::vector<float>>& v) { return [v](Tensor t) { t->set(1e-6); t->setSparse(v.first, v.second); }; } // NodeInitializer from_numpy(const cnpy::NpyArrayPtr& np) { // return [np](Tensor t) { // size_t size = 1; // for(size_t dim : np->shape) // size *= dim; // t->set((float*)np->data(), (float*)np->data() + size); // }; //} // move this somewhere else NodeInitializer from_word2vec(const std::string& file, int dimVoc, int dimEmb, bool normalize /*= false*/) { return [file, dimVoc, dimEmb, normalize](Tensor t) { auto embs = Word2VecReader().read(file, dimVoc, dimEmb); if(normalize) { float norm = 0; for(auto e : embs) norm += e * e; norm = std::sqrt(norm); if(norm != 0) for(auto& e : embs) e = e / norm; } t->set(embs); }; } NodeInitializer from_item(const io::Item& item) { if(item.mapped) { return [item](Tensor t) { // @TODO: implement other types, for now croak loudly. ABORT_IF(t->getBackend()->getDeviceId().type != DeviceType::cpu, "Memory mapping only works for CPU tensors"); ABORT_IF(!matchType<float>(t->type()), "Tensor type and type for mapping do not match"); auto mp = New<MemoryPiece>((uint8_t*)item.ptr, t->size() * sizeof(float)); t->reset(mp); }; } else { return [item](Tensor t) { // @TODO: implement other types, for now croak loudly. ABORT_IF(!matchType<float>(t->type()), "Tensor type and type for mapping do not match"); t->set((const float*)item.bytes.data(), (const float*)item.bytes.data() + t->size()); }; } } } // namespace inits } // namespace marian <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfocusframe.h" #include "qstyle.h" #include "qbitmap.h" #include "qstylepainter.h" #include "qstyleoption.h" #include "qdebug.h" #include <private/qwidget_p.h> QT_BEGIN_NAMESPACE class QFocusFramePrivate : public QWidgetPrivate { Q_DECLARE_PUBLIC(QFocusFrame) QWidget *widget; public: QFocusFramePrivate() { widget = 0; sendChildEvents = false; } void updateSize(); void update(); }; void QFocusFramePrivate::update() { Q_Q(QFocusFrame); q->setParent(widget->parentWidget()); updateSize(); if (q->parentWidget()->rect().intersects(q->geometry())) { if (q->style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, q)) q->raise(); else q->stackUnder(widget); q->show(); } else { q->hide(); } } void QFocusFramePrivate::updateSize() { Q_Q(QFocusFrame); int vmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameVMargin), hmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin); QRect geom(widget->x()-hmargin, widget->y()-vmargin, widget->width()+(hmargin*2), widget->height()+(vmargin*2)); if(q->geometry() == geom) return; q->setGeometry(geom); QStyleHintReturnMask mask; QStyleOption opt; q->initStyleOption(&opt); if (q->style()->styleHint(QStyle::SH_FocusFrame_Mask, &opt, q, &mask)) q->setMask(mask.region); } /*! Initialize \a option with the values from this QFocusFrame. This method is useful for subclasses when they need a QStyleOption, but don't want to fill in all the information themselves. \sa QStyleOption::initFrom() */ void QFocusFrame::initStyleOption(QStyleOption *option) const { if (!option) return; option->initFrom(this); } /*! \class QFocusFrame \brief The QFocusFrame widget provides a focus frame which can be outside of a widget's normal paintable area. \ingroup basicwidgets Normally an application will not need to create its own QFocusFrame as QStyle will handle this detail for you. A style writer can optionally use a QFocusFrame to have a focus area outside of the widget's paintable geometry. In this way space need not be reserved for the widget to have focus but only set on a QWidget with QFocusFrame::setWidget. It is, however, legal to create your own QFocusFrame on a custom widget and set its geometry manually via QWidget::setGeometry however you will not get auto-placement when the focused widget changes size or placement. */ /*! Constructs a QFocusFrame. The focus frame will not monitor \a parent for updates but rather can be placed manually or by using QFocusFrame::setWidget. A QFocusFrame sets Qt::WA_NoChildEventsForParent attribute; as a result the parent will not receive a QEvent::ChildInserted event, this will make it possible to manually set the geometry of the QFocusFrame inside of a QSplitter or other child event monitoring widget. \sa QFocusFrame::setWidget() */ QFocusFrame::QFocusFrame(QWidget *parent) : QWidget(*new QFocusFramePrivate, parent, 0) { setAttribute(Qt::WA_TransparentForMouseEvents); setFocusPolicy(Qt::NoFocus); setAttribute(Qt::WA_NoChildEventsForParent, true); setAttribute(Qt::WA_AcceptDrops, style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this)); } /*! Destructor. */ QFocusFrame::~QFocusFrame() { } /*! QFocusFrame will track changes to \a widget and resize itself automatically. If the monitored widget's parent changes, QFocusFrame will follow the widget and place itself around the widget automatically. If the monitored widget is deleted, QFocusFrame will set it to zero. \sa QFocusFrame::widget() */ void QFocusFrame::setWidget(QWidget *widget) { Q_D(QFocusFrame); if(widget == d->widget) return; if(d->widget) d->widget->removeEventFilter(this); if(widget && !widget->isWindow() && widget->parentWidget()->windowType() != Qt::SubWindow) { d->widget = widget; widget->installEventFilter(this); d->update(); } else { d->widget = 0; hide(); } } /*! Returns the currently monitored widget for automatically resize and update. \sa QFocusFrame::setWidget() */ QWidget * QFocusFrame::widget() const { Q_D(const QFocusFrame); return d->widget; } /*! \reimp */ void QFocusFrame::paintEvent(QPaintEvent *) { QStylePainter p(this); QStyleOption option; initStyleOption(&option); p.drawControl(QStyle::CE_FocusFrame, option); } /*! \reimp */ bool QFocusFrame::eventFilter(QObject *o, QEvent *e) { Q_D(QFocusFrame); if(o == d->widget) { switch(e->type()) { case QEvent::Move: case QEvent::Resize: d->updateSize(); break; case QEvent::Hide: case QEvent::StyleChange: hide(); break; case QEvent::ParentChange: d->update(); break; case QEvent::Show: d->update(); show(); break; case QEvent::PaletteChange: setPalette(d->widget->palette()); break; case QEvent::ZOrderChange: if (style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this)) raise(); else stackUnder(d->widget); break; case QEvent::Destroy: setWidget(0); break; default: break; } } return false; } /*! \reimp */ bool QFocusFrame::event(QEvent *e) { return QWidget::event(e); } QT_END_NAMESPACE <commit_msg>Focus frames in mac style gets clipped.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfocusframe.h" #include "qstyle.h" #include "qbitmap.h" #include "qstylepainter.h" #include "qstyleoption.h" #include "qdebug.h" #include <private/qwidget_p.h> QT_BEGIN_NAMESPACE class QFocusFramePrivate : public QWidgetPrivate { Q_DECLARE_PUBLIC(QFocusFrame) QWidget *widget; QWidget *frameParent; bool showFrameAboveWidget; public: QFocusFramePrivate() { widget = 0; frameParent = 0; sendChildEvents = false; showFrameAboveWidget = false; } void updateSize(); void update(); }; void QFocusFramePrivate::update() { Q_Q(QFocusFrame); q->setParent(frameParent); updateSize(); if (q->parentWidget()->rect().intersects(q->geometry())) { if (showFrameAboveWidget) q->raise(); else q->stackUnder(widget); q->show(); } else { q->hide(); } } void QFocusFramePrivate::updateSize() { Q_Q(QFocusFrame); int vmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameVMargin), hmargin = q->style()->pixelMetric(QStyle::PM_FocusFrameHMargin); QPoint pos(widget->x(), widget->y()); if (q->parentWidget() != widget->parentWidget()) pos = widget->parentWidget()->mapTo(q->parentWidget(), pos); QRect geom(pos.x()-hmargin, pos.y()-vmargin, widget->width()+(hmargin*2), widget->height()+(vmargin*2)); if(q->geometry() == geom) return; q->setGeometry(geom); QStyleHintReturnMask mask; QStyleOption opt; q->initStyleOption(&opt); if (q->style()->styleHint(QStyle::SH_FocusFrame_Mask, &opt, q, &mask)) q->setMask(mask.region); } /*! Initialize \a option with the values from this QFocusFrame. This method is useful for subclasses when they need a QStyleOption, but don't want to fill in all the information themselves. \sa QStyleOption::initFrom() */ void QFocusFrame::initStyleOption(QStyleOption *option) const { if (!option) return; option->initFrom(this); } /*! \class QFocusFrame \brief The QFocusFrame widget provides a focus frame which can be outside of a widget's normal paintable area. \ingroup basicwidgets Normally an application will not need to create its own QFocusFrame as QStyle will handle this detail for you. A style writer can optionally use a QFocusFrame to have a focus area outside of the widget's paintable geometry. In this way space need not be reserved for the widget to have focus but only set on a QWidget with QFocusFrame::setWidget. It is, however, legal to create your own QFocusFrame on a custom widget and set its geometry manually via QWidget::setGeometry however you will not get auto-placement when the focused widget changes size or placement. */ /*! Constructs a QFocusFrame. The focus frame will not monitor \a parent for updates but rather can be placed manually or by using QFocusFrame::setWidget. A QFocusFrame sets Qt::WA_NoChildEventsForParent attribute; as a result the parent will not receive a QEvent::ChildInserted event, this will make it possible to manually set the geometry of the QFocusFrame inside of a QSplitter or other child event monitoring widget. \sa QFocusFrame::setWidget() */ QFocusFrame::QFocusFrame(QWidget *parent) : QWidget(*new QFocusFramePrivate, parent, 0) { setAttribute(Qt::WA_TransparentForMouseEvents); setFocusPolicy(Qt::NoFocus); setAttribute(Qt::WA_NoChildEventsForParent, true); setAttribute(Qt::WA_AcceptDrops, style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this)); } /*! Destructor. */ QFocusFrame::~QFocusFrame() { } /*! QFocusFrame will track changes to \a widget and resize itself automatically. If the monitored widget's parent changes, QFocusFrame will follow the widget and place itself around the widget automatically. If the monitored widget is deleted, QFocusFrame will set it to zero. \sa QFocusFrame::widget() */ void QFocusFrame::setWidget(QWidget *widget) { Q_D(QFocusFrame); if (style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this)) d->showFrameAboveWidget = true; else d->showFrameAboveWidget = false; if (widget == d->widget) return; if (d->widget) { // Remove event filters from the widget hierarchy. QWidget *p = d->widget; do { p->removeEventFilter(this); if (!d->showFrameAboveWidget || p == d->frameParent) break; p = p->parentWidget(); }while (p); } if (widget && !widget->isWindow() && widget->parentWidget()->windowType() != Qt::SubWindow) { d->widget = widget; d->widget->installEventFilter(this); QWidget *p = widget->parentWidget(); QWidget *prev = 0; if (d->showFrameAboveWidget) { // Find the right parent for the focus frame. while (p) { // Traverse the hirerarchy of the 'widget' for setting event filter. // During this if come across toolbar or a top level, use that // as the parent for the focus frame. If we find a scroll area // use its viewport as the parent. bool isScrollArea = false; if (p->isWindow() || p->inherits("QToolBar") || (isScrollArea = p->inherits("QAbstractScrollArea"))) { d->frameParent = p; // The previous one in the hierarchy will be the viewport. if (prev && isScrollArea) d->frameParent = prev; break; } else { p->installEventFilter(this); prev = p; p = p->parentWidget(); } } } else { d->frameParent = p; } d->update(); } else { d->widget = 0; hide(); } } /*! Returns the currently monitored widget for automatically resize and update. \sa QFocusFrame::setWidget() */ QWidget * QFocusFrame::widget() const { Q_D(const QFocusFrame); return d->widget; } /*! \reimp */ void QFocusFrame::paintEvent(QPaintEvent *) { Q_D(QFocusFrame); QStylePainter p(this); QStyleOption option; initStyleOption(&option); int vmargin = style()->pixelMetric(QStyle::PM_FocusFrameVMargin); int hmargin = style()->pixelMetric(QStyle::PM_FocusFrameHMargin); QWidgetPrivate *wd = qt_widget_private(d->widget); QRect rect = wd->clipRect().adjusted(0, 0, hmargin*2, vmargin*2); p.setClipRect(rect); p.drawControl(QStyle::CE_FocusFrame, option); } /*! \reimp */ bool QFocusFrame::eventFilter(QObject *o, QEvent *e) { Q_D(QFocusFrame); if(o == d->widget) { switch(e->type()) { case QEvent::Move: case QEvent::Resize: d->updateSize(); break; case QEvent::Hide: case QEvent::StyleChange: hide(); break; case QEvent::ParentChange: if (d->showFrameAboveWidget) { QWidget *w = d->widget; setWidget(0); setWidget(w); } else { d->update(); } break; case QEvent::Show: d->update(); show(); break; case QEvent::PaletteChange: setPalette(d->widget->palette()); break; case QEvent::ZOrderChange: if (style()->styleHint(QStyle::SH_FocusFrame_AboveWidget, 0, this)) raise(); else stackUnder(d->widget); break; case QEvent::Destroy: setWidget(0); break; default: break; } } else if (d->showFrameAboveWidget) { // Handle changes in the parent widgets we are monitoring. switch(e->type()) { case QEvent::Move: case QEvent::Resize: d->updateSize(); break; case QEvent::ZOrderChange: raise(); break; default: break; } } return false; } /*! \reimp */ bool QFocusFrame::event(QEvent *e) { return QWidget::event(e); } QT_END_NAMESPACE <|endoftext|>
<commit_before>// // Matrix/macro.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // #ifndef EIGENJS_MATRIX_MACRO_HPP #define EIGENJS_MATRIX_MACRO_HPP #include <v8.h> #include <node.h> #include <nan.h> #include <boost/preprocessor/cat.hpp> #include "../throw_error.hpp" #include "../detail/add_complex.hpp" #define EIGENJS_MATRIX_BINARY_OPERATOR_CONTEXT( OP ) \ { \ NanScope(); \ \ if ( args.Length() == 1 ) { \ const T* const& obj = \ node::ObjectWrap::Unwrap< T >( args.This() ); \ const typename T::value_type& value = **obj; \ const typename T::value_type::Index& rows = value.rows(); \ const typename T::value_type::Index& cols = value.cols(); \ v8::Local<v8::Value> argv[] = { \ NanNew<v8::Integer>( rows ) \ , NanNew<v8::Integer>( cols ) \ }; \ \ if ( Matrix::is_matrix( args[0] ) ) { \ const Matrix* const& rhs_obj = \ node::ObjectWrap::Unwrap< Matrix >( args[0]->ToObject() ); \ const typename Matrix::value_type& rhs_matrix = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ v8::Local< v8::Object > instance = T::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ T* new_obj = node::ObjectWrap::Unwrap< T >( instance ); \ typename T::value_type& new_value = **new_obj; \ \ new_value = value OP rhs_matrix; \ \ NanReturnValue( instance ); \ } else if ( Vector::is_vector( args[0] ) ) { \ const Vector* const& rhs_obj = \ node::ObjectWrap::Unwrap< Vector >( args[0]->ToObject() ); \ const typename Vector::value_type& rhs_vector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ v8::Local< v8::Object > instance = T::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ T* new_obj = node::ObjectWrap::Unwrap< T >( instance ); \ typename T::value_type& new_value = **new_obj; \ \ new_value = value OP rhs_vector; \ \ NanReturnValue( instance ); \ } else if ( RowVector::is_rowvector( args[0] ) ) { \ const RowVector* const& rhs_obj = \ node::ObjectWrap::Unwrap< RowVector >( args[0]->ToObject() ); \ const typename RowVector::value_type& rhs_rowvector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ v8::Local< v8::Object > instance = T::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ T* new_obj = node::ObjectWrap::Unwrap< T >( instance ); \ typename T::value_type& new_value = **new_obj; \ \ new_value = value OP rhs_rowvector; \ \ NanReturnValue( instance ); \ } else if ( CMatrix::is_cmatrix( args[0]) ) { \ const CMatrix* const& rhs_obj = \ node::ObjectWrap::Unwrap< CMatrix >( args[0]->ToObject() ); \ const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ typedef typename detail::add_complex<T>::type CT; \ \ v8::Local< v8::Object > instance = CT::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ CT* new_obj = node::ObjectWrap::Unwrap< CT >( instance ); \ typename CT::value_type& new_value = **new_obj; \ \ new_value = \ value.template cast< typename Complex::value_type >() \ OP \ rhs_cmatrix; \ \ NanReturnValue( instance ); \ } else if ( CVector::is_cvector( args[0]) ) { \ const CVector* const& rhs_obj = \ node::ObjectWrap::Unwrap< CVector >( args[0]->ToObject() ); \ const typename CVector::value_type& rhs_cvector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ typedef typename detail::add_complex<T>::type CT; \ \ v8::Local< v8::Object > instance = CT::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ CT* new_obj = node::ObjectWrap::Unwrap< CT >( instance ); \ typename CT::value_type& new_value = **new_obj; \ \ new_value = \ value.template cast< typename Complex::value_type >() \ OP \ rhs_cvector; \ \ NanReturnValue( instance ); \ } \ } \ \ EIGENJS_THROW_ERROR_INVALID_ARGUMENT() \ NanReturnUndefined(); \ } \ /**/ #define EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE_CONTEXT( OP ) \ { \ NanScope(); \ \ if ( args.Length() == 1) { \ T* obj = node::ObjectWrap::Unwrap< T >( args.This() ); \ typename T::value_type& value = **obj; \ \ if ( Matrix::is_matrix( args[0] ) ) { \ const Matrix* const& rhs_obj = \ node::ObjectWrap::Unwrap< Matrix >( args[0]->ToObject() ); \ const typename Matrix::value_type& rhs_matrix = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ value BOOST_PP_CAT( OP, = ) rhs_matrix; \ \ NanReturnValue( args.This() ); \ } else if ( Vector::is_vector( args[0] ) ) { \ const Vector* const& rhs_obj = \ node::ObjectWrap::Unwrap< Vector >( args[0]->ToObject() ); \ const typename Vector::value_type& rhs_vector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ value BOOST_PP_CAT( OP, = ) rhs_vector; \ \ NanReturnValue( args.This() ); \ } else if ( RowVector::is_rowvector( args[0] ) ) { \ const RowVector* const& rhs_obj = \ node::ObjectWrap::Unwrap< RowVector >( args[0]->ToObject() ); \ const typename Vector::value_type& rhs_rowvector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ value BOOST_PP_CAT( OP, = ) rhs_rowvector; \ \ NanReturnValue( args.This() ); \ } \ } \ \ EIGENJS_THROW_ERROR_INVALID_ARGUMENT() \ NanReturnUndefined(); \ } \ /**/ #endif // EIGENJS_MATRIX_MACRO_HPP <commit_msg>src: use 'detail/unwrap_eigen_block' to abstract code<commit_after>// // Matrix/macro.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // #ifndef EIGENJS_MATRIX_MACRO_HPP #define EIGENJS_MATRIX_MACRO_HPP #include <v8.h> #include <node.h> #include <nan.h> #include <boost/preprocessor/cat.hpp> #include "../throw_error.hpp" #include "../detail/add_complex.hpp" #include "../detail/unwrap_eigen_block.hpp" #define EIGENJS_MATRIX_BINARY_OPERATOR_CONTEXT( OP ) \ { \ NanScope(); \ \ if ( args.Length() == 1 ) { \ const T* const& obj = \ node::ObjectWrap::Unwrap< T >( args.This() ); \ const typename T::value_type& value = **obj; \ const typename T::value_type::Index& rows = value.rows(); \ const typename T::value_type::Index& cols = value.cols(); \ v8::Local<v8::Value> argv[] = { \ NanNew<v8::Integer>( rows ) \ , NanNew<v8::Integer>( cols ) \ }; \ \ if ( Matrix::is_matrix( args[0] ) ) { \ const Matrix* const& rhs_obj = \ node::ObjectWrap::Unwrap< Matrix >( args[0]->ToObject() ); \ const typename Matrix::value_type& rhs_matrix = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ v8::Local< v8::Object > instance = U::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ U* new_obj = node::ObjectWrap::Unwrap< U >( instance ); \ typename U::value_type& new_value = **new_obj; \ \ new_value = value OP rhs_matrix; \ \ NanReturnValue( instance ); \ } else if ( Vector::is_vector( args[0] ) ) { \ const Vector* const& rhs_obj = \ node::ObjectWrap::Unwrap< Vector >( args[0]->ToObject() ); \ const typename Vector::value_type& rhs_vector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ v8::Local< v8::Object > instance = U::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ U* new_obj = node::ObjectWrap::Unwrap< U >( instance ); \ typename U::value_type& new_value = **new_obj; \ \ new_value = value OP rhs_vector; \ \ NanReturnValue( instance ); \ } else if ( RowVector::is_rowvector( args[0] ) ) { \ const RowVector* const& rhs_obj = \ node::ObjectWrap::Unwrap< RowVector >( args[0]->ToObject() ); \ const typename RowVector::value_type& rhs_rowvector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ v8::Local< v8::Object > instance = U::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ U* new_obj = node::ObjectWrap::Unwrap< U >( instance ); \ typename U::value_type& new_value = **new_obj; \ \ new_value = value OP rhs_rowvector; \ \ NanReturnValue( instance ); \ } else if ( CMatrix::is_cmatrix( args[0]) ) { \ const CMatrix* const& rhs_obj = \ node::ObjectWrap::Unwrap< CMatrix >( args[0]->ToObject() ); \ const typename CMatrix::value_type& rhs_cmatrix = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ typedef typename detail::add_complex<U>::type CU; \ \ v8::Local< v8::Object > instance = CU::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ CU* new_obj = node::ObjectWrap::Unwrap< CU >( instance ); \ typename CU::value_type& new_value = **new_obj; \ \ new_value = \ value.template cast< typename Complex::value_type >() \ OP \ rhs_cmatrix; \ \ NanReturnValue( instance ); \ } else if ( CVector::is_cvector( args[0]) ) { \ const CVector* const& rhs_obj = \ node::ObjectWrap::Unwrap< CVector >( args[0]->ToObject() ); \ const typename CVector::value_type& rhs_cvector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ typedef typename detail::add_complex<U>::type CU; \ \ v8::Local< v8::Object > instance = CU::new_instance( \ args \ , sizeof( argv ) / sizeof( v8::Local< v8::Value > ) \ , argv \ ); \ \ CU* new_obj = node::ObjectWrap::Unwrap< CU >( instance ); \ typename CU::value_type& new_value = **new_obj; \ \ new_value = \ value.template cast< typename Complex::value_type >() \ OP \ rhs_cvector; \ \ NanReturnValue( instance ); \ } \ } \ \ EIGENJS_THROW_ERROR_INVALID_ARGUMENT() \ NanReturnUndefined(); \ } \ /**/ #define EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE_CONTEXT( OP ) \ { \ NanScope(); \ \ if ( args.Length() == 1) { \ T* obj = node::ObjectWrap::Unwrap< T >( args.This() ); \ typename T::value_type& value = **obj; \ \ if ( Matrix::is_matrix( args[0] ) ) { \ const Matrix* const& rhs_obj = \ node::ObjectWrap::Unwrap< Matrix >( args[0]->ToObject() ); \ const typename Matrix::value_type& rhs_matrix = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ value BOOST_PP_CAT( OP, = ) rhs_matrix; \ \ NanReturnValue( args.This() ); \ } else if ( Vector::is_vector( args[0] ) ) { \ const Vector* const& rhs_obj = \ node::ObjectWrap::Unwrap< Vector >( args[0]->ToObject() ); \ const typename Vector::value_type& rhs_vector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ value BOOST_PP_CAT( OP, = ) rhs_vector; \ \ NanReturnValue( args.This() ); \ } else if ( RowVector::is_rowvector( args[0] ) ) { \ const RowVector* const& rhs_obj = \ node::ObjectWrap::Unwrap< RowVector >( args[0]->ToObject() ); \ const typename Vector::value_type& rhs_rowvector = **rhs_obj; \ \ if ( T::is_nonconformate_arguments( obj, rhs_obj ) ) { \ NanReturnUndefined(); \ } \ \ value BOOST_PP_CAT( OP, = ) rhs_rowvector; \ \ NanReturnValue( args.This() ); \ } \ } \ \ EIGENJS_THROW_ERROR_INVALID_ARGUMENT() \ NanReturnUndefined(); \ } \ /**/ #endif // EIGENJS_MATRIX_MACRO_HPP <|endoftext|>
<commit_before>#include "edit.h" #include "gusanos/allegro.h" //TEMP!!!!!!!!!!! #include <algorithm> #include <iostream> using std::cerr; using std::endl; namespace OmfgGUI { LuaReference Edit::metaTable; bool Edit::render() { Renderer* renderer = context()->renderer(); if(m_formatting.background.skin) { renderer->drawSkinnedBox(*m_formatting.background.skin, getRect(), m_formatting.background.color); } else { renderer->drawBox( getRect(), m_formatting.background.color, m_formatting.borders[0].color, m_formatting.borders[1].color, m_formatting.borders[2].color, m_formatting.borders[3].color); } //std::pair<int, int> dim = m_font->getDimensions(m_text.begin(), m_text.begin() + m_caretPos); assertCaretVisibility(renderer); int xoff = 5 - (int)m_hscroll; if(m_active) { std::pair<int, int> dim = renderer->getTextDimensions(*m_font, m_text.begin(), m_text.begin() + m_caretPos); if(m_selTo != m_caretPos) { std::pair<int, int> dim2 = renderer->getTextDimensions(*m_font, m_text.begin(), m_text.begin() + m_selTo); int x1 = m_rect.x1 + xoff; int x2 = x1; if(dim2.first < dim.first) x1 += dim2.first, x2 += dim.first; else x1 += dim.first, x2 += dim2.first; RGB color(50, 50, 120); renderer->drawBox(Rect(x1, m_rect.y1 + 2, x2, m_rect.y2 - 2), color, color, color, color, color); } renderer->drawVLine(m_rect.x1 + xoff + dim.first, m_rect.y1 + 2, m_rect.y2 - 2, RGB(255, 255, 255)); } if(m_font) renderer->drawText(*m_font, m_text, BaseFont::CenterV, m_rect.x1 + xoff, m_rect.centerY(), m_formatting.fontColor); return true; } void Edit::process() { if(m_caretPos > m_text.size()) m_caretPos = m_text.size(); } void Edit::setText(std::string const& aStr) { Wnd::setText(aStr); m_caretPos = std::min(m_caretPos, (ulong)m_text.size()); m_selTo = std::min(m_selTo, (ulong)m_text.size()); } void Edit::assertCaretVisibility(Renderer* renderer) { std::pair<int, int> dim = renderer->getTextDimensions(*m_font, m_text.begin(), m_text.begin() + m_caretPos); int relCaretPos = dim.first - (nit)m_hscroll; if(relCaretPos > getRect().getWidth()) { m_hscroll += relCaretPos - getRect().getWidth() + 5; } else if(relCaretPos < 0) { m_hscroll += relCaretPos; } } /* bool Edit::keyUp(int key) { return }*/ int Edit::classID() { return Context::Edit; } // TODO: Editing handlers } <commit_msg>small fix<commit_after>#include "edit.h" #include "gusanos/allegro.h" //TEMP!!!!!!!!!!! #include <algorithm> #include <iostream> using std::cerr; using std::endl; namespace OmfgGUI { LuaReference Edit::metaTable; bool Edit::render() { Renderer* renderer = context()->renderer(); if(m_formatting.background.skin) { renderer->drawSkinnedBox(*m_formatting.background.skin, getRect(), m_formatting.background.color); } else { renderer->drawBox( getRect(), m_formatting.background.color, m_formatting.borders[0].color, m_formatting.borders[1].color, m_formatting.borders[2].color, m_formatting.borders[3].color); } //std::pair<int, int> dim = m_font->getDimensions(m_text.begin(), m_text.begin() + m_caretPos); assertCaretVisibility(renderer); int xoff = 5 - (int)m_hscroll; if(m_active) { std::pair<int, int> dim = renderer->getTextDimensions(*m_font, m_text.begin(), m_text.begin() + m_caretPos); if(m_selTo != m_caretPos) { std::pair<int, int> dim2 = renderer->getTextDimensions(*m_font, m_text.begin(), m_text.begin() + m_selTo); int x1 = m_rect.x1 + xoff; int x2 = x1; if(dim2.first < dim.first) x1 += dim2.first, x2 += dim.first; else x1 += dim.first, x2 += dim2.first; RGB color(50, 50, 120); renderer->drawBox(Rect(x1, m_rect.y1 + 2, x2, m_rect.y2 - 2), color, color, color, color, color); } renderer->drawVLine(m_rect.x1 + xoff + dim.first, m_rect.y1 + 2, m_rect.y2 - 2, RGB(255, 255, 255)); } if(m_font) renderer->drawText(*m_font, m_text, BaseFont::CenterV, m_rect.x1 + xoff, m_rect.centerY(), m_formatting.fontColor); return true; } void Edit::process() { if(m_caretPos > m_text.size()) m_caretPos = m_text.size(); } void Edit::setText(std::string const& aStr) { Wnd::setText(aStr); m_caretPos = std::min(m_caretPos, (ulong)m_text.size()); m_selTo = std::min(m_selTo, (ulong)m_text.size()); } void Edit::assertCaretVisibility(Renderer* renderer) { std::pair<int, int> dim = renderer->getTextDimensions(*m_font, m_text.begin(), m_text.begin() + m_caretPos); int relCaretPos = dim.first - (int)m_hscroll; if(relCaretPos > getRect().getWidth()) { m_hscroll += relCaretPos - getRect().getWidth() + 5; } else if(relCaretPos < 0) { m_hscroll += relCaretPos; } } /* bool Edit::keyUp(int key) { return }*/ int Edit::classID() { return Context::Edit; } // TODO: Editing handlers } <|endoftext|>
<commit_before>/* Copyright 2008 Larry Gritz and the other authors and contributors. All Rights Reserved. Based on BSD-licensed software Copyright 2004 NVIDIA Corp. 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 software's owners 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. (This is the Modified BSD License) */ #include <cassert> #include <cstdio> #include <vector> extern "C" { #include "jpeglib.h" } #include "imageio.h" #include "fmath.h" #include "jpeg_pvt.h" OIIO_PLUGIN_NAMESPACE_BEGIN using namespace OpenImageIO; using namespace Jpeg_imageio_pvt; #define DBG if(0) // See JPEG library documentation in /usr/share/doc/libjpeg-devel-6b class JpgOutput : public ImageOutput { public: JpgOutput () { init(); } virtual ~JpgOutput () { close(); } virtual const char * format_name (void) const { return "jpeg"; } virtual bool supports (const std::string &property) const { return false; } virtual bool open (const std::string &name, const ImageSpec &spec, OpenMode mode=Create); virtual bool write_scanline (int y, int z, TypeDesc format, const void *data, stride_t xstride); virtual bool close (); virtual bool copy_image (ImageInput *in); private: FILE *m_fd; std::string m_filename; int m_next_scanline; // Which scanline is the next to write? std::vector<unsigned char> m_scratch; struct jpeg_compress_struct m_cinfo; struct jpeg_error_mgr c_jerr; jvirt_barray_ptr *m_copy_coeffs; struct jpeg_decompress_struct *m_copy_decompressor; void init (void) { m_fd = NULL; m_copy_coeffs = NULL; m_copy_decompressor = NULL; } }; OIIO_PLUGIN_EXPORTS_BEGIN DLLEXPORT ImageOutput *jpeg_output_imageio_create () { return new JpgOutput; } DLLEXPORT const char *jpeg_output_extensions[] = { "jpg", "jpe", "jpeg", NULL }; OIIO_PLUGIN_EXPORTS_END bool JpgOutput::open (const std::string &name, const ImageSpec &newspec, OpenMode mode) { if (mode != Create) { error ("%s does not support subimages or MIP levels", format_name()); return false; } // Save name and spec for later use m_filename = name; m_spec = newspec; // Check for things this format doesn't support if (m_spec.width < 1 || m_spec.height < 1) { error ("Image resolution must be at least 1x1, you asked for %d x %d", m_spec.width, m_spec.height); return false; } if (m_spec.depth < 1) m_spec.depth = 1; if (m_spec.depth > 1) { error ("%s does not support volume images (depth > 1)", format_name()); return false; } m_fd = fopen (name.c_str(), "wb"); if (m_fd == NULL) { error ("Unable to open file \"%s\"", name.c_str()); return false; } int quality = 98; const ImageIOParameter *qual = newspec.find_attribute ("CompressionQuality", TypeDesc::INT); if (qual) quality = * (const int *)qual->data(); m_cinfo.err = jpeg_std_error (&c_jerr); // set error handler jpeg_create_compress (&m_cinfo); // create compressor jpeg_stdio_dest (&m_cinfo, m_fd); // set output stream // Set image and compression parameters m_cinfo.image_width = m_spec.width; m_cinfo.image_height = m_spec.height; if (m_spec.nchannels == 3 || m_spec.nchannels == 4) { m_cinfo.input_components = 3; m_cinfo.in_color_space = JCS_RGB; m_spec.nchannels = 3; // Force RGBA -> RGB m_spec.alpha_channel = -1; // No alpha channel } else if (m_spec.nchannels == 1) { m_cinfo.input_components = 1; m_cinfo.in_color_space = JCS_GRAYSCALE; } m_cinfo.density_unit = 2; // RESUNIT_INCH; m_cinfo.X_density = 72; m_cinfo.Y_density = 72; m_cinfo.write_JFIF_header = true; if (m_copy_coeffs) { // Back door for copy() jpeg_copy_critical_parameters (m_copy_decompressor, &m_cinfo); DBG std::cout << "out open: copy_critical_parameters\n"; jpeg_write_coefficients (&m_cinfo, m_copy_coeffs); DBG std::cout << "out open: write_coefficients\n"; } else { // normal write of scanlines jpeg_set_defaults (&m_cinfo); // default compression DBG std::cout << "out open: set_defaults\n"; jpeg_set_quality (&m_cinfo, quality, TRUE); // baseline values DBG std::cout << "out open: set_quality\n"; jpeg_start_compress (&m_cinfo, TRUE); // start working DBG std::cout << "out open: start_compress\n"; } m_next_scanline = 0; // next scanline we'll write // Write JPEG comment, if sent an 'ImageDescription' ImageIOParameter *comment = m_spec.find_attribute ("ImageDescription", TypeDesc::STRING); if (comment && comment->data()) { const char **c = (const char **) comment->data(); jpeg_write_marker (&m_cinfo, JPEG_COM, (JOCTET*)*c, strlen(*c) + 1); } if (m_spec.linearity == ImageSpec::sRGB) m_spec.attribute ("Exif:ColorSpace", 1); // Write EXIF info, if we have anything std::vector<char> exif; encode_exif (m_spec, exif); if (exif.size()) jpeg_write_marker (&m_cinfo, JPEG_APP0+1, (JOCTET*)&exif[0], exif.size()); // Write IPTC IIM metadata tags, if we have anything std::vector<char> iptc; encode_iptc_iim (m_spec, iptc); if (iptc.size()) { static char photoshop[] = "Photoshop 3.0"; std::vector<char> head (photoshop, photoshop+strlen(photoshop)+1); static char _8BIM[] = "8BIM"; head.insert (head.end(), _8BIM, _8BIM+4); head.push_back (4); // 0x0404 head.push_back (4); head.push_back (0); // four bytes of zeroes head.push_back (0); head.push_back (0); head.push_back (0); head.push_back ((char)(iptc.size() >> 8)); // size of block head.push_back ((char)(iptc.size() & 0xff)); iptc.insert (iptc.begin(), head.begin(), head.end()); jpeg_write_marker (&m_cinfo, JPEG_APP0+13, (JOCTET*)&iptc[0], iptc.size()); } // Write XMP packet, if we have anything std::string xmp = OpenImageIO::encode_xmp (m_spec, true); if (! xmp.empty()) { static char prefix[] = "http://ns.adobe.com/xap/1.0/"; std::vector<char> block (prefix, prefix+strlen(prefix)+1); block.insert (block.end(), xmp.c_str(), xmp.c_str()+xmp.length()+1); jpeg_write_marker (&m_cinfo, JPEG_APP0+1, (JOCTET*)&block[0], block.size()); } m_spec.set_format (TypeDesc::UINT8); // JPG is only 8 bit return true; } bool JpgOutput::write_scanline (int y, int z, TypeDesc format, const void *data, stride_t xstride) { y -= m_spec.y; if (y != m_next_scanline) { error ("Attempt to write scanlines out of order to %s", m_filename.c_str()); return false; } if (y >= (int)m_cinfo.image_height) { error ("Attempt to write too many scanlines to %s", m_filename.c_str()); return false; } assert (y == (int)m_cinfo.next_scanline); data = to_native_scanline (format, data, xstride, m_scratch); jpeg_write_scanlines (&m_cinfo, (JSAMPLE**)&data, 1); ++m_next_scanline; return true; } bool JpgOutput::close () { if (! m_fd) // Already closed return true; if (m_next_scanline < spec().height && m_copy_coeffs == NULL) { // But if we've only written some scanlines, write the rest to avoid // errors std::vector<char> buf (spec().scanline_bytes(), 0); char *data = &buf[0]; while (m_next_scanline < spec().height) { jpeg_write_scanlines (&m_cinfo, (JSAMPLE **)&data, 1); // DBG std::cout << "out close: write_scanlines\n"; ++m_next_scanline; } } if (m_next_scanline >= spec().height || m_copy_coeffs) { DBG std::cout << "out close: about to finish_compress\n"; jpeg_finish_compress (&m_cinfo); DBG std::cout << "out close: finish_compress\n"; } else { DBG std::cout << "out close: about to abort_compress\n"; jpeg_abort_compress (&m_cinfo); DBG std::cout << "out close: abort_compress\n"; } DBG std::cout << "out close: about to destroy_compress\n"; jpeg_destroy_compress (&m_cinfo); fclose (m_fd); m_fd = NULL; init(); return true; } bool JpgOutput::copy_image (ImageInput *in) { if (in && !strcmp(in->format_name(), "jpeg")) { JpgInput *jpg_in = dynamic_cast<JpgInput *> (in); std::string in_name = jpg_in->filename (); DBG std::cout << "JPG copy_image from " << in_name << "\n"; // Save the original input spec and close it ImageSpec orig_in_spec = in->spec(); in->close (); DBG std::cout << "Closed old file\n"; // Re-open the input spec, with special request that the JpgInput // will recognize as a request to merely open, but not start the // decompressor. ImageSpec in_spec; ImageSpec config_spec; config_spec.attribute ("_jpeg:raw", 1); in->open (in_name, in_spec, config_spec); // Re-open the output std::string out_name = m_filename; ImageSpec orig_out_spec = spec(); close (); m_copy_coeffs = (jvirt_barray_ptr *)jpg_in->coeffs(); m_copy_decompressor = &jpg_in->m_cinfo; open (out_name, orig_out_spec); // Strangeness -- the write_coefficients somehow sets things up // so that certain writes only happen in close(), which MUST // happen while the input file is still open. So we go ahead // and close() now, so that the caller of copy_image() doesn't // close the input file first and then wonder why they crashed. close (); return true; } return ImageOutput::copy_image (in); } OIIO_PLUGIN_NAMESPACE_END <commit_msg>Fix the JPEG writer's implicit RGBA-to-RGB conversion. Was getting the strides all wrong. Review by: c42f<commit_after>/* Copyright 2008 Larry Gritz and the other authors and contributors. All Rights Reserved. Based on BSD-licensed software Copyright 2004 NVIDIA Corp. 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 software's owners 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. (This is the Modified BSD License) */ #include <cassert> #include <cstdio> #include <vector> extern "C" { #include "jpeglib.h" } #include "imageio.h" #include "fmath.h" #include "jpeg_pvt.h" OIIO_PLUGIN_NAMESPACE_BEGIN using namespace OpenImageIO; using namespace Jpeg_imageio_pvt; #define DBG if(0) // See JPEG library documentation in /usr/share/doc/libjpeg-devel-6b class JpgOutput : public ImageOutput { public: JpgOutput () { init(); } virtual ~JpgOutput () { close(); } virtual const char * format_name (void) const { return "jpeg"; } virtual bool supports (const std::string &property) const { return false; } virtual bool open (const std::string &name, const ImageSpec &spec, OpenMode mode=Create); virtual bool write_scanline (int y, int z, TypeDesc format, const void *data, stride_t xstride); virtual bool close (); virtual bool copy_image (ImageInput *in); private: FILE *m_fd; std::string m_filename; int m_next_scanline; // Which scanline is the next to write? std::vector<unsigned char> m_scratch; struct jpeg_compress_struct m_cinfo; struct jpeg_error_mgr c_jerr; jvirt_barray_ptr *m_copy_coeffs; struct jpeg_decompress_struct *m_copy_decompressor; void init (void) { m_fd = NULL; m_copy_coeffs = NULL; m_copy_decompressor = NULL; } }; OIIO_PLUGIN_EXPORTS_BEGIN DLLEXPORT ImageOutput *jpeg_output_imageio_create () { return new JpgOutput; } DLLEXPORT const char *jpeg_output_extensions[] = { "jpg", "jpe", "jpeg", NULL }; OIIO_PLUGIN_EXPORTS_END bool JpgOutput::open (const std::string &name, const ImageSpec &newspec, OpenMode mode) { if (mode != Create) { error ("%s does not support subimages or MIP levels", format_name()); return false; } // Save name and spec for later use m_filename = name; m_spec = newspec; // Check for things this format doesn't support if (m_spec.width < 1 || m_spec.height < 1) { error ("Image resolution must be at least 1x1, you asked for %d x %d", m_spec.width, m_spec.height); return false; } if (m_spec.depth < 1) m_spec.depth = 1; if (m_spec.depth > 1) { error ("%s does not support volume images (depth > 1)", format_name()); return false; } if (m_spec.nchannels != 1 && m_spec.nchannels != 3 && m_spec.nchannels != 4) { error ("%s does not support %d-channel images\n", format_name(), m_spec.nchannels); return false; } m_fd = fopen (name.c_str(), "wb"); if (m_fd == NULL) { error ("Unable to open file \"%s\"", name.c_str()); return false; } int quality = 98; const ImageIOParameter *qual = newspec.find_attribute ("CompressionQuality", TypeDesc::INT); if (qual) quality = * (const int *)qual->data(); m_cinfo.err = jpeg_std_error (&c_jerr); // set error handler jpeg_create_compress (&m_cinfo); // create compressor jpeg_stdio_dest (&m_cinfo, m_fd); // set output stream // Set image and compression parameters m_cinfo.image_width = m_spec.width; m_cinfo.image_height = m_spec.height; if (m_spec.nchannels == 3 || m_spec.nchannels == 4) { m_cinfo.input_components = 3; m_cinfo.in_color_space = JCS_RGB; } else if (m_spec.nchannels == 1) { m_cinfo.input_components = 1; m_cinfo.in_color_space = JCS_GRAYSCALE; } m_cinfo.density_unit = 2; // RESUNIT_INCH; m_cinfo.X_density = 72; m_cinfo.Y_density = 72; m_cinfo.write_JFIF_header = true; if (m_copy_coeffs) { // Back door for copy() jpeg_copy_critical_parameters (m_copy_decompressor, &m_cinfo); DBG std::cout << "out open: copy_critical_parameters\n"; jpeg_write_coefficients (&m_cinfo, m_copy_coeffs); DBG std::cout << "out open: write_coefficients\n"; } else { // normal write of scanlines jpeg_set_defaults (&m_cinfo); // default compression DBG std::cout << "out open: set_defaults\n"; jpeg_set_quality (&m_cinfo, quality, TRUE); // baseline values DBG std::cout << "out open: set_quality\n"; jpeg_start_compress (&m_cinfo, TRUE); // start working DBG std::cout << "out open: start_compress\n"; } m_next_scanline = 0; // next scanline we'll write // Write JPEG comment, if sent an 'ImageDescription' ImageIOParameter *comment = m_spec.find_attribute ("ImageDescription", TypeDesc::STRING); if (comment && comment->data()) { const char **c = (const char **) comment->data(); jpeg_write_marker (&m_cinfo, JPEG_COM, (JOCTET*)*c, strlen(*c) + 1); } if (m_spec.linearity == ImageSpec::sRGB) m_spec.attribute ("Exif:ColorSpace", 1); // Write EXIF info, if we have anything std::vector<char> exif; encode_exif (m_spec, exif); if (exif.size()) jpeg_write_marker (&m_cinfo, JPEG_APP0+1, (JOCTET*)&exif[0], exif.size()); // Write IPTC IIM metadata tags, if we have anything std::vector<char> iptc; encode_iptc_iim (m_spec, iptc); if (iptc.size()) { static char photoshop[] = "Photoshop 3.0"; std::vector<char> head (photoshop, photoshop+strlen(photoshop)+1); static char _8BIM[] = "8BIM"; head.insert (head.end(), _8BIM, _8BIM+4); head.push_back (4); // 0x0404 head.push_back (4); head.push_back (0); // four bytes of zeroes head.push_back (0); head.push_back (0); head.push_back (0); head.push_back ((char)(iptc.size() >> 8)); // size of block head.push_back ((char)(iptc.size() & 0xff)); iptc.insert (iptc.begin(), head.begin(), head.end()); jpeg_write_marker (&m_cinfo, JPEG_APP0+13, (JOCTET*)&iptc[0], iptc.size()); } // Write XMP packet, if we have anything std::string xmp = OpenImageIO::encode_xmp (m_spec, true); if (! xmp.empty()) { static char prefix[] = "http://ns.adobe.com/xap/1.0/"; std::vector<char> block (prefix, prefix+strlen(prefix)+1); block.insert (block.end(), xmp.c_str(), xmp.c_str()+xmp.length()+1); jpeg_write_marker (&m_cinfo, JPEG_APP0+1, (JOCTET*)&block[0], block.size()); } m_spec.set_format (TypeDesc::UINT8); // JPG is only 8 bit return true; } bool JpgOutput::write_scanline (int y, int z, TypeDesc format, const void *data, stride_t xstride) { y -= m_spec.y; if (y != m_next_scanline) { error ("Attempt to write scanlines out of order to %s", m_filename.c_str()); return false; } if (y >= (int)m_cinfo.image_height) { error ("Attempt to write too many scanlines to %s", m_filename.c_str()); return false; } assert (y == (int)m_cinfo.next_scanline); // It's so common to want to write RGBA data out as JPEG (which only // supports RGB) than it would be too frustrating to reject it. // Instead, we just silently drop the alpha. Here's where we do the // dirty work, temporarily doctoring the spec so that // to_native_scanline properly contiguizes the first three channels, // then we restore it. The call to to_native_scanline below needs // m_spec.nchannels to be set to the true number of channels we're // writing, or it won't arrange the data properly. But if we // doctored m_spec.nchannels = 3 permanently, then subsequent calls // to write_scanline (including any surrounding call to write_image) // with stride=AutoStride would screw up the strides since the // user's stride is actually not 3 channels. int save_nchannels = m_spec.nchannels; m_spec.nchannels = m_cinfo.input_components; data = to_native_scanline (format, data, xstride, m_scratch); m_spec.nchannels = save_nchannels; jpeg_write_scanlines (&m_cinfo, (JSAMPLE**)&data, 1); ++m_next_scanline; return true; } bool JpgOutput::close () { if (! m_fd) // Already closed return true; if (m_next_scanline < spec().height && m_copy_coeffs == NULL) { // But if we've only written some scanlines, write the rest to avoid // errors std::vector<char> buf (spec().scanline_bytes(), 0); char *data = &buf[0]; while (m_next_scanline < spec().height) { jpeg_write_scanlines (&m_cinfo, (JSAMPLE **)&data, 1); // DBG std::cout << "out close: write_scanlines\n"; ++m_next_scanline; } } if (m_next_scanline >= spec().height || m_copy_coeffs) { DBG std::cout << "out close: about to finish_compress\n"; jpeg_finish_compress (&m_cinfo); DBG std::cout << "out close: finish_compress\n"; } else { DBG std::cout << "out close: about to abort_compress\n"; jpeg_abort_compress (&m_cinfo); DBG std::cout << "out close: abort_compress\n"; } DBG std::cout << "out close: about to destroy_compress\n"; jpeg_destroy_compress (&m_cinfo); fclose (m_fd); m_fd = NULL; init(); return true; } bool JpgOutput::copy_image (ImageInput *in) { if (in && !strcmp(in->format_name(), "jpeg")) { JpgInput *jpg_in = dynamic_cast<JpgInput *> (in); std::string in_name = jpg_in->filename (); DBG std::cout << "JPG copy_image from " << in_name << "\n"; // Save the original input spec and close it ImageSpec orig_in_spec = in->spec(); in->close (); DBG std::cout << "Closed old file\n"; // Re-open the input spec, with special request that the JpgInput // will recognize as a request to merely open, but not start the // decompressor. ImageSpec in_spec; ImageSpec config_spec; config_spec.attribute ("_jpeg:raw", 1); in->open (in_name, in_spec, config_spec); // Re-open the output std::string out_name = m_filename; ImageSpec orig_out_spec = spec(); close (); m_copy_coeffs = (jvirt_barray_ptr *)jpg_in->coeffs(); m_copy_decompressor = &jpg_in->m_cinfo; open (out_name, orig_out_spec); // Strangeness -- the write_coefficients somehow sets things up // so that certain writes only happen in close(), which MUST // happen while the input file is still open. So we go ahead // and close() now, so that the caller of copy_image() doesn't // close the input file first and then wonder why they crashed. close (); return true; } return ImageOutput::copy_image (in); } OIIO_PLUGIN_NAMESPACE_END <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: rschash.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: pl $ $Date: 2001-10-10 11:51:30 $ * * 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): _______________________________________ * * ************************************************************************/ /****************** I N C L U D E S **************************************/ // C and C++ Includes. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> // Programmabhngige Includes. #ifndef _RSCHASH_HXX #include <rschash.hxx> #endif /****************** C O D E **********************************************/ /************************************************************************* |* |* HashTabel::HashTabel() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HashTabel :: HashTabel( USHORT nMaxEntries ){ nMax = nMaxEntries; // set max entries nFill = 0; // no entries lTry = 0; lAsk = 0; } /************************************************************************* |* |* HashTabel::~HashTabel() |* |* Beschreibung |* Ersterstellung MM 17.07.91 |* Letzte Aenderung MM 17.07.91 |* *************************************************************************/ HashTabel :: ~HashTabel(){ #ifdef DOS /* printf( "Maximum: %d, Fuellung: %d\n", nMax, nFill ); printf( "Anfragen: %ld, Versuche: %ld", lAsk, lTry ); if( lTry != 0 ) printf( ", V/E = %ld\n", lTry / lAsk ); */ #endif } /************************************************************************* |* |* HashTabel::Test_Insert() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HASHID HashTabel::Test_Insert( const void * pElement, BOOL bInsert ) { USHORT nHash; USHORT nIndex; USHORT nLoop; lAsk++; lTry++; nHash = HashFunc( pElement ); nIndex = nHash % nMax; nLoop = 0; // divide to range while( (nMax != nLoop) && IsEntry( nIndex ) ) { // is place occupied if( EQUAL == Compare( pElement, nIndex ) ) // is element in tabel return( nIndex ); // place of Element nLoop++; lTry++; nIndex = (USHORT)(nIndex + nHash + 7) % nMax; } if( bInsert ) { if( nMax == nLoop ) // is tabel full RscExit( 11 ); nFill++; return( nIndex ); // return free place } return( HASH_NONAME ); } /************************************************************************* |* |* HashTabel::Test() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 15.05.91 |* Letzte Aenderung MM 15.05.91 |* *************************************************************************/ HASHID HashTabel::Test( const void * pElement ){ return( Test_Insert( pElement, FALSE ) ); } /************************************************************************* |* |* HashTabel::Insert() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HASHID HashTabel::Insert( const void * pElement ){ // return free place in Tabel or the place, if Element is in the tabel return( Test_Insert( pElement, TRUE ) ); } /************************************************************************* |* |* HashString::HashString() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HashString::HashString( USHORT nMaxEntries ) : HashTabel( nMaxEntries ){ if( (long)nMaxEntries * sizeof( char * ) >= 0x10000 ){ // can't allocate more then 64k - 1 Bytes RscExit( 12 ); } // allocate ppStr = (char **)RscMem::Malloc( nMaxEntries * sizeof( char * ) ); memset( ppStr, 0, nMaxEntries * sizeof( char * ) ); paSC = new StringCon( (USHORT)40000 ); } /************************************************************************* |* |* ~HashString::HashString() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 02.06.91 |* Letzte Aenderung MM 02.06.91 |* *************************************************************************/ HashString::~HashString(){ delete paSC; RscMem::Free( (void *)ppStr ); } /************************************************************************* |* |* HashString::HashFunc() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ USHORT HashString :: HashFunc( const void * pElement ){ const char *pStr; USHORT nHash = 0; // hash value pStr = (const char *)pElement; while( *pStr ){ nHash ^= toupper( *pStr ) - 'A'; if( *++pStr ){ nHash ^= (toupper( *pStr ) - 'A') << 4; if( *++pStr ) nHash ^= (toupper( *pStr ) - 'A') << 8; } } return( nHash ); } /************************************************************************* |* |* HashString::IsEntry() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ BOOL HashString :: IsEntry( HASHID nIndex ){ // return TRUE if place is occupied // return FALSE if place is FREE // ppStr[ nIndex ] == pointer to stringtabel return( NULL != ppStr[ nIndex ] ); } /************************************************************************* |* |* HashString::Insert() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HASHID HashString :: Insert( const char * pElement ){ HASHID nIndex; nIndex = HashTabel::Insert( (const void *)pElement ); if( !IsEntry( nIndex ) )// is place not occupied ? // put string in the string tabel ppStr[ nIndex ] = paSC->Put( pElement ); return( nIndex ); } /************************************************************************* |* |* HashString::Test() |* |* Beschreibung |* Ersterstellung MM 05.11.91 |* Letzte Aenderung MM 05.11.91 |* *************************************************************************/ HASHID HashString :: Test( const char * pElement ){ return HashTabel::Test( (const void *)pElement ); } /************************************************************************* |* |* HashString::Get() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ char * HashString :: Get( HASHID nIndex ){ // return pointer to string if( nIndex != HASH_NONAME ) return( ppStr[ nIndex ] ); else return( NULL ); } /************************************************************************* |* |* HashString::Get() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ COMPARE HashString :: Compare( const void * pElement, HASHID nIndex ){ short nCmp; // Vergleichsresultat nCmp = rsc_stricmp( (const char *)pElement, ppStr[ nIndex ] ); if( 0 < nCmp ) return( GREATER ); else if( 0 == nCmp ) return( EQUAL ); else return( LESS ); } /************************************************************************* |* |* StringCon::StringCon() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ StringCon::StringCon( USHORT nMaxEntries ){ // allocate character field pField = (char * )RscMem::Malloc( nMaxEntries ); nMax = nMaxEntries; // set maximum of characters nFill = 0; // no character in tabel } /************************************************************************* |* |* StringCon::~StringCon() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 02.06.91 |* Letzte Aenderung MM 02.06.91 |* *************************************************************************/ StringCon::~StringCon(){ // free character field RscMem::Free( pField ); } /************************************************************************* |* |* StringCon::Put() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ char * StringCon :: Put( const char * pStr ) { // put string into the tabel char * pReturn = pField + nFill; // set return value while( nMax > (USHORT)(nFill +1) && *pStr ) // strcpy in tabel pField[ nFill++ ] = *pStr++; if( nMax == nFill +1 ){ // buffer overflow ? RscExit( 13 ); } else pField[ nFill++ ] = '\0'; // terminate with zero. return( pReturn ); // return pointer to string } <commit_msg>INTEGRATION: CWS mergebuild (1.2.68); FILE MERGED 2003/12/08 14:46:53 hjs 1.2.68.1: #i8252# fixed commandline problem; generic ids<commit_after>/************************************************************************* * * $RCSfile: rschash.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hjs $ $Date: 2004-06-26 20: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): _______________________________________ * * ************************************************************************/ /****************** I N C L U D E S **************************************/ // C and C++ Includes. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> // Programmabhngige Includes. #ifndef _RSCHASH_HXX #include <rschash.hxx> #endif /****************** C O D E **********************************************/ /************************************************************************* |* |* HashTabel::HashTabel() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HashTabel :: HashTabel( USHORT nMaxEntries ){ nMax = nMaxEntries; // set max entries nFill = 0; // no entries lTry = 0; lAsk = 0; } /************************************************************************* |* |* HashTabel::~HashTabel() |* |* Beschreibung |* Ersterstellung MM 17.07.91 |* Letzte Aenderung MM 17.07.91 |* *************************************************************************/ HashTabel :: ~HashTabel(){ #ifdef DOS /* printf( "Maximum: %d, Fuellung: %d\n", nMax, nFill ); printf( "Anfragen: %ld, Versuche: %ld", lAsk, lTry ); if( lTry != 0 ) printf( ", V/E = %ld\n", lTry / lAsk ); */ #endif } /************************************************************************* |* |* HashTabel::Test_Insert() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HASHID HashTabel::Test_Insert( const void * pElement, BOOL bInsert ) { USHORT nHash; USHORT nIndex; USHORT nLoop; lAsk++; lTry++; nHash = HashFunc( pElement ); nIndex = nHash % nMax; nLoop = 0; // divide to range while( (nMax != nLoop) && IsEntry( nIndex ) ) { // is place occupied if( EQUAL == Compare( pElement, nIndex ) ) // is element in tabel return( nIndex ); // place of Element nLoop++; lTry++; nIndex = (USHORT)(nIndex + nHash + 7) % nMax; } if( bInsert ) { if( nMax == nLoop ) // is tabel full RscExit( 11 ); nFill++; return( nIndex ); // return free place } return( HASH_NONAME ); } /************************************************************************* |* |* HashTabel::Test() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 15.05.91 |* Letzte Aenderung MM 15.05.91 |* *************************************************************************/ HASHID HashTabel::Test( const void * pElement ){ return( Test_Insert( pElement, FALSE ) ); } /************************************************************************* |* |* HashTabel::Insert() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HASHID HashTabel::Insert( const void * pElement ){ // return free place in Tabel or the place, if Element is in the tabel return( Test_Insert( pElement, TRUE ) ); } /************************************************************************* |* |* HashString::HashString() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HashString::HashString( USHORT nMaxEntries ) : HashTabel( nMaxEntries ){ if( (long)nMaxEntries * sizeof( char * ) >= 0x10000 ){ // can't allocate more then 64k - 1 Bytes RscExit( 12 ); } // allocate ppStr = (char **)RscMem::Malloc( nMaxEntries * sizeof( char * ) ); memset( ppStr, 0, nMaxEntries * sizeof( char * ) ); paSC = new StringCon( (USHORT)40000 ); } /************************************************************************* |* |* ~HashString::HashString() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 02.06.91 |* Letzte Aenderung MM 02.06.91 |* *************************************************************************/ HashString::~HashString(){ delete paSC; RscMem::Free( (void *)ppStr ); } /************************************************************************* |* |* HashString::HashFunc() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ USHORT HashString :: HashFunc( const void * pElement ){ return( Hash_Func( pElement )); } USHORT HashString :: Hash_Func( const void * pElement ){ const char *pStr; USHORT nHash = 0; // hash value pStr = (const char *)pElement; while( *pStr ){ nHash ^= toupper( *pStr ) - 'A'; if( *++pStr ){ nHash ^= (toupper( *pStr ) - 'A') << 4; if( *++pStr ) nHash ^= (toupper( *pStr ) - 'A') << 8; } } return( nHash ); } /************************************************************************* |* |* HashString::IsEntry() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ BOOL HashString :: IsEntry( HASHID nIndex ){ // return TRUE if place is occupied // return FALSE if place is FREE // ppStr[ nIndex ] == pointer to stringtabel return( NULL != ppStr[ nIndex ] ); } /************************************************************************* |* |* HashString::Insert() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ HASHID HashString :: Insert( const char * pElement ){ HASHID nIndex; nIndex = HashTabel::Insert( (const void *)pElement ); if( !IsEntry( nIndex ) )// is place not occupied ? // put string in the string tabel ppStr[ nIndex ] = paSC->Put( pElement ); return( nIndex ); } /************************************************************************* |* |* HashString::Test() |* |* Beschreibung |* Ersterstellung MM 05.11.91 |* Letzte Aenderung MM 05.11.91 |* *************************************************************************/ HASHID HashString :: Test( const char * pElement ){ return HashTabel::Test( (const void *)pElement ); } /************************************************************************* |* |* HashString::Get() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ char * HashString :: Get( HASHID nIndex ){ // return pointer to string if( nIndex != HASH_NONAME ) return( ppStr[ nIndex ] ); else return( NULL ); } /************************************************************************* |* |* HashString::Get() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ COMPARE HashString :: Compare( const void * pElement, HASHID nIndex ){ short nCmp; // Vergleichsresultat nCmp = rsc_stricmp( (const char *)pElement, ppStr[ nIndex ] ); if( 0 < nCmp ) return( GREATER ); else if( 0 == nCmp ) return( EQUAL ); else return( LESS ); } /************************************************************************* |* |* StringCon::StringCon() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ StringCon::StringCon( USHORT nMaxEntries ){ // allocate character field pField = (char * )RscMem::Malloc( nMaxEntries ); nMax = nMaxEntries; // set maximum of characters nFill = 0; // no character in tabel } /************************************************************************* |* |* StringCon::~StringCon() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 02.06.91 |* Letzte Aenderung MM 02.06.91 |* *************************************************************************/ StringCon::~StringCon(){ // free character field RscMem::Free( pField ); } /************************************************************************* |* |* StringCon::Put() |* |* Beschreibung HASHTAB.DOC |* Ersterstellung MM 20.03.90 |* Letzte Aenderung MM 27.06.90 |* *************************************************************************/ char * StringCon :: Put( const char * pStr ) { // put string into the tabel char * pReturn = pField + nFill; // set return value while( nMax > (USHORT)(nFill +1) && *pStr ) // strcpy in tabel pField[ nFill++ ] = *pStr++; if( nMax == nFill +1 ){ // buffer overflow ? RscExit( 13 ); } else pField[ nFill++ ] = '\0'; // terminate with zero. return( pReturn ); // return pointer to string } <|endoftext|>
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/benchmark_test.h" #include "bin/file.h" #include "platform/assert.h" #include "vm/dart_api_impl.h" #include "vm/stack_frame.h" #include "vm/unit_test.h" namespace dart { Benchmark* Benchmark::first_ = NULL; Benchmark* Benchmark::tail_ = NULL; const char* Benchmark::executable_ = NULL; void Benchmark::RunAll(const char* executable) { SetExecutable(executable); Benchmark* benchmark = first_; while (benchmark != NULL) { benchmark->RunBenchmark(); benchmark = benchmark->next_; } } // Compiler only implemented on IA32 and X64 now. #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) // // Measure compile of all functions in dart core lib classes. // BENCHMARK(CorelibCompileAll) { Timer timer(true, "Compile all of Core lib benchmark"); timer.Start(); const Error& error = Error::Handle(benchmark->isolate(), Library::CompileAll()); EXPECT(error.IsNull()); timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); benchmark->set_score(elapsed_time); } #endif // TARGET_ARCH_IA32 || TARGET_ARCH_X64 // // Measure creation of core isolate from a snapshot. // BENCHMARK(CorelibIsolateStartup) { const int kNumIterations = 100; char* err = NULL; Dart_Isolate base_isolate = Dart_CurrentIsolate(); Dart_Isolate test_isolate = Dart_CreateIsolate(NULL, NULL, NULL, NULL, &err); EXPECT(test_isolate != NULL); Dart_EnterScope(); uint8_t* buffer = NULL; intptr_t size = 0; Dart_Handle result = Dart_CreateSnapshot(&buffer, &size); EXPECT(!Dart_IsError(result)); Timer timer(true, "Core Isolate startup benchmark"); timer.Start(); for (int i = 0; i < kNumIterations; i++) { Dart_Isolate new_isolate = Dart_CreateIsolate(NULL, NULL, buffer, NULL, &err); EXPECT(new_isolate != NULL); Dart_ShutdownIsolate(); } timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); benchmark->set_score(elapsed_time / kNumIterations); Dart_EnterIsolate(test_isolate); Dart_ExitScope(); Dart_ShutdownIsolate(); Dart_EnterIsolate(base_isolate); } // // Measure invocation of Dart API functions. // static void InitNativeFields(Dart_NativeArguments args) { Dart_EnterScope(); int count = Dart_GetNativeArgumentCount(args); EXPECT_EQ(1, count); Dart_Handle recv = Dart_GetNativeArgument(args, 0); EXPECT(!Dart_IsError(recv)); Dart_Handle result = Dart_SetNativeInstanceField(recv, 0, 7); EXPECT(!Dart_IsError(result)); Dart_ExitScope(); } // The specific api functions called here are a bit arbitrary. We are // trying to get a sense of the overhead for using the dart api. static void UseDartApi(Dart_NativeArguments args) { Dart_EnterScope(); int count = Dart_GetNativeArgumentCount(args); EXPECT_EQ(3, count); // Get the receiver. Dart_Handle recv = Dart_GetNativeArgument(args, 0); EXPECT(!Dart_IsError(recv)); // Get param1. Dart_Handle param1 = Dart_GetNativeArgument(args, 1); EXPECT(!Dart_IsError(param1)); EXPECT(Dart_IsInteger(param1)); bool fits = false; Dart_Handle result = Dart_IntegerFitsIntoInt64(param1, &fits); EXPECT(!Dart_IsError(result) && fits); int64_t value1; result = Dart_IntegerToInt64(param1, &value1); EXPECT(!Dart_IsError(result)); EXPECT_LE(0, value1); EXPECT_LE(value1, 1000000); // Get native field from receiver. intptr_t value2; result = Dart_GetNativeInstanceField(recv, 0, &value2); EXPECT(!Dart_IsError(result)); EXPECT_EQ(7, value2); // Return param + receiver.field. Dart_SetReturnValue(args, Dart_NewInteger(value1 * value2)); Dart_ExitScope(); } static Dart_NativeFunction bm_uda_lookup(Dart_Handle name, int argument_count) { const char* cstr = NULL; Dart_Handle result = Dart_StringToCString(name, &cstr); EXPECT(!Dart_IsError(result)); if (strcmp(cstr, "init") == 0) { return InitNativeFields; } else { return UseDartApi; } } BENCHMARK(UseDartApi) { const int kNumIterations = 100000; const char* kScriptChars = "class Class extends NativeFieldsWrapper{\n" " int init() native 'init';\n" " int method(int param1, int param2) native 'method';\n" "}\n" "\n" "void benchmark(int count) {\n" " Class c = new Class();\n" " c.init();\n" " for (int i = 0; i < count; i++) {\n" " c.method(i,7);\n" " }\n" "}\n"; Dart_Handle lib = TestCase::LoadTestScript( kScriptChars, reinterpret_cast<Dart_NativeEntryResolver>(bm_uda_lookup)); // Create a native wrapper class with native fields. Dart_Handle result = Dart_CreateNativeWrapperClass( lib, Dart_NewString("NativeFieldsWrapper"), 1); EXPECT(!Dart_IsError(result)); Timer timer(true, "UseDartApi benchmark"); timer.Start(); Dart_Handle args[1]; args[0] = Dart_NewInteger(kNumIterations); Dart_Invoke(lib, Dart_NewString("benchmark"), 1, args); timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); benchmark->set_score(elapsed_time); } // // Measure compile of all dart2js(compiler) functions. // static char* ComputeDart2JSPath(const char* arg) { char buffer[2048]; char* dart2js_path = strdup(File::GetCanonicalPath(arg)); const char* compiler_path = "%s%slib%scompiler%scompiler.dart"; const char* path_separator = File::PathSeparator(); ASSERT(path_separator != NULL && strlen(path_separator) == 1); char* ptr = strrchr(dart2js_path, *path_separator); while (ptr != NULL) { *ptr = '\0'; OS::SNPrint(buffer, 2048, compiler_path, dart2js_path, path_separator, path_separator, path_separator); if (File::Exists(buffer)) { break; } ptr = strrchr(dart2js_path, *path_separator); } if (ptr == NULL) { free(dart2js_path); dart2js_path = NULL; } return dart2js_path; } static void func(Dart_NativeArguments args) { } static Dart_NativeFunction NativeResolver(Dart_Handle name, int arg_count) { return &func; } BENCHMARK(Dart2JSCompileAll) { char* dart_root = ComputeDart2JSPath(Benchmark::Executable()); Dart_Handle import_map; if (dart_root != NULL) { import_map = Dart_NewList(2); Dart_ListSetAt(import_map, 0, Dart_NewString("DART_ROOT")); Dart_ListSetAt(import_map, 1, Dart_NewString(dart_root)); } else { import_map = Dart_NewList(0); } const char* kScriptChars = "#import('${DART_ROOT}/lib/compiler/compiler.dart');"; Dart_Handle lib = TestCase::LoadTestScript( kScriptChars, reinterpret_cast<Dart_NativeEntryResolver>(NativeResolver), import_map); EXPECT(!Dart_IsError(lib)); Timer timer(true, "Compile all of dart2js benchmark"); timer.Start(); Dart_Handle result = Dart_CompileAll(); EXPECT(!Dart_IsError(result)); timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); benchmark->set_score(elapsed_time); free(dart_root); } // // Measure frame lookup during stack traversal. // static void StackFrame_accessFrame(Dart_NativeArguments args) { const int kNumIterations = 100; Dart_EnterScope(); Code& code = Code::Handle(); Timer timer(true, "LookupDartCode benchmark"); timer.Start(); for (int i = 0; i < kNumIterations; i++) { StackFrameIterator frames(StackFrameIterator::kDontValidateFrames); StackFrame* frame = frames.NextFrame(); while (frame != NULL) { if (frame->IsStubFrame()) { code ^= frame->LookupDartCode(); EXPECT(code.function() == Function::null()); } else if (frame->IsDartFrame()) { code ^= frame->LookupDartCode(); EXPECT(code.function() != Function::null()); } frame = frames.NextFrame(); } } timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); Dart_SetReturnValue(args, Dart_NewInteger(elapsed_time)); Dart_ExitScope(); } static Dart_NativeFunction StackFrameNativeResolver(Dart_Handle name, int arg_count) { return &StackFrame_accessFrame; } // Unit test case to verify stack frame iteration. BENCHMARK(FrameLookup) { const char* kScriptChars = "class StackFrame {" " static int accessFrame() native \"StackFrame_accessFrame\";" "} " "class First {" " First() { }" " int method1(int param) {" " if (param == 1) {" " param = method2(200);" " } else {" " param = method2(100);" " }" " return param;" " }" " int method2(int param) {" " if (param == 200) {" " return First.staticmethod(this, param);" " } else {" " return First.staticmethod(this, 10);" " }" " }" " static int staticmethod(First obj, int param) {" " if (param == 10) {" " return obj.method3(10);" " } else {" " return obj.method3(200);" " }" " }" " int method3(int param) {" " return StackFrame.accessFrame();" " }" "}" "class StackFrameTest {" " static int testMain() {" " First obj = new First();" " return obj.method1(1);" " }" "}"; Dart_Handle lib = TestCase::LoadTestScript( kScriptChars, reinterpret_cast<Dart_NativeEntryResolver>(StackFrameNativeResolver)); Dart_Handle cls = Dart_GetClass(lib, Dart_NewString("StackFrameTest")); Dart_Handle result = Dart_Invoke(cls, Dart_NewString("testMain"), 0, NULL); EXPECT_VALID(result); int64_t elapsed_time = 0; EXPECT(!Dart_IsError(Dart_IntegerToInt64(result, &elapsed_time))); benchmark->set_score(elapsed_time); } } // namespace dart <commit_msg>Increase the iteration count for the UseDartApi benchmark. Review URL: https://chromiumcodereview.appspot.com//10693034<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/benchmark_test.h" #include "bin/file.h" #include "platform/assert.h" #include "vm/dart_api_impl.h" #include "vm/stack_frame.h" #include "vm/unit_test.h" namespace dart { Benchmark* Benchmark::first_ = NULL; Benchmark* Benchmark::tail_ = NULL; const char* Benchmark::executable_ = NULL; void Benchmark::RunAll(const char* executable) { SetExecutable(executable); Benchmark* benchmark = first_; while (benchmark != NULL) { benchmark->RunBenchmark(); benchmark = benchmark->next_; } } // Compiler only implemented on IA32 and X64 now. #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) // // Measure compile of all functions in dart core lib classes. // BENCHMARK(CorelibCompileAll) { Timer timer(true, "Compile all of Core lib benchmark"); timer.Start(); const Error& error = Error::Handle(benchmark->isolate(), Library::CompileAll()); EXPECT(error.IsNull()); timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); benchmark->set_score(elapsed_time); } #endif // TARGET_ARCH_IA32 || TARGET_ARCH_X64 // // Measure creation of core isolate from a snapshot. // BENCHMARK(CorelibIsolateStartup) { const int kNumIterations = 100; char* err = NULL; Dart_Isolate base_isolate = Dart_CurrentIsolate(); Dart_Isolate test_isolate = Dart_CreateIsolate(NULL, NULL, NULL, NULL, &err); EXPECT(test_isolate != NULL); Dart_EnterScope(); uint8_t* buffer = NULL; intptr_t size = 0; Dart_Handle result = Dart_CreateSnapshot(&buffer, &size); EXPECT(!Dart_IsError(result)); Timer timer(true, "Core Isolate startup benchmark"); timer.Start(); for (int i = 0; i < kNumIterations; i++) { Dart_Isolate new_isolate = Dart_CreateIsolate(NULL, NULL, buffer, NULL, &err); EXPECT(new_isolate != NULL); Dart_ShutdownIsolate(); } timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); benchmark->set_score(elapsed_time / kNumIterations); Dart_EnterIsolate(test_isolate); Dart_ExitScope(); Dart_ShutdownIsolate(); Dart_EnterIsolate(base_isolate); } // // Measure invocation of Dart API functions. // static void InitNativeFields(Dart_NativeArguments args) { Dart_EnterScope(); int count = Dart_GetNativeArgumentCount(args); EXPECT_EQ(1, count); Dart_Handle recv = Dart_GetNativeArgument(args, 0); EXPECT(!Dart_IsError(recv)); Dart_Handle result = Dart_SetNativeInstanceField(recv, 0, 7); EXPECT(!Dart_IsError(result)); Dart_ExitScope(); } // The specific api functions called here are a bit arbitrary. We are // trying to get a sense of the overhead for using the dart api. static void UseDartApi(Dart_NativeArguments args) { Dart_EnterScope(); int count = Dart_GetNativeArgumentCount(args); EXPECT_EQ(3, count); // Get the receiver. Dart_Handle recv = Dart_GetNativeArgument(args, 0); EXPECT(!Dart_IsError(recv)); // Get param1. Dart_Handle param1 = Dart_GetNativeArgument(args, 1); EXPECT(!Dart_IsError(param1)); EXPECT(Dart_IsInteger(param1)); bool fits = false; Dart_Handle result = Dart_IntegerFitsIntoInt64(param1, &fits); EXPECT(!Dart_IsError(result) && fits); int64_t value1; result = Dart_IntegerToInt64(param1, &value1); EXPECT(!Dart_IsError(result)); EXPECT_LE(0, value1); EXPECT_LE(value1, 1000000); // Get native field from receiver. intptr_t value2; result = Dart_GetNativeInstanceField(recv, 0, &value2); EXPECT(!Dart_IsError(result)); EXPECT_EQ(7, value2); // Return param + receiver.field. Dart_SetReturnValue(args, Dart_NewInteger(value1 * value2)); Dart_ExitScope(); } static Dart_NativeFunction bm_uda_lookup(Dart_Handle name, int argument_count) { const char* cstr = NULL; Dart_Handle result = Dart_StringToCString(name, &cstr); EXPECT(!Dart_IsError(result)); if (strcmp(cstr, "init") == 0) { return InitNativeFields; } else { return UseDartApi; } } BENCHMARK(UseDartApi) { const int kNumIterations = 1000000; const char* kScriptChars = "class Class extends NativeFieldsWrapper{\n" " int init() native 'init';\n" " int method(int param1, int param2) native 'method';\n" "}\n" "\n" "void benchmark(int count) {\n" " Class c = new Class();\n" " c.init();\n" " for (int i = 0; i < count; i++) {\n" " c.method(i,7);\n" " }\n" "}\n"; Dart_Handle lib = TestCase::LoadTestScript( kScriptChars, reinterpret_cast<Dart_NativeEntryResolver>(bm_uda_lookup)); // Create a native wrapper class with native fields. Dart_Handle result = Dart_CreateNativeWrapperClass( lib, Dart_NewString("NativeFieldsWrapper"), 1); EXPECT(!Dart_IsError(result)); Timer timer(true, "UseDartApi benchmark"); timer.Start(); Dart_Handle args[1]; args[0] = Dart_NewInteger(kNumIterations); Dart_Invoke(lib, Dart_NewString("benchmark"), 1, args); timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); benchmark->set_score(elapsed_time); } // // Measure compile of all dart2js(compiler) functions. // static char* ComputeDart2JSPath(const char* arg) { char buffer[2048]; char* dart2js_path = strdup(File::GetCanonicalPath(arg)); const char* compiler_path = "%s%slib%scompiler%scompiler.dart"; const char* path_separator = File::PathSeparator(); ASSERT(path_separator != NULL && strlen(path_separator) == 1); char* ptr = strrchr(dart2js_path, *path_separator); while (ptr != NULL) { *ptr = '\0'; OS::SNPrint(buffer, 2048, compiler_path, dart2js_path, path_separator, path_separator, path_separator); if (File::Exists(buffer)) { break; } ptr = strrchr(dart2js_path, *path_separator); } if (ptr == NULL) { free(dart2js_path); dart2js_path = NULL; } return dart2js_path; } static void func(Dart_NativeArguments args) { } static Dart_NativeFunction NativeResolver(Dart_Handle name, int arg_count) { return &func; } BENCHMARK(Dart2JSCompileAll) { char* dart_root = ComputeDart2JSPath(Benchmark::Executable()); Dart_Handle import_map; if (dart_root != NULL) { import_map = Dart_NewList(2); Dart_ListSetAt(import_map, 0, Dart_NewString("DART_ROOT")); Dart_ListSetAt(import_map, 1, Dart_NewString(dart_root)); } else { import_map = Dart_NewList(0); } const char* kScriptChars = "#import('${DART_ROOT}/lib/compiler/compiler.dart');"; Dart_Handle lib = TestCase::LoadTestScript( kScriptChars, reinterpret_cast<Dart_NativeEntryResolver>(NativeResolver), import_map); EXPECT(!Dart_IsError(lib)); Timer timer(true, "Compile all of dart2js benchmark"); timer.Start(); Dart_Handle result = Dart_CompileAll(); EXPECT(!Dart_IsError(result)); timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); benchmark->set_score(elapsed_time); free(dart_root); } // // Measure frame lookup during stack traversal. // static void StackFrame_accessFrame(Dart_NativeArguments args) { const int kNumIterations = 100; Dart_EnterScope(); Code& code = Code::Handle(); Timer timer(true, "LookupDartCode benchmark"); timer.Start(); for (int i = 0; i < kNumIterations; i++) { StackFrameIterator frames(StackFrameIterator::kDontValidateFrames); StackFrame* frame = frames.NextFrame(); while (frame != NULL) { if (frame->IsStubFrame()) { code ^= frame->LookupDartCode(); EXPECT(code.function() == Function::null()); } else if (frame->IsDartFrame()) { code ^= frame->LookupDartCode(); EXPECT(code.function() != Function::null()); } frame = frames.NextFrame(); } } timer.Stop(); int64_t elapsed_time = timer.TotalElapsedTime(); Dart_SetReturnValue(args, Dart_NewInteger(elapsed_time)); Dart_ExitScope(); } static Dart_NativeFunction StackFrameNativeResolver(Dart_Handle name, int arg_count) { return &StackFrame_accessFrame; } // Unit test case to verify stack frame iteration. BENCHMARK(FrameLookup) { const char* kScriptChars = "class StackFrame {" " static int accessFrame() native \"StackFrame_accessFrame\";" "} " "class First {" " First() { }" " int method1(int param) {" " if (param == 1) {" " param = method2(200);" " } else {" " param = method2(100);" " }" " return param;" " }" " int method2(int param) {" " if (param == 200) {" " return First.staticmethod(this, param);" " } else {" " return First.staticmethod(this, 10);" " }" " }" " static int staticmethod(First obj, int param) {" " if (param == 10) {" " return obj.method3(10);" " } else {" " return obj.method3(200);" " }" " }" " int method3(int param) {" " return StackFrame.accessFrame();" " }" "}" "class StackFrameTest {" " static int testMain() {" " First obj = new First();" " return obj.method1(1);" " }" "}"; Dart_Handle lib = TestCase::LoadTestScript( kScriptChars, reinterpret_cast<Dart_NativeEntryResolver>(StackFrameNativeResolver)); Dart_Handle cls = Dart_GetClass(lib, Dart_NewString("StackFrameTest")); Dart_Handle result = Dart_Invoke(cls, Dart_NewString("testMain"), 0, NULL); EXPECT_VALID(result); int64_t elapsed_time = 0; EXPECT(!Dart_IsError(Dart_IntegerToInt64(result, &elapsed_time))); benchmark->set_score(elapsed_time); } } // namespace dart <|endoftext|>
<commit_before><commit_msg>fixed a typo<commit_after><|endoftext|>
<commit_before>#include "master.hpp" namespace factor { profiling_sample_count profiling_sample_count::record_counts() volatile { atomic::fence(); profiling_sample_count returned(sample_count, gc_sample_count, jit_sample_count, foreign_sample_count, foreign_thread_sample_count); atomic::fetch_subtract(&sample_count, returned.sample_count); atomic::fetch_subtract(&gc_sample_count, returned.gc_sample_count); atomic::fetch_subtract(&jit_sample_count, returned.jit_sample_count); atomic::fetch_subtract(&foreign_sample_count, returned.foreign_sample_count); atomic::fetch_subtract(&foreign_thread_sample_count, returned.foreign_thread_sample_count); return returned; } void profiling_sample_count::clear() volatile { sample_count = 0; gc_sample_count = 0; jit_sample_count = 0; foreign_sample_count = 0; foreign_thread_sample_count = 0; atomic::fence(); } profiling_sample::profiling_sample(factor_vm* vm, bool prolog_p, profiling_sample_count const& counts, cell thread) : counts(counts), thread(thread) { vm->record_callstack_sample(&callstack_begin, &callstack_end, prolog_p); } void factor_vm::record_sample(bool prolog_p) { profiling_sample_count counts = safepoint.sample_counts.record_counts(); if (!counts.empty()) samples.push_back(profiling_sample(this, prolog_p, counts, special_objects[OBJ_CURRENT_THREAD])); } void factor_vm::record_callstack_sample(cell* begin, cell* end, bool prolog_p) { *begin = sample_callstacks.size(); bool skip_p = prolog_p; auto recorder = [&](cell frame_top, cell size, code_block* owner, cell addr) { if (skip_p) skip_p = false; else sample_callstacks.push_back(owner->owner); }; iterate_callstack(ctx, recorder); *end = sample_callstacks.size(); std::reverse(sample_callstacks.begin() + *begin, sample_callstacks.end()); } void factor_vm::set_sampling_profiler(fixnum rate) { bool running_p = (bool)atomic::load(&sampling_profiler_p); if (rate > 0 && !running_p) start_sampling_profiler(rate); else if (rate == 0 && running_p) end_sampling_profiler(); } void factor_vm::start_sampling_profiler(fixnum rate) { samples_per_second = rate; safepoint.sample_counts.clear(); // Release the memory consumed by colleting samples. samples.clear(); samples.shrink_to_fit(); sample_callstacks.clear(); sample_callstacks.shrink_to_fit(); samples.reserve(10 * rate); sample_callstacks.reserve(100 * rate); atomic::store(&sampling_profiler_p, true); start_sampling_profiler_timer(); } void factor_vm::end_sampling_profiler() { atomic::store(&sampling_profiler_p, false); end_sampling_profiler_timer(); record_sample(false); } void factor_vm::primitive_sampling_profiler() { set_sampling_profiler(to_fixnum(ctx->pop())); } /* Allocates memory */ void factor_vm::primitive_get_samples() { if (atomic::load(&sampling_profiler_p) || samples.empty()) { ctx->push(false_object); } else { data_root<array> samples_array(allot_array(samples.size(), false_object), this); std::vector<profiling_sample>::const_iterator from_iter = samples.begin(); cell to_i = 0; for (; from_iter != samples.end(); ++from_iter, ++to_i) { data_root<array> sample(allot_array(7, false_object), this); set_array_nth(sample.untagged(), 0, tag_fixnum(from_iter->counts.sample_count)); set_array_nth(sample.untagged(), 1, tag_fixnum(from_iter->counts.gc_sample_count)); set_array_nth(sample.untagged(), 2, tag_fixnum(from_iter->counts.jit_sample_count)); set_array_nth(sample.untagged(), 3, tag_fixnum(from_iter->counts.foreign_sample_count)); set_array_nth(sample.untagged(), 4, tag_fixnum(from_iter->counts.foreign_thread_sample_count)); set_array_nth(sample.untagged(), 5, from_iter->thread); cell callstack_size = from_iter->callstack_end - from_iter->callstack_begin; data_root<array> callstack(allot_array(callstack_size, false_object), this); std::vector<cell>::const_iterator callstacks_begin = sample_callstacks.begin(), c_from_iter = callstacks_begin + from_iter->callstack_begin, c_from_iter_end = callstacks_begin + from_iter->callstack_end; cell c_to_i = 0; for (; c_from_iter != c_from_iter_end; ++c_from_iter, ++c_to_i) set_array_nth(callstack.untagged(), c_to_i, *c_from_iter); set_array_nth(sample.untagged(), 6, callstack.value()); set_array_nth(samples_array.untagged(), to_i, sample.value()); } ctx->push(samples_array.value()); } } } <commit_msg>vm: fix warning C4800: forcing value to bool<commit_after>#include "master.hpp" namespace factor { profiling_sample_count profiling_sample_count::record_counts() volatile { atomic::fence(); profiling_sample_count returned(sample_count, gc_sample_count, jit_sample_count, foreign_sample_count, foreign_thread_sample_count); atomic::fetch_subtract(&sample_count, returned.sample_count); atomic::fetch_subtract(&gc_sample_count, returned.gc_sample_count); atomic::fetch_subtract(&jit_sample_count, returned.jit_sample_count); atomic::fetch_subtract(&foreign_sample_count, returned.foreign_sample_count); atomic::fetch_subtract(&foreign_thread_sample_count, returned.foreign_thread_sample_count); return returned; } void profiling_sample_count::clear() volatile { sample_count = 0; gc_sample_count = 0; jit_sample_count = 0; foreign_sample_count = 0; foreign_thread_sample_count = 0; atomic::fence(); } profiling_sample::profiling_sample(factor_vm* vm, bool prolog_p, profiling_sample_count const& counts, cell thread) : counts(counts), thread(thread) { vm->record_callstack_sample(&callstack_begin, &callstack_end, prolog_p); } void factor_vm::record_sample(bool prolog_p) { profiling_sample_count counts = safepoint.sample_counts.record_counts(); if (!counts.empty()) samples.push_back(profiling_sample(this, prolog_p, counts, special_objects[OBJ_CURRENT_THREAD])); } void factor_vm::record_callstack_sample(cell* begin, cell* end, bool prolog_p) { *begin = sample_callstacks.size(); bool skip_p = prolog_p; auto recorder = [&](cell frame_top, cell size, code_block* owner, cell addr) { if (skip_p) skip_p = false; else sample_callstacks.push_back(owner->owner); }; iterate_callstack(ctx, recorder); *end = sample_callstacks.size(); std::reverse(sample_callstacks.begin() + *begin, sample_callstacks.end()); } void factor_vm::set_sampling_profiler(fixnum rate) { bool running_p = (atomic::load(&sampling_profiler_p) != 0); if (rate > 0 && !running_p) start_sampling_profiler(rate); else if (rate == 0 && running_p) end_sampling_profiler(); } void factor_vm::start_sampling_profiler(fixnum rate) { samples_per_second = rate; safepoint.sample_counts.clear(); // Release the memory consumed by colleting samples. samples.clear(); samples.shrink_to_fit(); sample_callstacks.clear(); sample_callstacks.shrink_to_fit(); samples.reserve(10 * rate); sample_callstacks.reserve(100 * rate); atomic::store(&sampling_profiler_p, true); start_sampling_profiler_timer(); } void factor_vm::end_sampling_profiler() { atomic::store(&sampling_profiler_p, false); end_sampling_profiler_timer(); record_sample(false); } void factor_vm::primitive_sampling_profiler() { set_sampling_profiler(to_fixnum(ctx->pop())); } /* Allocates memory */ void factor_vm::primitive_get_samples() { if (atomic::load(&sampling_profiler_p) || samples.empty()) { ctx->push(false_object); } else { data_root<array> samples_array(allot_array(samples.size(), false_object), this); std::vector<profiling_sample>::const_iterator from_iter = samples.begin(); cell to_i = 0; for (; from_iter != samples.end(); ++from_iter, ++to_i) { data_root<array> sample(allot_array(7, false_object), this); set_array_nth(sample.untagged(), 0, tag_fixnum(from_iter->counts.sample_count)); set_array_nth(sample.untagged(), 1, tag_fixnum(from_iter->counts.gc_sample_count)); set_array_nth(sample.untagged(), 2, tag_fixnum(from_iter->counts.jit_sample_count)); set_array_nth(sample.untagged(), 3, tag_fixnum(from_iter->counts.foreign_sample_count)); set_array_nth(sample.untagged(), 4, tag_fixnum(from_iter->counts.foreign_thread_sample_count)); set_array_nth(sample.untagged(), 5, from_iter->thread); cell callstack_size = from_iter->callstack_end - from_iter->callstack_begin; data_root<array> callstack(allot_array(callstack_size, false_object), this); std::vector<cell>::const_iterator callstacks_begin = sample_callstacks.begin(), c_from_iter = callstacks_begin + from_iter->callstack_begin, c_from_iter_end = callstacks_begin + from_iter->callstack_end; cell c_to_i = 0; for (; c_from_iter != c_from_iter_end; ++c_from_iter, ++c_to_i) set_array_nth(callstack.untagged(), c_to_i, *c_from_iter); set_array_nth(sample.untagged(), 6, callstack.value()); set_array_nth(samples_array.untagged(), to_i, sample.value()); } ctx->push(samples_array.value()); } } } <|endoftext|>
<commit_before>// Copyright (c) 2009 - Mozy, Inc. #include "mordor/pch.h" #include "log.h" #include <iostream> #include <boost/bind.hpp> #include <boost/regex.hpp> #include "assert.h" #include "config.h" #include "fiber.h" #include "mordor/streams/file.h" #include "mordor/string.h" #include "timer.h" namespace Mordor { static void enableLoggers(); static void enableStdoutLogging(); static void enableFileLogging(); #ifdef WINDOWS static void enableDebugLogging(); #endif static ConfigVar<std::string>::ptr g_logFatal = Config::lookup("log.fatalmask", std::string(".*"), "Regex of loggers to enable fatal for."); static ConfigVar<std::string>::ptr g_logError = Config::lookup("log.errormask", std::string(".*"), "Regex of loggers to enable error for."); static ConfigVar<std::string>::ptr g_logWarn = Config::lookup("log.warnmask", std::string(".*"), "Regex of loggers to enable warning for."); static ConfigVar<std::string>::ptr g_logInfo = Config::lookup("log.infomask", std::string(".*"), "Regex of loggers to enable info for."); static ConfigVar<std::string>::ptr g_logVerbose = Config::lookup("log.verbosemask", std::string(""), "Regex of loggers to enable verbose for."); static ConfigVar<std::string>::ptr g_logDebug = Config::lookup("log.debugmask", std::string(""), "Regex of loggers to enable debugging for."); static ConfigVar<std::string>::ptr g_logTrace = Config::lookup("log.tracemask", std::string(""), "Regex of loggers to enable trace for."); static ConfigVar<bool>::ptr g_logStdout = Config::lookup("log.stdout", false, "Log to stdout"); #ifdef WINDOWS static ConfigVar<bool>::ptr g_logDebugWindow = Config::lookup("log.debug", false, "Log to Debug Window"); #endif static ConfigVar<std::string>::ptr g_logFile = Config::lookup("log.file", std::string(""), "Log to file"); static FiberLocalStorage<bool> f_logDisabled; static unsigned long long g_start; namespace { static struct Initializer { Initializer() { g_start = TimerManager::now(); g_logFatal->monitor(&enableLoggers); g_logError->monitor(&enableLoggers); g_logWarn->monitor(&enableLoggers); g_logInfo->monitor(&enableLoggers); g_logVerbose->monitor(&enableLoggers); g_logDebug->monitor(&enableLoggers); g_logTrace->monitor(&enableLoggers); g_logFile->monitor(&enableFileLogging); g_logStdout->monitor(&enableStdoutLogging); #ifdef WINDOWS g_logDebugWindow->monitor(&enableDebugLogging); #endif } } g_init; } static void enableLogger(Logger::ptr logger, const boost::regex &fatalRegex, const boost::regex &errorRegex, const boost::regex &warnRegex, const boost::regex &infoRegex, const boost::regex &verboseRegex, const boost::regex &debugRegex, const boost::regex &traceRegex) { Log::Level level = Log::NONE; if (boost::regex_match(logger->name(), fatalRegex)) level = Log::FATAL; if (boost::regex_match(logger->name(), errorRegex)) level = Log::ERROR; if (boost::regex_match(logger->name(), warnRegex)) level = Log::WARNING; if (boost::regex_match(logger->name(), infoRegex)) level = Log::INFO; if (boost::regex_match(logger->name(), verboseRegex)) level = Log::VERBOSE; if (boost::regex_match(logger->name(), debugRegex)) level = Log::DEBUG; if (boost::regex_match(logger->name(), traceRegex)) level = Log::TRACE; if (logger->level() != level) logger->level(level, false); } static void enableLoggers() { boost::regex fatalRegex("^" + g_logFatal->val() + "$"); boost::regex errorRegex("^" + g_logError->val() + "$"); boost::regex warnRegex("^" + g_logWarn->val() + "$"); boost::regex infoRegex("^" + g_logInfo->val() + "$"); boost::regex verboseRegex("^" + g_logVerbose->val() + "$"); boost::regex debugRegex("^" + g_logDebug->val() + "$"); boost::regex traceRegex("^" + g_logTrace->val() + "$"); Log::visit(boost::bind(&enableLogger, _1, boost::cref(fatalRegex), boost::cref(errorRegex), boost::cref(warnRegex), boost::cref(infoRegex), boost::cref(verboseRegex), boost::cref(debugRegex), boost::cref(traceRegex))); } static void enableStdoutLogging() { static LogSink::ptr stdoutSink; bool log = g_logStdout->val(); if (stdoutSink.get() && !log) { Log::removeSink(stdoutSink); stdoutSink.reset(); } else if (!stdoutSink.get() && log) { stdoutSink.reset(new StdoutLogSink()); Log::addSink(stdoutSink); } } #ifdef WINDOWS static void enableDebugLogging() { static LogSink::ptr debugSink; bool log = g_logDebugWindow->val(); if (debugSink.get() && !log) { Log::removeSink(debugSink); debugSink.reset(); } else if (!debugSink.get() && log) { debugSink.reset(new DebugLogSink()); Log::addSink(debugSink); } } #endif static void enableFileLogging() { static LogSink::ptr fileSink; std::string file = g_logFile->val(); if (fileSink.get() && file.empty()) { Log::removeSink(fileSink); fileSink.reset(); } else if (!file.empty()) { if (fileSink.get()) { if (static_cast<FileLogSink*>(fileSink.get())->file() == file) return; Log::removeSink(fileSink); fileSink.reset(); } fileSink.reset(new FileLogSink(file)); Log::addSink(fileSink); } } void StdoutLogSink::log(const std::string &logger, boost::posix_time::ptime now, unsigned long long elapsed, tid_t thread, void *fiber, Log::Level level, const std::string &str, const char *file, int line) { std::ostringstream os; os << now << " " << elapsed << " " << level << " " << thread << " " << fiber << " " << logger << " " << file << ":" << line << " " << str << std::endl; std::cout << os.str(); std::cout.flush(); } #ifdef WINDOWS void DebugLogSink::log(const std::string &logger, boost::posix_time::ptime now, unsigned long long elapsed, tid_t thread, void *fiber, Log::Level level, const std::string &str, const char *file, int line) { std::wostringstream os; os << now << " " << elapsed << " " << level << " " << thread << " " << fiber << " " << toUtf16(logger) << " " << toUtf16(file) << ":" << line << " " << toUtf16(str) << std::endl; OutputDebugStringW(os.str().c_str()); } #endif FileLogSink::FileLogSink(const std::string &file) { m_stream.reset(new FileStream(file, FileStream::APPEND, FileStream::OPEN_OR_CREATE)); m_file = file; } void FileLogSink::log(const std::string &logger, boost::posix_time::ptime now, unsigned long long elapsed, tid_t thread, void *fiber, Log::Level level, const std::string &str, const char *file, int line) { std::ostringstream os; os << now << " " << elapsed << " " << level << " " << thread << " " << fiber << " " << logger << " " << file << ":" << line << " " << str << std::endl; std::string logline = os.str(); m_stream->write(logline.c_str(), logline.size()); m_stream->flush(); } static void deleteNothing(Logger *l) {} Logger::ptr Log::root() { static Logger::ptr _root(new Logger()); return _root; } Logger::ptr Log::lookup(const std::string &name) { Logger::ptr log = root(); if(name.empty() || name == ":"){ return log; } std::set<Logger::ptr, LoggerLess>::iterator it; Logger dummy(name, log); Logger::ptr dummyPtr(&dummy, &deleteNothing); size_t start = 0; std::string child_name; std::string node_name; while (start < name.size()) { size_t pos = name.find(':', start); if(pos == std::string::npos){ child_name = name.substr(start); start = name.size(); }else{ child_name = name.substr(start, pos - start); start = pos + 1; } if(child_name.empty()){ continue; } if(!node_name.empty()){ node_name += ":"; } node_name += child_name; dummyPtr->m_name = node_name; it = log->m_children.lower_bound(dummyPtr); if(it == log->m_children.end() || (*it)->m_name != node_name){ Logger::ptr child(new Logger(node_name, log)); log->m_children.insert(child); log = child; }else{ log = *it; } } return log; } void Log::visit(boost::function<void (boost::shared_ptr<Logger>)> dg) { std::list<Logger::ptr> toVisit; toVisit.push_back(root()); while (!toVisit.empty()) { Logger::ptr cur = toVisit.front(); toVisit.pop_front(); dg(cur); for (std::set<Logger::ptr, LoggerLess>::iterator it = cur->m_children.begin(); it != cur->m_children.end(); ++it) { toVisit.push_back(*it); } } } void Log::addSink(LogSink::ptr sink) { root()->addSink(sink); } void Log::removeSink(LogSink::ptr sink) { root()->removeSink(sink); } void Log::clearSinks() { root()->clearSinks(); } LogDisabler::LogDisabler() { m_disabled = !f_logDisabled; f_logDisabled = true; } LogDisabler::~LogDisabler() { if (m_disabled) f_logDisabled = false; } bool LoggerLess::operator ()(const Logger::ptr &lhs, const Logger::ptr &rhs) const { return lhs->m_name < rhs->m_name; } Logger::Logger() : m_name(":"), m_inheritSinks(false) {} Logger::Logger(const std::string &name, Logger::ptr parent) : m_name(name), m_parent(parent), m_level(Log::INFO), m_inheritSinks(true) {} bool Logger::enabled(Log::Level level) { return m_level >= level && !f_logDisabled; } void Logger::level(Log::Level level, bool propagate) { m_level = level; if (propagate) { for (std::set<Logger::ptr, LoggerLess>::iterator it(m_children.begin()); it != m_children.end(); ++it) { (*it)->level(level); } } } void Logger::removeSink(LogSink::ptr sink) { std::list<LogSink::ptr>::iterator it = std::find(m_sinks.begin(), m_sinks.end(), sink); if (it != m_sinks.end()) m_sinks.erase(it); } void Logger::log(Log::Level level, const std::string &str, const char *file, int line) { if (str.empty() || !enabled(level)) return; error_t error = lastError(); LogDisabler disable; unsigned long long elapsed = TimerManager::now() - g_start; boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); Logger::ptr _this = shared_from_this(); #ifdef WINDOWS DWORD thread = GetCurrentThreadId(); #elif defined(LINUX) pid_t thread = syscall(__NR_gettid); #else pid_t thread = getpid(); #endif void *fiber = Fiber::getThis().get(); bool somethingLogged = false; while (_this) { for (std::list<LogSink::ptr>::iterator it(_this->m_sinks.begin()); it != _this->m_sinks.end(); ++it) { somethingLogged = true; (*it)->log(m_name, now, elapsed, thread, fiber, level, str, file, line); } if (!_this->m_inheritSinks) break; _this = _this->m_parent.lock(); } // Restore lastError if (somethingLogged) lastError(error); } LogEvent::~LogEvent() { m_logger->log(m_level, m_os.str(), m_file, m_line); } static const char *levelStrs[] = { "NONE", "FATAL", "ERROR", "WARN", "INFO", "VERBOSE", "DEBUG", "TRACE", }; std::ostream &operator <<(std::ostream &os, Log::Level level) { MORDOR_ASSERT(level >= Log::FATAL && level <= Log::TRACE); return os << levelStrs[level]; } #ifdef WINDOWS static const wchar_t *levelStrsw[] = { L"NONE", L"FATAL", L"ERROR", L"WARN", L"INFO", L"VERBOSE", L"DEBUG", L"TRACE", }; std::wostream &operator <<(std::wostream &os, Log::Level level) { MORDOR_ASSERT(level >= Log::FATAL && level <= Log::TRACE); return os << levelStrsw[level]; } #endif } <commit_msg>FATAL logging is *always* enabled.<commit_after>// Copyright (c) 2009 - Mozy, Inc. #include "mordor/pch.h" #include "log.h" #include <iostream> #include <boost/bind.hpp> #include <boost/regex.hpp> #include "assert.h" #include "config.h" #include "fiber.h" #include "mordor/streams/file.h" #include "mordor/string.h" #include "timer.h" namespace Mordor { static void enableLoggers(); static void enableStdoutLogging(); static void enableFileLogging(); #ifdef WINDOWS static void enableDebugLogging(); #endif static ConfigVar<std::string>::ptr g_logError = Config::lookup("log.errormask", std::string(".*"), "Regex of loggers to enable error for."); static ConfigVar<std::string>::ptr g_logWarn = Config::lookup("log.warnmask", std::string(".*"), "Regex of loggers to enable warning for."); static ConfigVar<std::string>::ptr g_logInfo = Config::lookup("log.infomask", std::string(".*"), "Regex of loggers to enable info for."); static ConfigVar<std::string>::ptr g_logVerbose = Config::lookup("log.verbosemask", std::string(""), "Regex of loggers to enable verbose for."); static ConfigVar<std::string>::ptr g_logDebug = Config::lookup("log.debugmask", std::string(""), "Regex of loggers to enable debugging for."); static ConfigVar<std::string>::ptr g_logTrace = Config::lookup("log.tracemask", std::string(""), "Regex of loggers to enable trace for."); static ConfigVar<bool>::ptr g_logStdout = Config::lookup("log.stdout", false, "Log to stdout"); #ifdef WINDOWS static ConfigVar<bool>::ptr g_logDebugWindow = Config::lookup("log.debug", false, "Log to Debug Window"); #endif static ConfigVar<std::string>::ptr g_logFile = Config::lookup("log.file", std::string(""), "Log to file"); static FiberLocalStorage<bool> f_logDisabled; static unsigned long long g_start; namespace { static struct Initializer { Initializer() { g_start = TimerManager::now(); g_logError->monitor(&enableLoggers); g_logWarn->monitor(&enableLoggers); g_logInfo->monitor(&enableLoggers); g_logVerbose->monitor(&enableLoggers); g_logDebug->monitor(&enableLoggers); g_logTrace->monitor(&enableLoggers); g_logFile->monitor(&enableFileLogging); g_logStdout->monitor(&enableStdoutLogging); #ifdef WINDOWS g_logDebugWindow->monitor(&enableDebugLogging); #endif } } g_init; } static void enableLogger(Logger::ptr logger, const boost::regex &errorRegex, const boost::regex &warnRegex, const boost::regex &infoRegex, const boost::regex &verboseRegex, const boost::regex &debugRegex, const boost::regex &traceRegex) { Log::Level level = Log::FATAL; if (boost::regex_match(logger->name(), errorRegex)) level = Log::ERROR; if (boost::regex_match(logger->name(), warnRegex)) level = Log::WARNING; if (boost::regex_match(logger->name(), infoRegex)) level = Log::INFO; if (boost::regex_match(logger->name(), verboseRegex)) level = Log::VERBOSE; if (boost::regex_match(logger->name(), debugRegex)) level = Log::DEBUG; if (boost::regex_match(logger->name(), traceRegex)) level = Log::TRACE; if (logger->level() != level) logger->level(level, false); } static void enableLoggers() { boost::regex errorRegex("^" + g_logError->val() + "$"); boost::regex warnRegex("^" + g_logWarn->val() + "$"); boost::regex infoRegex("^" + g_logInfo->val() + "$"); boost::regex verboseRegex("^" + g_logVerbose->val() + "$"); boost::regex debugRegex("^" + g_logDebug->val() + "$"); boost::regex traceRegex("^" + g_logTrace->val() + "$"); Log::visit(boost::bind(&enableLogger, _1, boost::cref(errorRegex), boost::cref(warnRegex), boost::cref(infoRegex), boost::cref(verboseRegex), boost::cref(debugRegex), boost::cref(traceRegex))); } static void enableStdoutLogging() { static LogSink::ptr stdoutSink; bool log = g_logStdout->val(); if (stdoutSink.get() && !log) { Log::removeSink(stdoutSink); stdoutSink.reset(); } else if (!stdoutSink.get() && log) { stdoutSink.reset(new StdoutLogSink()); Log::addSink(stdoutSink); } } #ifdef WINDOWS static void enableDebugLogging() { static LogSink::ptr debugSink; bool log = g_logDebugWindow->val(); if (debugSink.get() && !log) { Log::removeSink(debugSink); debugSink.reset(); } else if (!debugSink.get() && log) { debugSink.reset(new DebugLogSink()); Log::addSink(debugSink); } } #endif static void enableFileLogging() { static LogSink::ptr fileSink; std::string file = g_logFile->val(); if (fileSink.get() && file.empty()) { Log::removeSink(fileSink); fileSink.reset(); } else if (!file.empty()) { if (fileSink.get()) { if (static_cast<FileLogSink*>(fileSink.get())->file() == file) return; Log::removeSink(fileSink); fileSink.reset(); } fileSink.reset(new FileLogSink(file)); Log::addSink(fileSink); } } void StdoutLogSink::log(const std::string &logger, boost::posix_time::ptime now, unsigned long long elapsed, tid_t thread, void *fiber, Log::Level level, const std::string &str, const char *file, int line) { std::ostringstream os; os << now << " " << elapsed << " " << level << " " << thread << " " << fiber << " " << logger << " " << file << ":" << line << " " << str << std::endl; std::cout << os.str(); std::cout.flush(); } #ifdef WINDOWS void DebugLogSink::log(const std::string &logger, boost::posix_time::ptime now, unsigned long long elapsed, tid_t thread, void *fiber, Log::Level level, const std::string &str, const char *file, int line) { std::wostringstream os; os << now << " " << elapsed << " " << level << " " << thread << " " << fiber << " " << toUtf16(logger) << " " << toUtf16(file) << ":" << line << " " << toUtf16(str) << std::endl; OutputDebugStringW(os.str().c_str()); } #endif FileLogSink::FileLogSink(const std::string &file) { m_stream.reset(new FileStream(file, FileStream::APPEND, FileStream::OPEN_OR_CREATE)); m_file = file; } void FileLogSink::log(const std::string &logger, boost::posix_time::ptime now, unsigned long long elapsed, tid_t thread, void *fiber, Log::Level level, const std::string &str, const char *file, int line) { std::ostringstream os; os << now << " " << elapsed << " " << level << " " << thread << " " << fiber << " " << logger << " " << file << ":" << line << " " << str << std::endl; std::string logline = os.str(); m_stream->write(logline.c_str(), logline.size()); m_stream->flush(); } static void deleteNothing(Logger *l) {} Logger::ptr Log::root() { static Logger::ptr _root(new Logger()); return _root; } Logger::ptr Log::lookup(const std::string &name) { Logger::ptr log = root(); if(name.empty() || name == ":"){ return log; } std::set<Logger::ptr, LoggerLess>::iterator it; Logger dummy(name, log); Logger::ptr dummyPtr(&dummy, &deleteNothing); size_t start = 0; std::string child_name; std::string node_name; while (start < name.size()) { size_t pos = name.find(':', start); if(pos == std::string::npos){ child_name = name.substr(start); start = name.size(); }else{ child_name = name.substr(start, pos - start); start = pos + 1; } if(child_name.empty()){ continue; } if(!node_name.empty()){ node_name += ":"; } node_name += child_name; dummyPtr->m_name = node_name; it = log->m_children.lower_bound(dummyPtr); if(it == log->m_children.end() || (*it)->m_name != node_name){ Logger::ptr child(new Logger(node_name, log)); log->m_children.insert(child); log = child; }else{ log = *it; } } return log; } void Log::visit(boost::function<void (boost::shared_ptr<Logger>)> dg) { std::list<Logger::ptr> toVisit; toVisit.push_back(root()); while (!toVisit.empty()) { Logger::ptr cur = toVisit.front(); toVisit.pop_front(); dg(cur); for (std::set<Logger::ptr, LoggerLess>::iterator it = cur->m_children.begin(); it != cur->m_children.end(); ++it) { toVisit.push_back(*it); } } } void Log::addSink(LogSink::ptr sink) { root()->addSink(sink); } void Log::removeSink(LogSink::ptr sink) { root()->removeSink(sink); } void Log::clearSinks() { root()->clearSinks(); } LogDisabler::LogDisabler() { m_disabled = !f_logDisabled; f_logDisabled = true; } LogDisabler::~LogDisabler() { if (m_disabled) f_logDisabled = false; } bool LoggerLess::operator ()(const Logger::ptr &lhs, const Logger::ptr &rhs) const { return lhs->m_name < rhs->m_name; } Logger::Logger() : m_name(":"), m_level(Log::INFO), m_inheritSinks(false) {} Logger::Logger(const std::string &name, Logger::ptr parent) : m_name(name), m_parent(parent), m_level(Log::INFO), m_inheritSinks(true) {} bool Logger::enabled(Log::Level level) { return level == Log::FATAL || m_level >= level && !f_logDisabled; } void Logger::level(Log::Level level, bool propagate) { m_level = level; if (propagate) { for (std::set<Logger::ptr, LoggerLess>::iterator it(m_children.begin()); it != m_children.end(); ++it) { (*it)->level(level); } } } void Logger::removeSink(LogSink::ptr sink) { std::list<LogSink::ptr>::iterator it = std::find(m_sinks.begin(), m_sinks.end(), sink); if (it != m_sinks.end()) m_sinks.erase(it); } void Logger::log(Log::Level level, const std::string &str, const char *file, int line) { if (str.empty() || !enabled(level)) return; error_t error = lastError(); LogDisabler disable; unsigned long long elapsed = TimerManager::now() - g_start; boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); Logger::ptr _this = shared_from_this(); #ifdef WINDOWS DWORD thread = GetCurrentThreadId(); #elif defined(LINUX) pid_t thread = syscall(__NR_gettid); #else pid_t thread = getpid(); #endif void *fiber = Fiber::getThis().get(); bool somethingLogged = false; while (_this) { for (std::list<LogSink::ptr>::iterator it(_this->m_sinks.begin()); it != _this->m_sinks.end(); ++it) { somethingLogged = true; (*it)->log(m_name, now, elapsed, thread, fiber, level, str, file, line); } if (!_this->m_inheritSinks) break; _this = _this->m_parent.lock(); } // Restore lastError if (somethingLogged) lastError(error); } LogEvent::~LogEvent() { m_logger->log(m_level, m_os.str(), m_file, m_line); } static const char *levelStrs[] = { "NONE", "FATAL", "ERROR", "WARN", "INFO", "VERBOSE", "DEBUG", "TRACE", }; std::ostream &operator <<(std::ostream &os, Log::Level level) { MORDOR_ASSERT(level >= Log::FATAL && level <= Log::TRACE); return os << levelStrs[level]; } #ifdef WINDOWS static const wchar_t *levelStrsw[] = { L"NONE", L"FATAL", L"ERROR", L"WARN", L"INFO", L"VERBOSE", L"DEBUG", L"TRACE", }; std::wostream &operator <<(std::wostream &os, Log::Level level) { MORDOR_ASSERT(level >= Log::FATAL && level <= Log::TRACE); return os << levelStrsw[level]; } #endif } <|endoftext|>
<commit_before>/* MicroFlo - Flow-Based Programming for microcontrollers * Copyright (c) 2013 Jon Nordby <jononor@gmail.com> * MicroFlo may be freely distributed under the MIT license * * Note: Arduino is under the LGPL license. */ #include "microflo.h" #include <string> #include <algorithm> #include <fstream> #include <time.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> #include <pty.h> #include <poll.h> namespace linux_serial { static int set_interface_attribs(int fd, int speed) { struct termios tty; if (tcgetattr(fd, &tty) < 0) { printf("Error from tcgetattr: %s\n", strerror(errno)); return -1; } cfsetospeed(&tty, (speed_t)speed); cfsetispeed(&tty, (speed_t)speed); tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */ tty.c_cflag &= ~CSIZE; tty.c_cflag |= CS8; /* 8-bit characters */ tty.c_cflag &= ~PARENB; /* no parity bit */ tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */ tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */ /* setup for non-canonical mode */ tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); tty.c_oflag &= ~OPOST; /* fetch bytes as they become available */ tty.c_cc[VMIN] = 0; tty.c_cc[VTIME] = 1; if (tcsetattr(fd, TCSANOW, &tty) != 0) { printf("Error from tcsetattr: %s\n", strerror(errno)); return -1; } return 0; } } //end namespace namespace { static const std::string SYS_GPIO_BASE = "/sys/class/gpio/"; static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } // PERFORMANCE: string-functions and file open/close for each I/O call. Consider capturing state in a class std::string read_sys_file(const std::string &path) { std::ifstream fs(path.c_str()); if (!fs){ return ""; } std::string res; fs >> res; fs.close(); return res; } bool write_sys_file(const std::string &path, const std::string &value) { std::ofstream fs(path.c_str()); if (!fs){ return false; } fs << value; fs.close(); return true; } timespec timespec_diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; } bool canRead(int fd, int timeoutUs) { const int nfds = 1; struct pollfd fds[nfds] = { { fd, POLLIN, 0 } }; struct timespec tv = { 0, 1000*timeoutUs }; const int ready = ppoll(&fds[0], nfds, &tv, NULL); return ready > 0; } } class LinuxSerialTransport : public HostTransport { public: LinuxSerialTransport(const std::string &p) : path(p) , slave(-1) , master(-1) , io(NULL) , controller(NULL) { } // implements HostTransport virtual void setup(IO *i, HostCommunication *c); virtual void runTick(); virtual void sendCommand(const uint8_t *buf, uint8_t len); private: std::string path; int slave; int master; IO *io; HostCommunication *controller; }; void LinuxSerialTransport::setup(IO *i, HostCommunication *c) { io = i; controller = c; const int ptyopened = openpty(&master, &slave, NULL, NULL, NULL); if (ptyopened != 0) { fprintf(stderr, "Failed to open PTY: %s\n", strerror(errno)); return; } // provide the slave end at @path unlink(path.c_str()); const char *devname = ttyname(slave); if (!devname) { fprintf(stderr, "Failed to get PTY name\n"); return; } const int symlinked = symlink(devname, path.c_str()); if (symlinked < 0) { fprintf(stderr, "Failed to create symlink for PTY: %s\n", strerror(errno)); } /* baudrate 115200, 8 bits, no parity, 1 stop bit */ if (master >= 0) { linux_serial::set_interface_attribs(master, B115200); } else { fprintf(stderr, "PTY master filedescriptor is invalid\n"); } } void LinuxSerialTransport::runTick() { const bool ready = canRead(master, 10); if (!ready) { return; } const size_t cmdSize = MICROFLO_CMD_SIZE; unsigned char buf[cmdSize]; const ssize_t bytesRead = read(master, buf, cmdSize); if (bytesRead > 0) { for (ssize_t i=0; i<bytesRead; i++) { controller->parseByte(buf[i]); } } } void LinuxSerialTransport::sendCommand(const uint8_t *b, uint8_t len) { // Make sure to pad to the cmd size const size_t cmdSize = MICROFLO_CMD_SIZE; char cmd[cmdSize]; for (uint8_t i=0; i<cmdSize; i++) { cmd[i] = ((i < len) ? b[i] : 0x00); } size_t written = write(master, cmd, cmdSize); //if (written != cmdSize) { // printf("Error from write: %d, %d\n", wlen, errno); //} tcdrain(master); /* delay for output */ } /** * I/O backend for embedded Linux boards/SOCs, like Raspberry PI, BeagleBone Black etc */ class LinuxIO : public IO { public: LinuxIO() { if (clock_gettime(CLOCK_MONOTONIC, &start_time) != 0) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } } ~LinuxIO() {} // Serial // TODO: support serial virtual void SerialBegin(uint8_t serialDevice, int baudrate) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } virtual long SerialDataAvailable(uint8_t serialDevice) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return 0; } virtual unsigned char SerialRead(uint8_t serialDevice) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return '\0'; } virtual void SerialWrite(uint8_t serialDevice, unsigned char b) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Pin config virtual void PinSetMode(MicroFlo::PinId pin, IO::PinMode mode) { if (!write_sys_file(SYS_GPIO_BASE+"export", std::to_string(pin))) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); return; } if (mode == IO::InputPin) { if (!write_sys_file(SYS_GPIO_BASE+"gpio"+std::to_string(pin)+"/direction", "in")) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } } else if (mode == IO::OutputPin) { if (write_sys_file(SYS_GPIO_BASE+"gpio"+std::to_string(pin)+"/direction", "out")) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } } else { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } } virtual void PinSetPullup(MicroFlo::PinId pin, IO::PullupMode mode) { // TODO: support pullup/pulldown config on common boards like RPi // Not exposed in sysfs, need to prod registers directly. // http://elinux.org/RPi_Low-level_peripherals#GPIO_Pull_Up.2FPull_Down_Register_Example MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Digital virtual void DigitalWrite(MicroFlo::PinId pin, bool val) { return gpio_write(pin, val); } virtual bool DigitalRead(MicroFlo::PinId pin) { return gpio_read(pin); } // Analog virtual long AnalogRead(MicroFlo::PinId pin) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return 0; } virtual void PwmWrite(MicroFlo::PinId pin, long dutyPercent) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Timer virtual long TimerCurrentMs() { timespec current_time; if (clock_gettime(CLOCK_MONOTONIC, &current_time) != 0) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } timespec since_start = timespec_diff(start_time, current_time); return (since_start.tv_sec*1000)+(since_start.tv_nsec/1000000); } virtual void AttachExternalInterrupt(uint8_t interrupt, IO::Interrupt::Mode mode, IOInterruptFunction func, void *user) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } private: // Assumes GPIO is set up as input bool gpio_read(int number){ std::string path = SYS_GPIO_BASE + "gpio" + std::to_string(number) + "/value"; std::string res = read_sys_file(path); if (res.empty()) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } res = rtrim(res); return res == "1"; } // Assumes GPIO is set up as output void gpio_write(int number, bool value){ std::string path = SYS_GPIO_BASE + "gpio" + std::to_string(number) + "/value"; if (!write_sys_file(path, value ? "1" : "0")) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } } private: struct timespec start_time; }; <commit_msg>linux: Always return in error paths<commit_after>/* MicroFlo - Flow-Based Programming for microcontrollers * Copyright (c) 2013 Jon Nordby <jononor@gmail.com> * MicroFlo may be freely distributed under the MIT license * * Note: Arduino is under the LGPL license. */ #include "microflo.h" #include <string> #include <algorithm> #include <fstream> #include <time.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> #include <pty.h> #include <poll.h> namespace linux_serial { static int set_interface_attribs(int fd, int speed) { struct termios tty; if (tcgetattr(fd, &tty) < 0) { printf("Error from tcgetattr: %s\n", strerror(errno)); return -1; } cfsetospeed(&tty, (speed_t)speed); cfsetispeed(&tty, (speed_t)speed); tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */ tty.c_cflag &= ~CSIZE; tty.c_cflag |= CS8; /* 8-bit characters */ tty.c_cflag &= ~PARENB; /* no parity bit */ tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */ tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */ /* setup for non-canonical mode */ tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); tty.c_oflag &= ~OPOST; /* fetch bytes as they become available */ tty.c_cc[VMIN] = 0; tty.c_cc[VTIME] = 1; if (tcsetattr(fd, TCSANOW, &tty) != 0) { printf("Error from tcsetattr: %s\n", strerror(errno)); return -1; } return 0; } } //end namespace namespace { static const std::string SYS_GPIO_BASE = "/sys/class/gpio/"; static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } // PERFORMANCE: string-functions and file open/close for each I/O call. Consider capturing state in a class std::string read_sys_file(const std::string &path) { std::ifstream fs(path.c_str()); if (!fs){ return ""; } std::string res; fs >> res; fs.close(); return res; } bool write_sys_file(const std::string &path, const std::string &value) { std::ofstream fs(path.c_str()); if (!fs){ return false; } fs << value; fs.close(); return true; } timespec timespec_diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; } bool canRead(int fd, int timeoutUs) { const int nfds = 1; struct pollfd fds[nfds] = { { fd, POLLIN, 0 } }; struct timespec tv = { 0, 1000*timeoutUs }; const int ready = ppoll(&fds[0], nfds, &tv, NULL); return ready > 0; } } class LinuxSerialTransport : public HostTransport { public: LinuxSerialTransport(std::string p) : path(p) , slave(-1) , master(-1) , io(NULL) , controller(NULL) { } // implements HostTransport virtual void setup(IO *i, HostCommunication *c); virtual void runTick(); virtual void sendCommand(const uint8_t *buf, uint8_t len); private: std::string path; int slave; int master; IO *io; HostCommunication *controller; }; void LinuxSerialTransport::setup(IO *i, HostCommunication *c) { io = i; controller = c; const int ptyopened = openpty(&master, &slave, NULL, NULL, NULL); if (ptyopened != 0) { fprintf(stderr, "Failed to open PTY: %s\n", strerror(errno)); return; } // provide the slave end at @path const char *linkname = path.c_str(); unlink(linkname); const char *devname = ttyname(slave); if (!devname) { fprintf(stderr, "Failed to get PTY name\n"); return; } const int symlinked = symlink(devname, linkname); if (symlinked < 0) { fprintf(stderr, "Failed to create symlink for PTY: %s\n", strerror(errno)); return; } /* baudrate 115200, 8 bits, no parity, 1 stop bit */ if (master >= 0) { linux_serial::set_interface_attribs(master, B115200); } else { fprintf(stderr, "PTY master filedescriptor is invalid\n"); return; } } void LinuxSerialTransport::runTick() { const bool ready = canRead(master, 10); if (!ready) { return; } const size_t cmdSize = MICROFLO_CMD_SIZE; unsigned char buf[cmdSize]; const ssize_t bytesRead = read(master, buf, cmdSize); if (bytesRead > 0) { for (ssize_t i=0; i<bytesRead; i++) { controller->parseByte(buf[i]); } } } void LinuxSerialTransport::sendCommand(const uint8_t *b, uint8_t len) { // Make sure to pad to the cmd size const size_t cmdSize = MICROFLO_CMD_SIZE; char cmd[cmdSize]; for (uint8_t i=0; i<cmdSize; i++) { cmd[i] = ((i < len) ? b[i] : 0x00); } size_t written = write(master, cmd, cmdSize); //if (written != cmdSize) { // printf("Error from write: %d, %d\n", wlen, errno); //} tcdrain(master); /* delay for output */ } /** * I/O backend for embedded Linux boards/SOCs, like Raspberry PI, BeagleBone Black etc */ class LinuxIO : public IO { public: LinuxIO() { if (clock_gettime(CLOCK_MONOTONIC, &start_time) != 0) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } } ~LinuxIO() {} // Serial // TODO: support serial virtual void SerialBegin(uint8_t serialDevice, int baudrate) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } virtual long SerialDataAvailable(uint8_t serialDevice) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return 0; } virtual unsigned char SerialRead(uint8_t serialDevice) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return '\0'; } virtual void SerialWrite(uint8_t serialDevice, unsigned char b) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Pin config virtual void PinSetMode(MicroFlo::PinId pin, IO::PinMode mode) { if (!write_sys_file(SYS_GPIO_BASE+"export", std::to_string(pin))) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); return; } if (mode == IO::InputPin) { if (!write_sys_file(SYS_GPIO_BASE+"gpio"+std::to_string(pin)+"/direction", "in")) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } } else if (mode == IO::OutputPin) { if (write_sys_file(SYS_GPIO_BASE+"gpio"+std::to_string(pin)+"/direction", "out")) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } } else { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } } virtual void PinSetPullup(MicroFlo::PinId pin, IO::PullupMode mode) { // TODO: support pullup/pulldown config on common boards like RPi // Not exposed in sysfs, need to prod registers directly. // http://elinux.org/RPi_Low-level_peripherals#GPIO_Pull_Up.2FPull_Down_Register_Example MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Digital virtual void DigitalWrite(MicroFlo::PinId pin, bool val) { return gpio_write(pin, val); } virtual bool DigitalRead(MicroFlo::PinId pin) { return gpio_read(pin); } // Analog virtual long AnalogRead(MicroFlo::PinId pin) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return 0; } virtual void PwmWrite(MicroFlo::PinId pin, long dutyPercent) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Timer virtual long TimerCurrentMs() { timespec current_time; if (clock_gettime(CLOCK_MONOTONIC, &current_time) != 0) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } timespec since_start = timespec_diff(start_time, current_time); return (since_start.tv_sec*1000)+(since_start.tv_nsec/1000000); } virtual void AttachExternalInterrupt(uint8_t interrupt, IO::Interrupt::Mode mode, IOInterruptFunction func, void *user) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } private: // Assumes GPIO is set up as input bool gpio_read(int number){ std::string path = SYS_GPIO_BASE + "gpio" + std::to_string(number) + "/value"; std::string res = read_sys_file(path); if (res.empty()) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } res = rtrim(res); return res == "1"; } // Assumes GPIO is set up as output void gpio_write(int number, bool value){ std::string path = SYS_GPIO_BASE + "gpio" + std::to_string(number) + "/value"; if (!write_sys_file(path, value ? "1" : "0")) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoFailure); } } private: struct timespec start_time; }; <|endoftext|>
<commit_before> #include "../libmmdpi/mmdpi.h" #include "../libmmdpix/mmdpix.h" //#include "../gl_xfile/gl_xfile.h" #if defined( _WIN32 ) # if defined( _DEBUG ) # pragma comment( lib, "../Debug/libmmdpi.lib" ) # pragma comment( lib, "../Debug/libmmdpix.lib" ) # else # pragma comment( lib, "../Release/libmmdpi.lib" ) # pragma comment( lib, "../Release/libmmdpix.lib" ) # endif #endif #include <iostream> #include "GL/glut.h" const int _zoom_default_ = -1024 * 2 * 0.1f;// * 16; float _y_pos_ = 11 * 0.1f; static mmdpi* p; static mmdpix* xfile; int _fps_ = 60 + 30; // +20 はラグのため int motion_flag = 0; float Zoom; float Rotate; float RotationAxis[ 3 ]; int screen_width, screen_height; int Argc; char** Argv; #include "fps.h" Fps* fps = 0x00; void end( void ); char* get_command_option( const char* option, int argc, char* argv[] ); void display( void ) { GLfloat light0pos[] = { 4.0, 16.0, -8.0, 1.0 }; glEnable( GL_DEPTH_TEST ); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); //glClearColor( 0.0, 0.0, 1.0, 1.0 ); // bule //glClearColor( 0.0, 0.2, 0.0, 1.0 ); // bule //glClearColor( 0.0, 0.0, 0.0, 1.0 ); // black //glClearColor( 1.0, 1.0, 1.0, 1.0 ); // white glClearColor( 0.5, 0.5, 0.5, 1.0 ); // gray glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glColor3d( 1.0, 0.0, 0.0 ); glLightfv( GL_LIGHT0, GL_POSITION, light0pos ); float diffuse[] = { 1.0, 1.0, 1.0, 1.0 }; float ambient[] = { 1.0, 1.0, 1.0, 1.0 }; glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse ); glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, ambient ); static float rot = 0.0f; // カメラ glMatrixMode( GL_MODELVIEW ); glPushMatrix(); { glRotatef( RotationAxis[ 0 ], 1, 0, 0 ); glRotatef( RotationAxis[ 1 ], 0, 1, 0 ); glScalef( 0.1f, 0.1f, 0.1f ); if( p ) p->draw(); } glPopMatrix(); glPushMatrix(); { glRotatef( RotationAxis[ 0 ], 1, 0, 0 ); glRotatef( RotationAxis[ 1 ] + 180.0f, 0, 1, 0 ); if( xfile ) xfile->draw(); } glPopMatrix(); glutSwapBuffers(); } void keyboard( unsigned char key, int x, int y ) { switch( key ) { case 'q': case 'Q': case '\033': /* '\033' は ESC の ASCII コード */ end(); exit( 0 ); case 'u': // fps if( fps->get_fps() < 120 ) { fps->set_fps( fps->get_fps() + 5 ); p->set_fps( fps->get_fps() ); } break; case 'd': if( fps->get_fps() > 10 ) { fps->set_fps( fps->get_fps() - 5 ); p->set_fps( fps->get_fps() ); } break; return ; default: break; } } void sp_keyboard( int key, int x, int y ) { //static float rotate = 0; //static float zoom = _zoom_default_; switch( key ) { case GLUT_KEY_PAGE_UP : _y_pos_ += 0.1f; break; case GLUT_KEY_PAGE_DOWN : _y_pos_ -= 0.1f; break; case GLUT_KEY_LEFT : Rotate += -0.05f; break; // ← case GLUT_KEY_UP : Zoom += +4; break; // ↑ case GLUT_KEY_RIGHT : Rotate += +0.05f; break; // → case GLUT_KEY_DOWN : Zoom += -4; break; // ↓ } glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( sin( Rotate ) * Zoom, _y_pos_, cos( Rotate ) * Zoom, 0, _y_pos_, 0, 0, 1, 0 ); } void idle( void ) { //glutPostRedisplay(); } void timer( int value ) { //glutTimerFunc( fps->get_wait_time() * 1000.0f, timer, 0 ); glutTimerFunc( 1000.0f / fps->get_fps(), timer, 0 ); fps->draw(); fps->update(); if( p && motion_flag && p->get_vmd( 0 ) ) { float frame = 30.0f / fps->get_mfps(); //fps->get_dframe(); // フレームを進める関数 //(MMD は1秒間に30フレームがデフォルト) // 60fpsで実行の場合、0.5frame ずつフレームにたいしてモーションを進める ( *p->get_vmd( 0 ) ) += frame; //( *p->get_vmd( 0 ) ) ++; if( p->get_vmd( 0 )->is_end() ) exit( 0 ); } mmdpiMatrix matrix; static float dy = 3.14f; //dy += 0.01f; //matrix.rotation( 0, 1, 0, dy ); //matrix.rotation( 0, 1, 0, 3.14f ); if( p ) p->set_bone_matrix( 0, matrix ); glutPostRedisplay(); } void resize( int w, int h ) { glViewport( 0, 0, w, h ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); //gluLookAt( 0.0f, _y_pos_, _zoom_default_, 0, _y_pos_, 0, 0, 1, 0 ); gluLookAt( sin( Rotate ) * Zoom, _y_pos_, cos( Rotate ) * Zoom, 0, _y_pos_, 0, 0, 1, 0 ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); // 透視投影 gluPerspective( 2.0f / 3, ( GLfloat )w / ( GLfloat )h, 1.0f, 65536.0f ); // 正投影 //glOrtho( -1.5, 1.5, -1.5, 1.5, -1.0, 1.0 ); glMatrixMode( GL_MODELVIEW ); screen_width = w; screen_height = h; } int MousePushFlag = 0; int MousePosX = 0, MousePosY = 0; void mouse_func( int button, int state, int x, int y ) { switch( button ) { case GLUT_LEFT_BUTTON: { switch( state ) { case GLUT_DOWN: { MousePushFlag = 1; MousePosX = x; MousePosY = y; } break; case GLUT_UP: { MousePushFlag = 0; } break; } } break; } } // 押してないとき void mouse_passive_func( int x, int y ) { } // 押してるとき void mouse_motion( int x, int y ) { if( MousePushFlag ) { float dy = ( float )( x - MousePosX ) / 4.0f; float dx = ( float )( y - MousePosY ) / 4.0f; MousePosX = x; MousePosY = y; RotationAxis[ 0 ] -= dx; RotationAxis[ 1 ] += dy; } } void init( int argc, char* argv[] ) { char* model_name = get_command_option( "-p", argc, argv ); if( model_name ) { p = new mmdpi(); if( p == 0x00 ) exit( 0 ); puts( model_name ); if( p->load( model_name ) ) exit( 0 ); } char* vmd_name = get_command_option( "-v", argc, argv ); if( vmd_name ) { motion_flag = 1; puts( vmd_name ); if( p->vmd_load( vmd_name ) ) motion_flag = 0; } char* xfile_name = get_command_option( "-x", argc, argv ); if( xfile_name ) { xfile = new mmdpix(); if( xfile == 0x00 ) exit( 0 ); xfile->load( xfile_name ); } char* fps_name = get_command_option( "-f", argc, argv ); if( fps_name ) { _fps_ = atoi( fps_name ); _fps_ = ( _fps_ < 6 || 480 < _fps_ )? 30.0f : _fps_ ; } fps = new Fps(); fps->set_fps( _fps_ ); if( p ) p->set_fps( _fps_ ); char* sound_name = get_command_option( "-s", argc, argv ); if( sound_name ) { system( sound_name ); } puts( "END Loading." ); } void end( void ) { delete fps; delete p; delete xfile; } char* get_command_option( const char* option, int argc, char* argv[] ) { int i; size_t option_length = strlen( option ); for( i = 0; i < argc; i ++ ) { if( strncmp( argv[ i ], option, option_length ) == 0 ) { char* r = argv[ i ] + option_length; if( *r ) return r; return argv[ i ]; } } return 0x00; } int main( int argc, char *argv[] ) { if( argc < 2 ) { printf( "argment: -p [pmd or pmx file name] \n" "argment: -v [vmd file name] \n" "argment: -x [x file name] \n" "argment: -f [fps] \n" ); return 0; } Zoom = _zoom_default_; Rotate = 0; Argc = argc; Argv = argv; glutInitWindowPosition( 200, 200 ); glutInitWindowSize( 640, 480 ); glutInit( &argc, argv ); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); glutCreateWindow( argv[ 0 ] ); glutDisplayFunc( display ); glutReshapeFunc( resize ); glutKeyboardFunc( keyboard ); glutSpecialFunc( sp_keyboard ); glutMouseFunc( mouse_func ); glutPassiveMotionFunc( mouse_passive_func ); glutMotionFunc( mouse_motion ); init( argc, argv ); //glutIdleFunc( idle ); glutTimerFunc( 1000.0f / 60.0f , timer, 0 ); glutMainLoop(); end(); return 0; } <commit_msg>Update gl_main.cpp<commit_after> #include "../libmmdpi/mmdpi.h" //#include "../libmmdpix/mmdpix.h" //#include "../gl_xfile/gl_xfile.h" #if defined( _WIN32 ) # if defined( _DEBUG ) # pragma comment( lib, "../Debug/libmmdpi.lib" ) //# pragma comment( lib, "../Debug/libmmdpix.lib" ) # else # pragma comment( lib, "../Release/libmmdpi.lib" ) //# pragma comment( lib, "../Release/libmmdpix.lib" ) # endif #endif #include <iostream> #include "GL/glut.h" const int _zoom_default_ = -1024 * 2 * 0.1f;// * 16; float _y_pos_ = 11 * 0.1f; static mmdpi* p; //static mmdpix* xfile; int _fps_ = 60 + 30; // +20 はラグのため int motion_flag = 0; float Zoom; float Rotate; float RotationAxis[ 3 ]; int screen_width, screen_height; int Argc; char** Argv; #include "fps.h" Fps* fps = 0x00; void end( void ); char* get_command_option( const char* option, int argc, char* argv[] ); void display( void ) { GLfloat light0pos[] = { 4.0, 16.0, -8.0, 1.0 }; glEnable( GL_DEPTH_TEST ); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); //glClearColor( 0.0, 0.0, 1.0, 1.0 ); // bule //glClearColor( 0.0, 0.2, 0.0, 1.0 ); // bule //glClearColor( 0.0, 0.0, 0.0, 1.0 ); // black //glClearColor( 1.0, 1.0, 1.0, 1.0 ); // white glClearColor( 0.5, 0.5, 0.5, 1.0 ); // gray glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glColor3d( 1.0, 0.0, 0.0 ); glLightfv( GL_LIGHT0, GL_POSITION, light0pos ); float diffuse[] = { 1.0, 1.0, 1.0, 1.0 }; float ambient[] = { 1.0, 1.0, 1.0, 1.0 }; glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse ); glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, ambient ); static float rot = 0.0f; // カメラ glMatrixMode( GL_MODELVIEW ); glPushMatrix(); { glRotatef( RotationAxis[ 0 ], 1, 0, 0 ); glRotatef( RotationAxis[ 1 ], 0, 1, 0 ); glScalef( 0.1f, 0.1f, 0.1f ); if( p ) p->draw(); } glPopMatrix(); glPushMatrix(); { glRotatef( RotationAxis[ 0 ], 1, 0, 0 ); glRotatef( RotationAxis[ 1 ] + 180.0f, 0, 1, 0 ); if( xfile ) xfile->draw(); } glPopMatrix(); glutSwapBuffers(); } void keyboard( unsigned char key, int x, int y ) { switch( key ) { case 'q': case 'Q': case '\033': /* '\033' は ESC の ASCII コード */ end(); exit( 0 ); case 'u': // fps if( fps->get_fps() < 120 ) { fps->set_fps( fps->get_fps() + 5 ); p->set_fps( fps->get_fps() ); } break; case 'd': if( fps->get_fps() > 10 ) { fps->set_fps( fps->get_fps() - 5 ); p->set_fps( fps->get_fps() ); } break; return ; default: break; } } void sp_keyboard( int key, int x, int y ) { //static float rotate = 0; //static float zoom = _zoom_default_; switch( key ) { case GLUT_KEY_PAGE_UP : _y_pos_ += 0.1f; break; case GLUT_KEY_PAGE_DOWN : _y_pos_ -= 0.1f; break; case GLUT_KEY_LEFT : Rotate += -0.05f; break; // ← case GLUT_KEY_UP : Zoom += +4; break; // ↑ case GLUT_KEY_RIGHT : Rotate += +0.05f; break; // → case GLUT_KEY_DOWN : Zoom += -4; break; // ↓ } glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( sin( Rotate ) * Zoom, _y_pos_, cos( Rotate ) * Zoom, 0, _y_pos_, 0, 0, 1, 0 ); } void idle( void ) { //glutPostRedisplay(); } void timer( int value ) { //glutTimerFunc( fps->get_wait_time() * 1000.0f, timer, 0 ); glutTimerFunc( 1000.0f / fps->get_fps(), timer, 0 ); fps->draw(); fps->update(); if( p && motion_flag && p->get_vmd( 0 ) ) { float frame = 30.0f / fps->get_mfps(); //fps->get_dframe(); // フレームを進める関数 //(MMD は1秒間に30フレームがデフォルト) // 60fpsで実行の場合、0.5frame ずつフレームにたいしてモーションを進める ( *p->get_vmd( 0 ) ) += frame; //( *p->get_vmd( 0 ) ) ++; if( p->get_vmd( 0 )->is_end() ) exit( 0 ); } mmdpiMatrix matrix; static float dy = 3.14f; //dy += 0.01f; //matrix.rotation( 0, 1, 0, dy ); //matrix.rotation( 0, 1, 0, 3.14f ); if( p ) p->set_bone_matrix( 0, matrix ); glutPostRedisplay(); } void resize( int w, int h ) { glViewport( 0, 0, w, h ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); //gluLookAt( 0.0f, _y_pos_, _zoom_default_, 0, _y_pos_, 0, 0, 1, 0 ); gluLookAt( sin( Rotate ) * Zoom, _y_pos_, cos( Rotate ) * Zoom, 0, _y_pos_, 0, 0, 1, 0 ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); // 透視投影 gluPerspective( 2.0f / 3, ( GLfloat )w / ( GLfloat )h, 1.0f, 65536.0f ); // 正投影 //glOrtho( -1.5, 1.5, -1.5, 1.5, -1.0, 1.0 ); glMatrixMode( GL_MODELVIEW ); screen_width = w; screen_height = h; } int MousePushFlag = 0; int MousePosX = 0, MousePosY = 0; void mouse_func( int button, int state, int x, int y ) { switch( button ) { case GLUT_LEFT_BUTTON: { switch( state ) { case GLUT_DOWN: { MousePushFlag = 1; MousePosX = x; MousePosY = y; } break; case GLUT_UP: { MousePushFlag = 0; } break; } } break; } } // 押してないとき void mouse_passive_func( int x, int y ) { } // 押してるとき void mouse_motion( int x, int y ) { if( MousePushFlag ) { float dy = ( float )( x - MousePosX ) / 4.0f; float dx = ( float )( y - MousePosY ) / 4.0f; MousePosX = x; MousePosY = y; RotationAxis[ 0 ] -= dx; RotationAxis[ 1 ] += dy; } } void init( int argc, char* argv[] ) { char* model_name = get_command_option( "-p", argc, argv ); if( model_name ) { p = new mmdpi(); if( p == 0x00 ) exit( 0 ); puts( model_name ); if( p->load( model_name ) ) exit( 0 ); } char* vmd_name = get_command_option( "-v", argc, argv ); if( vmd_name ) { motion_flag = 1; puts( vmd_name ); if( p->vmd_load( vmd_name ) ) motion_flag = 0; } /* char* xfile_name = get_command_option( "-x", argc, argv ); if( xfile_name ) { xfile = new mmdpix(); if( xfile == 0x00 ) exit( 0 ); xfile->load( xfile_name ); } */ char* fps_name = get_command_option( "-f", argc, argv ); if( fps_name ) { _fps_ = atoi( fps_name ); _fps_ = ( _fps_ < 6 || 480 < _fps_ )? 30.0f : _fps_ ; } fps = new Fps(); fps->set_fps( _fps_ ); if( p ) p->set_fps( _fps_ ); char* sound_name = get_command_option( "-s", argc, argv ); if( sound_name ) { system( sound_name ); } puts( "END Loading." ); } void end( void ) { delete fps; delete p; // delete xfile; } char* get_command_option( const char* option, int argc, char* argv[] ) { int i; size_t option_length = strlen( option ); for( i = 0; i < argc; i ++ ) { if( strncmp( argv[ i ], option, option_length ) == 0 ) { char* r = argv[ i ] + option_length; if( *r ) return r; return argv[ i ]; } } return 0x00; } int main( int argc, char *argv[] ) { if( argc < 2 ) { printf( "argment: -p [pmd or pmx file name] \n" "argment: -v [vmd file name] \n" "argment: -x [x file name] \n" "argment: -f [fps] \n" ); return 0; } Zoom = _zoom_default_; Rotate = 0; Argc = argc; Argv = argv; glutInitWindowPosition( 200, 200 ); glutInitWindowSize( 640, 480 ); glutInit( &argc, argv ); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); glutCreateWindow( argv[ 0 ] ); glutDisplayFunc( display ); glutReshapeFunc( resize ); glutKeyboardFunc( keyboard ); glutSpecialFunc( sp_keyboard ); glutMouseFunc( mouse_func ); glutPassiveMotionFunc( mouse_passive_func ); glutMotionFunc( mouse_motion ); init( argc, argv ); //glutIdleFunc( idle ); glutTimerFunc( 1000.0f / 60.0f , timer, 0 ); glutMainLoop(); end(); return 0; } <|endoftext|>
<commit_before>#include "ofApp.h" #include "control.h" namespace Software2552 { #define MAXSEND (1024*1024) shared_ptr<ofxJSON> OSCMessage::toJson(shared_ptr<ofxOscMessage> m) { if (m) { // bugbug data comes from one of http/s, string or local file but for now just a string shared_ptr<ofxJSON> p = std::make_shared<ofxJSON>(); if (p) { string output; string input = m->getArgAsString(0); if (uncompress(input.c_str(), input.size(), output)) { p->parse(output); } } return p; } return nullptr; } shared_ptr<ofxOscMessage> OSCMessage::fromJson(ofxJSON &data, const string&address) { shared_ptr<ofxOscMessage> p = std::make_shared<ofxOscMessage>(); if (p) { p->setAddress(address); // use 32 bits so we can talk to everyone easiy //bugbug if these are used find a way to parameterize //bugbug put all these items in json? or instead use them // to ignore messages, delete old ones? // even compress the small ones so more messages can use UDP string output; string input = data.getRawString(false); if (compress(input.c_str(), input.size(), output)) { p->addStringArg(output); // all data is in json } } return p; } void WriteOsc::setup(const string &hostname, int port) { sender.setup(hostname, port); startThread(); } void WriteOsc::threadedFunction() { while (1) { if (q.size() > 0) { lock(); shared_ptr<ofxOscMessage> m = q.front(); q.pop_front(); unlock(); if (m) { sender.sendMessage(*m, false); } } ofSleepMillis(10); } } // return true to ignore messages that have been added recently bool WriteOsc::ignoreDups(shared_ptr<ofxOscMessage> p, ofxJSON &data, const string&address) { // only add if its not in the list already for (int i = 0; i < memory.size(); ++i) { if (memory[i]->getAddress() == address && memory[i]->getArgAsString(0) == data.getRawString()) { return true; // ignore dup } } memory.push_front(p); if (memory.size() > 1000) { memory.erase(memory.end() - 200, memory.end());// find to the 1000 and 200 magic numbers bugbug } return false; } // add a message to be sent void WriteOsc::update(ofxJSON &data, const string&address) { if (data.size() > 0) { shared_ptr<ofxOscMessage> p = OSCMessage::fromJson(data, address); if (p) { if (checkForDups && ignoreDups(p, data, address)) { return; } lock(); q.push_front(p); //bugbub do we want to add a priority? front & back? not sure unlock(); } } } void ReadOsc::setup(int port) { receiver.setup(port); startThread(); } void ReadOsc::threadedFunction() { while (1) { // check for waiting messages while (receiver.hasWaitingMessages()) { shared_ptr<ofxOscMessage> p = std::make_shared<ofxOscMessage>(); if (p) { receiver.getNextMessage(*p); lock(); q[p->getAddress()].push_front(p); // will create a new queue if needed unlock(); } } ofSleepMillis(10); } } shared_ptr<ofxJSON> ReadOsc::get(const string&address) { shared_ptr<ofxJSON> j = nullptr; if (q.size() > 0) { lock(); MessageMap::iterator m = q.find(address); if (m != q.end() && m->second.size() > 0) { j = OSCMessage::toJson((m->second).back()); m->second.pop_back();// first in first out } unlock(); } return j; } void TCPServer::setup() { server.setup(11999); // optionally set the delimiter to something else. The delimiter in the client and the server have to be the same, default being [/TCP] server.setMessageDelimiter("\n"); startThread(); } // input data is deleted by this object at the right time (at least that is the plan) void TCPServer::update(const char * bytes, const size_t numBytes, char type, int clientID) { string buffer; if (compress(bytes, numBytes, buffer)) { // copy and compress data so caller can free passed data char *bytes2 = new char[sizeof(TCPMessage) + buffer.size()]; if (bytes2) { TCPMessage* m = (TCPMessage*)bytes2; m->numberOfBytes = sizeof(TCPMessage)+ buffer.size(); m->bytesSize = buffer.size(); //if (m->numberOfBytes > MAXSEND) { //ofLogError("TCPServer") << "too large " << m->numberOfBytes; //} m->type = type; m->clientID = clientID; m->t = 's'; memcpy_s(m->bytes, m->numberOfBytes, buffer.c_str(), buffer.size()); // hate the double buffer move bugbug go to source/sync? lock(); q.push_front(m); //bugbub do we want to add a priority? front & back? not sure unlock(); } } } // control data deletion (why we have our own thread) to avoid data copy since this code is in a Kinect crital path void TCPServer::threadedFunction() { while (1) { if (q.size() > 0) { lock(); TCPMessage* m = q.front(); q.pop_front(); unlock(); if (m) { sendbinary(m); delete m; } } ofSleepMillis(10); } } void TCPServer::sendbinary(TCPMessage *m) { if (m) { if (m->numberOfBytes > MAXSEND) { ofLogError("TCPServer::sendbinary") << "block too large " << m->numberOfBytes + " max " << MAXSEND; return; } if (m->clientID > 0) { server.sendRawBytes(m->clientID, (const char*)m, m->numberOfBytes); } else { server.sendRawBytesToAll((const char*)m, m->numberOfBytes); } } // we throttle the message sending frequency to once every 100ms ofSleepMillis(90); } char TCPClient::update(string& buffer) { char type = 0; if (tcpClient.isConnected()) { lock();// need to read one at a time to keep input organized TCPMessage* msg = (TCPMessage*)std::malloc(sizeof(TCPMessage)); if (!msg) { unlock(); return 0; } int messageSize = tcpClient.peekReceiveRawBytes((char*)msg, sizeof(TCPMessage)); //int messageSize = tcpClient.receiveRawBytes((char*)msg, sizeof(TCPMessage)+msg->numberOfBytes); if ((messageSize != sizeof(TCPMessage))) { free(msg); unlock(); ofSleepMillis(100); // maybe things will come back return 0; } if (msg->t != 's') { free(msg); unlock(); // not sure where the spurious data is coming from return 0; } if (msg->numberOfBytes > MAXSEND) { ofLogError("TCPServer::sendbinary") << "block too large " << msg->numberOfBytes + " max " << MAXSEND; free(msg); unlock(); ofSleepMillis(2000); // slow down, attack may be occuring return 0; } msg = (TCPMessage*)std::realloc(msg, msg->numberOfBytes); if (!msg) { ofSleepMillis(1000); // maybe things will come back unlock(); return 0; } //messageSize = tcpClient.receiveRawMsg((char*)msg, msg->numberOfBytes); messageSize = tcpClient.receiveRawBytes((char*)msg, msg->numberOfBytes); // if data was read if (messageSize == msg->numberOfBytes) { if (uncompress(msg->bytes, msg->bytesSize, buffer)) { type = msg->type; // data should change a litte } else { ofLogError("data ignored"); } } free(msg); unlock(); } else { if (!tcpClient.setup("127.0.0.1", 11999)) { ofSleepMillis(1000); } } return type; } void TCPClient::setup() { // optionally set the delimiter to something else. The delimiter in the client and the server have to be the same tcpClient.setMessageDelimiter("\n"); } }<commit_msg>data out of alignment<commit_after>#include "ofApp.h" #include "control.h" namespace Software2552 { #define MAXSEND (1024*1024) shared_ptr<ofxJSON> OSCMessage::toJson(shared_ptr<ofxOscMessage> m) { if (m) { // bugbug data comes from one of http/s, string or local file but for now just a string shared_ptr<ofxJSON> p = std::make_shared<ofxJSON>(); if (p) { string output; string input = m->getArgAsString(0); if (uncompress(input.c_str(), input.size(), output)) { p->parse(output); } } return p; } return nullptr; } shared_ptr<ofxOscMessage> OSCMessage::fromJson(ofxJSON &data, const string&address) { shared_ptr<ofxOscMessage> p = std::make_shared<ofxOscMessage>(); if (p) { p->setAddress(address); // use 32 bits so we can talk to everyone easiy //bugbug if these are used find a way to parameterize //bugbug put all these items in json? or instead use them // to ignore messages, delete old ones? // even compress the small ones so more messages can use UDP string output; string input = data.getRawString(false); if (compress(input.c_str(), input.size(), output)) { p->addStringArg(output); // all data is in json } } return p; } void WriteOsc::setup(const string &hostname, int port) { sender.setup(hostname, port); startThread(); } void WriteOsc::threadedFunction() { while (1) { if (q.size() > 0) { lock(); shared_ptr<ofxOscMessage> m = q.front(); q.pop_front(); unlock(); if (m) { sender.sendMessage(*m, false); } } ofSleepMillis(10); } } // return true to ignore messages that have been added recently bool WriteOsc::ignoreDups(shared_ptr<ofxOscMessage> p, ofxJSON &data, const string&address) { // only add if its not in the list already for (int i = 0; i < memory.size(); ++i) { if (memory[i]->getAddress() == address && memory[i]->getArgAsString(0) == data.getRawString()) { return true; // ignore dup } } memory.push_front(p); if (memory.size() > 1000) { memory.erase(memory.end() - 200, memory.end());// find to the 1000 and 200 magic numbers bugbug } return false; } // add a message to be sent void WriteOsc::update(ofxJSON &data, const string&address) { if (data.size() > 0) { shared_ptr<ofxOscMessage> p = OSCMessage::fromJson(data, address); if (p) { if (checkForDups && ignoreDups(p, data, address)) { return; } lock(); q.push_front(p); //bugbub do we want to add a priority? front & back? not sure unlock(); } } } void ReadOsc::setup(int port) { receiver.setup(port); startThread(); } void ReadOsc::threadedFunction() { while (1) { // check for waiting messages while (receiver.hasWaitingMessages()) { shared_ptr<ofxOscMessage> p = std::make_shared<ofxOscMessage>(); if (p) { receiver.getNextMessage(*p); lock(); q[p->getAddress()].push_front(p); // will create a new queue if needed unlock(); } } ofSleepMillis(10); } } shared_ptr<ofxJSON> ReadOsc::get(const string&address) { shared_ptr<ofxJSON> j = nullptr; if (q.size() > 0) { lock(); MessageMap::iterator m = q.find(address); if (m != q.end() && m->second.size() > 0) { j = OSCMessage::toJson((m->second).back()); m->second.pop_back();// first in first out } unlock(); } return j; } void TCPServer::setup() { server.setup(11999); // optionally set the delimiter to something else. The delimiter in the client and the server have to be the same, default being [/TCP] //server.setMessageDelimiter("\n"); startThread(); } // input data is deleted by this object at the right time (at least that is the plan) void TCPServer::update(const char * bytes, const size_t numBytes, char type, int clientID) { string buffer; if (compress(bytes, numBytes, buffer)) { // copy and compress data so caller can free passed data //buffer = "hi"; char *bytes2 = new char[sizeof(TCPMessage) + buffer.size()]; if (bytes2) { TCPMessage* m = (TCPMessage*)bytes2; m->numberOfBytes = sizeof(TCPMessage)+ buffer.size()-1; m->bytesSize = buffer.size(); m->type = type; m->clientID = clientID; m->t = 's'; memcpy_s(m->bytes, m->bytesSize, buffer.c_str(), buffer.size()); // hate the double buffer move bugbug go to source/sync? lock(); q.push_front(m); //bugbub do we want to add a priority? front & back? not sure unlock(); } } } // control data deletion (why we have our own thread) to avoid data copy since this code is in a Kinect crital path void TCPServer::threadedFunction() { while (1) { if (q.size() > 0) { lock(); TCPMessage* m = q.front(); q.pop_front(); unlock(); if (m) { sendbinary(m); delete m; } } ofSleepMillis(10); } } void TCPServer::sendbinary(TCPMessage *m) { if (m) { if (m->numberOfBytes > MAXSEND) { ofLogError("TCPServer::sendbinary") << "block too large " << m->numberOfBytes + " max " << MAXSEND; return; } if (m->clientID > 0) { server.sendRawBytes(m->clientID, (const char*)m, m->numberOfBytes); } else { server.sendRawBytesToAll((const char*)m, m->numberOfBytes); } } // we throttle the message sending frequency to once every 100ms ofSleepMillis(90); } char TCPClient::update(string& buffer) { char type = 0; if (tcpClient.isConnected()) { lock();// need to read one at a time to keep input organized TCPMessage* msg = (TCPMessage*)std::malloc(sizeof(TCPMessage)); if (!msg) { unlock(); return 0; } int messageSize = tcpClient.peekReceiveRawBytes((char*)msg, sizeof(TCPMessage)); //int messageSize = tcpClient.receiveRawBytes((char*)msg, sizeof(TCPMessage)+msg->numberOfBytes); if ((messageSize != sizeof(TCPMessage))) { free(msg); unlock(); ofSleepMillis(100); // maybe things will come back return 0; } if (msg->t != 's') { free(msg); unlock(); // not sure where the spurious data is coming from return 0; } if (msg->numberOfBytes > MAXSEND) { ofLogError("TCPServer::sendbinary") << "block too large " << msg->numberOfBytes + " max " << MAXSEND; free(msg); unlock(); ofSleepMillis(2000); // slow down, attack may be occuring return 0; } msg = (TCPMessage*)std::realloc(msg, msg->numberOfBytes); if (!msg) { ofSleepMillis(1000); // maybe things will come back unlock(); return 0; } //messageSize = tcpClient.receiveRawMsg((char*)msg, msg->numberOfBytes); messageSize = tcpClient.receiveRawBytes((char*)msg, msg->numberOfBytes); // if data was read if (messageSize == msg->numberOfBytes) { if (uncompress(msg->bytes, msg->bytesSize, buffer)) { type = msg->type; // data should change a litte } else { ofLogError("data ignored"); } } free(msg); unlock(); } else { if (!tcpClient.setup("127.0.0.1", 11999)) { ofSleepMillis(1000); } } return type; } void TCPClient::setup() { // optionally set the delimiter to something else. The delimiter in the client and the server have to be the same //tcpClient.setMessageDelimiter("\n"); } }<|endoftext|>
<commit_before>#include <cassert> #include <cmath> #include <iostream> #include <iomanip> #include "disassembler.h" namespace ceos { Disassembler::Disassembler(std::stringstream &&bytecode): m_bytecode(std::move(bytecode)) { auto size = m_bytecode.str().length(); m_width = std::ceil(std::log10(size + 1)) + 1; } Disassembler::HelperStream Disassembler::write(int offset) { std::cout << "[" << std::setfill(' ') << std::setw(m_width) << ((int)m_bytecode.tellg() - (offset * WORD_SIZE)) << "] " << m_padding; return HelperStream(); } int64_t Disassembler::read() { int64_t value; m_bytecode.read(reinterpret_cast<char *>(&value), sizeof(value)); return value; } std::string Disassembler::readStr() { std::stringstream dest; m_bytecode.get(*dest.rdbuf(), '\0'); m_bytecode.clear(); m_bytecode.ignore(1); return dest.str(); } int Disassembler::calculateJmpTarget(int target) { return (int)m_bytecode.tellg() - (2 * WORD_SIZE) + target; } void Disassembler::dump() { auto ceos = read(); assert(ceos == Section::Header); dumpStrings(); dumpFunctions(); dumpText(); } void Disassembler::dumpStrings() { assert(read() == Section::Strings); m_padding = ""; write(1) << "STRINGS:"; m_padding = " "; unsigned str_index = 0; while (true) { auto ceos = read(); if (ceos == Section::Header) { return; } m_bytecode.seekg(-sizeof(ceos), m_bytecode.cur); auto str = readStr(); while (m_bytecode.peek() == '\1') { m_bytecode.get(); } m_strings.push_back(str); write((float)(str.length() + 1)/WORD_SIZE) << "$" << str_index++ << ": " << str; } } void Disassembler::dumpFunctions() { assert(read() == Section::Functions); m_padding = ""; write(1) << "FUNCTIONS:"; m_padding = " "; while (true) { auto header = read(); if (header == Section::Header) { return; } assert(header == Section::FunctionHeader); auto fnID = read(); auto argCount = read(); m_functions.push_back(m_strings[fnID]); std::stringstream args; for (int i = 0; i < argCount; i++) { auto argID = read(); if (i) args << ", "; args << "$" << i << ": " << m_strings[argID]; } m_padding = ""; write(2 + argCount) << m_strings[fnID] << "(" << args.str() << "):"; m_padding = " "; while (true) { auto header = read(); m_bytecode.seekg(-sizeof(header), m_bytecode.cur); if (header == Section::FunctionHeader || header == Section::Header) { break; } auto opcode = read(); printOpcode(static_cast<Opcode::Type>(opcode)); } } } void Disassembler::dumpText() { assert(read() == Section::Text); m_padding = ""; write(1) << "TEXT:"; m_padding = " "; // skip size of lookup table m_bytecode.seekg(WORD_SIZE, m_bytecode.cur); while (true) { auto opcode = read(); if (m_bytecode.eof() || m_bytecode.fail()) { break; } printOpcode(static_cast<Opcode::Type>(opcode)); } } void Disassembler::printOpcode(Opcode::Type opcode) { switch (opcode) { case Opcode::push: { auto value = read(); write(1) << "push 0x" << std::setbase(16) << value << std::setbase(10); break; } case Opcode::call: { auto argc = read(); write(1) << "call (" << argc << ")"; break; } case Opcode::load_string: { auto stringID = read(); write(1) << "load_string $" << m_strings[stringID]; break; } case Opcode::lookup: { auto symbol = read(); auto cacheSlot = read(); write(2) << "lookup $" << symbol << "(" << m_strings[symbol] << ") [cacheSlot=" << cacheSlot << "]"; break; } case Opcode::create_closure: { auto fnID = read(); auto capturesScope = read() ? "true" : "false"; write(2) << "create_closure " << m_functions[fnID] << " [capturesScope=" << capturesScope << "]"; break; } case Opcode::jmp: { auto target = read(); write(1) << "jmp [" << calculateJmpTarget(target) << "]"; break; } case Opcode::jz: { auto target = read(); write(1) << "jz [" << calculateJmpTarget(target) << "]"; break; } case Opcode::push_arg: { auto argID = read(); write(1) << "push_arg $" << argID; break; } case Opcode::put_to_scope: { auto argID = read(); write(1) << "put_to_scope $" << m_strings[argID]; break; } case Opcode::bind: { auto stringID = read(); write(1) << "bind $" << m_strings[stringID]; break; } case Opcode::alloc_obj: { auto size = read(); auto tag = read(); write(2) << "alloc_obj (size=" << size << ", tag=" << tag << ")"; break; } case Opcode::alloc_list: { auto size = read(); write(1) << "alloc_list (size=" << size << ")"; break; } case Opcode::obj_store_at: { auto index = read(); write(1) << "obj_store_at #" << index; break; } case Opcode::obj_tag_test: { auto tag = read(); write(1) << "obj_tag_test #" << tag; break; } case Opcode::obj_load: { auto offset = read(); write(1) << "obj_load #" << offset; break; } case Opcode::stack_alloc: { auto size = read(); write(1) << "stack_alloc #" << size; break; } case Opcode::stack_store: { auto slot = read(); write(1) << "stack_store #" << slot; break; } case Opcode::stack_load: { auto slot = read(); write(1) << "stack_load #" << slot; break; } case Opcode::stack_free: { auto size = read(); write(1) << "stack_free #" << size; break; } default: write() << Opcode::typeName(static_cast<Opcode::Type>(opcode)); } } } <commit_msg>Fix disassembler when optional sections are ommited<commit_after>#include <cassert> #include <cmath> #include <iostream> #include <iomanip> #include "disassembler.h" namespace ceos { Disassembler::Disassembler(std::stringstream &&bytecode): m_bytecode(std::move(bytecode)) { auto size = m_bytecode.str().length(); m_width = std::ceil(std::log10(size + 1)) + 1; } Disassembler::HelperStream Disassembler::write(int offset) { std::cout << "[" << std::setfill(' ') << std::setw(m_width) << ((int)m_bytecode.tellg() - (offset * WORD_SIZE)) << "] " << m_padding; return HelperStream(); } int64_t Disassembler::read() { int64_t value; m_bytecode.read(reinterpret_cast<char *>(&value), sizeof(value)); return value; } std::string Disassembler::readStr() { std::stringstream dest; m_bytecode.get(*dest.rdbuf(), '\0'); m_bytecode.clear(); m_bytecode.ignore(1); return dest.str(); } int Disassembler::calculateJmpTarget(int target) { return (int)m_bytecode.tellg() - (2 * WORD_SIZE) + target; } void Disassembler::dump() { auto ceos = read(); assert(ceos == Section::Header); dumpStrings(); dumpFunctions(); dumpText(); assert(m_bytecode.eof()); } void Disassembler::dumpStrings() { auto header = read(); if (header != Section::Strings) { m_bytecode.seekg(-sizeof(header), m_bytecode.cur); return; } m_padding = ""; write(2) << "STRINGS:"; m_padding = " "; unsigned str_index = 0; while (true) { auto ceos = read(); if (ceos == Section::Header) { return; } m_bytecode.seekg(-sizeof(ceos), m_bytecode.cur); auto p = m_bytecode.tellg(); auto str = readStr(); while (m_bytecode.peek() == '\1') { m_bytecode.get(); } m_strings.push_back(str); write((float)(m_bytecode.tellg() - p)/WORD_SIZE) << "$" << str_index++ << ": " << str; } } void Disassembler::dumpFunctions() { auto header = read(); if (header != Section::Functions) { m_bytecode.seekg(-sizeof(header), m_bytecode.cur); return; } m_padding = ""; write(1) << "FUNCTIONS:"; m_padding = " "; while (true) { auto header = read(); if (header == Section::Header) { return; } assert(header == Section::FunctionHeader); auto fnID = read(); auto argCount = read(); m_functions.push_back(m_strings[fnID]); std::stringstream args; for (int i = 0; i < argCount; i++) { auto argID = read(); if (i) args << ", "; args << "$" << i << ": " << m_strings[argID]; } m_padding = ""; write(2 + argCount) << m_strings[fnID] << "(" << args.str() << "):"; m_padding = " "; while (true) { auto header = read(); m_bytecode.seekg(-sizeof(header), m_bytecode.cur); if (header == Section::FunctionHeader || header == Section::Header) { break; } auto opcode = read(); printOpcode(static_cast<Opcode::Type>(opcode)); } } } void Disassembler::dumpText() { auto header = read(); if (header != Section::Text) { m_bytecode.seekg(-sizeof(header), m_bytecode.cur); return; } m_padding = ""; write(1) << "TEXT:"; m_padding = " "; // skip size of lookup table m_bytecode.seekg(WORD_SIZE, m_bytecode.cur); while (true) { auto opcode = read(); if (m_bytecode.eof() || m_bytecode.fail()) { break; } printOpcode(static_cast<Opcode::Type>(opcode)); } } void Disassembler::printOpcode(Opcode::Type opcode) { switch (opcode) { case Opcode::push: { auto value = read(); write(1) << "push 0x" << std::setbase(16) << value << std::setbase(10); break; } case Opcode::call: { auto argc = read(); write(1) << "call (" << argc << ")"; break; } case Opcode::load_string: { auto stringID = read(); write(1) << "load_string $" << m_strings[stringID]; break; } case Opcode::lookup: { auto symbol = read(); auto cacheSlot = read(); write(2) << "lookup $" << symbol << "(" << m_strings[symbol] << ") [cacheSlot=" << cacheSlot << "]"; break; } case Opcode::create_closure: { auto fnID = read(); auto capturesScope = read() ? "true" : "false"; write(2) << "create_closure " << m_functions[fnID] << " [capturesScope=" << capturesScope << "]"; break; } case Opcode::jmp: { auto target = read(); write(1) << "jmp [" << calculateJmpTarget(target) << "]"; break; } case Opcode::jz: { auto target = read(); write(1) << "jz [" << calculateJmpTarget(target) << "]"; break; } case Opcode::push_arg: { auto argID = read(); write(1) << "push_arg $" << argID; break; } case Opcode::put_to_scope: { auto argID = read(); write(1) << "put_to_scope $" << m_strings[argID]; break; } case Opcode::bind: { auto stringID = read(); write(1) << "bind $" << m_strings[stringID]; break; } case Opcode::alloc_obj: { auto size = read(); auto tag = read(); write(2) << "alloc_obj (size=" << size << ", tag=" << tag << ")"; break; } case Opcode::alloc_list: { auto size = read(); write(1) << "alloc_list (size=" << size << ")"; break; } case Opcode::obj_store_at: { auto index = read(); write(1) << "obj_store_at #" << index; break; } case Opcode::obj_tag_test: { auto tag = read(); write(1) << "obj_tag_test #" << tag; break; } case Opcode::obj_load: { auto offset = read(); write(1) << "obj_load #" << offset; break; } case Opcode::stack_alloc: { auto size = read(); write(1) << "stack_alloc #" << size; break; } case Opcode::stack_store: { auto slot = read(); write(1) << "stack_store #" << slot; break; } case Opcode::stack_load: { auto slot = read(); write(1) << "stack_load #" << slot; break; } case Opcode::stack_free: { auto size = read(); write(1) << "stack_free #" << size; break; } default: write() << Opcode::typeName(static_cast<Opcode::Type>(opcode)); } } } <|endoftext|>
<commit_before><commit_msg>Adding Simplex algorithm and short description<commit_after><|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * helloDataManWriter.cpp * * Created on: Feb 16, 2017 * Author: Jason Wang */ #include <iostream> #include <vector> #include <adios2.h> int main(int argc, char *argv[]) { // Application variable std::vector<float> myFloats = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; const std::size_t Nx = myFloats.size(); try { adios::ADIOS adios(adios::DebugON); adios::IO &dataManIO = adios.DeclareIO("WANIO"); dataManIO.SetEngine("DataManWriter"); dataManIO.SetParameters("peer-to-peer=yes", "real_time=yes", "compress=no", "method=cache"); // Define variable and local size auto bpFloats = dataManIO.DefineVariable<float>("bpFloats", {}, {}, {Nx}); // Create engine smart pointer to DataMan Engine due to polymorphism, // Open returns a smart pointer to Engine containing the Derived class auto dataManWriter = dataManIO.Open("myFloats.bp", adios::OpenMode::Write); if (!dataManWriter) { throw std::ios_base::failure( "ERROR: failed to create DataMan I/O engine at Open\n"); } dataManWriter->Write<float>(bpFloats, myFloats.data()); dataManWriter->Close(); } catch (std::invalid_argument &e) { std::cout << "Invalid argument exception, STOPPING PROGRAM\n"; std::cout << e.what() << "\n"; } catch (std::ios_base::failure &e) { std::cout << "IO System base failure exception, STOPPING PROGRAM\n"; std::cout << e.what() << "\n"; } catch (std::exception &e) { std::cout << "Exception, STOPPING PROGRAM from rank\n"; std::cout << e.what() << "\n"; } return 0; } <commit_msg>fixed a problem in helloDataManWriter_nompi (#11)<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * helloDataManWriter.cpp * * Created on: Feb 16, 2017 * Author: Jason Wang */ #include <iostream> #include <vector> #include <adios2.h> int main(int argc, char *argv[]) { // Application variable std::vector<float> myFloats = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; const std::size_t Nx = myFloats.size(); try { adios::ADIOS adios(adios::DebugON); adios::IO &dataManIO = adios.DeclareIO("WANIO"); dataManIO.SetEngine("DataManWriter"); dataManIO.SetParameters("peer-to-peer=yes", "real_time=yes", "compress=no", "method=dump"); // Define variable and local size auto bpFloats = dataManIO.DefineVariable<float>("bpFloats", {}, {}, {Nx}); // Create engine smart pointer to DataMan Engine due to polymorphism, // Open returns a smart pointer to Engine containing the Derived class auto dataManWriter = dataManIO.Open("myFloats.bp", adios::OpenMode::Write); if (!dataManWriter) { throw std::ios_base::failure( "ERROR: failed to create DataMan I/O engine at Open\n"); } dataManWriter->Write<float>(bpFloats, myFloats.data()); dataManWriter->Close(); } catch (std::invalid_argument &e) { std::cout << "Invalid argument exception, STOPPING PROGRAM\n"; std::cout << e.what() << "\n"; } catch (std::ios_base::failure &e) { std::cout << "IO System base failure exception, STOPPING PROGRAM\n"; std::cout << e.what() << "\n"; } catch (std::exception &e) { std::cout << "Exception, STOPPING PROGRAM from rank\n"; std::cout << e.what() << "\n"; } return 0; } <|endoftext|>
<commit_before>/** * @file ctml.cpp * * Functions to read and write CTML. * */ /* $Author$ * $Revision$ * $Date$ */ // Copyright 2002 California Institute of Technology // turn off warnings under Windows #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "ctml.h" #define CTML_VERSION_1_4_1 namespace ctml { static doublereal fpValue(string val) { return atof(stripws(val).c_str()); } void addBool(XML_Node& node, string title, bool val) { string v = (val ? "true" : "false"); XML_Node& f = node.addChild("bool",v); f.addAttribute("title",title); } void addInteger(XML_Node& node, string title, int val, string units, string type) { XML_Node& f = node.addChild("integer",val); f.addAttribute("title",title); if (type != "") f.addAttribute("type",type); if (units != "") f.addAttribute("units",units); } void addIntegerArray(XML_Node& node, string title, int n, const int* vals, string units, string type, doublereal minval, doublereal maxval) { string fmt = "%8d"; int i; string v = ""; for (i = 0; i < n; i++) { v += int2str(vals[i],fmt); if (i == n-1) v += "\n"; else if (i > 0 && (i+1) % 3 == 0) v += ",\n"; else v += ", "; } XML_Node& f = node.addChild("intArray",v); f.addAttribute("title",title); if (type != "") f.addAttribute("type",type); f.addAttribute("size",n); if (units != "") f.addAttribute("units",units); if (minval != Undef) f.addAttribute("min",minval); if (maxval != Undef) f.addAttribute("max",maxval); } void addFloat(XML_Node& node, string title, doublereal val, string units, string type, doublereal minval, doublereal maxval) { string fmt = "%17.9E"; #ifdef CTML_VERSION_1_4 XML_Node& f = node.addChild("float",val,fmt); f.addAttribute("title",title); #else XML_Node& f = node.addChild(title,val,fmt); #endif if (type != "") f.addAttribute("type",type); if (units != "") f.addAttribute("units",units); if (minval != Undef) f.addAttribute("min",minval); if (maxval != Undef) f.addAttribute("max",maxval); } void addFloatArray(XML_Node& node, string title, int n, const double* vals, string units, string type, doublereal minval, doublereal maxval) { string fmt = "%17.9E"; int i; string v = ""; for (i = 0; i < n; i++) { v += fp2str(vals[i],fmt); if (i == n-1) v += "\n"; else if (i > 0 && (i+1) % 3 == 0) v += ",\n"; else v += ", "; } XML_Node& f = node.addChild("floatArray",v); f.addAttribute("title",title); if (type != "") f.addAttribute("type",type); f.addAttribute("size",n); if (units != "") f.addAttribute("units",units); if (minval != Undef) f.addAttribute("min",minval); if (maxval != Undef) f.addAttribute("max",maxval); } void addString(XML_Node& node, string title, string val, string type) { XML_Node& f = node.addChild("string",val); f.addAttribute("title",title); if (type != "") f.addAttribute("type",type); } XML_Node* getByTitle(XML_Node& node, string title) { XML_Node* s = node.findByAttr("title",title); if (s->parent() == &node) return s; else return 0; } string getString(const XML_Node& parent, string name) { if (!parent.hasChild(name)) return ""; return parent(name); } void getString(XML_Node& node, string title, string& val, string& type) { val = ""; type = ""; XML_Node* s = getByTitle(node, title); if (s) if (s->name() == "string") { val = (*s).value(); type = (*s)["type"]; return; } } void getIntegers(const XML_Node& node, map<string,int>& v) { vector<XML_Node*> f; node.getChildren("integer",f); int n = f.size(); integer x, x0, x1; string typ, title, vmin, vmax; for (int i = 0; i < n; i++) { const XML_Node& fi = *(f[i]); x = atoi(fi().c_str()); title = fi["title"]; vmin = fi["min"]; vmax = fi["max"]; if (vmin != "") x0 = atoi(vmin.c_str()); if (fi["max"] != "") x1 = atoi(vmax.c_str()); v[title] = x; } } void getStrings(const XML_Node& node, map<string,string>& v) { vector<XML_Node*> f; node.getChildren("string",f); int n = f.size(); string typ, title; for (int i = 0; i < n; i++) { const XML_Node& fi = *(f[i]); title = fi["title"]; v[title] = fi(); } } void getFloats(const XML_Node& node, map<string,double>& v, bool convert) { vector<XML_Node*> f; node.getChildren("float",f); int n = f.size(); doublereal x, x0, x1, fctr; string typ, title, units, vmin, vmax; for (int i = 0; i < n; i++) { const XML_Node& fi = *(f[i]); x = atof(fi().c_str()); x0 = Undef; x1 = Undef; typ = fi["type"]; title = fi["title"]; units = fi["units"]; vmin = fi["min"]; vmax = fi["max"]; if (vmin != "") { x0 = atof(vmin.c_str()); if (x < x0 - Tiny) { writelog("\nWarning: value "+fi()+" is below lower limit of " +vmin+".\n"); } } if (fi["max"] != "") { x1 = atof(vmax.c_str()); if (x > x1 + Tiny) { writelog("\nWarning: value "+fi()+" is above upper limit of " +vmax+".\n"); } } fctr = (convert ? toSI(units) : 1.0); // toSI(typ,units); v[title] = fctr*x; } } /** * Get a floating-point value from a child element. Returns a * double value for the child named 'name' of element 'parent'. If * 'type' is supplied and matches a known unit type, unit * conversion to SI will be done if the child element has an attribute * 'units'. */ doublereal getFloat(const XML_Node& parent, string name, string type) { if (!parent.hasChild(name)) throw CanteraError("getFloat (called from XML Node \"" + parent.name() + "\"): ", "no child XML element named " + name); const XML_Node& node = parent.child(name); doublereal x, x0, x1, fctr = 1.0; string units, vmin, vmax; x = atof(node().c_str()); x0 = Undef; x1 = Undef; units = node["units"]; vmin = node["min"]; vmax = node["max"]; if (vmin != "") { x0 = atof(vmin.c_str()); if (x < x0 - Tiny) { writelog("\nWarning: value "+node()+" is below lower limit of " +vmin+".\n"); } } if (node["max"] != "") { x1 = atof(vmax.c_str()); if (x > x1 + Tiny) { writelog("\nWarning: value "+node()+" is above upper limit of " +vmax+".\n"); } } if (type == "actEnergy" && units != "") fctr = actEnergyToSI(units); else if (type != "" && units != "") fctr = toSI(units); return fctr*x; } void getFloatArray(const XML_Node& node, vector_fp& v, bool convert) { int icom; string numstr; if (node.name() != "floatArray") throw CanteraError("getFloatArray","wrong element type: " +node.name()); v.clear(); doublereal vmin = Undef, vmax = Undef; doublereal funit = 1.0; if (node["units"] != "" && convert) { funit = toSI(node["units"]); } if (node["min"] != "") vmin = atof(node["min"].c_str()); if (node["max"] != "") vmax = atof(node["max"].c_str()); doublereal vv; string val = node.value(); while (1 > 0) { icom = val.find(','); if (icom >= 0) { numstr = val.substr(0,icom); val = val.substr(icom+1,val.size()); v.push_back(atof(numstr.c_str())); } else { v.push_back(atof(val.c_str())); break; } vv = v.back(); if (vmin != Undef && vv < vmin - Tiny) { writelog("\nWarning: value "+fp2str(vv)+ " is below lower limit of " +fp2str(vmin)+".\n"); } if (vmax != Undef && vv > vmax + Tiny) { writelog("\nWarning: value "+fp2str(vv)+ " is above upper limit of " +fp2str(vmin)+".\n"); } } int nv = v.size(); for (int n = 0; n < nv; n++) { v[n] *= funit; } } void getMap(const XML_Node& node, map<string, string>& m) { vector<string> v; getStringArray(node, v); string key, val; int n = v.size(); int icolon; for (int i = 0; i < n; i++) { icolon = v[i].find(":"); if (icolon < 0) { throw CanteraError("getMap","missing colon in map entry (" +v[i]+")"); } key = v[i].substr(0,icolon); val = v[i].substr(icolon+1, v.size()); m[key] = val; } } void getPairs(const XML_Node& node, vector<string>& key, vector<string>& val) { vector<string> v; getStringArray(node, v); int n = v.size(); int icolon; for (int i = 0; i < n; i++) { icolon = v[i].find(":"); if (icolon < 0) { throw CanteraError("getMap","missing colon in map entry (" +v[i]+")"); } key.push_back(v[i].substr(0,icolon)); val.push_back(v[i].substr(icolon+1, v.size())); } } void getStringArray(const XML_Node& node, vector<string>& v) { int ibegin, iend; v.clear(); string val = node.value(); while (1 > 0) { ibegin = val.find_first_not_of(" \n\t"); if (ibegin >= 0) { val = val.substr(ibegin,val.size()); iend = val.find_first_of(" \n\t"); if (iend > 0) { v.push_back(val.substr(0,iend)); val = val.substr(iend+1,val.size()); } else { v.push_back(val.substr(0,iend)); break; } } else break; } } void getFunction(const XML_Node& node, string& type, doublereal& xmin, doublereal& xmax, vector_fp& coeffs) { const XML_Node& c = node.child("floatArray"); coeffs.clear(); getFloatArray(c,coeffs); xmin = Undef; if (node["min"] != "") xmin = fpValue(node["min"]); if (node["max"] != "") xmax = fpValue(node["max"]); type = node["type"]; } } <commit_msg>Fixed a rather hideous error in getMap(), that was causing element compositions to be read incorrectly when the species is made up of a large numbers of a single element.<commit_after>/** * @file ctml.cpp * * Functions to read and write CTML. * */ /* $Author$ * $Revision$ * $Date$ */ // Copyright 2002 California Institute of Technology // turn off warnings under Windows #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "ctml.h" #define CTML_VERSION_1_4_1 namespace ctml { static doublereal fpValue(string val) { return atof(stripws(val).c_str()); } void addBool(XML_Node& node, string title, bool val) { string v = (val ? "true" : "false"); XML_Node& f = node.addChild("bool",v); f.addAttribute("title",title); } void addInteger(XML_Node& node, string title, int val, string units, string type) { XML_Node& f = node.addChild("integer",val); f.addAttribute("title",title); if (type != "") f.addAttribute("type",type); if (units != "") f.addAttribute("units",units); } void addIntegerArray(XML_Node& node, string title, int n, const int* vals, string units, string type, doublereal minval, doublereal maxval) { string fmt = "%8d"; int i; string v = ""; for (i = 0; i < n; i++) { v += int2str(vals[i],fmt); if (i == n-1) v += "\n"; else if (i > 0 && (i+1) % 3 == 0) v += ",\n"; else v += ", "; } XML_Node& f = node.addChild("intArray",v); f.addAttribute("title",title); if (type != "") f.addAttribute("type",type); f.addAttribute("size",n); if (units != "") f.addAttribute("units",units); if (minval != Undef) f.addAttribute("min",minval); if (maxval != Undef) f.addAttribute("max",maxval); } void addFloat(XML_Node& node, string title, doublereal val, string units, string type, doublereal minval, doublereal maxval) { string fmt = "%17.9E"; #ifdef CTML_VERSION_1_4 XML_Node& f = node.addChild("float",val,fmt); f.addAttribute("title",title); #else XML_Node& f = node.addChild(title,val,fmt); #endif if (type != "") f.addAttribute("type",type); if (units != "") f.addAttribute("units",units); if (minval != Undef) f.addAttribute("min",minval); if (maxval != Undef) f.addAttribute("max",maxval); } void addFloatArray(XML_Node& node, string title, int n, const double* vals, string units, string type, doublereal minval, doublereal maxval) { string fmt = "%17.9E"; int i; string v = ""; for (i = 0; i < n; i++) { v += fp2str(vals[i],fmt); if (i == n-1) v += "\n"; else if (i > 0 && (i+1) % 3 == 0) v += ",\n"; else v += ", "; } XML_Node& f = node.addChild("floatArray",v); f.addAttribute("title",title); if (type != "") f.addAttribute("type",type); f.addAttribute("size",n); if (units != "") f.addAttribute("units",units); if (minval != Undef) f.addAttribute("min",minval); if (maxval != Undef) f.addAttribute("max",maxval); } void addString(XML_Node& node, string title, string val, string type) { XML_Node& f = node.addChild("string",val); f.addAttribute("title",title); if (type != "") f.addAttribute("type",type); } XML_Node* getByTitle(XML_Node& node, string title) { XML_Node* s = node.findByAttr("title",title); if (s->parent() == &node) return s; else return 0; } string getString(const XML_Node& parent, string name) { if (!parent.hasChild(name)) return ""; return parent(name); } void getString(XML_Node& node, string title, string& val, string& type) { val = ""; type = ""; XML_Node* s = getByTitle(node, title); if (s) if (s->name() == "string") { val = (*s).value(); type = (*s)["type"]; return; } } void getIntegers(const XML_Node& node, map<string,int>& v) { vector<XML_Node*> f; node.getChildren("integer",f); int n = f.size(); integer x, x0, x1; string typ, title, vmin, vmax; for (int i = 0; i < n; i++) { const XML_Node& fi = *(f[i]); x = atoi(fi().c_str()); title = fi["title"]; vmin = fi["min"]; vmax = fi["max"]; if (vmin != "") x0 = atoi(vmin.c_str()); if (fi["max"] != "") x1 = atoi(vmax.c_str()); v[title] = x; } } void getStrings(const XML_Node& node, map<string,string>& v) { vector<XML_Node*> f; node.getChildren("string",f); int n = f.size(); string typ, title; for (int i = 0; i < n; i++) { const XML_Node& fi = *(f[i]); title = fi["title"]; v[title] = fi(); } } void getFloats(const XML_Node& node, map<string,double>& v, bool convert) { vector<XML_Node*> f; node.getChildren("float",f); int n = f.size(); doublereal x, x0, x1, fctr; string typ, title, units, vmin, vmax; for (int i = 0; i < n; i++) { const XML_Node& fi = *(f[i]); x = atof(fi().c_str()); x0 = Undef; x1 = Undef; typ = fi["type"]; title = fi["title"]; units = fi["units"]; vmin = fi["min"]; vmax = fi["max"]; if (vmin != "") { x0 = atof(vmin.c_str()); if (x < x0 - Tiny) { writelog("\nWarning: value "+fi()+" is below lower limit of " +vmin+".\n"); } } if (fi["max"] != "") { x1 = atof(vmax.c_str()); if (x > x1 + Tiny) { writelog("\nWarning: value "+fi()+" is above upper limit of " +vmax+".\n"); } } fctr = (convert ? toSI(units) : 1.0); // toSI(typ,units); v[title] = fctr*x; } } /** * Get a floating-point value from a child element. Returns a * double value for the child named 'name' of element 'parent'. If * 'type' is supplied and matches a known unit type, unit * conversion to SI will be done if the child element has an attribute * 'units'. */ doublereal getFloat(const XML_Node& parent, string name, string type) { if (!parent.hasChild(name)) throw CanteraError("getFloat (called from XML Node \"" + parent.name() + "\"): ", "no child XML element named " + name); const XML_Node& node = parent.child(name); doublereal x, x0, x1, fctr = 1.0; string units, vmin, vmax; x = atof(node().c_str()); x0 = Undef; x1 = Undef; units = node["units"]; vmin = node["min"]; vmax = node["max"]; if (vmin != "") { x0 = atof(vmin.c_str()); if (x < x0 - Tiny) { writelog("\nWarning: value "+node()+" is below lower limit of " +vmin+".\n"); } } if (node["max"] != "") { x1 = atof(vmax.c_str()); if (x > x1 + Tiny) { writelog("\nWarning: value "+node()+" is above upper limit of " +vmax+".\n"); } } if (type == "actEnergy" && units != "") fctr = actEnergyToSI(units); else if (type != "" && units != "") fctr = toSI(units); return fctr*x; } void getFloatArray(const XML_Node& node, vector_fp& v, bool convert) { int icom; string numstr; if (node.name() != "floatArray") throw CanteraError("getFloatArray","wrong element type: " +node.name()); v.clear(); doublereal vmin = Undef, vmax = Undef; doublereal funit = 1.0; if (node["units"] != "" && convert) { funit = toSI(node["units"]); } if (node["min"] != "") vmin = atof(node["min"].c_str()); if (node["max"] != "") vmax = atof(node["max"].c_str()); doublereal vv; string val = node.value(); while (1 > 0) { icom = val.find(','); if (icom >= 0) { numstr = val.substr(0,icom); val = val.substr(icom+1,val.size()); v.push_back(atof(numstr.c_str())); } else { v.push_back(atof(val.c_str())); break; } vv = v.back(); if (vmin != Undef && vv < vmin - Tiny) { writelog("\nWarning: value "+fp2str(vv)+ " is below lower limit of " +fp2str(vmin)+".\n"); } if (vmax != Undef && vv > vmax + Tiny) { writelog("\nWarning: value "+fp2str(vv)+ " is above upper limit of " +fp2str(vmin)+".\n"); } } int nv = v.size(); for (int n = 0; n < nv; n++) { v[n] *= funit; } } /** * This routine is used to interpret the value portions of XML * elements that contain colon separated pairs. These are used, * for example, in describing the element composition of species. * <atomArray> H:4 C:1 <atomArray\> * The string is first separated into a string vector according * to the location of white space. Then each string is again * separated into two parts according to the location of a * colon in the string. The first part of the string is * used as the key, while the second part of the string is * used as the value, in the return map. * It is an error to not find a colon in each string pair. */ void getMap(const XML_Node& node, map<string, string>& m) { vector<string> v; getStringArray(node, v); string key, val; int n = v.size(); string::size_type icolon; for (int i = 0; i < n; i++) { icolon = v[i].find(":"); if (icolon == string::npos) { throw CanteraError("getMap","missing colon in map entry (" +v[i]+")"); } key = v[i].substr(0,icolon); val = v[i].substr(icolon+1, v[i].size()); m[key] = val; } } void getPairs(const XML_Node& node, vector<string>& key, vector<string>& val) { vector<string> v; getStringArray(node, v); int n = v.size(); string::size_type icolon; for (int i = 0; i < n; i++) { icolon = v[i].find(":"); if (icolon == string::npos) { throw CanteraError("getMap","missing colon in map entry (" +v[i]+")"); } key.push_back(v[i].substr(0,icolon)); val.push_back(v[i].substr(icolon+1, v.size())); } } /** * This function interprets the value portion of an XML element * as a string. It then separates the string up into tokens * according to the location of white space. * The separate tokens are returned in the string vector, * v. */ void getStringArray(const XML_Node& node, vector<string>& v) { int ibegin, iend; v.clear(); string val = node.value(); while (1 > 0) { ibegin = val.find_first_not_of(" \n\t"); if (ibegin >= 0) { val = val.substr(ibegin,val.size()); iend = val.find_first_of(" \n\t"); if (iend > 0) { v.push_back(val.substr(0,iend)); val = val.substr(iend+1,val.size()); } else { v.push_back(val.substr(0,iend)); break; } } else break; } } void getFunction(const XML_Node& node, string& type, doublereal& xmin, doublereal& xmax, vector_fp& coeffs) { const XML_Node& c = node.child("floatArray"); coeffs.clear(); getFloatArray(c,coeffs); xmin = Undef; if (node["min"] != "") xmin = fpValue(node["min"]); if (node["max"] != "") xmax = fpValue(node["max"]); type = node["type"]; } } <|endoftext|>
<commit_before>/* * P2 * benchtree.cpp * Author: Jay Dey cs100vaj * Author: Joshua Yuen cs100vbc */ #include "RST.hpp" #include "BST.hpp" #include "countint.hpp" #include "string.h" #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <set> using namespace std; /** * A simple benchmarking program for RST. */ static void show_usage() { std::cerr << "./benchtree [rst / bst / set] [sorted / shuffled]" " [maximum tree size] [number of runs]" << std::endl; } int main (int argc, char** argv) { //incorrect usage if(argc != 5) { std::cout << "Amount of args: " <<argc <<std::endl; show_usage(); return 1; } //parse arg 2: keys in sorted or randomized order int sorted = 0; int shuffled = 0; if(std::string(argv[2])== "sorted") sorted = 1; else if(std::string(argv[2])== "shuffled") shuffled = 1; else { std::cout << "2nd Arg: " <<argc <<std::endl; show_usage(); return 1; } //parse arg 3: maximum size of tree int n = atoi( argv[3] ); if ( n == 0 ) { std::cout << "3rd arg " <<argc <<std::endl; show_usage(); return 1; } //parse arg 4: number of runs int runs = atoi( argv[4] ); if (runs == 0) { std::cout << "4th arg: " <<argc <<std::endl; show_usage(); return 1; } std::cout<< "# Benchmarking average number of comparisons for successful find" "\n# Data structure: " << argv[1] << "\n" "# Data: " << argv[2] << "\n" "# N is powers of 2, minus 1, from 1 to " << n << "\n" "# Averaging over " << runs << "runs for each N \n" "#\n" "# N \t avgcomps \t stdev\n" << std::endl; /* * parse arg 1: type of data structure * bst, rst, set */ if(strcmp(argv[1], "bst") == 0) { BST<countint> * bam = new BST<countint>(); std::vector<countint> v; v.clear(); //populate vector for (int i=0; i<n; i++) v.push_back(i); //shuffle if necessary if (shuffled == 1 && sorted != 1) std::random_shuffle(v.begin(), v.end()); //insert keys into structure std::vector<countint>::iterator vit = v.begin(); std::vector<countint>::iterator ven = v.end(); for (vit = v.begin(); vit != ven; ++vit) bam->insert(*vit); //comparisons int x = 1; while (x <= n) { double tot_avg = 0; double tot_sq_avg = 0; countint::clearcount(); for (int a = 0; a < runs; a++) { for (vit = v.begin(); vit != ven; ++vit) bam->find(*vit); double avgcomps = countint::getcount() / (double)x; tot_avg = tot_avg + avgcomps; tot_sq_avg = tot_sq_avg + pow(avgcomps, 2); } tot_avg = tot_avg / (double)runs; tot_sq_avg = tot_sq_avg / (double)runs; double stdev = sqrt(abs(tot_sq_avg - (pow(tot_avg, 2)))); std::cout << x << " \t " << tot_avg << " \t " << stdev << "\n" << std::endl; //(x^2) - 1 x = x*2+1; } } else if (strcmp(argv[1], "rst") == 0) { RST<countint> * ram = new RST<countint>(); std::vector<countint> v; v.clear(); //populate vector for (int i=0; i<n; i++) v.push_back(i); //shuffle if necessary if (shuffled == 1) std::random_shuffle(v.begin(), v.end()); //insert keys into structure std::vector<countint>::iterator vit = v.begin(); std::vector<countint>::iterator ven = v.end(); for (vit = v.begin(); vit != ven; ++vit) ram->insert(*vit); //comparisons int x = 1; while (x <= n) { double tot_avg = 0; double tot_sq_avg = 0; countint::clearcount(); for (int a = 0; a < runs; a++) { for (vit = v.begin(); vit != ven; ++vit) ram->find(*vit); double avgcomps = countint::getcount() / (double)x; tot_avg = tot_avg + avgcomps; tot_sq_avg = tot_sq_avg + pow(avgcomps, 2); } tot_avg = tot_avg / (double)runs; tot_sq_avg = tot_sq_avg / (double)runs; double stdev = sqrt(abs(tot_sq_avg - (pow(tot_avg, 2)))); std::cout << x << " \t " << tot_avg << " \t " << stdev << "\n" << std::endl; //(x^2) - 1 x = x*2+1; } } else if (strcmp(argv[1], "set") == 0) { std::set<countint> * sam = new std::set<countint>(); std::vector<countint> v; v.clear(); //populate vector for (int i=0; i<n; i++) v.push_back(i); //shuffle if necessary if (shuffled == 1) std::random_shuffle(v.begin(), v.end()); //insert keys into structure std::vector<countint>::iterator vit = v.begin(); std::vector<countint>::iterator ven = v.end(); for (vit = v.begin(); vit != ven; ++vit) sam->insert(*vit); //comparisons int x = 1; while (x <= n) { double tot_avg = 0; double tot_sq_avg = 0; countint::clearcount(); for (int a = 0; a < runs; a++) { for (vit = v.begin(); vit != ven; ++vit) sam->find(*vit); double avgcomps = countint::getcount() / (double)x; tot_avg = tot_avg + avgcomps; tot_sq_avg = tot_sq_avg + pow(avgcomps, 2); } tot_avg = tot_avg / (double)runs; tot_sq_avg = tot_sq_avg / (double)runs; double stdev = sqrt(abs(tot_sq_avg - (pow(tot_avg, 2)))); std::cout << x << " \t " << tot_avg << " \t " << stdev << "\n" << std::endl; //x^2 - 1 x = x*2+1; } } else { std::cout << "1st arg: " <<argc <<std::endl; show_usage(); return 1; } //SUCCESS //std::cout << "\nYOU'RE A WINNER\n" << std::endl; return 0; }; <commit_msg>no idea what I'm doing<commit_after>/* * P2 * benchtree.cpp * Author: Jay Dey cs100vaj * Author: Joshua Yuen cs100vbc */ #include "RST.hpp" #include "BST.hpp" #include "countint.hpp" #include "string.h" #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <set> using namespace std; /** * A simple benchmarking program for RST. */ static void show_usage() { std::cerr << "./benchtree [rst / bst / set] [sorted / shuffled]" " [maximum tree size] [number of runs]" << std::endl; } int main (int argc, char** argv) { //incorrect usage if(argc != 5) { std::cout << "Amount of args: " <<argc <<std::endl; show_usage(); return 1; } //parse arg 2: keys in sorted or randomized order int sorted = 0; int shuffled = 0; if(std::string(argv[2])== "sorted") sorted = 1; else if(std::string(argv[2])== "shuffled") shuffled = 1; else { std::cout << "2nd Arg: " <<argc <<std::endl; show_usage(); return 1; } //parse arg 3: maximum size of tree int n = atoi( argv[3] ); if ( n == 0 ) { std::cout << "3rd arg " <<argc <<std::endl; show_usage(); return 1; } //parse arg 4: number of runs int runs = atoi( argv[4] ); if (runs == 0) { std::cout << "4th arg: " <<argc <<std::endl; show_usage(); return 1; } std::cout<< "# Benchmarking average number of comparisons for successful find" "\n# Data structure: " << argv[1] << "\n" "# Data: " << argv[2] << "\n" "# N is powers of 2, minus 1, from 1 to " << n << "\n" "# Averaging over " << runs << " runs for each N \n" "#\n" "# N \t avgcomps \t stdev\n" << std::endl; /* * parse arg 1: type of data structure * bst, rst, set */ if(strcmp(argv[1], "bst") == 0) { std::cout << "entered BST" << std::endl; BST<countint> * bam = new BST<countint>(); std::vector<countint> v; v.clear(); //populate vector for (int i=0; i<n; i++) v.push_back(i); //shuffle if necessary if (shuffled == 1 && sorted != 1) std::random_shuffle(v.begin(), v.end()); //insert keys into structure std::vector<countint>::iterator vit = v.begin(); std::vector<countint>::iterator ven = v.end(); for (vit = v.begin(); vit != ven; ++vit) bam->insert(*vit); //comparisons int x = 1; while (x <= n) { double tot_avg = 0; double tot_sq_avg = 0; countint::clearcount(); for (int a = 0; a < runs; a++) { for (vit = v.begin(); vit != ven; ++vit) bam->find(*vit); double avgcomps = countint::getcount() / (double)x; tot_avg = tot_avg + avgcomps; tot_sq_avg = tot_sq_avg + pow(avgcomps, 2); } tot_avg = tot_avg / (double)runs; tot_sq_avg = tot_sq_avg / (double)runs; double stdev = sqrt(abs(tot_sq_avg - (pow(tot_avg, 2)))); std::cout<< " " << x << " \t " << tot_avg << " \t " << stdev <<std::endl; //(x^2) - 1 x = x*2+1; } } else if (strcmp(argv[1], "rst") == 0) { std::cout << "entered RST" << std::endl; int x = 1; double avgcomps, avgsq; while (x <= n) { avgcomps = avgsq = 0.0; for (int a = 1; a <= runs; a++) { RST<countint> * ram = new RST<countint>(); std::vector<countint> v; v.clear(); //populate vector for (int i=0; i<n; i++) v.push_back(i); //shuffle if necessary if (shuffled == 1) std::random_shuffle(v.begin(), v.end()); //insert keys into structure std::vector<countint>::iterator vit = v.begin(); std::vector<countint>::iterator ven = v.end(); for (vit = v.begin(); vit != ven; ++vit) ram->insert(*vit); countint::clearcount(); for (vit = v.begin(); vit != ven; ++vit) ram->find(*vit); avgcomps = avgcomps + countint::getcount()/(double)n; avgsq = avgsq + pow(avgcomps, 2); } avgcomps = avgcomps / (double)runs; avgsq = avgsq / (double)runs; double stdev = sqrt(abs(avgsq - (pow(avgcomps, 2)))); //cout << "BOOM" << endl; std::cout << x << " \t " << avgcomps << " \t " << stdev <<std::endl; //cout << "\n" <<endl; //(x^2) - 1 x = x*2+1; } } else if (strcmp(argv[1], "set") == 0) { std::cout << "entered SET" << std::endl; std::set<countint> * sam = new std::set<countint>(); std::vector<countint> v; v.clear(); //populate vector for (int i=0; i<n; i++) v.push_back(i); //shuffle if necessary if (shuffled == 1) std::random_shuffle(v.begin(), v.end()); //insert keys into structure std::vector<countint>::iterator vit = v.begin(); std::vector<countint>::iterator ven = v.end(); for (vit = v.begin(); vit != ven; ++vit) sam->insert(*vit); //comparisons int x = 1; while (x <= n) { double tot_avg = 0; double tot_sq_avg = 0; countint::clearcount(); for (int a = 0; a < runs; a++) { for (vit = v.begin(); vit != ven; ++vit) sam->find(*vit); double avgcomps = countint::getcount() / (double)x; tot_avg = tot_avg + avgcomps; tot_sq_avg = tot_sq_avg + pow(avgcomps, 2); } tot_avg = tot_avg / (double)runs; tot_sq_avg = tot_sq_avg / (double)runs; double stdev = sqrt(abs(tot_sq_avg - (pow(tot_avg, 2)))); std::cout << x << " \t " << tot_avg << " \t " << stdev << "\n" << std::endl; //x^2 - 1 x = x*2+1; } } else { std::cout << "1st arg: " <<argc <<std::endl; show_usage(); return 1; } //SUCCESS //std::cout << "\nYOU'RE A WINNER\n" << std::endl; return 0; }; <|endoftext|>
<commit_before>//------------------------------------------------------------------------------------------ // Name Jeremy Driesler & Candelario "Daniel" Eguia // Course CMPS-455 // Project No. 8 // Part No. 1 // Due date Mar. 15, 2015 // Professor Ray Ahmadnia // // This program displays: /* The trace of the input string and shows content of the stack after each match. -----------------Table--------------- states | i + - * / ( ) $ E 0 | TQ ~ ~ ~ ~ TQ ~ ~ Q 1 | ~ +TQ -TQ ~ ~ ~ L L T 2 | FR ~ ~ ~ ~ FR ~ ~ R 3 | ~ L L *FR /FR ~ L L F 4 | i ~ ~ ~ ~ (E) L L ------------------------------------------------------------------------------------------*/ #include <iostream> #include <string> using namespace std; int main() { string table[5][8] = { { "QT","~","~","~","~","QT","~","~" },{ "~","QT+","QT-","~","~","~","L","L" },{ "RF","~","~","~","~","RF","~","~" },{ "~","L","L","RF*","RF-","~","L","L" },{ "i","~","~","~","~",")E(","~","~" } }; char again; do { string w, stack = "$E"; //w will hold input string cout << "Enter a equation ending with '$' i.e. (i+i)$ : "; cin >> w; // initialize values int i = 0, col, state = 0; //will loop through the letters in the word until it encounters a '$' while (w[i] != '$') { //print the word letter by letter to prevent printing the '$' at the end cout << "\nRead: " << w[i] << endl; cout << "Stack\tPoped\tPushed\n"; cout << stack << "\t"; cout << stack.back() << "\t"; while ( stack.back() != w[i] ) { if ( stack.back() != 'L' ) { // L = Lamda state switch ( stack.back() ) { // converts char to integer state case 'E':state = 0; break; case 'Q':state = 1; break; case 'T':state = 2; break; case 'R':state = 3; break; case 'F':state = 4; break; } switch ( w[i] ) { case 'i':col = 0; break; case '+':col = 1; break; case '-':col = 2; break; case '*':col = 3; break; case '/':col = 4; break; case '(':col = 5; break; case ')':col = 6; break; case '$':col = 7; break; default: col = 8; //is used for any letter not in the lanuage } stack.pop_back(); // removes last char from stack stack += table[state][col]; // Push new states / terminals cout << table[state][col] << "\n"; cout << stack << "\t"; } else { // used when a Lamda state is reached stack.pop_back(); cout << endl << stack << '\t'; } cout << stack.back() << "\t"; // display next poped state if ( stack.back() == '~' ) break; // exits loop if in a null state } if ( stack.back() == '~' ) break; // exits loop if in a null state stack.pop_back(); // removes last char cout << endl; i++; } //output result user if ( w[i] != '$' && stack.back() != '$' ) cout << "Not accepted"; else cout << "Accepted"; cout << "\n\nContinue (y/n): "; cin >> again; } while ( again == 'y' ); //terminate the program system( "pause" ); return 0; } /*-----------------output--------------------- --------------------------------------------*/<commit_msg>Added output to the file<commit_after>//------------------------------------------------------------------------------------------ // Name Jeremy Driesler & Candelario "Daniel" Eguia // Course CMPS-455 // Project No. 8 // Part No. 1 // Due date Mar. 15, 2015 // Professor Ray Ahmadnia // // This program displays: /* The trace of the input string and shows content of the stack after each match. -----------------Table--------------- states | i + - * / ( ) $ E 0 | TQ ~ ~ ~ ~ TQ ~ ~ Q 1 | ~ +TQ -TQ ~ ~ ~ L L T 2 | FR ~ ~ ~ ~ FR ~ ~ R 3 | ~ L L *FR /FR ~ L L F 4 | i ~ ~ ~ ~ (E) L L ------------------------------------------------------------------------------------------*/ #include <iostream> #include <string> using namespace std; int main() { string table[5][8] = { { "QT","~","~","~","~","QT","~","~" },{ "~","QT+","QT-","~","~","~","L","L" },{ "RF","~","~","~","~","RF","~","~" },{ "~","L","L","RF*","RF-","~","L","L" },{ "i","~","~","~","~",")E(","~","~" } }; char again; do { string w, stack = "$E"; //w will hold input string cout << "Enter a equation ending with '$' i.e. (i+i)$ : "; cin >> w; // initialize values int i = 0, col, state = 0; //will loop through the letters in the word until it encounters a '$' while (w[i] != '$') { //print the word letter by letter to prevent printing the '$' at the end cout << "\nRead: " << w[i] << endl; cout << "Stack\tPoped\tPushed\n"; cout << stack << "\t"; cout << stack.back() << "\t"; while ( stack.back() != w[i] ) { if ( stack.back() != 'L' ) { // L = Lamda state switch ( stack.back() ) { // converts char to integer state case 'E':state = 0; break; case 'Q':state = 1; break; case 'T':state = 2; break; case 'R':state = 3; break; case 'F':state = 4; break; } switch ( w[i] ) { case 'i':col = 0; break; case '+':col = 1; break; case '-':col = 2; break; case '*':col = 3; break; case '/':col = 4; break; case '(':col = 5; break; case ')':col = 6; break; case '$':col = 7; break; default: col = 8; //is used for any letter not in the lanuage } stack.pop_back(); // removes last char from stack stack += table[state][col]; // Push new states / terminals cout << table[state][col] << "\n"; cout << stack << "\t"; } else { // used when a Lamda state is reached stack.pop_back(); cout << endl << stack << '\t'; } cout << stack.back() << "\t"; // display next poped state if ( stack.back() == '~' ) break; // exits loop if in a null state } if ( stack.back() == '~' ) break; // exits loop if in a null state stack.pop_back(); // removes last char cout << endl; i++; } //output result user if ( w[i] != '$' && stack.back() != '$' ) cout << "Not accepted"; else cout << "Accepted"; cout << "\n\nContinue (y/n): "; cin >> again; } while ( again == 'y' ); //terminate the program system( "pause" ); return 0; } /*-----------------output--------------------- Enter a equation ending with '$' i.e. (i+i)$ : (i+i)*i$ Read: ( Stack Poped Pushed $E E QT $QT T RF $QRF F )E( $QR)E( ( Read: i Stack Poped Pushed $QR)E E QT $QR)QT T RF $QR)QRF F i $QR)QRi i Read: + Stack Poped Pushed $QR)QR R L $QR)QL L $QR)Q Q QT+ $QR)QT+ + Read: i Stack Poped Pushed $QR)QT T RF $QR)QRF F i $QR)QRi i Read: ) Stack Poped Pushed $QR)QR R L $QR)QL L $QR)Q Q L $QR)L L $QR) ) Read: * Stack Poped Pushed $QR R RF* $QRF* * Read: i Stack Poped Pushed $QRF F i $QRi i Accepted Continue (y/n): y Enter a equation ending with '$' i.e. (i+i)$ : i*(i+i)$ Read: i Stack Poped Pushed $E E QT $QT T RF $QRF F i $QRi i Read: * Stack Poped Pushed $QR R RF* $QRF* * Read: ( Stack Poped Pushed $QRF F )E( $QR)E( ( Read: i Stack Poped Pushed $QR)E E QT $QR)QT T RF $QR)QRF F i $QR)QRi i Read: + Stack Poped Pushed $QR)QR R L $QR)QL L $QR)Q Q QT+ $QR)QT+ + Read: i Stack Poped Pushed $QR)QT T RF $QR)QRF F i $QR)QRi i Read: ) Stack Poped Pushed $QR)QR R L $QR)QL L $QR)Q Q L $QR)L L $QR) ) Accepted Continue (y/n): y Enter a equation ending with '$' i.e. (i+i)$ : i(i+i)$ Read: i Stack Poped Pushed $E E QT $QT T RF $QRF F i $QRi i Read: ( Stack Poped Pushed $QR R ~ $Q~ ~ Not accepted Continue (y/n): n Press any key to continue . . . --------------------------------------------*/<|endoftext|>
<commit_before>#include <iostream> #include <string> #include "STRTK/strtk.hpp" #include "SFML/System.hpp" #include "SFML/Graphics/Sprite.hpp" #include "SFML/Graphics/Text.hpp" #include "SFML/Graphics.hpp" #include "painter.h" #define WINDOW_WIDTH 1024 #define WINDOW_HEIGHT 768 Painter::Painter(RenderNode *node) { sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32), "OpenWeb"); paintNode(node, &window); } //SFML does not automatically wrap text to fit the window. This is a hurriedly //implemented, temporary solution, and will receive more attention in the future. //Right now, I am considering adopting SFGUI as an additional graphics library //to address this (and other) issues I have found with SFML. std::string Painter::parseTextToLines(std::string textToParse, int windowBoundary) { std::vector<std::string> wordVector; strtk::parse(textToParse, " ", wordVector); std::string parsedString; std::string temporaryString; sf::Text tempString; for (int i = 0; i < wordVector.size(); i++) { temporaryString = temporaryString + wordVector.at(i) + " "; tempString.setString(temporaryString); if (tempString.getLocalBounds().width < windowBoundary) { parsedString = parsedString + wordVector.at(i) + " "; } else { parsedString = parsedString + "\n" + wordVector.at(i) + " "; tempString.setString(""); temporaryString.clear(); } } return parsedString; } void Painter::paintNode(RenderNode *node, sf::RenderWindow *window) { try { sf::Text text; text.setString(parseTextToLines(node->getText(), 2048)); text.setCharacterSize(15); sf::Font font; if (!font.loadFromFile("fonts/LinLibertine_R.ttf")) { throw "Error: Could not load the font."; } text.setFont(font); while (window->isOpen()) { window->clear(); window->draw(text); window->display(); sf::Event event; while (window->pollEvent(event)) { if (sf::Event::Closed == event.type) { window->close(); } } } } catch (std::string error) { std::cout << error << std::endl; } } <commit_msg>Continued implementing the wrapping function. Will begin to work on implementing SFGUI next.<commit_after>#include <iostream> #include <string> #include "STRTK/strtk.hpp" #include "SFML/System.hpp" #include "SFML/Graphics/Sprite.hpp" #include "SFML/Graphics/Text.hpp" #include "SFML/Graphics.hpp" #include "painter.h" #define WINDOW_WIDTH 1024 #define WINDOW_HEIGHT 768 Painter::Painter(RenderNode *node) { sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32), "OpenWeb"); paintNode(node, &window); } //SFML does not automatically wrap text to fit the window. This is a hurriedly //implemented, temporary solution, and will receive more attention in the future. //Right now, I am considering adopting SFGUI as an additional graphics library //to address this (and other) issues I have found with SFML. std::string Painter::parseTextToLines(std::string textToParse, int windowBoundary) { std::vector<std::string> wordVector; strtk::parse(textToParse, " ", wordVector); std::string parsedString; std::string temporaryString; sf::Text tempString; for (unsigned int i = 0; i < wordVector.size(); i++) { temporaryString = temporaryString + wordVector.at(i) + " "; tempString.setString(temporaryString); if (tempString.getLocalBounds().width < windowBoundary) { parsedString = parsedString + wordVector.at(i) + " "; } else { parsedString = parsedString + "\n" + wordVector.at(i) + " "; tempString.setString(""); temporaryString.clear(); } } return parsedString; } void Painter::paintNode(RenderNode *node, sf::RenderWindow *window) { try { sf::Text text; text.setString(parseTextToLines(node->getText(), 2000)); text.setCharacterSize(15); sf::Font font; if (!font.loadFromFile("fonts/LinLibertine_R.ttf")) { throw "Error: Could not load the font."; } text.setFont(font); while (window->isOpen()) { window->clear(); window->draw(text); window->display(); sf::Event event; while (window->pollEvent(event)) { if (sf::Event::Closed == event.type) { window->close(); } } } } catch (std::string error) { std::cout << error << std::endl; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. * */ #ifndef ARP_HH_ #define ARP_HH_ #include "net.hh" #include "core/reactor.hh" #include "byteorder.hh" #include "ethernet.hh" #include "core/print.hh" #include <unordered_map> namespace net { class arp; class arp_for_protocol; template <typename L3> class arp_for; class arp_for_protocol { protected: arp& _arp; uint16_t _proto_num; public: arp_for_protocol(arp& a, uint16_t proto_num); virtual ~arp_for_protocol(); virtual future<> received(packet p) = 0; }; class arp { interface* _netif; l3_protocol _proto; subscription<packet, ethernet_address> _rx_packets; std::unordered_map<uint16_t, arp_for_protocol*> _arp_for_protocol; private: struct arp_hdr { packed<uint16_t> htype; packed<uint16_t> ptype; template <typename Adjuster> void adjust_endianness(Adjuster a) { return a(htype, ptype); } }; public: explicit arp(interface* netif); void add(uint16_t proto_num, arp_for_protocol* afp); void del(uint16_t proto_num); private: ethernet_address l2self() { return _netif->hw_address(); } future<> process_packet(packet p, ethernet_address from); template <class l3_proto> friend class arp_for; }; template <typename L3> class arp_for : public arp_for_protocol { public: using l2addr = ethernet_address; using l3addr = typename L3::address_type; private: enum oper { op_request = 1, op_reply = 2, }; struct arp_hdr { packed<uint16_t> htype; packed<uint16_t> ptype; uint8_t hlen; uint8_t plen; packed<uint16_t> oper; l2addr sender_hwaddr; l3addr sender_paddr; l2addr target_hwaddr; l3addr target_paddr; template <typename Adjuster> void adjust_endianness(Adjuster a) { a(htype, ptype, oper, sender_hwaddr, sender_paddr, target_hwaddr, target_paddr); } }; struct resolution { std::vector<promise<l2addr>> _waiters; }; private: l3addr _l3self = L3::broadcast_address(); std::unordered_map<l3addr, l2addr> _table; std::unordered_map<l3addr, resolution> _in_progress; private: packet make_query_packet(l3addr paddr); virtual future<> received(packet p) override; future<> handle_request(arp_hdr* ah); l2addr l2self() { return _arp.l2self(); } public: explicit arp_for(arp& a) : arp_for_protocol(a, L3::arp_protocol_type()) {} future<ethernet_address> lookup(const l3addr& addr); void learn(l2addr l2, l3addr l3); void run(); void set_self_addr(l3addr addr) { _l3self = addr; } friend class arp; }; template <typename L3> packet arp_for<L3>::make_query_packet(l3addr paddr) { arp_hdr hdr; hdr.htype = ethernet::arp_hardware_type(); hdr.ptype = L3::arp_protocol_type(); hdr.hlen = sizeof(l2addr); hdr.plen = sizeof(l3addr); hdr.oper = op_request; hdr.sender_hwaddr = l2self(); hdr.sender_paddr = _l3self; hdr.target_hwaddr = ethernet::broadcast_address(); hdr.target_paddr = paddr; hton(hdr); return packet(reinterpret_cast<char*>(&hdr), sizeof(hdr)); } template <typename L3> future<ethernet_address> arp_for<L3>::lookup(const l3addr& paddr) { auto i = _table.find(paddr); if (i != _table.end()) { return make_ready_future<ethernet_address>(i->second); } resolution& res = _in_progress[paddr]; res._waiters.emplace_back(); auto fut = res._waiters.back().get_future(); if (res._waiters.size() == 1) { return _arp._proto.send(ethernet::broadcast_address(), make_query_packet(paddr)).then( [fut = std::move(fut)] () mutable { return std::move(fut); }); } else { return fut; } } template <typename L3> void arp_for<L3>::learn(l2addr hwaddr, l3addr paddr) { _table[paddr] = hwaddr; auto i = _in_progress.find(paddr); if (i != _in_progress.end()) { for (auto&& pr : i->second._waiters) { pr.set_value(hwaddr); } _in_progress.erase(i); } } template <typename L3> future<> arp_for<L3>::received(packet p) { auto ah = p.get_header<arp_hdr>(); if (!ah) { return make_ready_future<>(); } ntoh(*ah); if (ah->hlen != sizeof(l2addr) || ah->plen != sizeof(l3addr)) { return make_ready_future<>(); } switch (ah->oper) { case op_request: return handle_request(ah); case op_reply: learn(ah->sender_hwaddr, ah->sender_paddr); return make_ready_future<>(); default: return make_ready_future<>(); } } template <typename L3> future<> arp_for<L3>::handle_request(arp_hdr* ah) { if (ah->target_paddr == _l3self && _l3self != L3::broadcast_address()) { ah->oper = op_reply; ah->target_hwaddr = ah->sender_hwaddr; ah->target_paddr = ah->sender_paddr; ah->sender_hwaddr = l2self(); ah->sender_paddr = _l3self; hton(*ah); packet p(reinterpret_cast<char*>(ah), sizeof(*ah)); return _arp._proto.send(ah->target_hwaddr, std::move(p)); } else { return make_ready_future<>(); } } } #endif /* ARP_HH_ */ <commit_msg>arp: retry lookup requests every second<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. * */ #ifndef ARP_HH_ #define ARP_HH_ #include "net.hh" #include "core/reactor.hh" #include "byteorder.hh" #include "ethernet.hh" #include "core/print.hh" #include <unordered_map> namespace net { class arp; class arp_for_protocol; template <typename L3> class arp_for; class arp_for_protocol { protected: arp& _arp; uint16_t _proto_num; public: arp_for_protocol(arp& a, uint16_t proto_num); virtual ~arp_for_protocol(); virtual future<> received(packet p) = 0; }; class arp { interface* _netif; l3_protocol _proto; subscription<packet, ethernet_address> _rx_packets; std::unordered_map<uint16_t, arp_for_protocol*> _arp_for_protocol; private: struct arp_hdr { packed<uint16_t> htype; packed<uint16_t> ptype; template <typename Adjuster> void adjust_endianness(Adjuster a) { return a(htype, ptype); } }; public: explicit arp(interface* netif); void add(uint16_t proto_num, arp_for_protocol* afp); void del(uint16_t proto_num); private: ethernet_address l2self() { return _netif->hw_address(); } future<> process_packet(packet p, ethernet_address from); template <class l3_proto> friend class arp_for; }; template <typename L3> class arp_for : public arp_for_protocol { public: using l2addr = ethernet_address; using l3addr = typename L3::address_type; private: enum oper { op_request = 1, op_reply = 2, }; struct arp_hdr { packed<uint16_t> htype; packed<uint16_t> ptype; uint8_t hlen; uint8_t plen; packed<uint16_t> oper; l2addr sender_hwaddr; l3addr sender_paddr; l2addr target_hwaddr; l3addr target_paddr; template <typename Adjuster> void adjust_endianness(Adjuster a) { a(htype, ptype, oper, sender_hwaddr, sender_paddr, target_hwaddr, target_paddr); } }; struct resolution { std::vector<promise<l2addr>> _waiters; timer _timeout_timer; }; private: l3addr _l3self = L3::broadcast_address(); std::unordered_map<l3addr, l2addr> _table; std::unordered_map<l3addr, resolution> _in_progress; private: packet make_query_packet(l3addr paddr); virtual future<> received(packet p) override; future<> handle_request(arp_hdr* ah); l2addr l2self() { return _arp.l2self(); } public: explicit arp_for(arp& a) : arp_for_protocol(a, L3::arp_protocol_type()) {} future<ethernet_address> lookup(const l3addr& addr); void learn(l2addr l2, l3addr l3); void run(); void set_self_addr(l3addr addr) { _l3self = addr; } friend class arp; }; template <typename L3> packet arp_for<L3>::make_query_packet(l3addr paddr) { arp_hdr hdr; hdr.htype = ethernet::arp_hardware_type(); hdr.ptype = L3::arp_protocol_type(); hdr.hlen = sizeof(l2addr); hdr.plen = sizeof(l3addr); hdr.oper = op_request; hdr.sender_hwaddr = l2self(); hdr.sender_paddr = _l3self; hdr.target_hwaddr = ethernet::broadcast_address(); hdr.target_paddr = paddr; hton(hdr); return packet(reinterpret_cast<char*>(&hdr), sizeof(hdr)); } template <typename L3> future<ethernet_address> arp_for<L3>::lookup(const l3addr& paddr) { auto i = _table.find(paddr); if (i != _table.end()) { return make_ready_future<ethernet_address>(i->second); } auto& res = _in_progress[paddr]; res._waiters.emplace_back(); auto fut = res._waiters.back().get_future(); if (res._waiters.size() == 1) { res._timeout_timer.set_callback([paddr, this] { _arp._proto.send(ethernet::broadcast_address(), make_query_packet(paddr)); }); res._timeout_timer.arm_periodic(std::chrono::seconds(1)); return _arp._proto.send(ethernet::broadcast_address(), make_query_packet(paddr)).then( [fut = std::move(fut)] () mutable { return std::move(fut); }); } else { return fut; } } template <typename L3> void arp_for<L3>::learn(l2addr hwaddr, l3addr paddr) { _table[paddr] = hwaddr; auto i = _in_progress.find(paddr); if (i != _in_progress.end()) { auto& res = i->second; res._timeout_timer.cancel(); for (auto &&pr : res._waiters) { pr.set_value(hwaddr); } _in_progress.erase(i); } } template <typename L3> future<> arp_for<L3>::received(packet p) { auto ah = p.get_header<arp_hdr>(); if (!ah) { return make_ready_future<>(); } ntoh(*ah); if (ah->hlen != sizeof(l2addr) || ah->plen != sizeof(l3addr)) { return make_ready_future<>(); } switch (ah->oper) { case op_request: return handle_request(ah); case op_reply: learn(ah->sender_hwaddr, ah->sender_paddr); return make_ready_future<>(); default: return make_ready_future<>(); } } template <typename L3> future<> arp_for<L3>::handle_request(arp_hdr* ah) { if (ah->target_paddr == _l3self && _l3self != L3::broadcast_address()) { ah->oper = op_reply; ah->target_hwaddr = ah->sender_hwaddr; ah->target_paddr = ah->sender_paddr; ah->sender_hwaddr = l2self(); ah->sender_paddr = _l3self; hton(*ah); packet p(reinterpret_cast<char*>(ah), sizeof(*ah)); return _arp._proto.send(ah->target_hwaddr, std::move(p)); } else { return make_ready_future<>(); } } } #endif /* ARP_HH_ */ <|endoftext|>
<commit_before>/* Copyright (c) 2010-2012, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QtCore> #include <QSysInfo> #include <TWebApplication> #include <TSystemGlobal> #include "servermanager.h" #include "processinfo.h" #ifdef Q_OS_UNIX # include <sys/utsname.h> #endif namespace TreeFrog { #ifdef Q_OS_WIN extern void WINAPI winServiceMain(DWORD argc, LPTSTR *argv); #endif enum CommandOption { Invalid = 0, EnvironmentSpecified, SocketSpecified, PrintVersion, PrintUsage, DaemonMode, WindowsServiceMode, SendSignal, }; typedef QHash<int, QString> VersionHash; #ifdef Q_OS_WIN Q_GLOBAL_STATIC_WITH_INITIALIZER(VersionHash, winVersion, { x->insert(QSysInfo::WV_XP, "Windows XP"); x->insert(QSysInfo::WV_2003, "Windows Server 2003"); x->insert(QSysInfo::WV_VISTA, "Windows Vista or Windows Server 2008"); x->insert(QSysInfo::WV_WINDOWS7, "Windows 7 or Windows Server 2008 R2"); }) #endif #ifdef Q_OS_DARWIN Q_GLOBAL_STATIC_WITH_INITIALIZER(VersionHash, macVersion, { x->insert(QSysInfo::MV_10_3, "Mac OS X 10.3 Panther"); x->insert(QSysInfo::MV_10_4, "Mac OS X 10.4 Tiger"); x->insert(QSysInfo::MV_10_5, "Mac OS X 10.5 Leopard"); x->insert(QSysInfo::MV_10_6, "Mac OS X 10.6 Snow Leopard"); #if QT_VERSION >= 0x040800 x->insert(QSysInfo::MV_10_7, "Mac OS X 10.7 Lion"); #endif }) #endif typedef QHash<QString, int> OptionHash; Q_GLOBAL_STATIC_WITH_INITIALIZER(OptionHash, options, { x->insert("-e", EnvironmentSpecified); x->insert("-s", SocketSpecified); x->insert("-v", PrintVersion); x->insert("-h", PrintUsage); x->insert("-d", DaemonMode); x->insert("-w", WindowsServiceMode); x->insert("-k", SendSignal); }) static void usage() { char text[] = "Usage: %1 [-d] [-e environment] [application-directory]\n" \ "Usage: %1 [-k stop|abort] [application-directory]\n" \ "Options:\n" \ " -d : run as a daemon process\n" \ " -e environment : specify an environment of the database settings\n" \ " -k : send signal to a manager process\n\n" \ "Type '%1 -h' to show this information.\n" \ "Type '%1 -v' to show the program version."; QString cmd = QFileInfo(QCoreApplication::applicationFilePath()).fileName(); puts(qPrintable(QString(text).arg(cmd))); } static bool checkArguments() { for (QStringListIterator i(QCoreApplication::arguments()); i.hasNext(); ) { const QString &arg = i.next(); if (arg.startsWith('-') && options()->value(arg, Invalid) == Invalid) { fprintf(stderr, "invalid argument\n"); return false; } } return true; } static bool startDaemon() { bool success; QStringList args = QCoreApplication::arguments(); args.removeAll("-d"); #ifdef Q_OS_WIN PROCESS_INFORMATION pinfo; STARTUPINFOW startupInfo = { sizeof(STARTUPINFO), 0, 0, 0, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; success = CreateProcess(0, (wchar_t*)args.join(" ").utf16(), 0, 0, FALSE, CREATE_UNICODE_ENVIRONMENT, 0, (wchar_t*)QDir::currentPath().utf16(), &startupInfo, &pinfo); if (success) { CloseHandle(pinfo.hThread); CloseHandle(pinfo.hProcess); } #else args.removeFirst(); // Removes the program name success = QProcess::startDetached(QCoreApplication::applicationFilePath(), args, QDir::currentPath()); #endif return success; } static void writeStartupLog() { tSystemInfo("TreeFrog Framework version " TF_VERSION_STR); QString qtversion = "Qt " QT_VERSION_STR; #if defined(Q_OS_WIN) qtversion += QLatin1String(" / ") + winVersion()->value(QSysInfo::WindowsVersion, "Windows"); #elif defined(Q_OS_DARWIN) qtversion += QLatin1String(" / ") + macVersion()->value(QSysInfo::MacintoshVersion, "Mac OS X"); #elif defined(Q_OS_UNIX) struct utsname uts; if (uname(&uts) == 0) { qtversion += QString(" / %1 %2").arg(uts.sysname).arg(uts.release); } #endif tSystemInfo("%s", qtversion.toLatin1().data()); } static QString pidFilePath() { QString base = QFileInfo(QCoreApplication::applicationFilePath()).baseName(); return Tf::app()->tmpPath() + base + ".pid"; } static qint64 readPidFileOfApplication() { QFile pidf(pidFilePath()); if (pidf.open(QIODevice::ReadOnly)) { qint64 pid = pidf.readLine(100).toLongLong(); if (pid > 0) { return pid; } } return -1; } static qint64 runningApplicationPid() { qint64 pid = readPidFileOfApplication(); if (pid > 0) { QString name = ProcessInfo(pid).processName().toLower(); if (name == "treefrog" || name == "treefrogd") return pid; } return -1; } static int killTreeFrogProcess(const QString &cmd) { qint64 pid = runningApplicationPid(); if (pid < 0) { printf("TreeFrog server not running\n"); return 1; } ProcessInfo pi(pid); if (cmd == "stop") { // stop command pi.terminate(); if (pi.waitForTerminated()) { printf("TreeFrog application servers shutdown completed\n"); } else { fprintf(stderr, "TreeFrog application servers shutdown failed\n"); } } else if (cmd == "abort") { // abort command pi.kill(); tSystemInfo("Killed TreeFrog manager process pid:%ld", (long)pid); ::unlink(pidFilePath().toLatin1().data()); // kill all 'tadpole' processes #if defined(Q_OS_WIN) && !defined(TF_NO_DEBUG) ProcessInfo::killProcesses("tadpoled"); #else ProcessInfo::killProcesses("tadpole"); #endif tSystemInfo("Killed TreeFrog application server processes"); printf("Killed TreeFrog application server processes\n"); } else if (cmd == "restart") { // restart command pi.restart(); printf("Sent a restart request\n"); } else { usage(); return 1; } return 0; } int managerMain(int argc, char *argv[]) { TWebApplication app(argc, argv); // Creates the semaphore for system log QSystemSemaphore semaphore("TreeFrogSystemLog", 1, QSystemSemaphore::Create); tSetupSystemLoggers(); #if defined(Q_OS_UNIX) app.watchUnixSignal(SIGTERM); app.watchUnixSignal(SIGINT); app.watchUnixSignal(SIGHUP); #elif defined(Q_OS_WIN) app.watchConsoleSignal(); #endif // Sets codec QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForLocale(codec); if (!checkArguments()) { return 1; } bool daemonMode = false; QString signalCmd; QStringList args = QCoreApplication::arguments(); args.removeFirst(); for (QStringListIterator i(args); i.hasNext(); ) { const QString &arg = i.next(); int cmd = options()->value(arg, Invalid); switch (cmd) { case PrintVersion: printf("%s version " TF_VERSION_STR " (r%d) (built on %s)\n", qPrintable(QFileInfo(argv[0]).baseName()), TF_SRC_REVISION, __DATE__); return 0; break; case PrintUsage: usage(); return 0; break; case DaemonMode: daemonMode = true; break; case WindowsServiceMode: // ignore break; case SendSignal: signalCmd = i.next(); // assign a command break; default: // do nothing break; } } if (!app.appSettingsFileExists()) { fprintf(stderr, "INI file not found [%s]\n\n", qPrintable(app.appSettingsFilePath())); return 1; } if (!signalCmd.isEmpty()) { return killTreeFrogProcess(signalCmd); } // Check TreeFrog processes are running qint64 pid = runningApplicationPid(); if (pid > 0) { fprintf(stderr, "Already running pid:%ld\n", (long)pid); return 1; } if (!app.isValidDatabaseSettings()) { tSystemError("Database settings not found [environment: %s]", qPrintable(app.databaseEnvironment())); fprintf(stderr, "database settings not found [environment: %s]\n\n", qPrintable(app.databaseEnvironment())); usage(); return 1; } // Check a port number quint16 listenPort = 0; QString svrname = app.appSettings().value("ListenPort").toString(); if (svrname.startsWith("unix:", Qt::CaseInsensitive)) { svrname.remove(0, 5); } else { int port = svrname.toInt(); if (port <= 0 || port > USHRT_MAX) { tSystemError("Invalid port number: %d", port); return 1; } listenPort = port; svrname.clear(); } // start daemon process if (daemonMode) { if ( !startDaemon() ) { fprintf(stderr, "Failed to create process\n\n"); return 1; } return 0; } int ret = 0; QFile pidfile; for (;;) { ServerManager *manager = 0; switch ( app.multiProcessingModule() ) { case TWebApplication::Thread: { manager = new ServerManager(1, 1, 0, &app); break; } case TWebApplication::Prefork: { int max = app.appSettings().value("MPM.prefork.MaxServers").toInt(); int min = app.appSettings().value("MPM.prefork.MinServers").toInt(); int spare = app.appSettings().value("MPM.prefork.SpareServers").toInt(); manager = new ServerManager(max, min, spare, &app); break; } default: tSystemError("Invalid MPM specified"); return 1; } // Startup writeStartupLog(); bool started; if (listenPort > 0) { // TCP/IP started = manager->start(QHostAddress::Any, listenPort); } else { // UNIX domain started = manager->start(svrname); } if (!started) { tSystemError("TreeFrog application server startup failed"); fprintf(stderr, "TreeFrog application server startup failed\n\n"); return 1; } // tmp directory QDir tmpDir(app.tmpPath()); if (!tmpDir.exists()) { tmpDir.mkpath("."); } // Writes the PID pidfile.setFileName(pidFilePath()); if (pidfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { pid = QCoreApplication::applicationPid(); pidfile.write( QString::number(pid).toLatin1() ); pidfile.close(); } else { tSystemError("File open failed: %s", qPrintable(pidfile.fileName())); } ret = app.exec(); tSystemDebug("tfmanager returnCode:%d", ret); manager->stop(); if (ret == 1) { // means SIGHUP tSystemDebug("Restarts TreeFrog application servers"); //continue; } else { break; } } if (!svrname.isEmpty()) { // UNIX domain file QFile(svrname).remove(); } pidfile.remove(); // Removes the PID file return 0; } } // namespace TreeFrog int main(int argc, char *argv[]) { #ifdef Q_OS_WIN for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-w") == 0) { // Windows service mode SERVICE_TABLE_ENTRY entry[] = { { (LPTSTR)TEXT(""), TreeFrog::winServiceMain }, { 0, 0 } }; StartServiceCtrlDispatcher(entry); return 0; } } #endif return TreeFrog::managerMain(argc, argv); } <commit_msg>Added "Mountain Lion" system info.<commit_after>/* Copyright (c) 2010-2012, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <QtCore> #include <QSysInfo> #include <TWebApplication> #include <TSystemGlobal> #include "servermanager.h" #include "processinfo.h" #ifdef Q_OS_UNIX # include <sys/utsname.h> #endif namespace TreeFrog { #ifdef Q_OS_WIN extern void WINAPI winServiceMain(DWORD argc, LPTSTR *argv); #endif enum CommandOption { Invalid = 0, EnvironmentSpecified, SocketSpecified, PrintVersion, PrintUsage, DaemonMode, WindowsServiceMode, SendSignal, }; typedef QHash<int, QString> VersionHash; #ifdef Q_OS_WIN Q_GLOBAL_STATIC_WITH_INITIALIZER(VersionHash, winVersion, { x->insert(QSysInfo::WV_XP, "Windows XP"); x->insert(QSysInfo::WV_2003, "Windows Server 2003"); x->insert(QSysInfo::WV_VISTA, "Windows Vista or Windows Server 2008"); x->insert(QSysInfo::WV_WINDOWS7, "Windows 7 or Windows Server 2008 R2"); }) #endif #ifdef Q_OS_DARWIN Q_GLOBAL_STATIC_WITH_INITIALIZER(VersionHash, macVersion, { x->insert(QSysInfo::MV_10_3, "Mac OS X 10.3 Panther"); x->insert(QSysInfo::MV_10_4, "Mac OS X 10.4 Tiger"); x->insert(QSysInfo::MV_10_5, "Mac OS X 10.5 Leopard"); x->insert(QSysInfo::MV_10_6, "Mac OS X 10.6 Snow Leopard"); #if QT_VERSION >= 0x040800 x->insert(QSysInfo::MV_10_7, "Mac OS X 10.7 Lion"); x->insert(QSysInfo::MV_10_8, "Mac OS X 10.8 Mountain Lion"); #endif }) #endif typedef QHash<QString, int> OptionHash; Q_GLOBAL_STATIC_WITH_INITIALIZER(OptionHash, options, { x->insert("-e", EnvironmentSpecified); x->insert("-s", SocketSpecified); x->insert("-v", PrintVersion); x->insert("-h", PrintUsage); x->insert("-d", DaemonMode); x->insert("-w", WindowsServiceMode); x->insert("-k", SendSignal); }) static void usage() { char text[] = "Usage: %1 [-d] [-e environment] [application-directory]\n" \ "Usage: %1 [-k stop|abort] [application-directory]\n" \ "Options:\n" \ " -d : run as a daemon process\n" \ " -e environment : specify an environment of the database settings\n" \ " -k : send signal to a manager process\n\n" \ "Type '%1 -h' to show this information.\n" \ "Type '%1 -v' to show the program version."; QString cmd = QFileInfo(QCoreApplication::applicationFilePath()).fileName(); puts(qPrintable(QString(text).arg(cmd))); } static bool checkArguments() { for (QStringListIterator i(QCoreApplication::arguments()); i.hasNext(); ) { const QString &arg = i.next(); if (arg.startsWith('-') && options()->value(arg, Invalid) == Invalid) { fprintf(stderr, "invalid argument\n"); return false; } } return true; } static bool startDaemon() { bool success; QStringList args = QCoreApplication::arguments(); args.removeAll("-d"); #ifdef Q_OS_WIN PROCESS_INFORMATION pinfo; STARTUPINFOW startupInfo = { sizeof(STARTUPINFO), 0, 0, 0, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; success = CreateProcess(0, (wchar_t*)args.join(" ").utf16(), 0, 0, FALSE, CREATE_UNICODE_ENVIRONMENT, 0, (wchar_t*)QDir::currentPath().utf16(), &startupInfo, &pinfo); if (success) { CloseHandle(pinfo.hThread); CloseHandle(pinfo.hProcess); } #else args.removeFirst(); // Removes the program name success = QProcess::startDetached(QCoreApplication::applicationFilePath(), args, QDir::currentPath()); #endif return success; } static void writeStartupLog() { tSystemInfo("TreeFrog Framework version " TF_VERSION_STR); QString qtversion = "Qt " QT_VERSION_STR; #if defined(Q_OS_WIN) qtversion += QLatin1String(" / ") + winVersion()->value(QSysInfo::WindowsVersion, "Windows"); #elif defined(Q_OS_DARWIN) qtversion += QLatin1String(" / ") + macVersion()->value(QSysInfo::MacintoshVersion, "Mac OS X"); #elif defined(Q_OS_UNIX) struct utsname uts; if (uname(&uts) == 0) { qtversion += QString(" / %1 %2").arg(uts.sysname).arg(uts.release); } #endif tSystemInfo("%s", qtversion.toLatin1().data()); } static QString pidFilePath() { QString base = QFileInfo(QCoreApplication::applicationFilePath()).baseName(); return Tf::app()->tmpPath() + base + ".pid"; } static qint64 readPidFileOfApplication() { QFile pidf(pidFilePath()); if (pidf.open(QIODevice::ReadOnly)) { qint64 pid = pidf.readLine(100).toLongLong(); if (pid > 0) { return pid; } } return -1; } static qint64 runningApplicationPid() { qint64 pid = readPidFileOfApplication(); if (pid > 0) { QString name = ProcessInfo(pid).processName().toLower(); if (name == "treefrog" || name == "treefrogd") return pid; } return -1; } static int killTreeFrogProcess(const QString &cmd) { qint64 pid = runningApplicationPid(); if (pid < 0) { printf("TreeFrog server not running\n"); return 1; } ProcessInfo pi(pid); if (cmd == "stop") { // stop command pi.terminate(); if (pi.waitForTerminated()) { printf("TreeFrog application servers shutdown completed\n"); } else { fprintf(stderr, "TreeFrog application servers shutdown failed\n"); } } else if (cmd == "abort") { // abort command pi.kill(); tSystemInfo("Killed TreeFrog manager process pid:%ld", (long)pid); ::unlink(pidFilePath().toLatin1().data()); // kill all 'tadpole' processes #if defined(Q_OS_WIN) && !defined(TF_NO_DEBUG) ProcessInfo::killProcesses("tadpoled"); #else ProcessInfo::killProcesses("tadpole"); #endif tSystemInfo("Killed TreeFrog application server processes"); printf("Killed TreeFrog application server processes\n"); } else if (cmd == "restart") { // restart command pi.restart(); printf("Sent a restart request\n"); } else { usage(); return 1; } return 0; } int managerMain(int argc, char *argv[]) { TWebApplication app(argc, argv); // Creates the semaphore for system log QSystemSemaphore semaphore("TreeFrogSystemLog", 1, QSystemSemaphore::Create); tSetupSystemLoggers(); #if defined(Q_OS_UNIX) app.watchUnixSignal(SIGTERM); app.watchUnixSignal(SIGINT); app.watchUnixSignal(SIGHUP); #elif defined(Q_OS_WIN) app.watchConsoleSignal(); #endif // Sets codec QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForLocale(codec); if (!checkArguments()) { return 1; } bool daemonMode = false; QString signalCmd; QStringList args = QCoreApplication::arguments(); args.removeFirst(); for (QStringListIterator i(args); i.hasNext(); ) { const QString &arg = i.next(); int cmd = options()->value(arg, Invalid); switch (cmd) { case PrintVersion: printf("%s version " TF_VERSION_STR " (r%d) (built on %s)\n", qPrintable(QFileInfo(argv[0]).baseName()), TF_SRC_REVISION, __DATE__); return 0; break; case PrintUsage: usage(); return 0; break; case DaemonMode: daemonMode = true; break; case WindowsServiceMode: // ignore break; case SendSignal: signalCmd = i.next(); // assign a command break; default: // do nothing break; } } if (!app.appSettingsFileExists()) { fprintf(stderr, "INI file not found [%s]\n\n", qPrintable(app.appSettingsFilePath())); return 1; } if (!signalCmd.isEmpty()) { return killTreeFrogProcess(signalCmd); } // Check TreeFrog processes are running qint64 pid = runningApplicationPid(); if (pid > 0) { fprintf(stderr, "Already running pid:%ld\n", (long)pid); return 1; } if (!app.isValidDatabaseSettings()) { tSystemError("Database settings not found [environment: %s]", qPrintable(app.databaseEnvironment())); fprintf(stderr, "database settings not found [environment: %s]\n\n", qPrintable(app.databaseEnvironment())); usage(); return 1; } // Check a port number quint16 listenPort = 0; QString svrname = app.appSettings().value("ListenPort").toString(); if (svrname.startsWith("unix:", Qt::CaseInsensitive)) { svrname.remove(0, 5); } else { int port = svrname.toInt(); if (port <= 0 || port > USHRT_MAX) { tSystemError("Invalid port number: %d", port); return 1; } listenPort = port; svrname.clear(); } // start daemon process if (daemonMode) { if ( !startDaemon() ) { fprintf(stderr, "Failed to create process\n\n"); return 1; } return 0; } int ret = 0; QFile pidfile; for (;;) { ServerManager *manager = 0; switch ( app.multiProcessingModule() ) { case TWebApplication::Thread: { manager = new ServerManager(1, 1, 0, &app); break; } case TWebApplication::Prefork: { int max = app.appSettings().value("MPM.prefork.MaxServers").toInt(); int min = app.appSettings().value("MPM.prefork.MinServers").toInt(); int spare = app.appSettings().value("MPM.prefork.SpareServers").toInt(); manager = new ServerManager(max, min, spare, &app); break; } default: tSystemError("Invalid MPM specified"); return 1; } // Startup writeStartupLog(); bool started; if (listenPort > 0) { // TCP/IP started = manager->start(QHostAddress::Any, listenPort); } else { // UNIX domain started = manager->start(svrname); } if (!started) { tSystemError("TreeFrog application server startup failed"); fprintf(stderr, "TreeFrog application server startup failed\n\n"); return 1; } // tmp directory QDir tmpDir(app.tmpPath()); if (!tmpDir.exists()) { tmpDir.mkpath("."); } // Writes the PID pidfile.setFileName(pidFilePath()); if (pidfile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { pid = QCoreApplication::applicationPid(); pidfile.write( QString::number(pid).toLatin1() ); pidfile.close(); } else { tSystemError("File open failed: %s", qPrintable(pidfile.fileName())); } ret = app.exec(); tSystemDebug("tfmanager returnCode:%d", ret); manager->stop(); if (ret == 1) { // means SIGHUP tSystemDebug("Restarts TreeFrog application servers"); //continue; } else { break; } } if (!svrname.isEmpty()) { // UNIX domain file QFile(svrname).remove(); } pidfile.remove(); // Removes the PID file return 0; } } // namespace TreeFrog int main(int argc, char *argv[]) { #ifdef Q_OS_WIN for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-w") == 0) { // Windows service mode SERVICE_TABLE_ENTRY entry[] = { { (LPTSTR)TEXT(""), TreeFrog::winServiceMain }, { 0, 0 } }; StartServiceCtrlDispatcher(entry); return 0; } } #endif return TreeFrog::managerMain(argc, argv); } <|endoftext|>
<commit_before>// Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Peter Grehan (grehan@iprg.nokia.com) coded all of this // NE2000/ether stuff. // eth_fbsd.cc - A FreeBSD packet filter implementation of // an ethernet pktmover. There are some problems and limitations // with FreeBSD: // - the source address of the frame is overwritten by // the hosts's source address. This causes problems with // learning bridges - since they cannot determine where // BOCHS 'is', they broadcast the frame to all ports. // - packets cannot be sent from BOCHS to the host // - TCP performance seems to be abysmal; I think this is // a timing problem somewhere. // - I haven't handled the case where multiple frames arrive // in a single BPF read. // // The /dev/bpf* devices need to be set up with the appropriate // permissions for this to work. // // The config line in .bochsrc should look something like: // // ne2k: ioaddr=0x280, irq=9, mac=00:a:b:c:1:2, ethmod=fbsd, ethdev=fxp0 // #include "bochs.h" #ifdef ETH_FBSD #define LOG_THIS this-> extern "C" { #include <fcntl.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <net/if.h> #include <net/bpf.h> }; #define BX_BPF_POLL 1000 // Poll for a frame every 1000 usecs #define BX_BPF_BUFSIZ 2048 // enough for an ether frame + bpf hdr #define BX_BPF_INSNSIZ 8 // number of bpf insns // template filter for a unicast mac address and all // multicast/broadcast frames static const struct bpf_insn macfilter[] = { BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xaaaaaaaa, 0, 2), BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 0), BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x0000aaaa, 2, 0), BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 0), BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x01, 0, 1), BPF_STMT(BPF_RET, 1514), BPF_STMT(BPF_RET, 0), }; // template filter for all frames static const struct bpf_insn promiscfilter[] = { BPF_STMT(BPF_RET, 1514) }; // // Define the class. This is private to this module // class bx_fbsd_pktmover_c : public eth_pktmover_c { public: bx_fbsd_pktmover_c(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg); void sendpkt(void *buf, unsigned io_len); private: char *fbsd_macaddr[6]; int bpf_fd; static void rx_timer_handler(void *); void rx_timer(void); int rx_timer_index; struct bpf_insn filter[BX_BPF_INSNSIZ]; FILE *txlog, *txlog_txt, *rxlog, *rxlog_txt; }; // // Define the static class that registers the derived pktmover class, // and allocates one on request. // class bx_fbsd_locator_c : public eth_locator_c { public: bx_fbsd_locator_c(void) : eth_locator_c("fbsd") {} protected: eth_pktmover_c *allocate(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg) { return (new bx_fbsd_pktmover_c(netif, macaddr, rxh, rxarg)); } } bx_fbsd_match; // // Define the methods for the bx_fbsd_pktmover derived class // // the constructor // // Open a bpf file descriptor, and attempt to bind to // the specified netif (Replicates libpcap open code) // bx_fbsd_pktmover_c::bx_fbsd_pktmover_c(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg) { char device[sizeof "/dev/bpf000"]; int tmpfd; int n = 0; struct ifreq ifr; struct bpf_version bv; struct bpf_program bp; u_int v; memcpy(fbsd_macaddr, macaddr, 6); do { (void)sprintf(device, "/dev/bpf%d", n++); this->bpf_fd = open(device, O_RDWR); } while (this->bpf_fd < 0); if (this->bpf_fd < 0) { BX_INFO(("eth_freebsd: could not open packet filter")); return; } if (ioctl(this->bpf_fd, BIOCVERSION, (caddr_t)&bv) < 0) { BX_INFO(("eth_freebsd: could not retrieve bpf version")); close(this->bpf_fd); this->bpf_fd = -1; return; } if (bv.bv_major != BPF_MAJOR_VERSION || bv.bv_minor < BPF_MINOR_VERSION) { BX_INFO(("eth_freebsd: bpf version mismatch")); close(this->bpf_fd); this->bpf_fd = -1; return; } // Set buffer size v = BX_BPF_BUFSIZ; if (ioctl(this->bpf_fd, BIOCSBLEN, (caddr_t)&v) < 0) { BX_INFO(("eth_freebsd: could not set buffer size")); close(this->bpf_fd); this->bpf_fd = -1; return; } (void)strncpy(ifr.ifr_name, netif, sizeof(ifr.ifr_name)); if (ioctl(this->bpf_fd, BIOCSETIF, (caddr_t)&ifr) < 0) { BX_INFO(("eth_freebsd: could not enable interface %s", netif)); close(this->bpf_fd); this->bpf_fd == -1; } // Verify that the device is an ethernet. if (ioctl(this->bpf_fd, BIOCGDLT, (caddr_t)&v) < 0) { BX_INFO(("eth_freebsd: could not retrieve datalink type")); close(this->bpf_fd); this->bpf_fd = -1; return; } if (v != DLT_EN10MB) { BX_INFO(("eth_freebsd: incorrect datalink type %d", v)); close(this->bpf_fd); this->bpf_fd = -1; return; } // Put the device into promisc mode. This could be optimised // to filter on a MAC address, broadcast, and all-multi, // but this will do for now. // if (ioctl(this->bpf_fd, BIOCPROMISC, NULL) < 0) { BX_INFO(("eth_freebsd: could not enable promisc mode")); close(this->bpf_fd); this->bpf_fd = -1; return; } // Set up non-blocking i/o v = 1; if (ioctl(this->bpf_fd, FIONBIO, &v) < 0) { BX_INFO(("eth_freebsd: could not enable non-blocking i/o")); close(this->bpf_fd); this->bpf_fd = -1; return; } // Install a filter #ifdef notdef memcpy(&this->filter, promiscfilter, sizeof(promiscfilter)); bp.bf_len = 1; #endif memcpy(&this->filter, macfilter, sizeof(macfilter)); this->filter[1].k = (macaddr[2] & 0xff) << 24 | (macaddr[3] & 0xff) << 16 | (macaddr[4] & 0xff) << 8 | (macaddr[5] & 0xff); this->filter[3].k = (macaddr[0] & 0xff) << 8 | (macaddr[1] & 0xff); bp.bf_len = 8; bp.bf_insns = &this->filter[0]; if (ioctl(this->bpf_fd, BIOCSETF, &bp) < 0) { BX_INFO(("eth_freebsd: could not set filter")); close(this->bpf_fd); this->bpf_fd = -1; return; } // Start the rx poll this->rx_timer_index = bx_pc_system.register_timer(this, this->rx_timer_handler, BX_BPF_POLL, 1, 1); // continuous, active this->rxh = rxh; this->rxarg = rxarg; #if BX_ETH_FBSD_LOGGING // eventually Bryce wants txlog to dump in pcap format so that // tcpdump -r FILE can read it and interpret packets. txlog = fopen ("ne2k-tx.log", "wb"); if (!txlog) BX_PANIC (("open ne2k-tx.log failed")); txlog_txt = fopen ("ne2k-txdump.txt", "wb"); if (!txlog_txt) BX_PANIC (("open ne2k-txdump.txt failed")); rxlog = fopen ("ne2k-rx.log", "wb"); if (!rxlog) BX_PANIC (("open ne2k-rx.log failed")); rxlog_txt = fopen ("ne2k-rxdump.txt", "wb"); if (!rxlog_txt) BX_PANIC (("open ne2k-rxdump.txt failed")); fprintf (txlog_txt, "null packetmover readable log file\n"); fprintf (txlog_txt, "net IF = %s\n", netif); fprintf (txlog_txt, "MAC address = "); fprintf (rxlog_txt, "null packetmover readable log file\n"); fprintf (rxlog_txt, "net IF = %s\n", netif); fprintf (rxlog_txt, "MAC address = "); for (int i=0; i<6; i++) { fprintf (txlog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : ""); fprintf (rxlog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : ""); } fprintf (txlog_txt, "\n--\n"); fflush (txlog_txt); fprintf (rxlog_txt, "\n--\n"); fflush (rxlog_txt); #endif } // the output routine - called with pre-formatted ethernet frame. void bx_fbsd_pktmover_c::sendpkt(void *buf, unsigned io_len) { #if BX_ETH_FBSD_LOGGING BX_DEBUG (("sendpkt length %u", io_len)); // dump raw bytes to a file, eventually dump in pcap format so that // tcpdump -r FILE can interpret them for us. int n = fwrite (buf, io_len, 1, txlog); if (n != 1) BX_ERROR (("fwrite to txlog failed", io_len)); // dump packet in hex into an ascii log file fprintf (txlog_txt, "NE2K transmitting a packet, length %u\n", io_len); Bit8u *charbuf = (Bit8u *)buf; for (n=0; n<io_len; n++) { if (((n % 16) == 0) && n>0) fprintf (txlog_txt, "\n"); fprintf (txlog_txt, "%02x ", charbuf[n]); } fprintf (txlog_txt, "\n--\n"); // flush log so that we see the packets as they arrive w/o buffering fflush (txlog); fflush (txlog_txt); #endif int status; if (this->bpf_fd != -1) status = write(this->bpf_fd, buf, io_len); } // The receive poll process void bx_fbsd_pktmover_c::rx_timer_handler(void *this_ptr) { bx_fbsd_pktmover_c *class_ptr = (bx_fbsd_pktmover_c *) this_ptr; class_ptr->rx_timer(); } void bx_fbsd_pktmover_c::rx_timer(void) { int nbytes = 0; Bit8u rxbuf[BX_BPF_BUFSIZ]; struct bpf_hdr *bhdr; nbytes = read(this->bpf_fd, rxbuf, sizeof(rxbuf)); if (nbytes > 0) { bhdr = (struct bpf_hdr *) rxbuf; // filter out packets sourced from this node if (memcmp(rxbuf + bhdr->bh_hdrlen + 6, this->fbsd_macaddr, 6)) { (*rxh)(rxarg, rxbuf + bhdr->bh_hdrlen, bhdr->bh_caplen); } #if BX_ETH_FBSD_LOGGING /// hey wait there is no receive data with a NULL ethernet, is there.... if (nbytes > 0) { BX_DEBUG (("receive packet length %u", nbytes)); // dump raw bytes to a file, eventually dump in pcap format so that // tcpdump -r FILE can interpret them for us. int n = fwrite (rxbuf, nbytes, 1, this->rxlog); if (n != 1) BX_ERROR (("fwrite to rxlog failed", nbytes)); // dump packet in hex into an ascii log file fprintf (this->rxlog_txt, "NE2K transmitting a packet, length %u\n", nbytes); Bit8u *charrxbuf = (Bit8u *)rxbuf; for (n=0; n<nbytes; n++) { if (((n % 16) == 0) && n>0) fprintf (this->rxlog_txt, "\n"); fprintf (this->rxlog_txt, "%02x ", rxbuf[n]); } fprintf (this->rxlog_txt, "\n--\n"); // flush log so that we see the packets as they arrive w/o buffering fflush (this->rxlog); fflush (this->rxlog_txt); } #endif } } #endif <commit_msg>- merge TX and RX log into a single ne2k.raw and ne2k.txt.<commit_after>// Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Peter Grehan (grehan@iprg.nokia.com) coded all of this // NE2000/ether stuff. // eth_fbsd.cc - A FreeBSD packet filter implementation of // an ethernet pktmover. There are some problems and limitations // with FreeBSD: // - the source address of the frame is overwritten by // the hosts's source address. This causes problems with // learning bridges - since they cannot determine where // BOCHS 'is', they broadcast the frame to all ports. // - packets cannot be sent from BOCHS to the host // - TCP performance seems to be abysmal; I think this is // a timing problem somewhere. // - I haven't handled the case where multiple frames arrive // in a single BPF read. // // The /dev/bpf* devices need to be set up with the appropriate // permissions for this to work. // // The config line in .bochsrc should look something like: // // ne2k: ioaddr=0x280, irq=9, mac=00:a:b:c:1:2, ethmod=fbsd, ethdev=fxp0 // #include "bochs.h" #ifdef ETH_FBSD #define LOG_THIS this-> extern "C" { #include <fcntl.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <net/if.h> #include <net/bpf.h> }; #define BX_BPF_POLL 1000 // Poll for a frame every 1000 usecs #define BX_BPF_BUFSIZ 2048 // enough for an ether frame + bpf hdr #define BX_BPF_INSNSIZ 8 // number of bpf insns // template filter for a unicast mac address and all // multicast/broadcast frames static const struct bpf_insn macfilter[] = { BPF_STMT(BPF_LD|BPF_W|BPF_ABS, 2), BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0xaaaaaaaa, 0, 2), BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 0), BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 0x0000aaaa, 2, 0), BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 0), BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x01, 0, 1), BPF_STMT(BPF_RET, 1514), BPF_STMT(BPF_RET, 0), }; // template filter for all frames static const struct bpf_insn promiscfilter[] = { BPF_STMT(BPF_RET, 1514) }; // // Define the class. This is private to this module // class bx_fbsd_pktmover_c : public eth_pktmover_c { public: bx_fbsd_pktmover_c(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg); void sendpkt(void *buf, unsigned io_len); private: char *fbsd_macaddr[6]; int bpf_fd; static void rx_timer_handler(void *); void rx_timer(void); int rx_timer_index; struct bpf_insn filter[BX_BPF_INSNSIZ]; FILE *ne2klog, *ne2klog_txt; }; // // Define the static class that registers the derived pktmover class, // and allocates one on request. // class bx_fbsd_locator_c : public eth_locator_c { public: bx_fbsd_locator_c(void) : eth_locator_c("fbsd") {} protected: eth_pktmover_c *allocate(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg) { return (new bx_fbsd_pktmover_c(netif, macaddr, rxh, rxarg)); } } bx_fbsd_match; // // Define the methods for the bx_fbsd_pktmover derived class // // the constructor // // Open a bpf file descriptor, and attempt to bind to // the specified netif (Replicates libpcap open code) // bx_fbsd_pktmover_c::bx_fbsd_pktmover_c(const char *netif, const char *macaddr, eth_rx_handler_t rxh, void *rxarg) { char device[sizeof "/dev/bpf000"]; int tmpfd; int n = 0; struct ifreq ifr; struct bpf_version bv; struct bpf_program bp; u_int v; memcpy(fbsd_macaddr, macaddr, 6); do { (void)sprintf(device, "/dev/bpf%d", n++); this->bpf_fd = open(device, O_RDWR); } while (this->bpf_fd < 0); if (this->bpf_fd < 0) { BX_INFO(("eth_freebsd: could not open packet filter")); return; } if (ioctl(this->bpf_fd, BIOCVERSION, (caddr_t)&bv) < 0) { BX_INFO(("eth_freebsd: could not retrieve bpf version")); close(this->bpf_fd); this->bpf_fd = -1; return; } if (bv.bv_major != BPF_MAJOR_VERSION || bv.bv_minor < BPF_MINOR_VERSION) { BX_INFO(("eth_freebsd: bpf version mismatch")); close(this->bpf_fd); this->bpf_fd = -1; return; } // Set buffer size v = BX_BPF_BUFSIZ; if (ioctl(this->bpf_fd, BIOCSBLEN, (caddr_t)&v) < 0) { BX_INFO(("eth_freebsd: could not set buffer size")); close(this->bpf_fd); this->bpf_fd = -1; return; } (void)strncpy(ifr.ifr_name, netif, sizeof(ifr.ifr_name)); if (ioctl(this->bpf_fd, BIOCSETIF, (caddr_t)&ifr) < 0) { BX_INFO(("eth_freebsd: could not enable interface %s", netif)); close(this->bpf_fd); this->bpf_fd == -1; } // Verify that the device is an ethernet. if (ioctl(this->bpf_fd, BIOCGDLT, (caddr_t)&v) < 0) { BX_INFO(("eth_freebsd: could not retrieve datalink type")); close(this->bpf_fd); this->bpf_fd = -1; return; } if (v != DLT_EN10MB) { BX_INFO(("eth_freebsd: incorrect datalink type %d", v)); close(this->bpf_fd); this->bpf_fd = -1; return; } // Put the device into promisc mode. This could be optimised // to filter on a MAC address, broadcast, and all-multi, // but this will do for now. // if (ioctl(this->bpf_fd, BIOCPROMISC, NULL) < 0) { BX_INFO(("eth_freebsd: could not enable promisc mode")); close(this->bpf_fd); this->bpf_fd = -1; return; } // Set up non-blocking i/o v = 1; if (ioctl(this->bpf_fd, FIONBIO, &v) < 0) { BX_INFO(("eth_freebsd: could not enable non-blocking i/o")); close(this->bpf_fd); this->bpf_fd = -1; return; } // Install a filter #ifdef notdef memcpy(&this->filter, promiscfilter, sizeof(promiscfilter)); bp.bf_len = 1; #endif memcpy(&this->filter, macfilter, sizeof(macfilter)); this->filter[1].k = (macaddr[2] & 0xff) << 24 | (macaddr[3] & 0xff) << 16 | (macaddr[4] & 0xff) << 8 | (macaddr[5] & 0xff); this->filter[3].k = (macaddr[0] & 0xff) << 8 | (macaddr[1] & 0xff); bp.bf_len = 8; bp.bf_insns = &this->filter[0]; if (ioctl(this->bpf_fd, BIOCSETF, &bp) < 0) { BX_INFO(("eth_freebsd: could not set filter")); close(this->bpf_fd); this->bpf_fd = -1; return; } // Start the rx poll this->rx_timer_index = bx_pc_system.register_timer(this, this->rx_timer_handler, BX_BPF_POLL, 1, 1); // continuous, active this->rxh = rxh; this->rxarg = rxarg; #if BX_ETH_FBSD_LOGGING // eventually Bryce wants ne2klog to dump in pcap format so that // tcpdump -r FILE can read it and interpret packets. ne2klog = fopen ("ne2k.raw", "wb"); if (!ne2klog) BX_PANIC (("open ne2k-tx.log failed")); ne2klog_txt = fopen ("ne2k.txt", "wb"); if (!ne2klog_txt) BX_PANIC (("open ne2k-txdump.txt failed")); fprintf (ne2klog_txt, "null packetmover readable log file\n"); fprintf (ne2klog_txt, "net IF = %s\n", netif); fprintf (ne2klog_txt, "MAC address = "); for (int i=0; i<6; i++) fprintf (ne2klog_txt, "%02x%s", 0xff & macaddr[i], i<5?":" : ""); fprintf (ne2klog_txt, "\n--\n"); fflush (ne2klog_txt); #endif } // the output routine - called with pre-formatted ethernet frame. void bx_fbsd_pktmover_c::sendpkt(void *buf, unsigned io_len) { #if BX_ETH_FBSD_LOGGING BX_DEBUG (("sendpkt length %u", io_len)); // dump raw bytes to a file, eventually dump in pcap format so that // tcpdump -r FILE can interpret them for us. int n = fwrite (buf, io_len, 1, ne2klog); if (n != 1) BX_ERROR (("fwrite to ne2klog failed", io_len)); // dump packet in hex into an ascii log file fprintf (ne2klog_txt, "NE2K TX packet, length %u\n", io_len); Bit8u *charbuf = (Bit8u *)buf; for (n=0; n<io_len; n++) { if (((n % 16) == 0) && n>0) fprintf (ne2klog_txt, "\n"); fprintf (ne2klog_txt, "%02x ", charbuf[n]); } fprintf (ne2klog_txt, "\n--\n"); // flush log so that we see the packets as they arrive w/o buffering fflush (ne2klog); fflush (ne2klog_txt); #endif int status; if (this->bpf_fd != -1) status = write(this->bpf_fd, buf, io_len); } // The receive poll process void bx_fbsd_pktmover_c::rx_timer_handler(void *this_ptr) { bx_fbsd_pktmover_c *class_ptr = (bx_fbsd_pktmover_c *) this_ptr; class_ptr->rx_timer(); } void bx_fbsd_pktmover_c::rx_timer(void) { int nbytes = 0; Bit8u rxbuf[BX_BPF_BUFSIZ]; struct bpf_hdr *bhdr; nbytes = read(this->bpf_fd, rxbuf, sizeof(rxbuf)); if (nbytes > 0) { bhdr = (struct bpf_hdr *) rxbuf; // filter out packets sourced from this node if (memcmp(rxbuf + bhdr->bh_hdrlen + 6, this->fbsd_macaddr, 6)) { (*rxh)(rxarg, rxbuf + bhdr->bh_hdrlen, bhdr->bh_caplen); } #if BX_ETH_FBSD_LOGGING /// hey wait there is no receive data with a NULL ethernet, is there.... if (nbytes > 0) { BX_DEBUG (("receive packet length %u", nbytes)); // dump raw bytes to a file, eventually dump in pcap format so that // tcpdump -r FILE can interpret them for us. int n = fwrite (rxbuf, nbytes, 1, ne2klog); if (n != 1) BX_ERROR (("fwrite to ne2klog failed", nbytes)); // dump packet in hex into an ascii log file fprintf (this->ne2klog_txt, "NE2K RX packet, length %u\n", nbytes); Bit8u *charrxbuf = (Bit8u *)rxbuf; for (n=0; n<nbytes; n++) { if (((n % 16) == 0) && n>0) fprintf (this->ne2klog_txt, "\n"); fprintf (this->ne2klog_txt, "%02x ", rxbuf[n]); } fprintf (this->ne2klog_txt, "\n--\n"); // flush log so that we see the packets as they arrive w/o buffering fflush (this->ne2klog); fflush (this->ne2klog_txt); } #endif } } #endif <|endoftext|>
<commit_before>#include "test_http_services.h" using namespace std; using namespace Datacratic; HttpService:: HttpService(const shared_ptr<ServiceProxies> & proxies) : ServiceBase("http-test-service", proxies), HttpEndpoint("http-test-service-ep"), portToUse(0), numReqs(0) { HttpEndpoint::setPollingMode(EndpointBase::MIN_CPU_POLLING); } HttpService:: ~HttpService() { shutdown(); } void HttpService:: start(const string & address, int numThreads) { init(portToUse, address, numThreads); waitListening(); } shared_ptr<ConnectionHandler> HttpService:: makeNewHandler() { return make_shared<HttpTestConnHandler>(); } void HttpTestConnHandler:: handleHttpPayload(const HttpHeader & header, const string & payload) { HttpService *svc = (HttpService *) httpEndpoint; svc->handleHttpPayload(*this, header, payload); } void HttpTestConnHandler:: sendResponse(int code, const string & body, const string & type) { putResponseOnWire(HttpResponse(code, type, body)); } HttpGetService:: HttpGetService(const shared_ptr<ServiceProxies> & proxies) : HttpService(proxies) {} void HttpGetService:: handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) { numReqs++; string key = header.verb + ":" + header.resource; if (header.resource == "/timeout") { sleep(3); handler.sendResponse(200, "Will time out", "text/plain"); } else if (header.resource == "/counter") { handler.sendResponse(200, to_string(numReqs), "text/plain"); } else if (header.resource == "/headers") { string headersBody("{\n"); bool first(true); for (const auto & it: header.headers) { if (first) { first = false; } else { headersBody += ",\n"; } headersBody += " \"" + it.first + "\": \"" + it.second + "\"\n"; } headersBody += "}\n"; handler.sendResponse(200, headersBody, "application/json"); } else if (header.resource == "/query-params") { string body = header.queryParams.uriEscaped(); handler.sendResponse(200, body, "text/plain"); } else if (header.resource == "/connection-close") { handler.send("HTTP/1.1 204 No contents\r\nConnection: close\r\n\r\n", PassiveConnectionHandler::NextAction::NEXT_CLOSE); } else if (header.resource == "/quiet-connection-close") { handler.send("HTTP/1.1 204 No contents\r\n\r\n", PassiveConnectionHandler::NextAction::NEXT_CLOSE); } else if (header.resource == "/abrupt-connection-close") { handler.send("", PassiveConnectionHandler::NextAction::NEXT_CLOSE); } else { const auto & it = responses_.find(key); if (it == responses_.end()) { handler.sendResponse(404, "Not found", "text/plain"); } else { const TestResponse & resp = it->second; handler.sendResponse(resp.code_, resp.body_, "text/plain"); } } } void HttpGetService:: addResponse(const string & verb, const string & resource, int code, const string & body) { string key = verb + ":" + resource; responses_[key] = TestResponse(code, body); } HttpUploadService:: HttpUploadService(const shared_ptr<ServiceProxies> & proxies) : HttpService(proxies) {} void HttpUploadService:: handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) { Json::Value response; string cType = header.contentType; if (cType.empty()) { cType = header.tryGetHeader("Content-Type"); } response["verb"] = header.verb; response["type"] = cType; response["payload"] = payload; Json::Value & jsonHeaders = response["headers"]; for (const auto & it: header.headers) { jsonHeaders[it.first] = it.second; } handler.sendResponse(200, response.toString(), "application/json"); } <commit_msg>test_http_service: restored MIN_CONTEXT_SWITCH_POLLING for higher performance<commit_after>#include "test_http_services.h" using namespace std; using namespace Datacratic; HttpService:: HttpService(const shared_ptr<ServiceProxies> & proxies) : ServiceBase("http-test-service", proxies), HttpEndpoint("http-test-service-ep"), portToUse(0), numReqs(0) { HttpEndpoint::setPollingMode(EndpointBase::MIN_CONTEXT_SWITCH_POLLING); } HttpService:: ~HttpService() { shutdown(); } void HttpService:: start(const string & address, int numThreads) { init(portToUse, address, numThreads); waitListening(); } shared_ptr<ConnectionHandler> HttpService:: makeNewHandler() { return make_shared<HttpTestConnHandler>(); } void HttpTestConnHandler:: handleHttpPayload(const HttpHeader & header, const string & payload) { HttpService *svc = (HttpService *) httpEndpoint; svc->handleHttpPayload(*this, header, payload); } void HttpTestConnHandler:: sendResponse(int code, const string & body, const string & type) { putResponseOnWire(HttpResponse(code, type, body)); } HttpGetService:: HttpGetService(const shared_ptr<ServiceProxies> & proxies) : HttpService(proxies) {} void HttpGetService:: handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) { numReqs++; string key = header.verb + ":" + header.resource; if (header.resource == "/timeout") { sleep(3); handler.sendResponse(200, "Will time out", "text/plain"); } else if (header.resource == "/counter") { handler.sendResponse(200, to_string(numReqs), "text/plain"); } else if (header.resource == "/headers") { string headersBody("{\n"); bool first(true); for (const auto & it: header.headers) { if (first) { first = false; } else { headersBody += ",\n"; } headersBody += " \"" + it.first + "\": \"" + it.second + "\"\n"; } headersBody += "}\n"; handler.sendResponse(200, headersBody, "application/json"); } else if (header.resource == "/query-params") { string body = header.queryParams.uriEscaped(); handler.sendResponse(200, body, "text/plain"); } else if (header.resource == "/connection-close") { handler.send("HTTP/1.1 204 No contents\r\nConnection: close\r\n\r\n", PassiveConnectionHandler::NextAction::NEXT_CLOSE); } else if (header.resource == "/quiet-connection-close") { handler.send("HTTP/1.1 204 No contents\r\n\r\n", PassiveConnectionHandler::NextAction::NEXT_CLOSE); } else if (header.resource == "/abrupt-connection-close") { handler.send("", PassiveConnectionHandler::NextAction::NEXT_CLOSE); } else { const auto & it = responses_.find(key); if (it == responses_.end()) { handler.sendResponse(404, "Not found", "text/plain"); } else { const TestResponse & resp = it->second; handler.sendResponse(resp.code_, resp.body_, "text/plain"); } } } void HttpGetService:: addResponse(const string & verb, const string & resource, int code, const string & body) { string key = verb + ":" + resource; responses_[key] = TestResponse(code, body); } HttpUploadService:: HttpUploadService(const shared_ptr<ServiceProxies> & proxies) : HttpService(proxies) {} void HttpUploadService:: handleHttpPayload(HttpTestConnHandler & handler, const HttpHeader & header, const string & payload) { Json::Value response; string cType = header.contentType; if (cType.empty()) { cType = header.tryGetHeader("Content-Type"); } response["verb"] = header.verb; response["type"] = cType; response["payload"] = payload; Json::Value & jsonHeaders = response["headers"]; for (const auto & it: header.headers) { jsonHeaders[it.first] = it.second; } handler.sendResponse(200, response.toString(), "application/json"); } <|endoftext|>
<commit_before>/** * \file * \remark This file is part of VITA. * * \copyright Copyright (C) 2014-2015 EOS di Manlio Morini. * * \license * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/ */ #if !defined(VITA_GA_I_GA_H) # error "Don't include this file directly, include the specific .h instead" #endif #if !defined(VITA_INDIVIDUAL_GA_ITERATOR_TCC) #define VITA_INDIVIDUAL_GA_ITERATOR_TCC /// /// \brief Iterator to scan the active genes of an individual /// class i_ga::const_iterator { public: using iterator_category = std::forward_iterator_tag; using difference_type = std::ptrdiff_t ; using value_type = locus; using pointer = const value_type *; using reference = const value_type &; /// /// \brief Builds an empty iterator. /// /// Empty iterator is used as sentry (it is the value returned by /// i_ga::end()). /// const_iterator() : sup_(0), i_(std::numeric_limits<category_t>::max()) {} /// /// \param[in] id an individual. /// explicit const_iterator(const i_ga &id) : sup_(id.parameters()), i_(0) { } /// /// \return locus of the next active symbol. /// const_iterator &operator++() { ++i_; if (i_ >= sup_) i_ = std::numeric_limits<category_t>::max(); return *this;; } /// /// \param[in] rhs second term of comparison. /// /// Returns `true` if iterators point to the same locus. /// bool operator==(const const_iterator &rhs) const { return i_ == rhs.i_; } bool operator!=(const const_iterator &rhs) const { return !(*this == rhs); } /// /// \return the current locus of the individual. /// value_type operator*() const { return {0, i_}; } private: // Private data members const category_t sup_; category_t i_; }; // class i_ga::const_iterator #endif // Include guard <commit_msg>[REF] Changing the types of private data members in i_ga::const_iterator is now simpler<commit_after>/** * \file * \remark This file is part of VITA. * * \copyright Copyright (C) 2014-2016 EOS di Manlio Morini. * * \license * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/ */ #if !defined(VITA_GA_I_GA_H) # error "Don't include this file directly, include the specific .h instead" #endif #if !defined(VITA_INDIVIDUAL_GA_ITERATOR_TCC) #define VITA_INDIVIDUAL_GA_ITERATOR_TCC /// /// \brief Iterator to scan the active genes of an individual /// class i_ga::const_iterator { public: using iterator_category = std::forward_iterator_tag; using difference_type = std::ptrdiff_t ; using value_type = locus; using pointer = const value_type *; using reference = const value_type &; /// /// \brief Builds an empty iterator. /// /// Empty iterator is used as sentry (it is the value returned by /// i_ga::end()). /// const_iterator() : sup_(0), i_(std::numeric_limits<decltype(i_)>::max()) {} /// /// \param[in] id an individual. /// explicit const_iterator(const i_ga &id) : sup_(id.parameters()), i_(0) { } /// /// \return locus of the next active symbol. /// const_iterator &operator++() { ++i_; if (i_ >= sup_) i_ = std::numeric_limits<decltype(i_)>::max(); return *this;; } /// /// \param[in] rhs second term of comparison. /// /// Returns `true` if iterators point to the same locus. /// bool operator==(const const_iterator &rhs) const { return i_ == rhs.i_; } bool operator!=(const const_iterator &rhs) const { return !(*this == rhs); } /// /// \return the current locus of the individual. /// value_type operator*() const { return {0, i_}; } private: const category_t sup_; category_t i_; }; // class i_ga::const_iterator #endif // Include guard <|endoftext|>
<commit_before>#include "JeuxState.h" using namespace Ogre; JeuxState::JeuxState() : m_Loader(0), m_TerrainImported(true), m_SceneFile(Ogre::StringUtil::BLANK), // m_HelpInfo(Ogre::StringUtil::BLANK), m_Fly(false), m_FallVelocity(0) { m_MoveSpeed = 0.1f; m_RotateSpeed = 0.3f; m_bQuit = false; m_bSettingsMode = false; inputManager = InputManager::getSingletonPtr(); mCamNames.clear(); // m_HelpInfo = Ogre::String("Use [W][A][S][D] keys for movement.\nKeys [1]-[9] to switch between cameras.\n[0] toggles SceneNode debug visuals.\n\nPress [C] to toggle clamp to terrain (gravity).\n\n[G] toggles the detail panel.\n[R] cycles polygonModes (Solid/Wireframe/Points).\n[T] cycles various filtering.\n\n\nPress [ESC] to quit."); } JeuxState::~JeuxState(void) { delete m_Loader; } void JeuxState::enter() { using namespace CEGUI; inputManager->addKeyListener(this,"Game"); XsiliumFramework::getInstance()->m_pLog->logMessage("Entering JeuxState..."); CEGUI::WindowManager& winMgr(CEGUI::WindowManager::getSingleton()); CEGUI::Window* parent = winMgr.createWindow("DefaultWindow", "CEGUIApp/Console"); CEGUI::Window* d_root = winMgr.loadLayoutFromFile("XsiliumConsole.layout"); Console * d_console = new Console(d_root); // we will destroy the console box windows ourselves d_root->setDestroyedByParent(false); // Do events wire-up d_root->subscribeEvent(CEGUI::Window::EventKeyDown, Event::Subscriber(&Console::handleKeyDown, d_console)); d_root->getChild("Console/Button")-> subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Console::handleSubmit, d_console)); d_root->getChild("Console/Editbox")-> subscribeEvent(Editbox::EventTextAccepted, Event::Subscriber(&Console::handleSubmit, d_console)); // attach this window if parent is valid parent->addChild(d_root); m_pSceneMgr = XsiliumFramework::getInstance()->m_pRoot->createSceneManager(ST_GENERIC, "GameSceneMgr"); m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.7f, 0.7f, 0.7f)); m_pRSQ = m_pSceneMgr->createRayQuery(Ray()); // m_pRSQ->setQueryMask(OGRE_HEAD_MASK); m_pCamera = m_pSceneMgr->createCamera("GameCamera"); m_pCamera->setPosition(Ogre::Vector3(5, 60, 60)); m_pCamera->lookAt(Ogre::Vector3(5, 20, 0)); m_pCamera->setNearClipDistance(5); m_pCamera->setAspectRatio(Real(XsiliumFramework::getInstance()->m_pViewport->getActualWidth()) / Real(XsiliumFramework::getInstance()->m_pViewport->getActualHeight())); XsiliumFramework::getInstance()->m_pViewport->setCamera(m_pCamera); m_pCurrentObject = 0; // buildGUI(); CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(d_root); createScene(); } bool JeuxState::pause() { XsiliumFramework::getInstance()->m_pLog->logMessage("Pausing JeuxState..."); return true; } void JeuxState::resume() { XsiliumFramework::getInstance()->m_pLog->logMessage("Resuming JeuxState..."); // buildGUI(); XsiliumFramework::getInstance()->m_pViewport->setCamera(m_pCamera); m_bQuit = false; } void JeuxState::exit() { XsiliumFramework::getInstance()->m_pLog->logMessage("Leaving JeuxState..."); m_pSceneMgr->destroyCamera(m_pCamera); m_pSceneMgr->destroyQuery(m_pRSQ); if(m_pSceneMgr) XsiliumFramework::getInstance()->m_pRoot->destroySceneManager(m_pSceneMgr); inputManager->removeKeyListener(this); } void JeuxState::createScene() { m_Loader = new DotSceneLoader(); m_Loader->parseDotScene(m_SceneFile, "General", m_pSceneMgr); // Get rid of the initial camera m_pSceneMgr->destroyCamera(m_pCamera); // Loop through all cameras and grab their name and set their debug representation Ogre::SceneManager::CameraIterator cameras = m_pSceneMgr->getCameraIterator(); while (cameras.hasMoreElements()) { Ogre::Camera* camera = cameras.getNext(); mCamNames.push_back(camera->getName()); Ogre::Entity* debugEnt = m_pSceneMgr->createEntity(camera->getName() + Ogre::String("_debug"), "scbCamera.mesh"); try{ Ogre::SceneNode* sNode = m_pSceneMgr->getSceneNode(camera->getName()); sNode->attachObject(debugEnt); sNode->scale(0.5, 0.5, 0.5); }catch (...){ Ogre::SceneNode* pNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(camera->getName()); pNode->setPosition(camera->getPosition()); pNode->setOrientation(camera->getOrientation()); pNode->attachObject(debugEnt); pNode->scale(0.5, 0.5, 0.5); } } // Grab the first available camera, for now Ogre::String cameraName = mCamNames[0]; try { m_ActiveCamera = m_pSceneMgr->getCamera(cameraName); m_Window->getViewport(0)->setCamera(m_ActiveCamera); mCameraMan->setCamera(m_ActiveCamera); m_pSceneMgr->getEntity(m_ActiveCamera->getName() + Ogre::String("_debug"))->setVisible(false); for(unsigned int ij = 0;ij < m_Loader->mPGHandles.size();ij++) { m_Loader->mPGHandles[ij]->setCamera(m_ActiveCamera); } } catch (Ogre::Exception& e) { Ogre::LogManager::getSingleton().logMessage("SampleApp::createScene : setting the active camera to (\"" + cameraName + ") failed: " + e.getFullDescription()); } } void JeuxState::moveCamera() { } void JeuxState::getInput() { } void JeuxState::update(double timeSinceLastFrame) { m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame; // XsiliumFramework::getInstance()->m_pTrayMgr->frameRenderingQueued(m_FrameEvent); CEGUI::System& gui_system(CEGUI::System::getSingleton()); gui_system.injectTimePulse(timeSinceLastFrame); gui_system.getDefaultGUIContext().injectTimePulse(timeSinceLastFrame); if(m_bQuit == true) { popGameState(); return; } // if(!XsiliumFramework::getInstance()->m_pTrayMgr->isDialogVisible()) { /* if(m_pDetailsPanel->isVisible()) { m_pDetailsPanel->setParamValue(0, Ogre::StringConverter::toString(m_pCamera->getDerivedPosition().x)); m_pDetailsPanel->setParamValue(1, Ogre::StringConverter::toString(m_pCamera->getDerivedPosition().y)); m_pDetailsPanel->setParamValue(2, Ogre::StringConverter::toString(m_pCamera->getDerivedPosition().z)); m_pDetailsPanel->setParamValue(3, Ogre::StringConverter::toString(m_pCamera->getDerivedOrientation().w)); m_pDetailsPanel->setParamValue(4, Ogre::StringConverter::toString(m_pCamera->getDerivedOrientation().x)); m_pDetailsPanel->setParamValue(5, Ogre::StringConverter::toString(m_pCamera->getDerivedOrientation().y)); m_pDetailsPanel->setParamValue(6, Ogre::StringConverter::toString(m_pCamera->getDerivedOrientation().z)); if(m_bSettingsMode) m_pDetailsPanel->setParamValue(7, "Buffered Input"); else m_pDetailsPanel->setParamValue(7, "Un-Buffered Input"); } */ } m_MoveScale = m_MoveSpeed * timeSinceLastFrame; m_RotScale = m_RotateSpeed * timeSinceLastFrame; m_TranslateVector = Vector3::ZERO; getInput(); moveCamera(); } bool JeuxState::keyPressed(const OIS::KeyEvent &keyEventRef) { switch(keyEventRef.key) { case OIS::KC_ESCAPE: m_bQuit = true; break; default: break; } return true; } bool JeuxState::keyReleased(const OIS::KeyEvent &keyEventRef) { return true; } <commit_msg>Ajout des includes potentiellement nécessairents<commit_after>#include "JeuxState.h" #include "DotSceneLoader.h" #include "PagedGeometry.h" #include "GrassLoader.h" #include "BatchPage.h" #include "ImpostorPage.h" #include "TreeLoader3D.h" using namespace Ogre; using namespace Forests; JeuxState::JeuxState() : m_Loader(0), m_TerrainImported(true), m_SceneFile(Ogre::StringUtil::BLANK), // m_HelpInfo(Ogre::StringUtil::BLANK), m_Fly(false), m_FallVelocity(0) { m_MoveSpeed = 0.1f; m_RotateSpeed = 0.3f; m_bQuit = false; m_bSettingsMode = false; inputManager = InputManager::getSingletonPtr(); mCamNames.clear(); // m_HelpInfo = Ogre::String("Use [W][A][S][D] keys for movement.\nKeys [1]-[9] to switch between cameras.\n[0] toggles SceneNode debug visuals.\n\nPress [C] to toggle clamp to terrain (gravity).\n\n[G] toggles the detail panel.\n[R] cycles polygonModes (Solid/Wireframe/Points).\n[T] cycles various filtering.\n\n\nPress [ESC] to quit."); } JeuxState::~JeuxState(void) { delete m_Loader; } void JeuxState::enter() { using namespace CEGUI; inputManager->addKeyListener(this,"Game"); XsiliumFramework::getInstance()->m_pLog->logMessage("Entering JeuxState..."); CEGUI::WindowManager& winMgr(CEGUI::WindowManager::getSingleton()); CEGUI::Window* parent = winMgr.createWindow("DefaultWindow", "CEGUIApp/Console"); CEGUI::Window* d_root = winMgr.loadLayoutFromFile("XsiliumConsole.layout"); Console * d_console = new Console(d_root); // we will destroy the console box windows ourselves d_root->setDestroyedByParent(false); // Do events wire-up d_root->subscribeEvent(CEGUI::Window::EventKeyDown, Event::Subscriber(&Console::handleKeyDown, d_console)); d_root->getChild("Console/Button")-> subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Console::handleSubmit, d_console)); d_root->getChild("Console/Editbox")-> subscribeEvent(Editbox::EventTextAccepted, Event::Subscriber(&Console::handleSubmit, d_console)); // attach this window if parent is valid parent->addChild(d_root); m_pSceneMgr = XsiliumFramework::getInstance()->m_pRoot->createSceneManager(ST_GENERIC, "GameSceneMgr"); m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.7f, 0.7f, 0.7f)); m_pRSQ = m_pSceneMgr->createRayQuery(Ray()); // m_pRSQ->setQueryMask(OGRE_HEAD_MASK); m_pCamera = m_pSceneMgr->createCamera("GameCamera"); m_pCamera->setPosition(Ogre::Vector3(5, 60, 60)); m_pCamera->lookAt(Ogre::Vector3(5, 20, 0)); m_pCamera->setNearClipDistance(5); m_pCamera->setAspectRatio(Real(XsiliumFramework::getInstance()->m_pViewport->getActualWidth()) / Real(XsiliumFramework::getInstance()->m_pViewport->getActualHeight())); XsiliumFramework::getInstance()->m_pViewport->setCamera(m_pCamera); m_pCurrentObject = 0; // buildGUI(); CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(d_root); createScene(); } bool JeuxState::pause() { XsiliumFramework::getInstance()->m_pLog->logMessage("Pausing JeuxState..."); return true; } void JeuxState::resume() { XsiliumFramework::getInstance()->m_pLog->logMessage("Resuming JeuxState..."); // buildGUI(); XsiliumFramework::getInstance()->m_pViewport->setCamera(m_pCamera); m_bQuit = false; } void JeuxState::exit() { XsiliumFramework::getInstance()->m_pLog->logMessage("Leaving JeuxState..."); m_pSceneMgr->destroyCamera(m_pCamera); m_pSceneMgr->destroyQuery(m_pRSQ); if(m_pSceneMgr) XsiliumFramework::getInstance()->m_pRoot->destroySceneManager(m_pSceneMgr); inputManager->removeKeyListener(this); } void JeuxState::createScene() { m_Loader = new DotSceneLoader(); m_Loader->parseDotScene(m_SceneFile, "General", m_pSceneMgr); // Get rid of the initial camera m_pSceneMgr->destroyCamera(m_pCamera); // Loop through all cameras and grab their name and set their debug representation Ogre::SceneManager::CameraIterator cameras = m_pSceneMgr->getCameraIterator(); while (cameras.hasMoreElements()) { Ogre::Camera* camera = cameras.getNext(); mCamNames.push_back(camera->getName()); Ogre::Entity* debugEnt = m_pSceneMgr->createEntity(camera->getName() + Ogre::String("_debug"), "scbCamera.mesh"); try{ Ogre::SceneNode* sNode = m_pSceneMgr->getSceneNode(camera->getName()); sNode->attachObject(debugEnt); sNode->scale(0.5, 0.5, 0.5); }catch (...){ Ogre::SceneNode* pNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(camera->getName()); pNode->setPosition(camera->getPosition()); pNode->setOrientation(camera->getOrientation()); pNode->attachObject(debugEnt); pNode->scale(0.5, 0.5, 0.5); } } // Grab the first available camera, for now Ogre::String cameraName = mCamNames[0]; try { m_ActiveCamera = m_pSceneMgr->getCamera(cameraName); m_Window->getViewport(0)->setCamera(m_ActiveCamera); mCameraMan->setCamera(m_ActiveCamera); m_pSceneMgr->getEntity(m_ActiveCamera->getName() + Ogre::String("_debug"))->setVisible(false); for(unsigned int ij = 0;ij < m_Loader->mPGHandles.size();ij++) { m_Loader->mPGHandles[ij]->setCamera(m_ActiveCamera); } } catch (Ogre::Exception& e) { Ogre::LogManager::getSingleton().logMessage("SampleApp::createScene : setting the active camera to (\"" + cameraName + ") failed: " + e.getFullDescription()); } } void JeuxState::moveCamera() { } void JeuxState::getInput() { } void JeuxState::update(double timeSinceLastFrame) { m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame; // XsiliumFramework::getInstance()->m_pTrayMgr->frameRenderingQueued(m_FrameEvent); CEGUI::System& gui_system(CEGUI::System::getSingleton()); gui_system.injectTimePulse(timeSinceLastFrame); gui_system.getDefaultGUIContext().injectTimePulse(timeSinceLastFrame); if(m_bQuit == true) { popGameState(); return; } // if(!XsiliumFramework::getInstance()->m_pTrayMgr->isDialogVisible()) { /* if(m_pDetailsPanel->isVisible()) { m_pDetailsPanel->setParamValue(0, Ogre::StringConverter::toString(m_pCamera->getDerivedPosition().x)); m_pDetailsPanel->setParamValue(1, Ogre::StringConverter::toString(m_pCamera->getDerivedPosition().y)); m_pDetailsPanel->setParamValue(2, Ogre::StringConverter::toString(m_pCamera->getDerivedPosition().z)); m_pDetailsPanel->setParamValue(3, Ogre::StringConverter::toString(m_pCamera->getDerivedOrientation().w)); m_pDetailsPanel->setParamValue(4, Ogre::StringConverter::toString(m_pCamera->getDerivedOrientation().x)); m_pDetailsPanel->setParamValue(5, Ogre::StringConverter::toString(m_pCamera->getDerivedOrientation().y)); m_pDetailsPanel->setParamValue(6, Ogre::StringConverter::toString(m_pCamera->getDerivedOrientation().z)); if(m_bSettingsMode) m_pDetailsPanel->setParamValue(7, "Buffered Input"); else m_pDetailsPanel->setParamValue(7, "Un-Buffered Input"); } */ } m_MoveScale = m_MoveSpeed * timeSinceLastFrame; m_RotScale = m_RotateSpeed * timeSinceLastFrame; m_TranslateVector = Vector3::ZERO; getInput(); moveCamera(); } bool JeuxState::keyPressed(const OIS::KeyEvent &keyEventRef) { switch(keyEventRef.key) { case OIS::KC_ESCAPE: m_bQuit = true; break; default: break; } return true; } bool JeuxState::keyReleased(const OIS::KeyEvent &keyEventRef) { return true; } <|endoftext|>
<commit_before>inline bool cmp(line a, line b){ if(a == b){ return false; } if(ccw(origin, a.first, b.first) && !ccw(origin, a.second, b.first)){ return ccw(a.first, a.second, b.first) != ccw(a.first, a.second, origin); } else if(ccw(origin, a.first, b.second) && !ccw(origin,a.second, b.second)){ return ccw(a.first,a.second, b.second) != ccw(a.first,a.second, origin); } else{ return ccw(b.first, b.second, a.first) == ccw(b.first, b.second, origin); } } <commit_msg>padronizando<commit_after>inline bool cmpActive(line a, line b){ if(a == b) return false; // if lines are the same, ignore // checks if b.p1 is in the sector defined by a.p1 and a.p2 if(ccw(origin, a.p1, b.p1) && !ccw(origin, a.p2, b.p1)){ // if it is, checks if b.p1 is on the same side of line a as origin return ccw(a.p1, a.p2, b.p1) != ccw(a.p1, a.p2, origin); } else if(ccw(origin, a.p1, b.p2) && !ccw(origin, a.p2, b.p2)){ // if b.p1 isn't in the sector, but b.p2 is return ccw(a.p1, a.p2, b.p2) != ccw(a.p1, a.p2, origin); } else{ // this was missing: when interval A is completely inside B, so we can // choose any point of A we want return ccw(b.p1, b.p2, a.p1) == ccw(b.p1, b.p2, origin); } } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX24T ファースト・サンプル @n ・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/cmt_io.hpp" #include "common/sci_io.hpp" #include "common/fixed_fifo.hpp" #include "common/format.hpp" #include "common/iica_io.hpp" #include "common/command.hpp" #include "chip/DS3231.hpp" namespace { typedef device::system_io<10000000> SYSTEM_IO; typedef device::PORT<device::PORT0, device::bitpos::B0> LED; typedef device::SCI1 SCI_CH; static const char* system_str_ = { "RX24T" }; class cmt_task { public: void operator() () { } }; typedef utils::fixed_fifo<char, 512> RXB; // RX (RECV) バッファの定義 typedef utils::fixed_fifo<char, 256> TXB; // TX (SEND) バッファの定義 typedef device::sci_io<SCI_CH, RXB, TXB> SCI; // SCI ポートの第二候補を選択する場合 // typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::option::SECOND> SCI; SCI sci_; typedef device::cmt_io<device::CMT0> CMT; CMT cmt_; typedef device::iica_io<device::RIIC0> I2C; I2C i2c_; chip::DS3231<I2C> rtc_(i2c_); utils::command<128> command_; time_t get_time_() { time_t t = 0; if(!rtc_.get_time(t)) { utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(i2c_.get_last_error()); } return t; } void disp_time_(time_t t) { struct tm *m = localtime(&t); utils::format("%s %s %d %02d:%02d:%02d %4d\n") % get_wday(m->tm_wday) % get_mon(m->tm_mon) % static_cast<uint32_t>(m->tm_mday) % static_cast<uint32_t>(m->tm_hour) % static_cast<uint32_t>(m->tm_min) % static_cast<uint32_t>(m->tm_sec) % static_cast<uint32_t>(m->tm_year + 1900); } const char* get_dec_(const char* p, char tmch, int& value) { int v = 0; char ch; while((ch = *p) != 0) { ++p; if(ch == tmch) { break; } else if(ch >= '0' && ch <= '9') { v *= 10; v += ch - '0'; } else { return nullptr; } } value = v; return p; } void set_time_date_() { time_t t = get_time_(); if(t == 0) return; struct tm *m = localtime(&t); bool err = false; if(command_.get_words() == 3) { char buff[12]; if(command_.get_word(1, buff, sizeof(buff))) { const char* p = buff; int vs[3]; uint8_t i; for(i = 0; i < 3; ++i) { p = get_dec_(p, '/', vs[i]); if(p == nullptr) { break; } } if(p != nullptr && p[0] == 0 && i == 3) { if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900; if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1; if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2]; } else { err = true; } } if(command_.get_word(2, buff, sizeof(buff))) { const char* p = buff; int vs[3]; uint8_t i; for(i = 0; i < 3; ++i) { p = get_dec_(p, ':', vs[i]); if(p == nullptr) { break; } } if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) { if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0]; if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1]; if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2]; else m->tm_sec = 0; } else { err = true; } } } if(err) { utils::format("Can't analize Time/Date input.\n"); return; } time_t tt = mktime(m); if(!rtc_.set_time(tt)) { utils::format("Stall RTC write...\n"); } } } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } void sci_puts(const char* str) { sci_.puts(str); } char sci_getch(void) { return sci_.getch(); } uint16_t sci_length() { return sci_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { SYSTEM_IO::setup_system_clock(); LED::DIR = 1; LED::P = 0; { // タイマー設定(100Hz) uint8_t intr = 4; cmt_.start(100, intr); } { // SCI の開始 uint8_t intr = 2; // 割り込みレベル uint32_t baud = 115200; // ボーレート sci_.start(baud, intr); } auto clk = F_ICLK / 1000000; utils::format("Start DS3231 (I2C) sample for '%s' %d[MHz]\n") % system_str_ % clk; { // IICA(I2C) の開始 uint8_t intr_level = 0; if(!i2c_.start(I2C::speed::fast, intr_level)) { utils::format("IICA start error (%d)\n") % static_cast<int>(i2c_.get_last_error()); } } // DS3231(RTC) の開始 if(!rtc_.start()) { utils::format("Stall DS3231: (%d)\n") % static_cast<int>(i2c_.get_last_error()); } command_.set_prompt("# "); uint32_t cnt = 0; while(1) { cmt_.sync(); ++cnt; if(cnt >= 50) { cnt = 0; } if(cnt < 25) { LED::P = 0; } else { LED::P = 1; } // コマンド入力と、コマンド解析 if(command_.service()) { uint8_t cmdn = command_.get_words(); if(cmdn >= 1) { if(command_.cmp_word(0, "date")) { if(cmdn == 1) { time_t t = get_time_(); if(t != 0) { disp_time_(t); } } else { set_time_date_(); } } else if(command_.cmp_word(0, "help")) { utils::format("date\n"); utils::format("date yyyy/mm/dd hh:mm[:ss]\n"); } else { char buff[128]; if(command_.get_word(0, buff, sizeof(buff))) { utils::format("Command error: %s\n") % buff; } } } } } } <commit_msg>Rename: cmt_io to cmt_mgr<commit_after>//=====================================================================// /*! @file @brief RX24T ファースト・サンプル @n ・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/cmt_mgr.hpp" #include "common/sci_io.hpp" #include "common/fixed_fifo.hpp" #include "common/format.hpp" #include "common/iica_io.hpp" #include "common/command.hpp" #include "chip/DS3231.hpp" namespace { typedef device::system_io<10000000> SYSTEM_IO; typedef device::PORT<device::PORT0, device::bitpos::B0> LED; typedef device::SCI1 SCI_CH; static const char* system_str_ = { "RX24T" }; class cmt_task { public: void operator() () { } }; typedef utils::fixed_fifo<char, 512> RXB; // RX (RECV) バッファの定義 typedef utils::fixed_fifo<char, 256> TXB; // TX (SEND) バッファの定義 typedef device::sci_io<SCI_CH, RXB, TXB> SCI; // SCI ポートの第二候補を選択する場合 // typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::option::SECOND> SCI; SCI sci_; typedef device::cmt_mgr<device::CMT0> CMT; CMT cmt_; typedef device::iica_io<device::RIIC0> I2C; I2C i2c_; chip::DS3231<I2C> rtc_(i2c_); utils::command<128> command_; time_t get_time_() { time_t t = 0; if(!rtc_.get_time(t)) { utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(i2c_.get_last_error()); } return t; } void disp_time_(time_t t) { struct tm *m = localtime(&t); utils::format("%s %s %d %02d:%02d:%02d %4d\n") % get_wday(m->tm_wday) % get_mon(m->tm_mon) % static_cast<uint32_t>(m->tm_mday) % static_cast<uint32_t>(m->tm_hour) % static_cast<uint32_t>(m->tm_min) % static_cast<uint32_t>(m->tm_sec) % static_cast<uint32_t>(m->tm_year + 1900); } const char* get_dec_(const char* p, char tmch, int& value) { int v = 0; char ch; while((ch = *p) != 0) { ++p; if(ch == tmch) { break; } else if(ch >= '0' && ch <= '9') { v *= 10; v += ch - '0'; } else { return nullptr; } } value = v; return p; } void set_time_date_() { time_t t = get_time_(); if(t == 0) return; struct tm *m = localtime(&t); bool err = false; if(command_.get_words() == 3) { char buff[12]; if(command_.get_word(1, buff, sizeof(buff))) { const char* p = buff; int vs[3]; uint8_t i; for(i = 0; i < 3; ++i) { p = get_dec_(p, '/', vs[i]); if(p == nullptr) { break; } } if(p != nullptr && p[0] == 0 && i == 3) { if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900; if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1; if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2]; } else { err = true; } } if(command_.get_word(2, buff, sizeof(buff))) { const char* p = buff; int vs[3]; uint8_t i; for(i = 0; i < 3; ++i) { p = get_dec_(p, ':', vs[i]); if(p == nullptr) { break; } } if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) { if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0]; if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1]; if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2]; else m->tm_sec = 0; } else { err = true; } } } if(err) { utils::format("Can't analize Time/Date input.\n"); return; } time_t tt = mktime(m); if(!rtc_.set_time(tt)) { utils::format("Stall RTC write...\n"); } } } extern "C" { void sci_putch(char ch) { sci_.putch(ch); } void sci_puts(const char* str) { sci_.puts(str); } char sci_getch(void) { return sci_.getch(); } uint16_t sci_length() { return sci_.recv_length(); } } int main(int argc, char** argv); int main(int argc, char** argv) { SYSTEM_IO::setup_system_clock(); LED::DIR = 1; LED::P = 0; { // タイマー設定(100Hz) uint8_t intr = 4; cmt_.start(100, intr); } { // SCI の開始 uint8_t intr = 2; // 割り込みレベル uint32_t baud = 115200; // ボーレート sci_.start(baud, intr); } auto clk = F_ICLK / 1000000; utils::format("Start DS3231 (I2C) sample for '%s' %d[MHz]\n") % system_str_ % clk; { // IICA(I2C) の開始 uint8_t intr_level = 0; if(!i2c_.start(I2C::speed::fast, intr_level)) { utils::format("IICA start error (%d)\n") % static_cast<int>(i2c_.get_last_error()); } } // DS3231(RTC) の開始 if(!rtc_.start()) { utils::format("Stall DS3231: (%d)\n") % static_cast<int>(i2c_.get_last_error()); } command_.set_prompt("# "); uint32_t cnt = 0; while(1) { cmt_.sync(); ++cnt; if(cnt >= 50) { cnt = 0; } if(cnt < 25) { LED::P = 0; } else { LED::P = 1; } // コマンド入力と、コマンド解析 if(command_.service()) { uint8_t cmdn = command_.get_words(); if(cmdn >= 1) { if(command_.cmp_word(0, "date")) { if(cmdn == 1) { time_t t = get_time_(); if(t != 0) { disp_time_(t); } } else { set_time_date_(); } } else if(command_.cmp_word(0, "help")) { utils::format("date\n"); utils::format("date yyyy/mm/dd hh:mm[:ss]\n"); } else { char buff[128]; if(command_.get_word(0, buff, sizeof(buff))) { utils::format("Command error: %s\n") % buff; } } } } } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbSystem.h" #include <string.h> // strdup #if defined(WIN32) || defined(WIN32CE) /*===================================================================== WIN32 / MSVC++ implementation *====================================================================*/ #ifndef WIN32CE # include <io.h> #else # include <wce_io.h> #endif #else /*===================================================================== POSIX (Unix) implementation *====================================================================*/ #include <sys/types.h> #include <dirent.h> #endif namespace otb { //GetExtension from uiig library. std::string System::GetExtension( const std::string& filename ) { // This assumes that the final '.' in a file name is the delimiter // for the file's extension type const std::string::size_type it = filename.find_last_of( "." ); // This determines the file's type by creating a new string // who's value is the extension of the input filename // eg. "myimage.gif" has an extension of "gif" std::string fileExt( filename, it+1, filename.length() ); return( fileExt ); } //GetRootName from uiig library. std::string System::GetRootName( const std::string& filename ) { const std::string fileExt = GetExtension(filename); // Create a base filename // i.e Image.ent --> Image if( fileExt.length() > 0 ) { const std::string::size_type it = filename.find_last_of( fileExt ); std::string baseName( filename, 0, it-fileExt.length() ); return( baseName ); } //Default to return same as input when the extension is nothing (Analyze) return( filename ); } bool System::IsAFileName(std::string pszPath) { return( ! IsADirName(pszPath) ); } //GetPathName. std::string System::GetPathName( const std::string& filename ) { const std::string::size_type it = filename.find_last_of( OTB_FILE_SEPARATOR ); std::string pathName( filename, 0, it ); return( pathName ); } //GetExtension from uiig library. std::string System::GetShortFileName( const std::string& filename ) { const std::string::size_type it = filename.find_last_of( OTB_FILE_SEPARATOR ); std::string shortFileName( filename, it+1, filename.length() ); return( shortFileName ); } #if defined(WIN32) || defined(WIN32CE) /*===================================================================== WIN32 / MSVC++ implementation *====================================================================*/ bool System::IsADirName(std::string pszPath) { struct _finddata_t c_file; long hFile; bool isADir(false); std::string pszFileSpec; std::string path(pszPath); if (pszPath.empty() == true) path = "."; pszFileSpec = path + "\\*.*"; if ( (hFile = _findfirst( pszFileSpec.c_str(), &c_file )) != -1L ) { isADir = true; _findclose( hFile ); } else { isADir = false; } return isADir; } std::vector<std::string> System::Readdir(std::string pszPath) { struct _finddata_t c_file; long hFile; std::vector<std::string> listFileFind; std::string pszFileSpec; std::string path(pszPath); if (pszPath.empty() == true) path = "."; pszFileSpec = path + "\\*.*"; if ( (hFile = _findfirst( pszFileSpec.c_str(), &c_file )) != -1L ) { do { listFileFind.push_back(c_file.name); } while( _findnext( hFile, &c_file ) == 0 ); _findclose( hFile ); } return listFileFind; } #else /*===================================================================== POSIX (Unix) implementation *====================================================================*/ bool System::IsADirName(std::string pszPath) { bool isADir(false); DIR *hDir; struct dirent *psDirEntry; std::string path(pszPath); if (pszPath.empty() == true) path = "."; if ( (hDir = opendir(path.c_str())) != NULL ) { isADir = true; closedir( hDir ); } else { isADir = false; } return isADir; } /** * Read names in a directory. * * This function abstracts access to directory contains. It returns a * list of strings containing the names of files, and directories in this * directory. The resulting string list becomes the responsibility of the * application and should be freed with CSLDestroy() when no longer needed. * * Note that no error is issued via CPLError() if the directory path is * invalid, though NULL is returned. * * @param pszPath the relative, or absolute path of a directory to read. * @return The list of entries in the directory, or NULL if the directory * doesn't exist. */ std::vector<std::string> System::Readdir(std::string pszPath) { DIR *hDir; std::vector<std::string> listFileFind; struct dirent *psDirEntry; std::string path(pszPath); if (pszPath.empty() == true) path = "."; if ( (hDir = opendir(path.c_str())) != NULL ) { while( (psDirEntry = readdir(hDir)) != NULL ) { listFileFind.push_back(psDirEntry->d_name); } closedir( hDir ); } return listFileFind; } #endif } <commit_msg>Modifications pour la compatibilité du code avec Cygwin<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbSystem.h" #include <string.h> // strdup #if (defined(WIN32) || defined(WIN32CE)) && !defined(__CYGWIN__) /*===================================================================== WIN32 / MSVC++ implementation *====================================================================*/ #ifndef WIN32CE # include <io.h> #else # include <wce_io.h> #endif #else /*===================================================================== POSIX (Unix) implementation *====================================================================*/ #include <sys/types.h> #include <dirent.h> #endif namespace otb { //GetExtension from uiig library. std::string System::GetExtension( const std::string& filename ) { // This assumes that the final '.' in a file name is the delimiter // for the file's extension type const std::string::size_type it = filename.find_last_of( "." ); // This determines the file's type by creating a new string // who's value is the extension of the input filename // eg. "myimage.gif" has an extension of "gif" std::string fileExt( filename, it+1, filename.length() ); return( fileExt ); } //GetRootName from uiig library. std::string System::GetRootName( const std::string& filename ) { const std::string fileExt = GetExtension(filename); // Create a base filename // i.e Image.ent --> Image if( fileExt.length() > 0 ) { const std::string::size_type it = filename.find_last_of( fileExt ); std::string baseName( filename, 0, it-fileExt.length() ); return( baseName ); } //Default to return same as input when the extension is nothing (Analyze) return( filename ); } bool System::IsAFileName(std::string pszPath) { return( ! IsADirName(pszPath) ); } //GetPathName. std::string System::GetPathName( const std::string& filename ) { const std::string::size_type it = filename.find_last_of( OTB_FILE_SEPARATOR ); std::string pathName( filename, 0, it ); return( pathName ); } //GetExtension from uiig library. std::string System::GetShortFileName( const std::string& filename ) { const std::string::size_type it = filename.find_last_of( OTB_FILE_SEPARATOR ); std::string shortFileName( filename, it+1, filename.length() ); return( shortFileName ); } #if (defined(WIN32) || defined(WIN32CE)) && !defined(__CYGWIN__) /*===================================================================== WIN32 / MSVC++ implementation *====================================================================*/ bool System::IsADirName(std::string pszPath) { struct _finddata_t c_file; long hFile; bool isADir(false); std::string pszFileSpec; std::string path(pszPath); if (pszPath.empty() == true) path = "."; pszFileSpec = path + "\\*.*"; if ( (hFile = _findfirst( pszFileSpec.c_str(), &c_file )) != -1L ) { isADir = true; _findclose( hFile ); } else { isADir = false; } return isADir; } std::vector<std::string> System::Readdir(std::string pszPath) { struct _finddata_t c_file; long hFile; std::vector<std::string> listFileFind; std::string pszFileSpec; std::string path(pszPath); if (pszPath.empty() == true) path = "."; pszFileSpec = path + "\\*.*"; if ( (hFile = _findfirst( pszFileSpec.c_str(), &c_file )) != -1L ) { do { listFileFind.push_back(c_file.name); } while( _findnext( hFile, &c_file ) == 0 ); _findclose( hFile ); } return listFileFind; } #else /*===================================================================== POSIX (Unix) implementation *====================================================================*/ bool System::IsADirName(std::string pszPath) { bool isADir(false); DIR *hDir; struct dirent *psDirEntry; std::string path(pszPath); if (pszPath.empty() == true) path = "."; if ( (hDir = opendir(path.c_str())) != NULL ) { isADir = true; closedir( hDir ); } else { isADir = false; } return isADir; } /** * Read names in a directory. * * This function abstracts access to directory contains. It returns a * list of strings containing the names of files, and directories in this * directory. The resulting string list becomes the responsibility of the * application and should be freed with CSLDestroy() when no longer needed. * * Note that no error is issued via CPLError() if the directory path is * invalid, though NULL is returned. * * @param pszPath the relative, or absolute path of a directory to read. * @return The list of entries in the directory, or NULL if the directory * doesn't exist. */ std::vector<std::string> System::Readdir(std::string pszPath) { DIR *hDir; std::vector<std::string> listFileFind; struct dirent *psDirEntry; std::string path(pszPath); if (pszPath.empty() == true) path = "."; if ( (hDir = opendir(path.c_str())) != NULL ) { while( (psDirEntry = readdir(hDir)) != NULL ) { listFileFind.push_back(psDirEntry->d_name); } closedir( hDir ); } return listFileFind; } #endif } <|endoftext|>
<commit_before>#include "IR.h" #include "ParallelRVar.h" #include "IRMutator.h" #include "Debug.h" #include "CSE.h" #include "Simplify.h" #include "IROperator.h" namespace Halide { namespace Internal { using std::string; using std::vector; using std::map; /** Find all calls arguments to the given function. Note that we don't * pick up lets for simplicity. This makes the comparison * conservative, because the let variables become unknowns. */ class FindLoads : public IRVisitor { using IRVisitor::visit; const string &func; void visit(const Call *op) { if (op->name == func && op->call_type == Call::Halide) { loads.push_back(op->args); } IRVisitor::visit(op); } public: FindLoads(const string &f) : func(f) {} vector<vector<Expr> > loads; }; /** Rename all free variables to unique new names. */ class RenameFreeVars : public IRMutator { using IRMutator::visit; map<string, string> new_names; void visit(const Variable *op) { if (!op->param.defined() && !op->image.defined()) { expr = Variable::make(op->type, get_new_name(op->name)); } } public: string get_new_name(const string &s) { map<string, string>::iterator iter = new_names.find(s); if (iter != new_names.end()) { return iter->second; } else { string new_name = s + "$_"; new_names[s] = new_name; return new_name; } } }; bool can_parallelize_rvar(const string &v, const string &f, const ReductionDefinition &r) { FindLoads find(f); for (size_t i = 0; i < r.values.size(); i++) { r.values[i].accept(&find); } // Make an expr representing the store done by a different thread. RenameFreeVars renamer; vector<Expr> other_store(r.args.size()); for (size_t i = 0; i < r.args.size(); i++) { other_store[i] = renamer.mutate(r.args[i]); } // Construct an expression which is true when the two threads are // in fact two different threads. We'll use this liberally in the // following conditions to give the simplifier the best chance. Expr distinct_v = (Variable::make(Int(32), v) != Variable::make(Int(32), renamer.get_new_name(v))); // Construct an expression which is true if there's a collision // between this thread's store and the other thread's store. Expr hazard = const_true(); for (size_t i = 0; i < r.args.size(); i++) { hazard = hazard && (distinct_v && (r.args[i] == other_store[i])); } // Add expressions that are true if there's a collision between // the other thread's store and this thread's loads. for (size_t i = 0; i < find.loads.size(); i++) { internal_assert(find.loads[i].size() == other_store.size()); Expr check = const_true(); for (size_t j = 0; j < find.loads[i].size(); j++) { check = check && (distinct_v && (find.loads[i][j] == other_store[j])); } hazard = hazard || check; } // Make a scope representing the bounds of the reduction domain Scope<Interval> bounds; if (r.domain.defined()) { for (size_t i = 0; i < r.domain.domain().size(); i++) { const ReductionVariable &rv = r.domain.domain()[i]; Interval in = Interval(rv.min, simplify(rv.min + rv.extent - 1)); bounds.push(rv.var, in); bounds.push(renamer.get_new_name(rv.var), in); } } debug(3) << "Attempting to falsify: " << hazard << "\n"; hazard = simplify(hazard, false, bounds); debug(3) << "Simplified to: " << hazard << "\n"; return is_zero(hazard); } } } <commit_msg>Fix bug in RenameFreeVars mutator<commit_after>#include "IR.h" #include "ParallelRVar.h" #include "IRMutator.h" #include "Debug.h" #include "CSE.h" #include "Simplify.h" #include "IROperator.h" namespace Halide { namespace Internal { using std::string; using std::vector; using std::map; /** Find all calls arguments to the given function. Note that we don't * pick up lets for simplicity. This makes the comparison * conservative, because the let variables become unknowns. */ class FindLoads : public IRVisitor { using IRVisitor::visit; const string &func; void visit(const Call *op) { if (op->name == func && op->call_type == Call::Halide) { loads.push_back(op->args); } IRVisitor::visit(op); } public: FindLoads(const string &f) : func(f) {} vector<vector<Expr> > loads; }; /** Rename all free variables to unique new names. */ class RenameFreeVars : public IRMutator { using IRMutator::visit; map<string, string> new_names; void visit(const Variable *op) { if (!op->param.defined() && !op->image.defined()) { expr = Variable::make(op->type, get_new_name(op->name)); } else { expr = op; } } public: string get_new_name(const string &s) { map<string, string>::iterator iter = new_names.find(s); if (iter != new_names.end()) { return iter->second; } else { string new_name = s + "$_"; new_names[s] = new_name; return new_name; } } }; bool can_parallelize_rvar(const string &v, const string &f, const ReductionDefinition &r) { FindLoads find(f); for (size_t i = 0; i < r.values.size(); i++) { r.values[i].accept(&find); } // Make an expr representing the store done by a different thread. RenameFreeVars renamer; vector<Expr> other_store(r.args.size()); for (size_t i = 0; i < r.args.size(); i++) { other_store[i] = renamer.mutate(r.args[i]); } // Construct an expression which is true when the two threads are // in fact two different threads. We'll use this liberally in the // following conditions to give the simplifier the best chance. Expr distinct_v = (Variable::make(Int(32), v) != Variable::make(Int(32), renamer.get_new_name(v))); // Construct an expression which is true if there's a collision // between this thread's store and the other thread's store. Expr hazard = const_true(); for (size_t i = 0; i < r.args.size(); i++) { hazard = hazard && (distinct_v && (r.args[i] == other_store[i])); } // Add expressions that are true if there's a collision between // the other thread's store and this thread's loads. for (size_t i = 0; i < find.loads.size(); i++) { internal_assert(find.loads[i].size() == other_store.size()); Expr check = const_true(); for (size_t j = 0; j < find.loads[i].size(); j++) { check = check && (distinct_v && (find.loads[i][j] == other_store[j])); } hazard = hazard || check; } // Make a scope representing the bounds of the reduction domain Scope<Interval> bounds; if (r.domain.defined()) { for (size_t i = 0; i < r.domain.domain().size(); i++) { const ReductionVariable &rv = r.domain.domain()[i]; Interval in = Interval(rv.min, simplify(rv.min + rv.extent - 1)); bounds.push(rv.var, in); bounds.push(renamer.get_new_name(rv.var), in); } } debug(3) << "Attempting to falsify: " << hazard << "\n"; hazard = simplify(hazard, false, bounds); debug(3) << "Simplified to: " << hazard << "\n"; return is_zero(hazard); } } } <|endoftext|>
<commit_before>/// /// \file AliFemtoCorrFctn3DLCMSSym.cxx /// #include "AliFemtoCorrFctn3DLCMSSym.h" #include "AliFemtoPairCut.h" #include <TH3F.h> #ifdef __ROOT__ /// \cond CLASSIMP ClassImp(AliFemtoCorrFctn3DLCMSSym); /// \endcond #endif //____________________________ AliFemtoCorrFctn3DLCMSSym::AliFemtoCorrFctn3DLCMSSym(const char* title, const int nbins, const float QHi): AliFemtoCorrFctn() , fNumerator(NULL) , fDenominator(NULL) , fNumeratorW(NULL) , fDenominatorW(NULL) , fUseLCMS(1) { // Basic constructor TString hist_title = TString::Format("%s; q_{out} (GeV); q_{side} (GeV); q_{long} (GeV)", title); // set up numerator fNumerator = new TH3F(TString("Num") + title, hist_title, nbins, -QHi, QHi, nbins, -QHi, QHi, nbins, -QHi, QHi); // set up denominator fDenominator = new TH3F(TString("Den") + title, hist_title, nbins, -QHi, QHi, nbins, -QHi, QHi, nbins, -QHi, QHi); // Weighted by qinv histos // set up numerator fNumeratorW = new TH3F(TString("NumWqinv") + title, hist_title, nbins, -QHi, QHi, nbins, -QHi, QHi, nbins, -QHi, QHi); // set up denominator fDenominatorW = new TH3F(TString("DenWqinv") + title, hist_title, nbins, -QHi, QHi, nbins, -QHi, QHi, nbins, -QHi, QHi); // to enable error bar calculation... fNumerator->Sumw2(); fDenominator->Sumw2(); fNumeratorW->Sumw2(); fDenominatorW->Sumw2(); } AliFemtoCorrFctn3DLCMSSym::AliFemtoCorrFctn3DLCMSSym(const AliFemtoCorrFctn3DLCMSSym& aCorrFctn): AliFemtoCorrFctn(aCorrFctn) , fNumerator(new TH3F(*aCorrFctn.fNumerator)) , fDenominator(new TH3F(*aCorrFctn.fDenominator)) , fNumeratorW(new TH3F(*aCorrFctn.fNumeratorW)) , fDenominatorW(new TH3F(*aCorrFctn.fDenominatorW)) , fUseLCMS(aCorrFctn.fUseLCMS) { // Copy constructor fNumerator->Sumw2(); fDenominator->Sumw2(); fNumeratorW->Sumw2(); fDenominatorW->Sumw2(); } //____________________________ AliFemtoCorrFctn3DLCMSSym::~AliFemtoCorrFctn3DLCMSSym() { // Destructor delete fNumerator; delete fDenominator; delete fNumeratorW; delete fDenominatorW; } //_________________________ AliFemtoCorrFctn3DLCMSSym& AliFemtoCorrFctn3DLCMSSym::operator=(const AliFemtoCorrFctn3DLCMSSym& aCorrFctn) { // assignment operator if (this == &aCorrFctn) return *this; AliFemtoCorrFctn::operator=(aCorrFctn); *fNumerator = *aCorrFctn.fNumerator; *fDenominator = *aCorrFctn.fDenominator; *fNumeratorW = *aCorrFctn.fNumeratorW; *fDenominatorW = *aCorrFctn.fDenominatorW; fUseLCMS = aCorrFctn.fUseLCMS; fNumerator->Sumw2(); fDenominator->Sumw2(); fNumeratorW->Sumw2(); fDenominatorW->Sumw2(); return *this; } //_________________________ void AliFemtoCorrFctn3DLCMSSym::WriteOutHistos() { // Write out all histograms to file fNumerator->Write(); fDenominator->Write(); fNumeratorW->Write(); fDenominatorW->Write(); } //______________________________ TList* AliFemtoCorrFctn3DLCMSSym::GetOutputList() { // Prepare the list of objects to be written to the output TList *tOutputList = new TList(); tOutputList->Add(fNumerator); tOutputList->Add(fDenominator); tOutputList->Add(fNumeratorW); tOutputList->Add(fDenominatorW); return tOutputList; } //_________________________ void AliFemtoCorrFctn3DLCMSSym::Finish() { #if ROOT_VERSION_CODE >= ROOT_VERSION(6, 10, 8) // remove {under,over}flow to shrink file sizes fNumerator->ClearUnderflowAndOverflow(); fDenominator->ClearUnderflowAndOverflow(); fNumeratorW->ClearUnderflowAndOverflow(); fDenominatorW->ClearUnderflowAndOverflow(); #endif } //____________________________ AliFemtoString AliFemtoCorrFctn3DLCMSSym::Report() { AliFemtoString report = "LCMS Frame Bertsch-Pratt 3D Correlation Function Report:\n"; report += Form("Number of entries in numerator:\t%E\n", fNumerator->GetEntries()); report += Form("Number of entries in denominator:\t%E\n", fDenominator->GetEntries()); if (fPairCut) { report += "Here is the PairCut specific to this CorrFctn\n"; report += fPairCut->Report(); } else { report += "No PairCut specific to this CorrFctn\n"; } return report; } //____________________________ void AliFemtoCorrFctn3DLCMSSym::AddRealPair(AliFemtoPair* pair) { // perform operations on real pairs if (fPairCut && !fPairCut->Pass(pair)) { return; } if (fUseLCMS) { const Double_t qout = pair->QOutCMS(), qside = pair->QSideCMS(), qlong = pair->QLongCMS(); fNumerator->Fill(qout, qside, qlong, 1.0); fNumeratorW->Fill(qout, qside, qlong, pair->QInv()); } else { const Double_t qout = pair->QOutPf(), qside = pair->QSidePf(), qlong = pair->QLongPf(); fNumerator->Fill(qout, qside, qlong, 1.0); fNumeratorW->Fill(qout, qside, qlong, pair->QInv()); } } //____________________________ void AliFemtoCorrFctn3DLCMSSym::AddMixedPair(AliFemtoPair* pair) { // perform operations on mixed pairs if (fPairCut && !fPairCut->Pass(pair)) { return; } if (fUseLCMS) { const Double_t qout = pair->QOutCMS(), qside = pair->QSideCMS(), qlong = pair->QLongCMS(); fDenominator->Fill(qout, qside, qlong, 1.0); fDenominatorW->Fill(qout, qside, qlong, pair->QInv()); } else { const Double_t qout = pair->QOutPf(), qside = pair->QSidePf(), qlong = pair->QLongPf(); fDenominator->Fill(qout, qside, qlong, 1.0); fDenominatorW->Fill(qout, qside, qlong, pair->QInv()); } } void AliFemtoCorrFctn3DLCMSSym::SetUseLCMS(int aUseLCMS) { fUseLCMS = aUseLCMS; } int AliFemtoCorrFctn3DLCMSSym::GetUseLCMS() { return fUseLCMS; } <commit_msg>AliFemtoCorrFctn3DLCMSSym - Fix extraneous Sumw2 calls + overflow omission<commit_after>/// /// \file AliFemtoCorrFctn3DLCMSSym.cxx /// #include "AliFemtoCorrFctn3DLCMSSym.h" #include "AliFemtoPairCut.h" #include <TH3F.h> #ifdef __ROOT__ /// \cond CLASSIMP ClassImp(AliFemtoCorrFctn3DLCMSSym); /// \endcond #endif AliFemtoCorrFctn3DLCMSSym::AliFemtoCorrFctn3DLCMSSym(const char* title, const int nbins, const float QHi): AliFemtoCorrFctn() , fNumerator(nullptr) , fDenominator(nullptr) , fNumeratorW(nullptr) , fDenominatorW(nullptr) , fUseLCMS(1) { // Basic constructor TString hist_title = TString::Format("%s; q_{out} (GeV); q_{side} (GeV); q_{long} (GeV)", title); // set up numerator fNumerator = new TH3F(TString("Num") + title, hist_title, nbins, -QHi, QHi, nbins, -QHi, QHi, nbins, -QHi, QHi); // set up denominator fDenominator = new TH3F(TString("Den") + title, hist_title, nbins, -QHi, QHi, nbins, -QHi, QHi, nbins, -QHi, QHi); // Weighted by qinv histos // set up numerator fNumeratorW = new TH3F(TString("NumWqinv") + title, hist_title, nbins, -QHi, QHi, nbins, -QHi, QHi, nbins, -QHi, QHi); // set up denominator fDenominatorW = new TH3F(TString("DenWqinv") + title, hist_title, nbins, -QHi, QHi, nbins, -QHi, QHi, nbins, -QHi, QHi); // to enable error bar calculation... fNumerator->Sumw2(); fDenominator->Sumw2(); fNumeratorW->Sumw2(); fDenominatorW->Sumw2(); } AliFemtoCorrFctn3DLCMSSym::AliFemtoCorrFctn3DLCMSSym(const AliFemtoCorrFctn3DLCMSSym& aCorrFctn): AliFemtoCorrFctn(aCorrFctn) , fNumerator(new TH3F(*aCorrFctn.fNumerator)) , fDenominator(new TH3F(*aCorrFctn.fDenominator)) , fNumeratorW(new TH3F(*aCorrFctn.fNumeratorW)) , fDenominatorW(new TH3F(*aCorrFctn.fDenominatorW)) , fUseLCMS(aCorrFctn.fUseLCMS) { // Copy constructor } //____________________________ AliFemtoCorrFctn3DLCMSSym::~AliFemtoCorrFctn3DLCMSSym() { // Destructor delete fNumerator; delete fDenominator; delete fNumeratorW; delete fDenominatorW; } //_________________________ AliFemtoCorrFctn3DLCMSSym& AliFemtoCorrFctn3DLCMSSym::operator=(const AliFemtoCorrFctn3DLCMSSym& aCorrFctn) { // assignment operator if (this == &aCorrFctn) return *this; AliFemtoCorrFctn::operator=(aCorrFctn); *fNumerator = *aCorrFctn.fNumerator; *fDenominator = *aCorrFctn.fDenominator; *fNumeratorW = *aCorrFctn.fNumeratorW; *fDenominatorW = *aCorrFctn.fDenominatorW; fUseLCMS = aCorrFctn.fUseLCMS; return *this; } //_________________________ void AliFemtoCorrFctn3DLCMSSym::WriteOutHistos() { // Write out all histograms to file fNumerator->Write(); fDenominator->Write(); fNumeratorW->Write(); fDenominatorW->Write(); } //______________________________ TList* AliFemtoCorrFctn3DLCMSSym::GetOutputList() { // Prepare the list of objects to be written to the output TList *tOutputList = new TList(); tOutputList->Add(fNumerator); tOutputList->Add(fDenominator); tOutputList->Add(fNumeratorW); tOutputList->Add(fDenominatorW); return tOutputList; } //_________________________ void AliFemtoCorrFctn3DLCMSSym::Finish() { } //____________________________ AliFemtoString AliFemtoCorrFctn3DLCMSSym::Report() { AliFemtoString report = "LCMS Frame Bertsch-Pratt 3D Correlation Function Report:\n"; report += Form("Number of entries in numerator:\t%E\n", fNumerator->GetEntries()); report += Form("Number of entries in denominator:\t%E\n", fDenominator->GetEntries()); if (fPairCut) { report += "Here is the PairCut specific to this CorrFctn\n"; report += fPairCut->Report(); } else { report += "No PairCut specific to this CorrFctn\n"; } return report; } //____________________________ void AliFemtoCorrFctn3DLCMSSym::AddRealPair(AliFemtoPair* pair) { // perform operations on real pairs if (fPairCut && !fPairCut->Pass(pair)) { return; } const Double_t qout = (fUseLCMS) ? pair->QOutCMS() : pair->QOutPf(), qside = (fUseLCMS) ? pair->QSideCMS() : pair->QSidePf(), qlong = (fUseLCMS) ? pair->QLongCMS() : pair->QLongPf(); Int_t bin = fNumerator->FindBin(qout, qside, qlong); // avoid overflow bins if (!(fNumerator->IsBinOverflow(bin) or fNumerator->IsBinUnderflow(bin))) { fNumerator->Fill(qout, qside, qlong, 1.0); fNumeratorW->Fill(qout, qside, qlong, pair->QInv()); } } //____________________________ void AliFemtoCorrFctn3DLCMSSym::AddMixedPair(AliFemtoPair* pair) { // perform operations on mixed pairs if (fPairCut && !fPairCut->Pass(pair)) { return; } const Double_t qout = (fUseLCMS) ? pair->QOutCMS() : pair->QOutPf(), qside = (fUseLCMS) ? pair->QSideCMS() : pair->QSidePf(), qlong = (fUseLCMS) ? pair->QLongCMS() : pair->QLongPf(); Int_t bin = fDenominator->FindBin(qout, qside, qlong); // avoid overflow bins if (!(fDenominator->IsBinOverflow(bin) or fDenominator->IsBinUnderflow(bin))) { fDenominator->Fill(qout, qside, qlong, 1.0); fDenominatorW->Fill(qout, qside, qlong, pair->QInv()); } } void AliFemtoCorrFctn3DLCMSSym::SetUseLCMS(int aUseLCMS) { fUseLCMS = aUseLCMS; } int AliFemtoCorrFctn3DLCMSSym::GetUseLCMS() { return fUseLCMS; } <|endoftext|>
<commit_before><commit_msg>Attempt at fixing reported GCC 3.4 bugs due to increased pedantry. Not tested since I don't have a machine with GCC 3.4 yet, but it doesn't break on 3.2, so....<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/glue/webcursor.h" #include "webkit/glue/webkit_resources.h" #if defined(OS_WIN) #include "base/gfx/gdi_util.h" #endif WebCursor::WebCursor() : type_(ARROW), hotspot_x_(0), hotspot_y_(0), bitmap_() { } WebCursor::WebCursor(Type cursor_type) : type_(cursor_type), hotspot_x_(0), hotspot_y_(0), bitmap_() { } WebCursor::WebCursor(const WebCursorBitmapPtr bitmap, int hotspot_x, int hotspot_y) : type_(ARROW), hotspot_x_(0), hotspot_y_(0) { if (bitmap) { type_ = CUSTOM; hotspot_x_ = hotspot_x; hotspot_y_ = hotspot_y; #if defined(OS_MACOSX) CGImageRetain(bitmap_ = bitmap); #else bitmap_ = *bitmap; #endif } else { #if defined(OS_MACOSX) bitmap_ = NULL; #else memset(&bitmap_, 0, sizeof(bitmap_)); #endif } } WebCursor::~WebCursor() { #if defined(OS_MACOSX) CGImageRelease(bitmap_); #endif } WebCursor::WebCursor(const WebCursor& other) { type_ = other.type_; hotspot_x_ = other.hotspot_x_; hotspot_y_ = other.hotspot_y_; #if defined(OS_MACOSX) bitmap_ = NULL; // set_bitmap releases bitmap_. #endif set_bitmap(other.bitmap_); } WebCursor& WebCursor::operator=(const WebCursor& other) { if (this != &other) { type_ = other.type_; hotspot_x_ = other.hotspot_x_; hotspot_y_ = other.hotspot_y_; set_bitmap(other.bitmap_); } return *this; } #if defined(OS_WIN) HCURSOR WebCursor::GetCursor(HINSTANCE module_handle) const { if (type_ == CUSTOM) return NULL; static LPCWSTR cursor_resources[] = { IDC_ARROW, IDC_IBEAM, IDC_WAIT, IDC_CROSS, IDC_UPARROW, IDC_SIZE, IDC_ICON, IDC_SIZENWSE, IDC_SIZENESW, IDC_SIZEWE, IDC_SIZENS, IDC_SIZEALL, IDC_NO, IDC_HAND, IDC_APPSTARTING, IDC_HELP, // webkit resources MAKEINTRESOURCE(IDC_ALIAS), MAKEINTRESOURCE(IDC_CELL), MAKEINTRESOURCE(IDC_COLRESIZE), MAKEINTRESOURCE(IDC_COPYCUR), MAKEINTRESOURCE(IDC_ROWRESIZE), MAKEINTRESOURCE(IDC_VERTICALTEXT), MAKEINTRESOURCE(IDC_ZOOMIN), MAKEINTRESOURCE(IDC_ZOOMOUT) }; HINSTANCE instance_to_use = NULL; if (type_ > HELP) instance_to_use = module_handle; HCURSOR cursor_handle = LoadCursor(instance_to_use, cursor_resources[type_]); return cursor_handle; } HCURSOR WebCursor::GetCustomCursor() const { if (type_ != CUSTOM) return NULL; BITMAPINFO cursor_bitmap_info = {0}; gfx::CreateBitmapHeader(bitmap_.width(), bitmap_.height(), reinterpret_cast<BITMAPINFOHEADER*>(&cursor_bitmap_info)); HDC dc = ::GetDC(0); HDC workingDC = CreateCompatibleDC(dc); HBITMAP bitmap_handle = CreateDIBSection(dc, &cursor_bitmap_info, DIB_RGB_COLORS, 0, 0, 0); SkAutoLockPixels bitmap_lock(bitmap_); SetDIBits(0, bitmap_handle, 0, bitmap_.width(), bitmap_.getPixels(), &cursor_bitmap_info, DIB_RGB_COLORS); HBITMAP old_bitmap = reinterpret_cast<HBITMAP>(SelectObject(workingDC, bitmap_handle)); SetBkMode(workingDC, TRANSPARENT); SelectObject(workingDC, old_bitmap); HBITMAP mask = CreateBitmap(bitmap_.width(), bitmap_.height(), 1, 1, NULL); ICONINFO ii = {0}; ii.fIcon = FALSE; ii.xHotspot = hotspot_x_; ii.yHotspot = hotspot_y_; ii.hbmMask = mask; ii.hbmColor = bitmap_handle; HCURSOR cursor_handle = CreateIconIndirect(&ii); DeleteObject(mask); DeleteObject(bitmap_handle); DeleteDC(workingDC); ::ReleaseDC(0, dc); return cursor_handle; } #endif #if !defined(OS_MACOSX) bool WebCursor::IsSameBitmap(const WebCursorBitmap& bitmap) const { SkAutoLockPixels new_bitmap_lock(bitmap); SkAutoLockPixels bitmap_lock(bitmap_); return (memcmp(bitmap_.getPixels(), bitmap.getPixels(), bitmap_.getSize()) == 0); } bool WebCursor::IsEqual(const WebCursor& other) const { if (type_ != other.type_) return false; if(type_ == CUSTOM) return IsSameBitmap(other.bitmap_); return true; } #endif <commit_msg>Fix a bug in cursor handling when the width and height of the image differ. We were using the width of the image, when the width is actually inferred by the Windows API call. Instead, we were supposed to pass the height.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/glue/webcursor.h" #include "webkit/glue/webkit_resources.h" #if defined(OS_WIN) #include "base/gfx/gdi_util.h" #endif WebCursor::WebCursor() : type_(ARROW), hotspot_x_(0), hotspot_y_(0), bitmap_() { } WebCursor::WebCursor(Type cursor_type) : type_(cursor_type), hotspot_x_(0), hotspot_y_(0), bitmap_() { } WebCursor::WebCursor(const WebCursorBitmapPtr bitmap, int hotspot_x, int hotspot_y) : type_(ARROW), hotspot_x_(0), hotspot_y_(0) { if (bitmap) { type_ = CUSTOM; hotspot_x_ = hotspot_x; hotspot_y_ = hotspot_y; #if defined(OS_MACOSX) CGImageRetain(bitmap_ = bitmap); #else bitmap_ = *bitmap; #endif } else { #if defined(OS_MACOSX) bitmap_ = NULL; #else memset(&bitmap_, 0, sizeof(bitmap_)); #endif } } WebCursor::~WebCursor() { #if defined(OS_MACOSX) CGImageRelease(bitmap_); #endif } WebCursor::WebCursor(const WebCursor& other) { type_ = other.type_; hotspot_x_ = other.hotspot_x_; hotspot_y_ = other.hotspot_y_; #if defined(OS_MACOSX) bitmap_ = NULL; // set_bitmap releases bitmap_. #endif set_bitmap(other.bitmap_); } WebCursor& WebCursor::operator=(const WebCursor& other) { if (this != &other) { type_ = other.type_; hotspot_x_ = other.hotspot_x_; hotspot_y_ = other.hotspot_y_; set_bitmap(other.bitmap_); } return *this; } #if defined(OS_WIN) HCURSOR WebCursor::GetCursor(HINSTANCE module_handle) const { if (type_ == CUSTOM) return NULL; static LPCWSTR cursor_resources[] = { IDC_ARROW, IDC_IBEAM, IDC_WAIT, IDC_CROSS, IDC_UPARROW, IDC_SIZE, IDC_ICON, IDC_SIZENWSE, IDC_SIZENESW, IDC_SIZEWE, IDC_SIZENS, IDC_SIZEALL, IDC_NO, IDC_HAND, IDC_APPSTARTING, IDC_HELP, // webkit resources MAKEINTRESOURCE(IDC_ALIAS), MAKEINTRESOURCE(IDC_CELL), MAKEINTRESOURCE(IDC_COLRESIZE), MAKEINTRESOURCE(IDC_COPYCUR), MAKEINTRESOURCE(IDC_ROWRESIZE), MAKEINTRESOURCE(IDC_VERTICALTEXT), MAKEINTRESOURCE(IDC_ZOOMIN), MAKEINTRESOURCE(IDC_ZOOMOUT) }; HINSTANCE instance_to_use = NULL; if (type_ > HELP) instance_to_use = module_handle; HCURSOR cursor_handle = LoadCursor(instance_to_use, cursor_resources[type_]); return cursor_handle; } HCURSOR WebCursor::GetCustomCursor() const { if (type_ != CUSTOM) return NULL; BITMAPINFO cursor_bitmap_info = {0}; gfx::CreateBitmapHeader(bitmap_.width(), bitmap_.height(), reinterpret_cast<BITMAPINFOHEADER*>(&cursor_bitmap_info)); HDC dc = ::GetDC(0); HDC workingDC = CreateCompatibleDC(dc); HBITMAP bitmap_handle = CreateDIBSection(dc, &cursor_bitmap_info, DIB_RGB_COLORS, 0, 0, 0); SkAutoLockPixels bitmap_lock(bitmap_); SetDIBits(0, bitmap_handle, 0, bitmap_.height(), bitmap_.getPixels(), &cursor_bitmap_info, DIB_RGB_COLORS); HBITMAP old_bitmap = reinterpret_cast<HBITMAP>(SelectObject(workingDC, bitmap_handle)); SetBkMode(workingDC, TRANSPARENT); SelectObject(workingDC, old_bitmap); HBITMAP mask = CreateBitmap(bitmap_.width(), bitmap_.height(), 1, 1, NULL); ICONINFO ii = {0}; ii.fIcon = FALSE; ii.xHotspot = hotspot_x_; ii.yHotspot = hotspot_y_; ii.hbmMask = mask; ii.hbmColor = bitmap_handle; HCURSOR cursor_handle = CreateIconIndirect(&ii); DeleteObject(mask); DeleteObject(bitmap_handle); DeleteDC(workingDC); ::ReleaseDC(0, dc); return cursor_handle; } #endif #if !defined(OS_MACOSX) bool WebCursor::IsSameBitmap(const WebCursorBitmap& bitmap) const { SkAutoLockPixels new_bitmap_lock(bitmap); SkAutoLockPixels bitmap_lock(bitmap_); return (memcmp(bitmap_.getPixels(), bitmap.getPixels(), bitmap_.getSize()) == 0); } bool WebCursor::IsEqual(const WebCursor& other) const { if (type_ != other.type_) return false; if(type_ == CUSTOM) return IsSameBitmap(other.bitmap_); return true; } #endif <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Institute for Artificial Intelligence, * Universität Bremen. * 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 Institute for Artificial Intelligence, * Universität Bremen, nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /** \author Jan Winkler */ #include <PluginSystem.h> namespace beliefstate { PluginSystem::PluginSystem(int argc, char** argv) { m_argc = argc; m_argv = argv; this->setMessagePrefixLabel("plugins"); } PluginSystem::~PluginSystem() { m_lstLoadedPlugins.reverse(); // Trigger kill signals for(PluginInstance* icCurrent : m_lstLoadedPlugins) { icCurrent->setRunning(false); } // Join all threads for(PluginInstance* icCurrent : m_lstLoadedPlugins) { icCurrent->waitForJoin(); } // Delete all structures for(PluginInstance* icCurrent : m_lstLoadedPlugins) { icCurrent->unload(); delete icCurrent; } m_lstLoadedPlugins.clear(); } string PluginSystem::pluginNameFromPath(string strPath) { // Remove path const size_t last_slash_idx = strPath.find_last_of("\\/"); if(std::string::npos != last_slash_idx) { strPath.erase(0, last_slash_idx + 1); } // Remove extension const size_t period_idx = strPath.rfind('.'); if(std::string::npos != period_idx) { strPath.erase(period_idx); } // Remove plugin prefix std::string strPrefix = "libbs_plugin_"; if(strPath.substr(0, strPrefix.size()) == strPrefix) { strPath = strPath.substr(strPrefix.size()); } return strPath; } bool PluginSystem::pluginLoaded(std::string strPluginName) { for(PluginInstance* icCurrent : m_lstLoadedPlugins) { if(icCurrent->name() == strPluginName) { return true; } } return false; } void PluginSystem::setLoadDevelopmentPlugins(bool bLoadDevelopmentPlugins) { m_bLoadDevelopmentPlugins = bLoadDevelopmentPlugins; } bool PluginSystem::loadDevelopmentPlugins() { return m_bLoadDevelopmentPlugins; } bool PluginSystem::pluginFailedToLoadBefore(std::string strName) { for(std::string strPluginName : m_lstLoadFailedPlugins) { if(strPluginName == strName) { return true; } } return false; } Result PluginSystem::loadPluginLibrary(std::string strFilepath, bool bIsNameOnly) { PluginInstance* icLoad = NULL; std::string strPrefix = "libbs_plugin_"; std::string strSuffix = ".so"; if(bIsNameOnly) { strFilepath = strPrefix + strFilepath + strSuffix; } std::list<std::string> lstSearchPaths = m_lstPluginSearchPaths; lstSearchPaths.push_front("./"); // Add local path as search path Result resLoad = defaultResult(); resLoad.bSuccess = false; if(this->pluginLoaded(this->pluginNameFromPath(strFilepath))) { this->info("Plugin '" + this->pluginNameFromPath(strFilepath) + "' already loaded."); resLoad.bSuccess = true; } else { if(!this->pluginFailedToLoadBefore(strFilepath)) { for(string strSP : lstSearchPaths) { string strSearchFilepath = strSP + (strSP[strSP.size() - 1] != '/' && strFilepath[0] != '/' && strSP.size() > 0 ? "/" : "") + strFilepath; icLoad = new PluginInstance(); resLoad = icLoad->loadPluginLibrary(strSearchFilepath); resLoad.piPlugin = icLoad; if(resLoad.bSuccess) { // Check if this is a development plugin and if we're supposed to load it. if((icLoad->developmentPlugin() && m_bLoadDevelopmentPlugins) || !icLoad->developmentPlugin()) { if(icLoad->developmentPlugin()) { this->info("This is a development plugin: '" + strFilepath + "'"); } // Check and meet dependencies std::list<std::string> lstDeps = icLoad->dependencies(); for(string strDep : lstDeps) { if(this->pluginLoaded(strDep) == false) { Result resLoadDep = this->loadPluginLibrary(strPrefix + strDep + strSuffix); if(resLoadDep.bSuccess == false) { this->fail("Unable to meet dependency of '" + strSearchFilepath + "': '" + strDep + "'"); resLoad.bSuccess = false; resLoad.riResultIdentifier = RI_PLUGIN_DEPENDENCY_NOT_MET; resLoad.strErrorMessage = strDep; break; } } } } else { this->info("Not loading development plugin: '" + strFilepath + "'"); resLoad.bSuccess = false; resLoad.riResultIdentifier = RI_PLUGIN_DEVELOPMENT_NOT_LOADING; } if(resLoad.bSuccess) { // Initialize the plugin Result rsResult = icLoad->init(m_argc, m_argv); if(rsResult.bSuccess) { m_lstLoadedPlugins.push_back(icLoad); } else { resLoad.bSuccess = false; resLoad.riResultIdentifier = RI_PLUGIN_LOADING_FAILED; } break; } } else { resLoad.bSuccess = false; resLoad.riResultIdentifier = RI_PLUGIN_LOADING_FAILED; } if(resLoad.bSuccess == false) { icLoad->unload(); m_lstLoadFailedPlugins.push_back(strFilepath); delete icLoad; } else { break; } } } else { this->warn("This plugin failed to load before. Skipping it."); } } if(resLoad.bSuccess == false) { this->fail("Failed to load plugin '" + strFilepath + "'"); } else { resLoad.piPlugin = icLoad; } return resLoad; } void PluginSystem::queueUnloadPluginInstance(PluginInstance* icUnload) { m_lstUnloadPlugins.push_back(icUnload); } int PluginSystem::spreadEvent(Event evEvent) { int nReceivers = 0; for(PluginInstance* piPlugin : m_lstLoadedPlugins) { if(piPlugin->subscribedToEvent(evEvent.strEventName)) { piPlugin->consumeEvent(evEvent); nReceivers++; } } return nReceivers; } int PluginSystem::spreadServiceEvent(ServiceEvent seServiceEvent) { list<Event> lstResultEvents; int nReceivers = 0; for(PluginInstance* piPlugin : m_lstLoadedPlugins) { if(piPlugin->offersService(seServiceEvent.strServiceName) || seServiceEvent.siServiceIdentifier == SI_RESPONSE) { Event evResult = piPlugin->consumeServiceEvent(seServiceEvent); nReceivers++; if(seServiceEvent.smResultModifier != SM_IGNORE_RESULTS) { evResult.nOriginID = piPlugin->pluginID(); lstResultEvents.push_back(evResult); if(seServiceEvent.smResultModifier == SM_FIRST_RESULT) { break; } else { // Aggregate results } } } } PluginInstance* piRequester = this->pluginInstanceByID(seServiceEvent.nRequesterID); if(piRequester && seServiceEvent.smResultModifier != SM_IGNORE_RESULTS) { ServiceEvent seResponses = seServiceEvent; seResponses.lstResultEvents = lstResultEvents; seResponses.siServiceIdentifier = SI_RESPONSE; piRequester->consumeServiceEvent(seResponses); } return nReceivers; } Result PluginSystem::cycle() { Result resCycle = defaultResult(); for(PluginInstance* icCurrent : m_lstLoadedPlugins) { Result resCurrent = icCurrent->cycle(); for(StatusMessage smCurrent : resCurrent.lstStatusMessages) { resCycle.lstStatusMessages.push_back(smCurrent); } if(resCurrent.bSuccess == false) { // NOTE(winkler): This might also be a good place to implement // a recovery mechanism in case a plugin actually fails during // its cycle. Reload plugins and notify all "depending" // plugins (in order of dependency) to "recover". this->queueUnloadPluginInstance(icCurrent); } else { for(Event evtCurrent : resCurrent.lstEvents) { resCycle.lstEvents.push_back(evtCurrent); } for(ServiceEvent seCurrent : resCurrent.lstServiceEvents) { resCycle.lstServiceEvents.push_back(seCurrent); } } } for(PluginInstance* icCurrent : m_lstUnloadPlugins) { icCurrent->unload(); m_lstLoadedPlugins.remove(icCurrent); delete icCurrent; } return resCycle; } void PluginSystem::addPluginSearchPath(std::string strPath) { // Make sure it is in there only once. m_lstPluginSearchPaths.remove(strPath); m_lstPluginSearchPaths.push_back(strPath); } PluginInstance* PluginSystem::pluginInstanceByID(int nID) { for(PluginInstance* icCurrent : m_lstLoadedPlugins) { if(icCurrent->pluginID() == nID) { return icCurrent; } } return NULL; } } <commit_msg>Implemented convenience method for adding multiple plugin search paths<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, Institute for Artificial Intelligence, * Universität Bremen. * 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 Institute for Artificial Intelligence, * Universität Bremen, nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /** \author Jan Winkler */ #include <PluginSystem.h> namespace beliefstate { PluginSystem::PluginSystem(int argc, char** argv) { m_argc = argc; m_argv = argv; this->setMessagePrefixLabel("plugins"); } PluginSystem::~PluginSystem() { m_lstLoadedPlugins.reverse(); // Trigger kill signals for(PluginInstance* icCurrent : m_lstLoadedPlugins) { icCurrent->setRunning(false); } // Join all threads for(PluginInstance* icCurrent : m_lstLoadedPlugins) { icCurrent->waitForJoin(); } // Delete all structures for(PluginInstance* icCurrent : m_lstLoadedPlugins) { icCurrent->unload(); delete icCurrent; } m_lstLoadedPlugins.clear(); } string PluginSystem::pluginNameFromPath(string strPath) { // Remove path const size_t last_slash_idx = strPath.find_last_of("\\/"); if(std::string::npos != last_slash_idx) { strPath.erase(0, last_slash_idx + 1); } // Remove extension const size_t period_idx = strPath.rfind('.'); if(std::string::npos != period_idx) { strPath.erase(period_idx); } // Remove plugin prefix std::string strPrefix = "libbs_plugin_"; if(strPath.substr(0, strPrefix.size()) == strPrefix) { strPath = strPath.substr(strPrefix.size()); } return strPath; } bool PluginSystem::pluginLoaded(std::string strPluginName) { for(PluginInstance* icCurrent : m_lstLoadedPlugins) { if(icCurrent->name() == strPluginName) { return true; } } return false; } void PluginSystem::setLoadDevelopmentPlugins(bool bLoadDevelopmentPlugins) { m_bLoadDevelopmentPlugins = bLoadDevelopmentPlugins; } bool PluginSystem::loadDevelopmentPlugins() { return m_bLoadDevelopmentPlugins; } bool PluginSystem::pluginFailedToLoadBefore(std::string strName) { for(std::string strPluginName : m_lstLoadFailedPlugins) { if(strPluginName == strName) { return true; } } return false; } Result PluginSystem::loadPluginLibrary(std::string strFilepath, bool bIsNameOnly) { PluginInstance* icLoad = NULL; std::string strPrefix = "libbs_plugin_"; std::string strSuffix = ".so"; if(bIsNameOnly) { strFilepath = strPrefix + strFilepath + strSuffix; } std::list<std::string> lstSearchPaths = m_lstPluginSearchPaths; lstSearchPaths.push_front("./"); // Add local path as search path Result resLoad = defaultResult(); resLoad.bSuccess = false; if(this->pluginLoaded(this->pluginNameFromPath(strFilepath))) { this->info("Plugin '" + this->pluginNameFromPath(strFilepath) + "' already loaded."); resLoad.bSuccess = true; } else { if(!this->pluginFailedToLoadBefore(strFilepath)) { for(string strSP : lstSearchPaths) { string strSearchFilepath = strSP + (strSP[strSP.size() - 1] != '/' && strFilepath[0] != '/' && strSP.size() > 0 ? "/" : "") + strFilepath; icLoad = new PluginInstance(); resLoad = icLoad->loadPluginLibrary(strSearchFilepath); resLoad.piPlugin = icLoad; if(resLoad.bSuccess) { // Check if this is a development plugin and if we're supposed to load it. if((icLoad->developmentPlugin() && m_bLoadDevelopmentPlugins) || !icLoad->developmentPlugin()) { if(icLoad->developmentPlugin()) { this->info("This is a development plugin: '" + strFilepath + "'"); } // Check and meet dependencies std::list<std::string> lstDeps = icLoad->dependencies(); for(string strDep : lstDeps) { if(this->pluginLoaded(strDep) == false) { Result resLoadDep = this->loadPluginLibrary(strPrefix + strDep + strSuffix); if(resLoadDep.bSuccess == false) { this->fail("Unable to meet dependency of '" + strSearchFilepath + "': '" + strDep + "'"); resLoad.bSuccess = false; resLoad.riResultIdentifier = RI_PLUGIN_DEPENDENCY_NOT_MET; resLoad.strErrorMessage = strDep; break; } } } } else { this->info("Not loading development plugin: '" + strFilepath + "'"); resLoad.bSuccess = false; resLoad.riResultIdentifier = RI_PLUGIN_DEVELOPMENT_NOT_LOADING; } if(resLoad.bSuccess) { // Initialize the plugin Result rsResult = icLoad->init(m_argc, m_argv); if(rsResult.bSuccess) { m_lstLoadedPlugins.push_back(icLoad); } else { resLoad.bSuccess = false; resLoad.riResultIdentifier = RI_PLUGIN_LOADING_FAILED; } break; } } else { resLoad.bSuccess = false; resLoad.riResultIdentifier = RI_PLUGIN_LOADING_FAILED; } if(resLoad.bSuccess == false) { icLoad->unload(); m_lstLoadFailedPlugins.push_back(strFilepath); delete icLoad; } else { break; } } } else { this->warn("This plugin failed to load before. Skipping it."); } } if(resLoad.bSuccess == false) { this->fail("Failed to load plugin '" + strFilepath + "'"); } else { resLoad.piPlugin = icLoad; } return resLoad; } void PluginSystem::queueUnloadPluginInstance(PluginInstance* icUnload) { m_lstUnloadPlugins.push_back(icUnload); } int PluginSystem::spreadEvent(Event evEvent) { int nReceivers = 0; for(PluginInstance* piPlugin : m_lstLoadedPlugins) { if(piPlugin->subscribedToEvent(evEvent.strEventName)) { piPlugin->consumeEvent(evEvent); nReceivers++; } } return nReceivers; } int PluginSystem::spreadServiceEvent(ServiceEvent seServiceEvent) { list<Event> lstResultEvents; int nReceivers = 0; for(PluginInstance* piPlugin : m_lstLoadedPlugins) { if(piPlugin->offersService(seServiceEvent.strServiceName) || seServiceEvent.siServiceIdentifier == SI_RESPONSE) { Event evResult = piPlugin->consumeServiceEvent(seServiceEvent); nReceivers++; if(seServiceEvent.smResultModifier != SM_IGNORE_RESULTS) { evResult.nOriginID = piPlugin->pluginID(); lstResultEvents.push_back(evResult); if(seServiceEvent.smResultModifier == SM_FIRST_RESULT) { break; } else { // Aggregate results } } } } PluginInstance* piRequester = this->pluginInstanceByID(seServiceEvent.nRequesterID); if(piRequester && seServiceEvent.smResultModifier != SM_IGNORE_RESULTS) { ServiceEvent seResponses = seServiceEvent; seResponses.lstResultEvents = lstResultEvents; seResponses.siServiceIdentifier = SI_RESPONSE; piRequester->consumeServiceEvent(seResponses); } return nReceivers; } Result PluginSystem::cycle() { Result resCycle = defaultResult(); for(PluginInstance* icCurrent : m_lstLoadedPlugins) { Result resCurrent = icCurrent->cycle(); for(StatusMessage smCurrent : resCurrent.lstStatusMessages) { resCycle.lstStatusMessages.push_back(smCurrent); } if(resCurrent.bSuccess == false) { // NOTE(winkler): This might also be a good place to implement // a recovery mechanism in case a plugin actually fails during // its cycle. Reload plugins and notify all "depending" // plugins (in order of dependency) to "recover". this->queueUnloadPluginInstance(icCurrent); } else { for(Event evtCurrent : resCurrent.lstEvents) { resCycle.lstEvents.push_back(evtCurrent); } for(ServiceEvent seCurrent : resCurrent.lstServiceEvents) { resCycle.lstServiceEvents.push_back(seCurrent); } } } for(PluginInstance* icCurrent : m_lstUnloadPlugins) { icCurrent->unload(); m_lstLoadedPlugins.remove(icCurrent); delete icCurrent; } return resCycle; } void PluginSystem::addPluginSearchPaths(std::list<std::string> lstPaths) { for(std::string strPath : lstPaths) { this->addPluginSearchPath(strPath); } } void PluginSystem::addPluginSearchPath(std::string strPath) { // Make sure it is in there only once. m_lstPluginSearchPaths.remove(strPath); m_lstPluginSearchPaths.push_back(strPath); } PluginInstance* PluginSystem::pluginInstanceByID(int nID) { for(PluginInstance* icCurrent : m_lstLoadedPlugins) { if(icCurrent->pluginID() == nID) { return icCurrent; } } return NULL; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ComponentDefinition.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-07-13 15:20:10 $ * * 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 DBA_COREDATAACESS_COMPONENTDEFINITION_HXX #include "ComponentDefinition.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition() { static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration; } //........................................................................ namespace dbaccess { //........................................................................ DBG_NAME(OComponentDefinition_Impl) OComponentDefinition_Impl::OComponentDefinition_Impl() { DBG_CTOR(OComponentDefinition_Impl,NULL); } // ----------------------------------------------------------------------------- OComponentDefinition_Impl::~OComponentDefinition_Impl() { DBG_DTOR(OComponentDefinition_Impl,NULL); } //========================================================================== //= OComponentDefinition //========================================================================== //-------------------------------------------------------------------------- DBG_NAME(OComponentDefinition) //-------------------------------------------------------------------------- void OComponentDefinition::registerProperties() { OComponentDefinition_Impl& rDefinition( getDefinition() ); ODataSettings::registerPropertiesFor( &rDefinition ); registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED, &rDefinition.m_aProps.aTitle, ::getCppuType(&rDefinition.m_aProps.aTitle)); if ( m_bTable ) { registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND, &rDefinition.m_sSchemaName, ::getCppuType(&rDefinition.m_sSchemaName)); registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND, &rDefinition.m_sCatalogName, ::getCppuType(&rDefinition.m_sCatalogName)); } } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB ,const Reference< XInterface >& _xParentContainer ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_xParentContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); } //-------------------------------------------------------------------------- OComponentDefinition::~OComponentDefinition() { DBG_DTOR(OComponentDefinition, NULL); } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer ,const ::rtl::OUString& _rElementName ,const Reference< XMultiServiceFactory >& _xORB ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_rxContainer,_pImpl) ,ODataSettings(m_aBHelper) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); m_pImpl->m_aProps.aTitle = _rElementName; DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !"); } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition); IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE); IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE) //-------------------------------------------------------------------------- ::rtl::OUString OComponentDefinition::getImplementationName_Static( ) throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition")); } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(2); aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION; aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content")); return aServices; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------------ Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl))); } // ----------------------------------------------------------------------------- void SAL_CALL OComponentDefinition::disposing() { OContentHelper::disposing(); if ( m_pColumns.is() ) { m_pColumns->disposing(); m_pColumns.reset(); } } // ----------------------------------------------------------------------------- IPropertyArrayHelper& OComponentDefinition::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new OPropertyArrayHelper(aProps); } //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( ) throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed); if ( !m_pColumns.is() ) { ::std::vector< ::rtl::OUString> aNames; const OComponentDefinition_Impl& rDefinition( getDefinition() ); aNames.reserve( rDefinition.size() ); OComponentDefinition_Impl::const_iterator aIter = rDefinition.begin(); OComponentDefinition_Impl::const_iterator aEnd = rDefinition.end(); for ( ; aIter != aEnd; ++aIter ) aNames.push_back( aIter->first ); m_pColumns = TColumnsHelper( new OColumns( *this, m_aMutex, sal_True, aNames, this, NULL, sal_True, sal_False, sal_False ) ) ); m_pColumns->setParent(*this); } return m_pColumns.getRef(); } // ----------------------------------------------------------------------------- OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const { const OComponentDefinition_Impl& rDefinition( getDefinition() ); OComponentDefinition_Impl::const_iterator aFind = rDefinition.find( _rName ); if ( aFind != rDefinition.end() ) return new OTableColumnWrapper( aFind->second, aFind->second, sal_True ); return new OTableColumn( _rName ); } // ----------------------------------------------------------------------------- Reference< ::com::sun::star::beans::XPropertySet > OComponentDefinition::createColumnDescriptor() { return new OTableColumnDescriptor(); } // ----------------------------------------------------------------------------- void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) { ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName) { getDefinition().erase( _sName ); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnAppended( const Reference< XPropertySet >& _rxSourceDescriptor ) { ::rtl::OUString sName; _rxSourceDescriptor->getPropertyValue( PROPERTY_NAME ) >>= sName; Reference<XPropertySet> xColDesc = new OTableColumnDescriptor(); ::comphelper::copyProperties( _rxSourceDescriptor, xColDesc ); getDefinition().insert( sName, xColDesc ); // formerly, here was a setParent at the xColDesc. The parent used was an adapter (ChildHelper_Impl) // which held another XChild weak, and forwarded all getParent requests to this other XChild. // m_pColumns was used for this. This was nonsense, since m_pColumns dies when our instance dies, // but xColDesc will live longer than this. So effectively, the setParent call was pretty useless. // // The intention for this parenting was that the column descriptor is able to find the data source, // by traveling up the parent hierachy until there's an XDataSource. This didn't work (which // for instance causes #i65023#). We need another way to properly ensure this. notifyDataSourceModified(); } //........................................................................ } // namespace dbaccess //........................................................................ <commit_msg>#i10000# syntax error<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ComponentDefinition.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-07-17 13:08:59 $ * * 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 DBA_COREDATAACESS_COMPONENTDEFINITION_HXX #include "ComponentDefinition.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif #ifndef DBACCESS_SHARED_DBASTRINGS_HRC #include "dbastrings.hrc" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _DBACORE_DEFINITIONCOLUMN_HXX_ #include "definitioncolumn.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::osl; using namespace ::comphelper; using namespace ::cppu; extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition() { static ::dbaccess::OMultiInstanceAutoRegistration< ::dbaccess::OComponentDefinition > aAutoRegistration; } //........................................................................ namespace dbaccess { //........................................................................ DBG_NAME(OComponentDefinition_Impl) OComponentDefinition_Impl::OComponentDefinition_Impl() { DBG_CTOR(OComponentDefinition_Impl,NULL); } // ----------------------------------------------------------------------------- OComponentDefinition_Impl::~OComponentDefinition_Impl() { DBG_DTOR(OComponentDefinition_Impl,NULL); } //========================================================================== //= OComponentDefinition //========================================================================== //-------------------------------------------------------------------------- DBG_NAME(OComponentDefinition) //-------------------------------------------------------------------------- void OComponentDefinition::registerProperties() { OComponentDefinition_Impl& rDefinition( getDefinition() ); ODataSettings::registerPropertiesFor( &rDefinition ); registerProperty(PROPERTY_NAME, PROPERTY_ID_NAME, PropertyAttribute::BOUND | PropertyAttribute::READONLY|PropertyAttribute::CONSTRAINED, &rDefinition.m_aProps.aTitle, ::getCppuType(&rDefinition.m_aProps.aTitle)); if ( m_bTable ) { registerProperty(PROPERTY_SCHEMANAME, PROPERTY_ID_SCHEMANAME, PropertyAttribute::BOUND, &rDefinition.m_sSchemaName, ::getCppuType(&rDefinition.m_sSchemaName)); registerProperty(PROPERTY_CATALOGNAME, PROPERTY_ID_CATALOGNAME, PropertyAttribute::BOUND, &rDefinition.m_sCatalogName, ::getCppuType(&rDefinition.m_sCatalogName)); } } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition(const Reference< XMultiServiceFactory >& _xORB ,const Reference< XInterface >& _xParentContainer ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_xParentContainer,_pImpl) ,ODataSettings(m_aBHelper,!_bTable) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); } //-------------------------------------------------------------------------- OComponentDefinition::~OComponentDefinition() { DBG_DTOR(OComponentDefinition, NULL); } //-------------------------------------------------------------------------- OComponentDefinition::OComponentDefinition( const Reference< XInterface >& _rxContainer ,const ::rtl::OUString& _rElementName ,const Reference< XMultiServiceFactory >& _xORB ,const TContentPtr& _pImpl ,sal_Bool _bTable) :OContentHelper(_xORB,_rxContainer,_pImpl) ,ODataSettings(m_aBHelper) ,m_bTable(_bTable) { DBG_CTOR(OComponentDefinition, NULL); registerProperties(); m_pImpl->m_aProps.aTitle = _rElementName; DBG_ASSERT(m_pImpl->m_aProps.aTitle.getLength() != 0, "OComponentDefinition::OComponentDefinition : invalid name !"); } //-------------------------------------------------------------------------- IMPLEMENT_IMPLEMENTATION_ID(OComponentDefinition); IMPLEMENT_GETTYPES3(OComponentDefinition,ODataSettings,OContentHelper,OComponentDefinition_BASE); IMPLEMENT_FORWARD_XINTERFACE3( OComponentDefinition,OContentHelper,ODataSettings,OComponentDefinition_BASE) //-------------------------------------------------------------------------- ::rtl::OUString OComponentDefinition::getImplementationName_Static( ) throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.dba.OComponentDefinition")); } //-------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OComponentDefinition::getImplementationName( ) throw(RuntimeException) { return getImplementationName_Static(); } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > OComponentDefinition::getSupportedServiceNames_Static( ) throw(RuntimeException) { Sequence< ::rtl::OUString > aServices(2); aServices.getArray()[0] = SERVICE_SDB_TABLEDEFINITION; aServices.getArray()[1] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.Content")); return aServices; } //-------------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL OComponentDefinition::getSupportedServiceNames( ) throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------------ Reference< XInterface > OComponentDefinition::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new OComponentDefinition(_rxFactory,NULL,TContentPtr(new OComponentDefinition_Impl))); } // ----------------------------------------------------------------------------- void SAL_CALL OComponentDefinition::disposing() { OContentHelper::disposing(); if ( m_pColumns.is() ) { m_pColumns->disposing(); m_pColumns.reset(); } } // ----------------------------------------------------------------------------- IPropertyArrayHelper& OComponentDefinition::getInfoHelper() { return *getArrayHelper(); } //-------------------------------------------------------------------------- IPropertyArrayHelper* OComponentDefinition::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new OPropertyArrayHelper(aProps); } //-------------------------------------------------------------------------- Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( ) throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); ::connectivity::checkDisposed(OContentHelper::rBHelper.bDisposed); if ( !m_pColumns.is() ) { ::std::vector< ::rtl::OUString> aNames; const OComponentDefinition_Impl& rDefinition( getDefinition() ); aNames.reserve( rDefinition.size() ); OComponentDefinition_Impl::const_iterator aIter = rDefinition.begin(); OComponentDefinition_Impl::const_iterator aEnd = rDefinition.end(); for ( ; aIter != aEnd; ++aIter ) aNames.push_back( aIter->first ); m_pColumns = TColumnsHelper( new OColumns( *this, m_aMutex, sal_True, aNames, this, NULL, sal_True, sal_False, sal_False ) ); m_pColumns->setParent(*this); } return m_pColumns.getRef(); } // ----------------------------------------------------------------------------- OColumn* OComponentDefinition::createColumn(const ::rtl::OUString& _rName) const { const OComponentDefinition_Impl& rDefinition( getDefinition() ); OComponentDefinition_Impl::const_iterator aFind = rDefinition.find( _rName ); if ( aFind != rDefinition.end() ) return new OTableColumnWrapper( aFind->second, aFind->second, sal_True ); return new OTableColumn( _rName ); } // ----------------------------------------------------------------------------- Reference< ::com::sun::star::beans::XPropertySet > OComponentDefinition::createColumnDescriptor() { return new OTableColumnDescriptor(); } // ----------------------------------------------------------------------------- void OComponentDefinition::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) { ODataSettings::setFastPropertyValue_NoBroadcast(nHandle,rValue); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnDropped(const ::rtl::OUString& _sName) { getDefinition().erase( _sName ); notifyDataSourceModified(); } // ----------------------------------------------------------------------------- void OComponentDefinition::columnAppended( const Reference< XPropertySet >& _rxSourceDescriptor ) { ::rtl::OUString sName; _rxSourceDescriptor->getPropertyValue( PROPERTY_NAME ) >>= sName; Reference<XPropertySet> xColDesc = new OTableColumnDescriptor(); ::comphelper::copyProperties( _rxSourceDescriptor, xColDesc ); getDefinition().insert( sName, xColDesc ); // formerly, here was a setParent at the xColDesc. The parent used was an adapter (ChildHelper_Impl) // which held another XChild weak, and forwarded all getParent requests to this other XChild. // m_pColumns was used for this. This was nonsense, since m_pColumns dies when our instance dies, // but xColDesc will live longer than this. So effectively, the setParent call was pretty useless. // // The intention for this parenting was that the column descriptor is able to find the data source, // by traveling up the parent hierachy until there's an XDataSource. This didn't work (which // for instance causes #i65023#). We need another way to properly ensure this. notifyDataSourceModified(); } //........................................................................ } // namespace dbaccess //........................................................................ <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <limits.h> #include <pthread.h> #include <stdint.h> #include <stdint.h> #include <string.h> #include <algorithm> #include <string> #include "geopm_hash.h" #include "Exception.hpp" #include "ProfileTable.hpp" namespace geopm { ProfileTable::ProfileTable(size_t size, void *buffer) : m_buffer_size(size) , m_table_length(table_length(m_buffer_size)) , m_mask(m_table_length - 1) , m_table((struct table_entry_s *)buffer) , m_key_map_lock(PTHREAD_MUTEX_INITIALIZER) , m_is_pshared(true) , m_key_map_last(m_key_map.end()) { if (buffer == NULL) { throw Exception("ProfileTable: Buffer pointer is NULL", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } if (M_TABLE_DEPTH_MAX < 4) { throw Exception("ProfileTable: Table depth must be at least 4", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } struct table_entry_s table_init; memset((void *)&table_init, 0, sizeof(struct table_entry_s)); pthread_mutexattr_t lock_attr; int err = pthread_mutexattr_init(&lock_attr); if (err) { throw Exception("ProfileTable: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (m_is_pshared) { err = pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED); if (err) { throw Exception("ProfileTable: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } for (size_t i = 0; i < m_table_length; ++i) { m_table[i] = table_init; err = pthread_mutex_init(&(m_table[i].lock), &lock_attr); if (err) { throw Exception("ProfileTable: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } } ProfileTable::~ProfileTable() { } size_t ProfileTable::table_length(size_t buffer_size) const { size_t private_size = GEOPM_NUM_REGION_ID_PRIVATE * sizeof(struct table_entry_s); if (buffer_size < private_size + sizeof(struct table_entry_s)) { throw Exception("ProfileTable: Buffer size too small", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } size_t result = (buffer_size - private_size) / sizeof(struct table_entry_s); // The closest power of two small enough to fit in the buffer if (result) { result--; result |= result >> 1; result |= result >> 2; result |= result >> 4; result |= result >> 8; result |= result >> 16; result |= result >> 32; result++; result = result >> 1; } if (result * sizeof(struct table_entry_s) + private_size > buffer_size) { result /= 2; } if (result <= 0) { throw Exception("ProfileTable: Failing to created empty table, increase size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } result += GEOPM_NUM_REGION_ID_PRIVATE; return result; } size_t ProfileTable::hash(uint64_t key) const { size_t result = 0; if (key == GEOPM_REGION_ID_MPI) { result = m_mask + 1; } else if (key == GEOPM_REGION_ID_OUTER) { result = m_mask + 2; } else { result = geopm_crc32_u64(0, key) & m_mask; } return result; } void ProfileTable::insert(uint64_t key, const struct geopm_prof_message_s &value) { if (key == 0) { throw Exception("ProfileTable::insert(): zero is not a valid key", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } size_t table_idx = hash(key); int err = pthread_mutex_lock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::insert(): pthread_mutex_lock()", err, __FILE__, __LINE__); } bool is_stored = false; for (size_t i = 0; !is_stored && i != M_TABLE_DEPTH_MAX; ++i) { if (m_table[table_idx].key[i] == 0 || (m_table[table_idx].key[i] == key && !sticky(m_table[table_idx].value[i]))) { m_table[table_idx].key[i] = key; m_table[table_idx].value[i] = value; is_stored = true; } } err = pthread_mutex_unlock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::insert(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } if (!is_stored) { int entry_index = 0; // We have overflowed the table entry. Clear it out unless there is a region exit in // the first position, then save it. If there is an region enter in the last position, // then copy it to the first open position, insert the current entry, and invalidate // the rest of the entries. if (m_table[table_idx].value[0].progress == 1.0) { ++entry_index; } if (m_table[table_idx].value[M_TABLE_DEPTH_MAX - 1].progress == 0.0) { m_table[table_idx].value[entry_index] = m_table[table_idx].value[M_TABLE_DEPTH_MAX - 1]; m_table[table_idx].key[entry_index] = m_table[table_idx].key[M_TABLE_DEPTH_MAX - 1]; ++entry_index; } m_table[table_idx].key[entry_index] = key; m_table[table_idx].value[entry_index] = value; m_table[table_idx].key[entry_index + 1] = 0; } } struct geopm_prof_message_s ProfileTable::find(uint64_t key) { if (key == 0) { throw Exception("ProfileTable::find(): zero is not a valid key", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } size_t table_idx = hash(key); const struct geopm_prof_message_s *result_ptr = NULL; int err = pthread_mutex_lock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::find(): pthread_mutex_lock()", err, __FILE__, __LINE__); } for (size_t i = 0; i < M_TABLE_DEPTH_MAX; ++i) { if (m_table[table_idx].key[i] == key) { result_ptr = m_table[table_idx].value + i; break; } } err = pthread_mutex_unlock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::find(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } if (result_ptr == NULL) { throw Exception("ProfileTable::find(): key not found", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return *result_ptr; } uint64_t ProfileTable::key(const std::string &name) { uint64_t result = 0; int err = pthread_mutex_lock(&(m_key_map_lock)); if (err) { throw Exception("ProfileTable::key(): pthread_mutex_lock()", err, __FILE__, __LINE__); } auto key_map_it = m_key_map.find(name); err = pthread_mutex_unlock(&(m_key_map_lock)); if (err) { throw Exception("ProfileTable::key(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } if (key_map_it != m_key_map.end()) { result = key_map_it->second; } else { result = geopm_crc32_str(0, (char *)(&name.front())); if (!result) { throw Exception("ProfileTable::key(): CRC 32 hashed to zero!", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutex_lock(&(m_key_map_lock)); if (err) { throw Exception("ProfileTable::key(): pthread_mutex_lock()", err, __FILE__, __LINE__); } if (m_key_set.find(result) != m_key_set.end()) { throw Exception("ProfileTable::key(): String hash collision", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_key_set.insert(result); m_key_map.insert(std::pair<const std::string, uint64_t>(name, result)); m_key_map_last = m_key_map.begin(); err = pthread_mutex_unlock(&(m_key_map_lock)); if (err) { throw Exception("ProfileTable::key(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } } return result; } size_t ProfileTable::capacity(void) const { return m_table_length * M_TABLE_DEPTH_MAX; } size_t ProfileTable::size(void) const { int err; size_t result = 0; for (size_t table_idx = 0; table_idx < m_table_length; ++table_idx) { err = pthread_mutex_lock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::size(): pthread_mutex_lock()", err, __FILE__, __LINE__); } for (int depth = 0; depth < M_TABLE_DEPTH_MAX && m_table[table_idx].key[depth]; ++depth) { ++result; } err = pthread_mutex_unlock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::size(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } } return result; } void ProfileTable::dump(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::iterator content, size_t &length) { int err; length = 0; for (size_t table_idx = 0; table_idx < m_table_length; ++table_idx) { err = pthread_mutex_lock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::dump(): pthread_mutex_lock()", err, __FILE__, __LINE__); } for (int depth = 0; depth < M_TABLE_DEPTH_MAX && m_table[table_idx].key[depth]; ++depth) { content->first = m_table[table_idx].key[depth]; content->second = m_table[table_idx].value[depth]; m_table[table_idx].key[depth] = 0; ++content; ++length; } err = pthread_mutex_unlock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::dump(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } } } bool ProfileTable::name_fill(size_t header_offset) { bool result = false; size_t buffer_remain = m_buffer_size - header_offset - 1; char *buffer_ptr = (char *)m_table + header_offset; while (m_key_map_last != m_key_map.end() && buffer_remain > (*m_key_map_last).first.length()) { strncpy(buffer_ptr, (*m_key_map_last).first.c_str(), buffer_remain); buffer_remain -= (*m_key_map_last).first.length() + 1; buffer_ptr += (*m_key_map_last).first.length() + 1; ++m_key_map_last; } memset(buffer_ptr, 0, buffer_remain); if (m_key_map_last == m_key_map.end() && buffer_remain) { // We are done, set last character to -1 buffer_ptr[buffer_remain] = (char) 1; m_key_map_last = m_key_map.begin(); result = true; } else { buffer_ptr[buffer_remain] = '\0'; } return result; } bool ProfileTable::name_set(size_t header_offset, std::set<std::string> &name) { char tmp_name[NAME_MAX]; bool result = false; size_t buffer_remain = m_buffer_size - header_offset - 1; char *buffer_ptr = (char *)m_table + header_offset; while (buffer_remain) { tmp_name[NAME_MAX - 1] = '\0'; strncpy(tmp_name, buffer_ptr, NAME_MAX); if (tmp_name[NAME_MAX - 1] != '\0') { throw Exception("ProfileTable::name_set(): key string is too long", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (strlen(tmp_name)) { name.insert(std::string(tmp_name)); buffer_remain -= strlen(tmp_name) + 1; buffer_ptr += strlen(tmp_name) + 1; } else { if (buffer_ptr[buffer_remain] == (char) 1) { result = true; } buffer_remain = 0; } } return result; } bool ProfileTable::sticky(const struct geopm_prof_message_s &value) { bool result = false; if (value.progress == 0.0 || value.progress == 1.0) { result = true; } return result; } } <commit_msg>Remove private entries from mask calculation.<commit_after>/* * Copyright (c) 2015, 2016, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <limits.h> #include <pthread.h> #include <stdint.h> #include <stdint.h> #include <string.h> #include <algorithm> #include <string> #include "geopm_hash.h" #include "Exception.hpp" #include "ProfileTable.hpp" namespace geopm { ProfileTable::ProfileTable(size_t size, void *buffer) : m_buffer_size(size) , m_table_length(table_length(m_buffer_size)) , m_mask(m_table_length - GEOPM_NUM_REGION_ID_PRIVATE - 1) , m_table((struct table_entry_s *)buffer) , m_key_map_lock(PTHREAD_MUTEX_INITIALIZER) , m_is_pshared(true) , m_key_map_last(m_key_map.end()) { if (buffer == NULL) { throw Exception("ProfileTable: Buffer pointer is NULL", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } if (M_TABLE_DEPTH_MAX < 4) { throw Exception("ProfileTable: Table depth must be at least 4", GEOPM_ERROR_LOGIC, __FILE__, __LINE__); } struct table_entry_s table_init; memset((void *)&table_init, 0, sizeof(struct table_entry_s)); pthread_mutexattr_t lock_attr; int err = pthread_mutexattr_init(&lock_attr); if (err) { throw Exception("ProfileTable: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (m_is_pshared) { err = pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED); if (err) { throw Exception("ProfileTable: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } for (size_t i = 0; i < m_table_length; ++i) { m_table[i] = table_init; err = pthread_mutex_init(&(m_table[i].lock), &lock_attr); if (err) { throw Exception("ProfileTable: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } } } ProfileTable::~ProfileTable() { } size_t ProfileTable::table_length(size_t buffer_size) const { size_t private_size = GEOPM_NUM_REGION_ID_PRIVATE * sizeof(struct table_entry_s); if (buffer_size < private_size + sizeof(struct table_entry_s)) { throw Exception("ProfileTable: Buffer size too small", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } size_t result = (buffer_size - private_size) / sizeof(struct table_entry_s); // The closest power of two small enough to fit in the buffer if (result) { result--; result |= result >> 1; result |= result >> 2; result |= result >> 4; result |= result >> 8; result |= result >> 16; result |= result >> 32; result++; result = result >> 1; } if (result * sizeof(struct table_entry_s) + private_size > buffer_size) { result /= 2; } if (result <= 0) { throw Exception("ProfileTable: Failing to created empty table, increase size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } result += GEOPM_NUM_REGION_ID_PRIVATE; return result; } size_t ProfileTable::hash(uint64_t key) const { size_t result = 0; if (key == GEOPM_REGION_ID_MPI) { result = m_mask + 1; } else if (key == GEOPM_REGION_ID_OUTER) { result = m_mask + 2; } else { result = geopm_crc32_u64(0, key) & m_mask; } return result; } void ProfileTable::insert(uint64_t key, const struct geopm_prof_message_s &value) { if (key == 0) { throw Exception("ProfileTable::insert(): zero is not a valid key", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } size_t table_idx = hash(key); int err = pthread_mutex_lock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::insert(): pthread_mutex_lock()", err, __FILE__, __LINE__); } bool is_stored = false; for (size_t i = 0; !is_stored && i != M_TABLE_DEPTH_MAX; ++i) { if (m_table[table_idx].key[i] == 0 || (m_table[table_idx].key[i] == key && !sticky(m_table[table_idx].value[i]))) { m_table[table_idx].key[i] = key; m_table[table_idx].value[i] = value; is_stored = true; } } err = pthread_mutex_unlock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::insert(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } if (!is_stored) { int entry_index = 0; // We have overflowed the table entry. Clear it out unless there is a region exit in // the first position, then save it. If there is an region enter in the last position, // then copy it to the first open position, insert the current entry, and invalidate // the rest of the entries. if (m_table[table_idx].value[0].progress == 1.0) { ++entry_index; } if (m_table[table_idx].value[M_TABLE_DEPTH_MAX - 1].progress == 0.0) { m_table[table_idx].value[entry_index] = m_table[table_idx].value[M_TABLE_DEPTH_MAX - 1]; m_table[table_idx].key[entry_index] = m_table[table_idx].key[M_TABLE_DEPTH_MAX - 1]; ++entry_index; } m_table[table_idx].key[entry_index] = key; m_table[table_idx].value[entry_index] = value; m_table[table_idx].key[entry_index + 1] = 0; } } struct geopm_prof_message_s ProfileTable::find(uint64_t key) { if (key == 0) { throw Exception("ProfileTable::find(): zero is not a valid key", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } size_t table_idx = hash(key); const struct geopm_prof_message_s *result_ptr = NULL; int err = pthread_mutex_lock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::find(): pthread_mutex_lock()", err, __FILE__, __LINE__); } for (size_t i = 0; i < M_TABLE_DEPTH_MAX; ++i) { if (m_table[table_idx].key[i] == key) { result_ptr = m_table[table_idx].value + i; break; } } err = pthread_mutex_unlock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::find(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } if (result_ptr == NULL) { throw Exception("ProfileTable::find(): key not found", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return *result_ptr; } uint64_t ProfileTable::key(const std::string &name) { uint64_t result = 0; int err = pthread_mutex_lock(&(m_key_map_lock)); if (err) { throw Exception("ProfileTable::key(): pthread_mutex_lock()", err, __FILE__, __LINE__); } auto key_map_it = m_key_map.find(name); err = pthread_mutex_unlock(&(m_key_map_lock)); if (err) { throw Exception("ProfileTable::key(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } if (key_map_it != m_key_map.end()) { result = key_map_it->second; } else { result = geopm_crc32_str(0, (char *)(&name.front())); if (!result) { throw Exception("ProfileTable::key(): CRC 32 hashed to zero!", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } err = pthread_mutex_lock(&(m_key_map_lock)); if (err) { throw Exception("ProfileTable::key(): pthread_mutex_lock()", err, __FILE__, __LINE__); } if (m_key_set.find(result) != m_key_set.end()) { throw Exception("ProfileTable::key(): String hash collision", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } m_key_set.insert(result); m_key_map.insert(std::pair<const std::string, uint64_t>(name, result)); m_key_map_last = m_key_map.begin(); err = pthread_mutex_unlock(&(m_key_map_lock)); if (err) { throw Exception("ProfileTable::key(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } } return result; } size_t ProfileTable::capacity(void) const { return m_table_length * M_TABLE_DEPTH_MAX; } size_t ProfileTable::size(void) const { int err; size_t result = 0; for (size_t table_idx = 0; table_idx < m_table_length; ++table_idx) { err = pthread_mutex_lock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::size(): pthread_mutex_lock()", err, __FILE__, __LINE__); } for (int depth = 0; depth < M_TABLE_DEPTH_MAX && m_table[table_idx].key[depth]; ++depth) { ++result; } err = pthread_mutex_unlock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::size(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } } return result; } void ProfileTable::dump(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::iterator content, size_t &length) { int err; length = 0; for (size_t table_idx = 0; table_idx < m_table_length; ++table_idx) { err = pthread_mutex_lock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::dump(): pthread_mutex_lock()", err, __FILE__, __LINE__); } for (int depth = 0; depth < M_TABLE_DEPTH_MAX && m_table[table_idx].key[depth]; ++depth) { content->first = m_table[table_idx].key[depth]; content->second = m_table[table_idx].value[depth]; m_table[table_idx].key[depth] = 0; ++content; ++length; } err = pthread_mutex_unlock(&(m_table[table_idx].lock)); if (err) { throw Exception("ProfileTable::dump(): pthread_mutex_unlock()", err, __FILE__, __LINE__); } } } bool ProfileTable::name_fill(size_t header_offset) { bool result = false; size_t buffer_remain = m_buffer_size - header_offset - 1; char *buffer_ptr = (char *)m_table + header_offset; while (m_key_map_last != m_key_map.end() && buffer_remain > (*m_key_map_last).first.length()) { strncpy(buffer_ptr, (*m_key_map_last).first.c_str(), buffer_remain); buffer_remain -= (*m_key_map_last).first.length() + 1; buffer_ptr += (*m_key_map_last).first.length() + 1; ++m_key_map_last; } memset(buffer_ptr, 0, buffer_remain); if (m_key_map_last == m_key_map.end() && buffer_remain) { // We are done, set last character to -1 buffer_ptr[buffer_remain] = (char) 1; m_key_map_last = m_key_map.begin(); result = true; } else { buffer_ptr[buffer_remain] = '\0'; } return result; } bool ProfileTable::name_set(size_t header_offset, std::set<std::string> &name) { char tmp_name[NAME_MAX]; bool result = false; size_t buffer_remain = m_buffer_size - header_offset - 1; char *buffer_ptr = (char *)m_table + header_offset; while (buffer_remain) { tmp_name[NAME_MAX - 1] = '\0'; strncpy(tmp_name, buffer_ptr, NAME_MAX); if (tmp_name[NAME_MAX - 1] != '\0') { throw Exception("ProfileTable::name_set(): key string is too long", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (strlen(tmp_name)) { name.insert(std::string(tmp_name)); buffer_remain -= strlen(tmp_name) + 1; buffer_ptr += strlen(tmp_name) + 1; } else { if (buffer_ptr[buffer_remain] == (char) 1) { result = true; } buffer_remain = 0; } } return result; } bool ProfileTable::sticky(const struct geopm_prof_message_s &value) { bool result = false; if (value.progress == 0.0 || value.progress == 1.0) { result = true; } return result; } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * f.thauer@web.de * * * * 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. * ***************************************************************************/ /////// can be removed for non-qt-guis //////////// #include <qapplication.h> #ifdef __APPLE__ #include <QMacStyle> #endif /////////////////////////////////////////////////// #include "session.h" #include "guiwrapper.h" #include "configfile.h" #include <net/socket_startup.h> #include <curl/curl.h> #include <QtGui> #include <QtCore> #include <iostream> #include <cstdlib> #include <ctime> #ifdef _MSC_VER #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define ENABLE_LEAK_CHECK() \ { \ int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \ tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \ _CrtSetDbgFlag(tmpFlag); \ } #endif #endif #ifndef ENABLE_LEAK_CHECK #define ENABLE_LEAK_CHECK() #endif //Uncomment this for RELEASE // #include <QtPlugin> // Q_IMPORT_PLUGIN(qjpeg) // Q_IMPORT_PLUGIN(qgif) using namespace std; class GuiWrapper; class Game; int main( int argc, char **argv ) { //ENABLE_LEAK_CHECK(); //_CrtSetBreakAlloc(49937); socket_startup(); curl_global_init(CURL_GLOBAL_NOTHING); /////// can be removed for non-qt-guis //////////// QApplication a( argc, argv ); //create defaultconfig ConfigFile *myConfig = new ConfigFile(argv[0], false); // set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets a.setStyle(new QPlastiqueStyle); QString myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str()); //set QApplication default font QFontDatabase::addApplicationFont (myAppDataPath +"fonts/n019003l.pfb"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/VeraBd.ttf"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/c059013l.pfb"); #ifdef _WIN32 QString font1String("font-family: \"Arial\";"); a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }"); #else // #ifdef __APPLE__ // QString font1String("font-family: \"Lucida Grande\";"); // #else QString font1String("font-family: \"Nimbus Sans L\";"); // #endif a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }"); #endif //Set translations QTranslator qtTranslator; qtTranslator.load(QString(myAppDataPath +"translations/qt_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&qtTranslator); QTranslator translator; translator.load(QString(myAppDataPath +"translations/pokerth_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&translator); #ifdef __APPLE__ QDir dir(QApplication::applicationDirPath()); dir.cdUp(); dir.cd("plugins"); QApplication::setLibraryPaths(QStringList(dir.absolutePath())); #endif qRegisterMetaType<unsigned>("unsigned"); qRegisterMetaType<boost::shared_ptr<Game> >("boost::shared_ptr<Game>"); qRegisterMetaType<ServerStats>("ServerStats"); /////////////////////////////////////////////////// boost::shared_ptr<GuiInterface> myGuiInterface(new GuiWrapper(myConfig)); { boost::shared_ptr<Session> session(new Session(myGuiInterface.get(), myConfig)); session->init(); // TODO handle error myGuiInterface->setSession(session); } int retVal = a.exec(); socket_cleanup(); return retVal; } <commit_msg>Changed curl_global_init call to initialize everything. Added missing cleanup call.<commit_after>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * f.thauer@web.de * * * * 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. * ***************************************************************************/ /////// can be removed for non-qt-guis //////////// #include <qapplication.h> #ifdef __APPLE__ #include <QMacStyle> #endif /////////////////////////////////////////////////// #include "session.h" #include "guiwrapper.h" #include "configfile.h" #include <net/socket_startup.h> #include <curl/curl.h> #include <QtGui> #include <QtCore> #include <iostream> #include <cstdlib> #include <ctime> #ifdef _MSC_VER #ifdef _DEBUG #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #define ENABLE_LEAK_CHECK() \ { \ int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \ tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \ _CrtSetDbgFlag(tmpFlag); \ } #endif #endif #ifndef ENABLE_LEAK_CHECK #define ENABLE_LEAK_CHECK() #endif //Uncomment this for RELEASE // #include <QtPlugin> // Q_IMPORT_PLUGIN(qjpeg) // Q_IMPORT_PLUGIN(qgif) using namespace std; class GuiWrapper; class Game; int main( int argc, char **argv ) { //ENABLE_LEAK_CHECK(); //_CrtSetBreakAlloc(49937); socket_startup(); curl_global_init(CURL_GLOBAL_ALL); /////// can be removed for non-qt-guis //////////// QApplication a( argc, argv ); //create defaultconfig ConfigFile *myConfig = new ConfigFile(argv[0], false); // set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets a.setStyle(new QPlastiqueStyle); QString myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str()); //set QApplication default font QFontDatabase::addApplicationFont (myAppDataPath +"fonts/n019003l.pfb"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/VeraBd.ttf"); QFontDatabase::addApplicationFont (myAppDataPath +"fonts/c059013l.pfb"); #ifdef _WIN32 QString font1String("font-family: \"Arial\";"); a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }"); #else // #ifdef __APPLE__ // QString font1String("font-family: \"Lucida Grande\";"); // #else QString font1String("font-family: \"Nimbus Sans L\";"); // #endif a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }"); #endif //Set translations QTranslator qtTranslator; qtTranslator.load(QString(myAppDataPath +"translations/qt_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&qtTranslator); QTranslator translator; translator.load(QString(myAppDataPath +"translations/pokerth_") + QString::fromStdString(myConfig->readConfigString("Language"))); a.installTranslator(&translator); #ifdef __APPLE__ QDir dir(QApplication::applicationDirPath()); dir.cdUp(); dir.cd("plugins"); QApplication::setLibraryPaths(QStringList(dir.absolutePath())); #endif qRegisterMetaType<unsigned>("unsigned"); qRegisterMetaType<boost::shared_ptr<Game> >("boost::shared_ptr<Game>"); qRegisterMetaType<ServerStats>("ServerStats"); /////////////////////////////////////////////////// boost::shared_ptr<GuiInterface> myGuiInterface(new GuiWrapper(myConfig)); { boost::shared_ptr<Session> session(new Session(myGuiInterface.get(), myConfig)); session->init(); // TODO handle error myGuiInterface->setSession(session); } int retVal = a.exec(); curl_global_cleanup(); socket_cleanup(); return retVal; } <|endoftext|>
<commit_before>/** event.hpp - Support file for writing LV2 plugins in C++ Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA */ /** @file event.hpp C++ convenience header for the LV2 Event extension. */ #ifndef LV2_EVENT_HPP #define LV2_EVENT_HPP #include <lv2/lv2plug.in/ns/ext/event/event.h> namespace LV2 { } #endif /* LV2_EVENT_HPP */ <commit_msg>Formatting this header<commit_after>/** event.hpp - Support file for writing LV2 plugins in C++ Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA */ /** @file event.hpp C++ convenience header for the LV2 Event extension. LV2 C Version Support: 1.6 (2012-04-17) DEPRECATED */ #ifndef LV2_EVENT_HPP #define LV2_EVENT_HPP #include <lv2/lv2plug.in/ns/ext/event/event.h> #include <lv2mm/types.hpp> namespace LV2 { } #endif /* LV2_EVENT_HPP */ <|endoftext|>
<commit_before>/****************************************************************************** Copyright 2013 Scientific Computation Research Center, Rensselaer Polytechnic Institute. All rights reserved. The LICENSE file included with this distribution describes the terms of the SCOREC Non-Commercial License this program is distributed under. *******************************************************************************/ #include "maSnapper.h" #include "maAdapt.h" #include "maShapeHandler.h" #include <apfCavityOp.h> namespace ma { Snapper::Snapper(Adapt* a, Tag* st, bool is) { adapter = a; snapTag = st; collapse.Init(a); isSimple = is; dug = false; } bool Snapper::setVert(Entity* v, apf::CavityOp* o) { vert = v; if (!o->requestLocality(&vert, 1)) return false; if (isSimple) return true; /* in order to try an edge collapse (we don't yet know which edge), bring in a cavity such that all adjacent edges have both vertices local. This is basically two layers of elements around the vertex */ apf::Up edges; adapter->mesh->getUp(vert,edges); apf::Up ovs; ovs.n = edges.n; for (int i = 0; i < edges.n; ++i) ovs.e[i] = apf::getEdgeVertOppositeVert(adapter->mesh, edges.e[i], vert); return o->requestLocality(&ovs.e[0], ovs.n); } static void collectBadElements(Adapt* a, Upward& es, apf::Up& bes) { bes.n = 0; for (size_t i = 0; i < es.getSize(); ++i) { /* for now, when snapping a vertex on the boundary layer, ignore the quality of layer elements. not only do we not have metrics for this, but the algorithm that moves curves would need to change */ if (getFlag(a, es[i], LAYER)) continue; double quality = a->shape->getQuality(es[i]); if (quality < a->input->validQuality) bes.e[bes.n++] = es[i]; } assert(bes.n < (int)(sizeof(bes.e) / sizeof(Entity*))); } static bool trySnapping(Adapt* adapter, Tag* tag, Entity* vert, apf::Up& badElements) { Mesh* mesh = adapter->mesh; Vector x = getPosition(mesh, vert); Vector s; mesh->getDoubleTag(vert, tag, &s[0]); /* move the vertex to the desired point */ mesh->setPoint(vert, 0, s); Upward elements; mesh->getAdjacent(vert, mesh->getDimension(), elements); /* check resulting cavity */ collectBadElements(adapter, elements, badElements); if (badElements.n) { /* not ok, put the vertex back where it was */ mesh->setPoint(vert, 0, x); return false; } else { /* ok, take off the snap tag */ mesh->removeTag(vert, tag); return true; } } static bool tryDiggingEdge(Adapt* adapter, Collapse& collapse, Entity* e) { Mesh* mesh = adapter->mesh; assert(mesh->getType(e) == EDGE); if ( ! collapse.setEdge(e)) return false; if ( ! collapse.checkClass()) return false; if ( ! collapse.checkTopo()) return false; double q = adapter->input->validQuality; if ( ! collapse.tryBothDirections(q)) return false; collapse.destroyOldElements(); return true; } static bool tryDigging2(Adapt* a, Collapse& c, apf::Up& badElements) { Mesh* m = a->mesh; for (int i = 0; i < badElements.n; ++i) { Entity* elem = badElements.e[i]; Vector center = apf::getLinearCentroid(m, elem); Downward edges; int nedges = m->getDownward(elem, 1, edges); for (int j = 0; j < nedges; ++j) if (tryDiggingEdge(a, c, edges[j])) return true; } return false; } static bool tryDigging(Adapt* a, Collapse& c, Entity* v, apf::Up& badElements) { bool hadItBefore = getFlag(a, v, DONT_COLLAPSE); setFlag(a, v, DONT_COLLAPSE); bool ok = tryDigging2(a, c, badElements); if (!hadItBefore) clearFlag(a, v, DONT_COLLAPSE); return ok; } bool Snapper::run() { dug = false; apf::Up badElements; bool ok = trySnapping(adapter, snapTag, vert, badElements); if (isSimple) return ok; if (ok) return true; dug = tryDigging(adapter, collapse, vert, badElements); if (!dug) return false; return trySnapping(adapter, snapTag, vert, badElements); } } <commit_msg>remove unneeded variable<commit_after>/****************************************************************************** Copyright 2013 Scientific Computation Research Center, Rensselaer Polytechnic Institute. All rights reserved. The LICENSE file included with this distribution describes the terms of the SCOREC Non-Commercial License this program is distributed under. *******************************************************************************/ #include "maSnapper.h" #include "maAdapt.h" #include "maShapeHandler.h" #include <apfCavityOp.h> namespace ma { Snapper::Snapper(Adapt* a, Tag* st, bool is) { adapter = a; snapTag = st; collapse.Init(a); isSimple = is; dug = false; } bool Snapper::setVert(Entity* v, apf::CavityOp* o) { vert = v; if (!o->requestLocality(&vert, 1)) return false; if (isSimple) return true; /* in order to try an edge collapse (we don't yet know which edge), bring in a cavity such that all adjacent edges have both vertices local. This is basically two layers of elements around the vertex */ apf::Up edges; adapter->mesh->getUp(vert,edges); apf::Up ovs; ovs.n = edges.n; for (int i = 0; i < edges.n; ++i) ovs.e[i] = apf::getEdgeVertOppositeVert(adapter->mesh, edges.e[i], vert); return o->requestLocality(&ovs.e[0], ovs.n); } static void collectBadElements(Adapt* a, Upward& es, apf::Up& bes) { bes.n = 0; for (size_t i = 0; i < es.getSize(); ++i) { /* for now, when snapping a vertex on the boundary layer, ignore the quality of layer elements. not only do we not have metrics for this, but the algorithm that moves curves would need to change */ if (getFlag(a, es[i], LAYER)) continue; double quality = a->shape->getQuality(es[i]); if (quality < a->input->validQuality) bes.e[bes.n++] = es[i]; } assert(bes.n < (int)(sizeof(bes.e) / sizeof(Entity*))); } static bool trySnapping(Adapt* adapter, Tag* tag, Entity* vert, apf::Up& badElements) { Mesh* mesh = adapter->mesh; Vector x = getPosition(mesh, vert); Vector s; mesh->getDoubleTag(vert, tag, &s[0]); /* move the vertex to the desired point */ mesh->setPoint(vert, 0, s); Upward elements; mesh->getAdjacent(vert, mesh->getDimension(), elements); /* check resulting cavity */ collectBadElements(adapter, elements, badElements); if (badElements.n) { /* not ok, put the vertex back where it was */ mesh->setPoint(vert, 0, x); return false; } else { /* ok, take off the snap tag */ mesh->removeTag(vert, tag); return true; } } static bool tryDiggingEdge(Adapt* adapter, Collapse& collapse, Entity* e) { Mesh* mesh = adapter->mesh; assert(mesh->getType(e) == EDGE); if ( ! collapse.setEdge(e)) return false; if ( ! collapse.checkClass()) return false; if ( ! collapse.checkTopo()) return false; double q = adapter->input->validQuality; if ( ! collapse.tryBothDirections(q)) return false; collapse.destroyOldElements(); return true; } static bool tryDigging2(Adapt* a, Collapse& c, apf::Up& badElements) { Mesh* m = a->mesh; for (int i = 0; i < badElements.n; ++i) { Entity* elem = badElements.e[i]; Downward edges; int nedges = m->getDownward(elem, 1, edges); for (int j = 0; j < nedges; ++j) if (tryDiggingEdge(a, c, edges[j])) return true; } return false; } static bool tryDigging(Adapt* a, Collapse& c, Entity* v, apf::Up& badElements) { bool hadItBefore = getFlag(a, v, DONT_COLLAPSE); setFlag(a, v, DONT_COLLAPSE); bool ok = tryDigging2(a, c, badElements); if (!hadItBefore) clearFlag(a, v, DONT_COLLAPSE); return ok; } bool Snapper::run() { dug = false; apf::Up badElements; bool ok = trySnapping(adapter, snapTag, vert, badElements); if (isSimple) return ok; if (ok) return true; dug = tryDigging(adapter, collapse, vert, badElements); if (!dug) return false; return trySnapping(adapter, snapTag, vert, badElements); } } <|endoftext|>
<commit_before>#include "game.hpp" #define SCORE_MAX 3 // helper functions static void draw(); static void resetBall(); // game state functions static void menuTitle(); static void gameSetup(); static void gameMain(); static void gamePause(); static void menuWin(); static void menuLose(); void (*gameTick)(){ &menuTitle }; Ball ball; Player player; Computer computer; void draw() { // cool border around the screen arduboy.drawRect(0, 0, WIDTH, HEIGHT, WHITE); // dotted line in the middle for (uint8_t i{ 2 }; i < HEIGHT; i += 8) { arduboy.drawFastVLine(WIDTH / 2, i, 4, WHITE); } // scores arduboy.setCursor(WIDTH/2 - 12, 2); arduboy.print(player.score); arduboy.setCursor(WIDTH/2 + 3, 2); arduboy.print(computer.score); // objects ball.draw(); player.draw(); computer.draw(); } void resetBall() { ball.x = WIDTH / 2; ball.y = HEIGHT / 2; ball.dx = 1; ball.dy = 1; } void menuTitle() { arduboy.setCursor(0, 0); arduboy.print(F("Press A to\nstart")); if (arduboy.pressed(A_BUTTON)) { gameTick = &gameSetup; } } void gameSetup() { arduboy.initRandomSeed(); resetBall(); player.x = 9; player.y = 24; // i thought of something funnier than 24... player.score = 0; computer.x = WIDTH - PADDLE_WIDTH - 9; computer.y = 25; // twenyfiiive! computer.score = 0; draw(); arduboy.display(); delay(1000); gameTick = &gameMain; } void gameMain() { draw(); // pause the game if needed if (arduboy.justPressed(A_BUTTON)) { gameTick = &gamePause; return; } ball.move(); // check if someone scored if (ball.x >= WIDTH - BALL_SIZE) { sound.tone(POINT_FREQ, POINT_DUR); if (++player.score >= SCORE_MAX) { gameTick = &menuWin; return; } else { resetBall(); } } else if (ball.x < 1) { sound.tone(POINT_FREQ, POINT_DUR); if (++computer.score >= SCORE_MAX) { gameTick = &menuLose; return; } else { resetBall(); } } ball.bounce(); player.move(); computer.move(); } void gamePause() { draw(); // resume the game if needed if (arduboy.justPressed(A_BUTTON)) { gameTick = &gameMain; } } void menuWin() { arduboy.setCursor(0, 0); arduboy.print(F("You win!\nPress A to\nrestart")); if (arduboy.pressed(A_BUTTON)) { gameTick = &gameSetup; } } void menuLose() { arduboy.setCursor(0, 0); arduboy.print(F("You lost!\nPress A to\nrestart")); if (arduboy.pressed(A_BUTTON)) { gameTick = &gameSetup; } } <commit_msg>Use justPressed for menu transitions<commit_after>#include "game.hpp" #define SCORE_MAX 3 // helper functions static void draw(); static void resetBall(); // game state functions static void menuTitle(); static void gameSetup(); static void gameMain(); static void gamePause(); static void menuWin(); static void menuLose(); void (*gameTick)(){ &menuTitle }; Ball ball; Player player; Computer computer; void draw() { // cool border around the screen arduboy.drawRect(0, 0, WIDTH, HEIGHT, WHITE); // dotted line in the middle for (uint8_t i{ 2 }; i < HEIGHT; i += 8) { arduboy.drawFastVLine(WIDTH / 2, i, 4, WHITE); } // scores arduboy.setCursor(WIDTH/2 - 12, 2); arduboy.print(player.score); arduboy.setCursor(WIDTH/2 + 3, 2); arduboy.print(computer.score); // objects ball.draw(); player.draw(); computer.draw(); } void resetBall() { ball.x = WIDTH / 2; ball.y = HEIGHT / 2; ball.dx = 1; ball.dy = 1; } void menuTitle() { arduboy.setCursor(0, 0); arduboy.print(F("Press A to\nstart")); if (arduboy.justPressed(A_BUTTON)) { gameTick = &gameSetup; } } void gameSetup() { arduboy.initRandomSeed(); resetBall(); player.x = 9; player.y = 24; // i thought of something funnier than 24... player.score = 0; computer.x = WIDTH - PADDLE_WIDTH - 9; computer.y = 25; // twenyfiiive! computer.score = 0; draw(); arduboy.display(); delay(1000); gameTick = &gameMain; } void gameMain() { draw(); // pause the game if needed if (arduboy.justPressed(A_BUTTON)) { gameTick = &gamePause; return; } ball.move(); // check if someone scored if (ball.x >= WIDTH - BALL_SIZE) { sound.tone(POINT_FREQ, POINT_DUR); if (++player.score >= SCORE_MAX) { gameTick = &menuWin; return; } else { resetBall(); } } else if (ball.x < 1) { sound.tone(POINT_FREQ, POINT_DUR); if (++computer.score >= SCORE_MAX) { gameTick = &menuLose; return; } else { resetBall(); } } ball.bounce(); player.move(); computer.move(); } void gamePause() { draw(); // resume the game if needed if (arduboy.justPressed(A_BUTTON)) { gameTick = &gameMain; } } void menuWin() { arduboy.setCursor(0, 0); arduboy.print(F("You win!\nPress A to\nrestart")); if (arduboy.justPressed(A_BUTTON)) { gameTick = &gameSetup; } } void menuLose() { arduboy.setCursor(0, 0); arduboy.print(F("You lost!\nPress A to\nrestart")); if (arduboy.justPressed(A_BUTTON)) { gameTick = &gameSetup; } } <|endoftext|>
<commit_before>#include "SolarPayload.h" #include "Payload.h" //using namespace theapi; namespace theapi { SolarPayload::SolarPayload() { setMsgType(); _payload.DeviceId = 0; _payload.MessageId = 0; _payload.Flags = 0; _payload.VCC = 0; _payload.ChargeMv = 0; _payload.ChargeMa = 0; _payload.Light = 0; _payload.CpuTemperature = 0; _payload.Temperature = 0; _payload.rssi = 0; _payload.snr = 0; _payload.frq_error = 0; } uint8_t SolarPayload::size() { return SIZE; } void SolarPayload::setMsgType() { _payload.MessageType = theapi::Payload::SOLAR; } uint8_t SolarPayload::getMsgType() { return _payload.MessageType; } uint16_t SolarPayload::getDeviceId() { return _payload.DeviceId; } void SolarPayload::setDeviceId(uint16_t val) { _payload.DeviceId = val; } // The id, not neccessarily unique, of the message. uint8_t SolarPayload::getMsgId() { return _payload.MessageId; } void SolarPayload::setMsgId(uint8_t id) { _payload.MessageId = id; } uint8_t SolarPayload::getFlags() { return _payload.Flags; } void SolarPayload::setFlags(uint8_t byte) { _payload.Flags = byte; } uint16_t SolarPayload::getVcc() { return _payload.VCC; } void SolarPayload::setVcc(uint16_t val) { _payload.VCC = val; } uint16_t SolarPayload::getChargeMv() { return _payload.ChargeMv; } void SolarPayload::setChargeMv(uint16_t val) { _payload.ChargeMv = val; } int16_t SolarPayload::getChargeMa() { return _payload.ChargeMa; } void SolarPayload::setChargeMa(int16_t val) { _payload.ChargeMa = val; } uint16_t SolarPayload::getLight() { return _payload.Light; } void SolarPayload::setLight(uint16_t val) { _payload.Light = val; } int16_t SolarPayload::getCpuTemperature() { return _payload.CpuTemperature; } void SolarPayload::setCpuTemperature(int16_t val) { _payload.CpuTemperature = val; } int16_t SolarPayload::getTemperature() { return _payload.Temperature; } void SolarPayload::setTemperature(int16_t val) { _payload.Temperature = val; } int16_t SignalPayload::getSnr() { return _payload.snr; } void SignalPayload::setSnr(int16_t val) { _payload.snr = val; } int16_t SignalPayload::getFreqError() { return _payload.frq_error; } // Populates the given buffer with the payload data. void SolarPayload::serialize(uint8_t buffer[SolarPayload::SIZE]) { buffer[0] = _payload.MessageType; buffer[1] = _payload.DeviceId; buffer[2] = _payload.MessageId; buffer[3] = _payload.Flags; buffer[4] = (_payload.VCC >> 8); buffer[5] = _payload.VCC; buffer[6] = (_payload.ChargeMv >> 8); buffer[7] = _payload.ChargeMv; buffer[8] = (_payload.ChargeMa >> 8); buffer[9] = _payload.ChargeMa; buffer[10] = (_payload.Light >> 8); buffer[11] = _payload.Light; buffer[12] = (_payload.CpuTemperature >> 8); buffer[13] = _payload.CpuTemperature; buffer[14] = (_payload.Temperature >> 8); buffer[15] = _payload.Temperature; } // Parse the byte data from the buffer. void SolarPayload::unserialize(uint8_t buffer[SolarPayload::SIZE]) { _payload.MessageType = buffer[0]; _payload.DeviceId = buffer[1]; _payload.MessageId = buffer[2]; _payload.Flags = buffer[3]; _payload.VCC = (buffer[4] << 8) | buffer[5]; _payload.ChargeMv = (buffer[6] << 8) | buffer[7]; _payload.ChargeMa = (buffer[8] << 8) | buffer[9]; _payload.Light = (buffer[10] << 8) | buffer[11]; _payload.CpuTemperature = (buffer[12] << 8) | buffer[13]; _payload.Temperature = (buffer[14] << 8) | buffer[15]; _payload.VCC = (buffer[4] << 8) | buffer[5]; } } <commit_msg>Data size<commit_after>#include "SolarPayload.h" #include "Payload.h" //using namespace theapi; namespace theapi { SolarPayload::SolarPayload() { setMsgType(); _payload.DeviceId = 0; _payload.MessageId = 0; _payload.Flags = 0; _payload.VCC = 0; _payload.ChargeMv = 0; _payload.ChargeMa = 0; _payload.Light = 0; _payload.CpuTemperature = 0; _payload.Temperature = 0; _payload.rssi = 0; _payload.snr = 0; _payload.frq_error = 0; } uint8_t SolarPayload::size() { return SIZE; } uint8_t SolarPayload::dataSize() { return DATA_SIZE; } void SolarPayload::setMsgType() { _payload.MessageType = theapi::Payload::SOLAR; } uint8_t SolarPayload::getMsgType() { return _payload.MessageType; } uint16_t SolarPayload::getDeviceId() { return _payload.DeviceId; } void SolarPayload::setDeviceId(uint16_t val) { _payload.DeviceId = val; } // The id, not neccessarily unique, of the message. uint8_t SolarPayload::getMsgId() { return _payload.MessageId; } void SolarPayload::setMsgId(uint8_t id) { _payload.MessageId = id; } uint8_t SolarPayload::getFlags() { return _payload.Flags; } void SolarPayload::setFlags(uint8_t byte) { _payload.Flags = byte; } uint16_t SolarPayload::getVcc() { return _payload.VCC; } void SolarPayload::setVcc(uint16_t val) { _payload.VCC = val; } uint16_t SolarPayload::getChargeMv() { return _payload.ChargeMv; } void SolarPayload::setChargeMv(uint16_t val) { _payload.ChargeMv = val; } int16_t SolarPayload::getChargeMa() { return _payload.ChargeMa; } void SolarPayload::setChargeMa(int16_t val) { _payload.ChargeMa = val; } uint16_t SolarPayload::getLight() { return _payload.Light; } void SolarPayload::setLight(uint16_t val) { _payload.Light = val; } int16_t SolarPayload::getCpuTemperature() { return _payload.CpuTemperature; } void SolarPayload::setCpuTemperature(int16_t val) { _payload.CpuTemperature = val; } int16_t SolarPayload::getTemperature() { return _payload.Temperature; } void SolarPayload::setTemperature(int16_t val) { _payload.Temperature = val; } int16_t SignalPayload::getSnr() { return _payload.snr; } void SignalPayload::setSnr(int16_t val) { _payload.snr = val; } int16_t SignalPayload::getFreqError() { return _payload.frq_error; } // Populates the given buffer with the payload data. void SolarPayload::serialize(uint8_t buffer[SolarPayload::SIZE]) { buffer[0] = _payload.MessageType; buffer[1] = _payload.DeviceId; buffer[2] = _payload.MessageId; buffer[3] = _payload.Flags; buffer[4] = (_payload.VCC >> 8); buffer[5] = _payload.VCC; buffer[6] = (_payload.ChargeMv >> 8); buffer[7] = _payload.ChargeMv; buffer[8] = (_payload.ChargeMa >> 8); buffer[9] = _payload.ChargeMa; buffer[10] = (_payload.Light >> 8); buffer[11] = _payload.Light; buffer[12] = (_payload.CpuTemperature >> 8); buffer[13] = _payload.CpuTemperature; buffer[14] = (_payload.Temperature >> 8); buffer[15] = _payload.Temperature; } // Parse the byte data from the buffer. void SolarPayload::unserialize(uint8_t buffer[SolarPayload::SIZE]) { _payload.MessageType = buffer[0]; _payload.DeviceId = buffer[1]; _payload.MessageId = buffer[2]; _payload.Flags = buffer[3]; _payload.VCC = (buffer[4] << 8) | buffer[5]; _payload.ChargeMv = (buffer[6] << 8) | buffer[7]; _payload.ChargeMa = (buffer[8] << 8) | buffer[9]; _payload.Light = (buffer[10] << 8) | buffer[11]; _payload.CpuTemperature = (buffer[12] << 8) | buffer[13]; _payload.Temperature = (buffer[14] << 8) | buffer[15]; _payload.VCC = (buffer[4] << 8) | buffer[5]; } } <|endoftext|>
<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <vector> #include <iostream> #include <exception> #include <iomanip> #include <random> #include <algorithm> #include <configuration.hpp> #include <ArgumentList.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Stencil.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize); int main(int argc, char * argv[]) { bool reInit = true; unsigned int nrIterations = 0; unsigned int samplingFactor = 100; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int vectorSize = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int matrixWidth = 0; unsigned int padding = 0; // Random number generation std::random_device randomDevice; std::default_random_engine randomEngine(randomDevice()); std::uniform_int_distribution<unsigned int> uniformDistribution(0, magicValue); try { isa::utils::ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); if ( args.getSwitch("-sampling") ) { samplingFactor = args.getSwitchArgument< unsigned int >("-factor"); } nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); vectorSize = args.getSwitchArgument< unsigned int >("-vector"); padding = args.getSwitchArgument< unsigned int >("-padding"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); matrixWidth = args.getSwitchArgument< unsigned int >("-matrix_width"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... [-sampling -factor ...] -iterations ... -vector ... -padding ... -max_threads ... -max_items ... -matrix_width ... [-local]" << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = 0; // Allocate host memory std::vector< inputDataType > input((matrixWidth + 2) * isa::utils::pad(matrixWidth + 2, padding)), output(matrixWidth * isa::utils::pad(matrixWidth, padding)), output_c; cl::Buffer input_d, output_d; for ( unsigned int y = 0; y < matrixWidth + 2; y++ ) { for ( unsigned int x = 0; x < matrixWidth + 2; x++ ) { if ( y == 0 || y == (matrixWidth - 1) ) { input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0; } else if ( x == 0 || x == (matrixWidth - 1) ) { input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0; } else { input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = uniformDistribution(randomEngine); } } } output_c.resize(output.size()); // Run the control TuneBench::stencil2D(input, output_c, matrixWidth, padding); // Generate tuning configurations std::vector<TuneBench::Stencil2DConf> configurations; for ( unsigned int threadsD0 = vectorSize; threadsD0 <= maxThreads; threadsD0 += vectorSize) { for ( unsigned int threadsD1 = 1; threadsD0 * threadsD1 <= maxThreads; threadsD1++ ) { for ( unsigned int itemsD0 = 1; itemsD0 <= maxItems; itemsD0++ ) { if ( matrixWidth % (threadsD0 * itemsD0) != 0 ) { continue; } for ( unsigned int itemsD1 = 1; itemsD0 * itemsD1 <= maxItems; itemsD1++ ) { if ( matrixWidth % (threadsD1 * itemsD1) != 0 ) { continue; } for ( unsigned int local = 0; local < 2; local++ ) { TuneBench::Stencil2DConf configuration; configuration.setLocalMemory(static_cast<bool>(local)); configuration.setNrThreadsD0(threadsD0); configuration.setNrThreadsD1(threadsD1); configuration.setNrItemsD0(itemsD0); configuration.setNrItemsD1(itemsD1); configurations.push_back(configuration); } } } } } if ( samplingFactor < 100 ) { unsigned int newSize = static_cast<unsigned int>((configurations.size() * samplingFactor) / 100.0); std::shuffle(configurations.begin(), configurations.end(), randomEngine); configurations.resize(newSize); } std::cout << std::fixed << std::endl; std::cout << "# matrixWidth *configuration* GFLOP/s time stdDeviation COV" << std::endl << std::endl; for ( auto configuration = configurations.begin(); configuration != configurations.end(); ++configuration ) { // Generate kernel double gflops = isa::utils::giga(static_cast< uint64_t >(matrixWidth) * matrixWidth * 18.0); cl::Event clEvent; cl::Kernel * kernel; isa::utils::Timer timer; std::string * code = TuneBench::getStencil2DOpenCL(*configuration, inputDataName, matrixWidth, padding); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector< cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d, output.size()); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("stencil2D", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global(matrixWidth / (configuration).getNrItemsD0(), matrixWidth / (*configuration).getNrItemsD1()); cl::NDRange local((*configuration).getNrThreadsD0(), (*configuration).getNrThreadsD1()); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); timer.stop(); } clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent); clEvent.wait(); } catch ( cl::Error & err ) { reInit = true; std::cerr << "OpenCL kernel execution error ("; std::cerr << (*configuration).print(); std::cerr << "): "; std::cerr << isa::utils::toString(err.err()) << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } break; } delete kernel; bool error = false; for ( unsigned int y = 0; y < matrixWidth; y++ ) { for ( unsigned int x = 0; x < matrixWidth; x++ ) { if ( !isa::utils::same(output[(y * isa::utils::pad(matrixWidth, padding)) + x], output_c[(y * isa::utils::pad(matrixWidth, padding)) + x]) ) { std::cerr << "Output error (" << (*configuration).print() << ")." << std::endl; error = true; break; } } if ( error ) { break; } } if ( error ) { continue; } std::cout << matrixWidth << " "; std::cout << (*configuration).print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl; } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, outputSize * sizeof(inputDataType), 0, 0); clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <commit_msg>Typo.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <vector> #include <iostream> #include <exception> #include <iomanip> #include <random> #include <algorithm> #include <configuration.hpp> #include <ArgumentList.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Stencil.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize); int main(int argc, char * argv[]) { bool reInit = true; unsigned int nrIterations = 0; unsigned int samplingFactor = 100; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int vectorSize = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int matrixWidth = 0; unsigned int padding = 0; // Random number generation std::random_device randomDevice; std::default_random_engine randomEngine(randomDevice()); std::uniform_int_distribution<unsigned int> uniformDistribution(0, magicValue); try { isa::utils::ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); if ( args.getSwitch("-sampling") ) { samplingFactor = args.getSwitchArgument< unsigned int >("-factor"); } nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); vectorSize = args.getSwitchArgument< unsigned int >("-vector"); padding = args.getSwitchArgument< unsigned int >("-padding"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); matrixWidth = args.getSwitchArgument< unsigned int >("-matrix_width"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... [-sampling -factor ...] -iterations ... -vector ... -padding ... -max_threads ... -max_items ... -matrix_width ... [-local]" << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = 0; // Allocate host memory std::vector< inputDataType > input((matrixWidth + 2) * isa::utils::pad(matrixWidth + 2, padding)), output(matrixWidth * isa::utils::pad(matrixWidth, padding)), output_c; cl::Buffer input_d, output_d; for ( unsigned int y = 0; y < matrixWidth + 2; y++ ) { for ( unsigned int x = 0; x < matrixWidth + 2; x++ ) { if ( y == 0 || y == (matrixWidth - 1) ) { input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0; } else if ( x == 0 || x == (matrixWidth - 1) ) { input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0; } else { input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = uniformDistribution(randomEngine); } } } output_c.resize(output.size()); // Run the control TuneBench::stencil2D(input, output_c, matrixWidth, padding); // Generate tuning configurations std::vector<TuneBench::Stencil2DConf> configurations; for ( unsigned int threadsD0 = vectorSize; threadsD0 <= maxThreads; threadsD0 += vectorSize) { for ( unsigned int threadsD1 = 1; threadsD0 * threadsD1 <= maxThreads; threadsD1++ ) { for ( unsigned int itemsD0 = 1; itemsD0 <= maxItems; itemsD0++ ) { if ( matrixWidth % (threadsD0 * itemsD0) != 0 ) { continue; } for ( unsigned int itemsD1 = 1; itemsD0 * itemsD1 <= maxItems; itemsD1++ ) { if ( matrixWidth % (threadsD1 * itemsD1) != 0 ) { continue; } for ( unsigned int local = 0; local < 2; local++ ) { TuneBench::Stencil2DConf configuration; configuration.setLocalMemory(static_cast<bool>(local)); configuration.setNrThreadsD0(threadsD0); configuration.setNrThreadsD1(threadsD1); configuration.setNrItemsD0(itemsD0); configuration.setNrItemsD1(itemsD1); configurations.push_back(configuration); } } } } } if ( samplingFactor < 100 ) { unsigned int newSize = static_cast<unsigned int>((configurations.size() * samplingFactor) / 100.0); std::shuffle(configurations.begin(), configurations.end(), randomEngine); configurations.resize(newSize); } std::cout << std::fixed << std::endl; std::cout << "# matrixWidth *configuration* GFLOP/s time stdDeviation COV" << std::endl << std::endl; for ( auto configuration = configurations.begin(); configuration != configurations.end(); ++configuration ) { // Generate kernel double gflops = isa::utils::giga(static_cast< uint64_t >(matrixWidth) * matrixWidth * 18.0); cl::Event clEvent; cl::Kernel * kernel; isa::utils::Timer timer; std::string * code = TuneBench::getStencil2DOpenCL(*configuration, inputDataName, matrixWidth, padding); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector< cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d, output.size()); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("stencil2D", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global(matrixWidth / (*configuration).getNrItemsD0(), matrixWidth / (*configuration).getNrItemsD1()); cl::NDRange local((*configuration).getNrThreadsD0(), (*configuration).getNrThreadsD1()); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); timer.stop(); } clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent); clEvent.wait(); } catch ( cl::Error & err ) { reInit = true; std::cerr << "OpenCL kernel execution error ("; std::cerr << (*configuration).print(); std::cerr << "): "; std::cerr << isa::utils::toString(err.err()) << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } break; } delete kernel; bool error = false; for ( unsigned int y = 0; y < matrixWidth; y++ ) { for ( unsigned int x = 0; x < matrixWidth; x++ ) { if ( !isa::utils::same(output[(y * isa::utils::pad(matrixWidth, padding)) + x], output_c[(y * isa::utils::pad(matrixWidth, padding)) + x]) ) { std::cerr << "Output error (" << (*configuration).print() << ")." << std::endl; error = true; break; } } if ( error ) { break; } } if ( error ) { continue; } std::cout << matrixWidth << " "; std::cout << (*configuration).print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl; } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, outputSize * sizeof(inputDataType), 0, 0); clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <|endoftext|>
<commit_before>/* kv */ static int proc_get(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ std::string val; int ret = serv->ssdb->get(req[1], &val); if(ret == 1){ resp->push_back("ok"); resp->push_back(val); }else if(ret == 0){ resp->push_back("not_found"); }else{ log_error("fail"); resp->push_back("fail"); } } return 0; } static int proc_set(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 3){ resp->push_back("client_error"); }else{ int ret = serv->ssdb->set(req[1], req[2]); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); resp->push_back("1"); } } return 0; } static int proc_setx(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 4){ resp->push_back("client_error"); return 0; } int ret; ret = serv->ssdb->set(req[1], req[2]); if(ret == -1){ resp->push_back("error"); return 0; } ret = serv->expiration->set_ttl(req[1], req[3].Int()); if(ret == -1){ resp->push_back("error"); return 0; } resp->push_back("ok"); return 0; } static int proc_exists(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ const Bytes key = req[1]; std::string val; int ret = serv->ssdb->get(key, &val); if(ret == 1){ resp->push_back("ok"); resp->push_back("1"); }else if(ret == 0){ resp->push_back("ok"); resp->push_back("0"); }else{ resp->push_back("error"); resp->push_back("0"); } } return 0; } static int proc_multi_exists(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ resp->push_back("ok"); for(Request::const_iterator it=req.begin()+1; it!=req.end(); it++){ const Bytes key = *it; std::string val; int ret = serv->ssdb->get(key, &val); resp->push_back(key.String()); if(ret == 1){ resp->push_back("1"); }else if(ret == 0){ resp->push_back("0"); }else{ resp->push_back("0"); } } } return 0; } static int proc_multi_set(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 3 || req.size() % 2 != 1){ resp->push_back("client_error"); }else{ int ret = serv->ssdb->multi_set(req, 1); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); char buf[20]; sprintf(buf, "%d", ret); resp->push_back(buf); } } return 0; } static int proc_multi_del(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ int ret = serv->ssdb->multi_del(req, 1); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); char buf[20]; sprintf(buf, "%d", ret); resp->push_back(buf); } } return 0; } static int proc_multi_get(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ resp->push_back("ok"); for(int i=1; i<req.size(); i++){ std::string val; int ret = serv->ssdb->get(req[i], &val); if(ret == 1){ resp->push_back(req[i].String()); resp->push_back(val); }else if(ret == 0){ // }else{ // error log_error("fail"); } } } return 0; } static int proc_del(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ int ret = serv->ssdb->del(req[1]); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); resp->push_back("1"); } } return 0; } static int proc_scan(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 4){ resp->push_back("client_error"); }else{ uint64_t limit = req[3].Uint64(); KIterator *it = serv->ssdb->scan(req[1], req[2], limit); resp->push_back("ok"); while(it->next()){ resp->push_back(it->key); resp->push_back(it->val); } delete it; } return 0; } static int proc_rscan(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 4){ resp->push_back("client_error"); }else{ uint64_t limit = req[3].Uint64(); KIterator *it = serv->ssdb->rscan(req[1], req[2], limit); resp->push_back("ok"); while(it->next()){ resp->push_back(it->key); resp->push_back(it->val); } delete it; } return 0; } static int proc_keys(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 4){ resp->push_back("client_error"); }else{ uint64_t limit = req[3].Uint64(); KIterator *it = serv->ssdb->scan(req[1], req[2], limit); it->return_val(false); resp->push_back("ok"); while(it->next()){ resp->push_back(it->key); } delete it; } return 0; } // dir := +1|-1 static int _incr(SSDB *ssdb, const Request &req, Response *resp, int dir){ if(req.size() <= 1){ resp->push_back("client_error"); }else{ std::string new_val; int64_t val = 1; if(req.size() > 2){ val = req[2].Int64(); } int ret = ssdb->incr(req[1], dir * val, &new_val); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); resp->push_back(new_val); } } return 0; } static int proc_incr(Server *serv, Link *link, const Request &req, Response *resp){ return _incr(serv->ssdb, req, resp, 1); } static int proc_decr(Server *serv, Link *link, const Request &req, Response *resp){ return _incr(serv->ssdb, req, resp, -1); } <commit_msg>setx returns ok 1<commit_after>/* kv */ static int proc_get(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ std::string val; int ret = serv->ssdb->get(req[1], &val); if(ret == 1){ resp->push_back("ok"); resp->push_back(val); }else if(ret == 0){ resp->push_back("not_found"); }else{ log_error("fail"); resp->push_back("fail"); } } return 0; } static int proc_set(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 3){ resp->push_back("client_error"); }else{ int ret = serv->ssdb->set(req[1], req[2]); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); resp->push_back("1"); } } return 0; } static int proc_setx(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 4){ resp->push_back("client_error"); return 0; } int ret; ret = serv->ssdb->set(req[1], req[2]); if(ret == -1){ resp->push_back("error"); return 0; } ret = serv->expiration->set_ttl(req[1], req[3].Int()); if(ret == -1){ resp->push_back("error"); return 0; } resp->push_back("ok"); resp->push_back("1"); return 0; } static int proc_exists(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ const Bytes key = req[1]; std::string val; int ret = serv->ssdb->get(key, &val); if(ret == 1){ resp->push_back("ok"); resp->push_back("1"); }else if(ret == 0){ resp->push_back("ok"); resp->push_back("0"); }else{ resp->push_back("error"); resp->push_back("0"); } } return 0; } static int proc_multi_exists(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ resp->push_back("ok"); for(Request::const_iterator it=req.begin()+1; it!=req.end(); it++){ const Bytes key = *it; std::string val; int ret = serv->ssdb->get(key, &val); resp->push_back(key.String()); if(ret == 1){ resp->push_back("1"); }else if(ret == 0){ resp->push_back("0"); }else{ resp->push_back("0"); } } } return 0; } static int proc_multi_set(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 3 || req.size() % 2 != 1){ resp->push_back("client_error"); }else{ int ret = serv->ssdb->multi_set(req, 1); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); char buf[20]; sprintf(buf, "%d", ret); resp->push_back(buf); } } return 0; } static int proc_multi_del(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ int ret = serv->ssdb->multi_del(req, 1); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); char buf[20]; sprintf(buf, "%d", ret); resp->push_back(buf); } } return 0; } static int proc_multi_get(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ resp->push_back("ok"); for(int i=1; i<req.size(); i++){ std::string val; int ret = serv->ssdb->get(req[i], &val); if(ret == 1){ resp->push_back(req[i].String()); resp->push_back(val); }else if(ret == 0){ // }else{ // error log_error("fail"); } } } return 0; } static int proc_del(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 2){ resp->push_back("client_error"); }else{ int ret = serv->ssdb->del(req[1]); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); resp->push_back("1"); } } return 0; } static int proc_scan(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 4){ resp->push_back("client_error"); }else{ uint64_t limit = req[3].Uint64(); KIterator *it = serv->ssdb->scan(req[1], req[2], limit); resp->push_back("ok"); while(it->next()){ resp->push_back(it->key); resp->push_back(it->val); } delete it; } return 0; } static int proc_rscan(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 4){ resp->push_back("client_error"); }else{ uint64_t limit = req[3].Uint64(); KIterator *it = serv->ssdb->rscan(req[1], req[2], limit); resp->push_back("ok"); while(it->next()){ resp->push_back(it->key); resp->push_back(it->val); } delete it; } return 0; } static int proc_keys(Server *serv, Link *link, const Request &req, Response *resp){ if(req.size() < 4){ resp->push_back("client_error"); }else{ uint64_t limit = req[3].Uint64(); KIterator *it = serv->ssdb->scan(req[1], req[2], limit); it->return_val(false); resp->push_back("ok"); while(it->next()){ resp->push_back(it->key); } delete it; } return 0; } // dir := +1|-1 static int _incr(SSDB *ssdb, const Request &req, Response *resp, int dir){ if(req.size() <= 1){ resp->push_back("client_error"); }else{ std::string new_val; int64_t val = 1; if(req.size() > 2){ val = req[2].Int64(); } int ret = ssdb->incr(req[1], dir * val, &new_val); if(ret == -1){ resp->push_back("error"); }else{ resp->push_back("ok"); resp->push_back(new_val); } } return 0; } static int proc_incr(Server *serv, Link *link, const Request &req, Response *resp){ return _incr(serv->ssdb, req, resp, 1); } static int proc_decr(Server *serv, Link *link, const Request &req, Response *resp){ return _incr(serv->ssdb, req, resp, -1); } <|endoftext|>
<commit_before>#include "magic.h" using namespace cv; Point point1, point2; /* vertical points of the bounding box */ bool drag = false; bool select_flag = false; Rect rect; /* bounding box */ Mat img, roiImg; /* roiImg - the part of the image in the bounding box */ void mouseHandler(int event, int x, int y, int flags, void* param){ if (event == CV_EVENT_LBUTTONDOWN && !drag){ /* left button clicked. ROI selection begins */ point1 = Point(x, y); drag = true; } if (event == CV_EVENT_MOUSEMOVE && drag){ /* mouse dragged. ROI being selected */ Mat img1 = img.clone(); point2 = Point(x, y); rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 3, 8, 0); imshow("image", img1); } if (event == CV_EVENT_LBUTTONUP && drag){ point2 = Point(x, y); rect = Rect(point1.x,point1.y,x-point1.x,y-point1.y); drag = false; roiImg = img(rect); } if (event == CV_EVENT_LBUTTONUP){ /* ROI selected */ select_flag = true; drag = false; } } int main(int argc, char* argv[]){ if(argc < 2){ printf("usage: Magic <Video_Path> [output_dir] [skip_frames] [background]\n"); } std::string output; if(argc >= 3) { output = argv[2]; } else { output = "."; } int skip_frames = 0; if(argc >= 4) { skip_frames = std::atoi(argv[3]); } VideoCapture cap(argv[1]); // load the video if(!cap.isOpened()) // check if we succeeded return -1; // Write some info about File int frames = cap.get(CV_CAP_PROP_FRAME_COUNT); double fps = cap.get(CV_CAP_PROP_FPS); printf("Number of Frames: %d\n", frames); printf("FPS: %f\n", fps); // Contains the working image Mat dst, in, temp; if(argc >= 5) { in = imread(argv[4]); } else { cap >> in; } img = in.clone(); imshow("image", img); int k; while(1){ cvSetMouseCallback("image", mouseHandler, NULL); if (select_flag){ imshow("ROI", roiImg); //show the image bounded by the box } rectangle(img, rect, CV_RGB(255, 0, 0), 3, 8, 0); imshow("image", img); k = waitKey(10); // if(k != -1) { // printf("Key pressed %d\n", k); // } if (k == 27){ //ESC destroyAllWindows(); waitKey(1); break; } } if(!select_flag){ rect = Rect(0,0,img.cols, img.rows); } // Background temp = in(rect); Mat background; cvtColor(temp, background, CV_RGB2GRAY); vector<Vec3f> circles; /// Apply the Hough Transform to find the circles HoughCircles(background, circles, CV_HOUGH_GRADIENT, 1, 100, 200, 100, 0, 0); /// Draw the circles detected for( size_t i = 0; i < circles.size(); i++ ) { Point2f center(circles[i][0], circles[i][1]); float radius = circles[i][2]; // circle center circle(temp, center, 3, Scalar(0,255,0), -1, 8, 0 ); // circle outline circle(temp, center, radius, Scalar(0,0,255), 3, 8, 0 ); printf("Circle %d with r=%f at x=%f, y=%f\n", i, radius, center.x, center.y); } imshow("image", temp); waitKey(0); destroyWindow("image"); waitKey(1); //Set image parameter vector<int> imageout_params; imwrite(output + "/bg_circle.tiff", temp, imageout_params); imwrite(output + "/bg.tiff", background, imageout_params); std::vector<Point2i> points; Point2f center; float radius; std::ofstream fs (output + "/positions.csv", std::ofstream::out); fs << "Frame,Time,Radius,x,y\n"; for(int i = 0; i <= frames-1;i++){ cap >> in; if(i > skip_frames) { temp = in(rect); cvtColor(temp, dst, CV_RGB2GRAY, 0); absdiff(dst, background, temp); threshold(temp, dst, 30, 255, THRESH_BINARY); points.clear(); // if there is no non zero point this throws an exception. findNonZero(dst, points); minEnclosingCircle(points, center, radius); fs << i <<","<< i/fps <<","<< radius <<","<< center.x <<","<< center.y << "\n"; std::cout << "\r" << i << "/" << frames; // imwrite(output + "/test-"+ std::to_string(i)+".tiff", dst, imageout_params); } } fs << std::endl; fs.close(); }<commit_msg>add safeguards<commit_after>#include "magic.h" using namespace cv; Point point1, point2; /* vertical points of the bounding box */ bool drag = false; bool select_flag = false; Rect rect; /* bounding box */ Mat img, roiImg; /* roiImg - the part of the image in the bounding box */ void mouseHandler(int event, int x, int y, int flags, void* param){ if (event == CV_EVENT_LBUTTONDOWN && !drag){ /* left button clicked. ROI selection begins */ point1 = Point(x, y); drag = true; } if (event == CV_EVENT_MOUSEMOVE && drag){ /* mouse dragged. ROI being selected */ Mat img1 = img.clone(); point2 = Point(x, y); rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 3, 8, 0); imshow("image", img1); } if (event == CV_EVENT_LBUTTONUP && drag){ point2 = Point(x, y); rect = Rect(point1.x,point1.y,x-point1.x,y-point1.y); drag = false; roiImg = img(rect); } if (event == CV_EVENT_LBUTTONUP){ /* ROI selected */ select_flag = true; drag = false; } } int main(int argc, char* argv[]){ if(argc < 2){ printf("usage: Magic <Video_Path> [output_dir] [skip_frames] [background]\n"); } std::string output; if(argc >= 3) { output = argv[2]; } else { output = "."; } int skip_frames = 0; if(argc >= 4) { skip_frames = std::atoi(argv[3]); } VideoCapture cap(argv[1]); // load the video if(!cap.isOpened()) // check if we succeeded return -1; // Write some info about File int frames = cap.get(CV_CAP_PROP_FRAME_COUNT); double fps = cap.get(CV_CAP_PROP_FPS); printf("Number of Frames: %d\n", frames); printf("FPS: %f\n", fps); // Contains the working image Mat dst, in, temp; if(argc >= 5) { in = imread(argv[4]); } else { cap >> in; } img = in.clone(); imshow("image", img); int k; while(1){ cvSetMouseCallback("image", mouseHandler, NULL); if (select_flag){ imshow("ROI", roiImg); //show the image bounded by the box } rectangle(img, rect, CV_RGB(255, 0, 0), 3, 8, 0); imshow("image", img); k = waitKey(10); // if(k != -1) { // printf("Key pressed %d\n", k); // } if (k == 27){ //ESC destroyAllWindows(); waitKey(1); break; } } if(!select_flag){ rect = Rect(0,0,img.cols, img.rows); } // Background temp = in(rect); Mat background; cvtColor(temp, background, CV_RGB2GRAY); vector<Vec3f> circles; /// Apply the Hough Transform to find the circles HoughCircles(background, circles, CV_HOUGH_GRADIENT, 1, 300, 200, 100, 0, 0); /// Draw the circles detected for( size_t i = 0; i < circles.size(); i++ ) { Point2f center(circles[i][0], circles[i][1]); float radius = circles[i][2]; // circle center circle(temp, center, 3, Scalar(0,255,0), -1, 8, 0 ); // circle outline circle(temp, center, radius, Scalar(0,0,255), 3, 8, 0 ); printf("Circle %d with r=%f at x=%f, y=%f\n", i, radius, center.x, center.y); } imshow("image", temp); waitKey(0); destroyWindow("image"); waitKey(1); //Set image parameter vector<int> imageout_params; imwrite(output + "/bg_circle.tiff", temp, imageout_params); imwrite(output + "/bg.tiff", background, imageout_params); std::vector<Point2i> points; Point2f center; float radius; std::ofstream fs (output + "/positions.csv", std::ofstream::out); fs << "Frame,Time,Radius,x,y\n"; for(int i = 0; i <= frames-1;i++){ cap >> in; if(i > skip_frames) { temp = in(rect); cvtColor(temp, dst, CV_RGB2GRAY, 0); absdiff(dst, background, temp); threshold(temp, dst, 30, 255, THRESH_BINARY); points.clear(); if(countNonZero(dst) > 0) { findNonZero(dst, points); minEnclosingCircle(points, center, radius); fs << i <<","<< i/fps <<","<< radius <<","<< center.x <<","<< center.y << "\n"; } std::cout << "\r" << i << "/" << frames; // imwrite(output + "/test-"+ std::to_string(i)+".tiff", dst, imageout_params); } } fs << std::endl; fs.close(); }<|endoftext|>
<commit_before>/* * cgtprelay.cpp * * Created on: 21.08.2014 * Author: andreas */ #include "cgtprelay.hpp" #include "cgtpcore.hpp" using namespace rofgtp; /*static*/std::map<rofl::cdpid, cgtprelay*> cgtprelay::gtprelays; void cgtprelay::handle_read( rofl::csocket& socket) { unsigned int pkts_rcvd_in_round = 0; rofl::cmemory *mem = new rofl::cmemory(1518); try { rofcore::logging::debug << "[cgtprelay][handle_read] " << std::endl; int flags = 0; rofl::csockaddr from; int rc = socket.recv(mem->somem(), mem->memlen(), flags, from); mem->resize(rc); rofl::fgtpuframe gtpu(mem->somem(), mem->memlen()); switch (from.get_family()) { case AF_INET: try { // create label-in for received GTP message rofgtp::caddress_gtp_in4 gtp_src_addr( rofl::caddress_in4(from.ca_s4addr, sizeof(struct sockaddr_in)), rofgtp::cport(from.ca_s4addr, sizeof(struct sockaddr_in))); rofgtp::caddress_gtp_in4 gtp_dst_addr( rofl::caddress_in4(socket.get_laddr().ca_s4addr, sizeof(struct sockaddr_in)), rofgtp::cport(socket.get_laddr().ca_s4addr, sizeof(struct sockaddr_in))); rofgtp::clabel_in4 label_in(gtp_src_addr, gtp_dst_addr, rofgtp::cteid(gtpu.get_teid())); rofcore::logging::debug << "[cgtprelay][handle_read] label-in: " << std::endl << label_in; // find associated label-out for label-in const rofgtp::clabel_in4& label_out = cgtpcore::get_gtp_core(dpid). get_relay_in4(label_in).get_label_out(); rofcore::logging::debug << "[cgtprelay][handle_read] label-out: " << std::endl << label_out; // set TEID for outgoing packet gtpu.set_teid(label_out.get_teid().get_value()); // forward GTP message set_socket(label_out.get_saddr()).send(mem, rofl::csockaddr(label_out.get_daddr().get_addr(), label_out.get_daddr().get_port().get_value())); // set OFP shortcut into datapath cgtpcore::set_gtp_core(dpid).set_relay_in4(label_in).handle_dpt_open(rofl::crofdpt::get_dpt(dpid)); } catch (eGtpCoreNotFound& e) { } catch (eRelayNotFound& e) { } break; case AF_INET6: try { // create label-in for received GTP message rofgtp::caddress_gtp_in6 gtp_src_addr( rofl::caddress_in6(from.ca_s6addr, sizeof(struct sockaddr_in6)), rofgtp::cport(from.ca_s6addr, sizeof(struct sockaddr_in6))); rofgtp::caddress_gtp_in6 gtp_dst_addr( rofl::caddress_in6(socket.get_laddr().ca_s6addr, sizeof(struct sockaddr_in6)), rofgtp::cport(socket.get_laddr().ca_s6addr, sizeof(struct sockaddr_in6))); rofgtp::clabel_in6 label_in(gtp_src_addr, gtp_dst_addr, rofgtp::cteid(gtpu.get_teid())); rofcore::logging::debug << "[cgtprelay][handle_read] label-in: " << std::endl << label_in; // find associated label-out for label-in const rofgtp::clabel_in6& label_out = cgtpcore::get_gtp_core(dpid). get_relay_in6(label_in).get_label_out(); rofcore::logging::debug << "[cgtprelay][handle_read] label-out: " << std::endl << label_out; // set TEID for outgoing packet gtpu.set_teid(label_out.get_teid().get_value()); // forward GTP message set_socket(label_out.get_saddr()).send(mem, rofl::csockaddr(label_out.get_daddr().get_addr(), label_out.get_daddr().get_port().get_value())); // set OFP shortcut into datapath cgtpcore::set_gtp_core(dpid).set_relay_in6(label_in).handle_dpt_open(rofl::crofdpt::get_dpt(dpid)); } catch (eGtpCoreNotFound& e) { } catch (eRelayNotFound& e) { } break; default: { }; } } catch (rofl::eSocketRxAgain& e) { rofcore::logging::debug << "[cgtprelay][handle_read] eSocketRxAgain: no further data available on socket" << std::endl; delete mem; } catch (rofl::eSysCall& e) { rofcore::logging::warn << "[cgtprelay][handle_read] failed to read from socket: " << e << std::endl; delete mem; } catch (rofl::RoflException& e) { rofcore::logging::warn << "[cgtprelay][handle_read] dropping invalid message: " << e << std::endl; delete mem; } } <commit_msg>cgtprelay => added debug output for caught exceptions in method handle_read()<commit_after>/* * cgtprelay.cpp * * Created on: 21.08.2014 * Author: andreas */ #include "cgtprelay.hpp" #include "cgtpcore.hpp" using namespace rofgtp; /*static*/std::map<rofl::cdpid, cgtprelay*> cgtprelay::gtprelays; void cgtprelay::handle_read( rofl::csocket& socket) { unsigned int pkts_rcvd_in_round = 0; rofl::cmemory *mem = new rofl::cmemory(1518); try { rofcore::logging::debug << "[cgtprelay][handle_read] " << std::endl; int flags = 0; rofl::csockaddr from; int rc = socket.recv(mem->somem(), mem->memlen(), flags, from); mem->resize(rc); rofl::fgtpuframe gtpu(mem->somem(), mem->memlen()); switch (from.get_family()) { case AF_INET: try { // create label-in for received GTP message rofgtp::caddress_gtp_in4 gtp_src_addr( rofl::caddress_in4(from.ca_s4addr, sizeof(struct sockaddr_in)), rofgtp::cport(from.ca_s4addr, sizeof(struct sockaddr_in))); rofgtp::caddress_gtp_in4 gtp_dst_addr( rofl::caddress_in4(socket.get_laddr().ca_s4addr, sizeof(struct sockaddr_in)), rofgtp::cport(socket.get_laddr().ca_s4addr, sizeof(struct sockaddr_in))); rofgtp::clabel_in4 label_in(gtp_src_addr, gtp_dst_addr, rofgtp::cteid(gtpu.get_teid())); rofcore::logging::debug << "[cgtprelay][handle_read] label-in: " << std::endl << label_in; // find associated label-out for label-in const rofgtp::clabel_in4& label_out = cgtpcore::get_gtp_core(dpid). get_relay_in4(label_in).get_label_out(); rofcore::logging::debug << "[cgtprelay][handle_read] label-out: " << std::endl << label_out; // set TEID for outgoing packet gtpu.set_teid(label_out.get_teid().get_value()); // forward GTP message set_socket(label_out.get_saddr()).send(mem, rofl::csockaddr(label_out.get_daddr().get_addr(), label_out.get_daddr().get_port().get_value())); // set OFP shortcut into datapath cgtpcore::set_gtp_core(dpid).set_relay_in4(label_in).handle_dpt_open(rofl::crofdpt::get_dpt(dpid)); } catch (eGtpCoreNotFound& e) { rofcore::logging::debug << "[cgtprelay][handle_read] gtpcore not found" << std::endl; } catch (eRelayNotFound& e) { rofcore::logging::debug << "[cgtprelay][handle_read] relay_in4 not found" << std::endl; } break; case AF_INET6: try { // create label-in for received GTP message rofgtp::caddress_gtp_in6 gtp_src_addr( rofl::caddress_in6(from.ca_s6addr, sizeof(struct sockaddr_in6)), rofgtp::cport(from.ca_s6addr, sizeof(struct sockaddr_in6))); rofgtp::caddress_gtp_in6 gtp_dst_addr( rofl::caddress_in6(socket.get_laddr().ca_s6addr, sizeof(struct sockaddr_in6)), rofgtp::cport(socket.get_laddr().ca_s6addr, sizeof(struct sockaddr_in6))); rofgtp::clabel_in6 label_in(gtp_src_addr, gtp_dst_addr, rofgtp::cteid(gtpu.get_teid())); rofcore::logging::debug << "[cgtprelay][handle_read] label-in: " << std::endl << label_in; // find associated label-out for label-in const rofgtp::clabel_in6& label_out = cgtpcore::get_gtp_core(dpid). get_relay_in6(label_in).get_label_out(); rofcore::logging::debug << "[cgtprelay][handle_read] label-out: " << std::endl << label_out; // set TEID for outgoing packet gtpu.set_teid(label_out.get_teid().get_value()); // forward GTP message set_socket(label_out.get_saddr()).send(mem, rofl::csockaddr(label_out.get_daddr().get_addr(), label_out.get_daddr().get_port().get_value())); // set OFP shortcut into datapath cgtpcore::set_gtp_core(dpid).set_relay_in6(label_in).handle_dpt_open(rofl::crofdpt::get_dpt(dpid)); } catch (eGtpCoreNotFound& e) { rofcore::logging::debug << "[cgtprelay][handle_read] gtpcore not found" << std::endl; } catch (eRelayNotFound& e) { rofcore::logging::debug << "[cgtprelay][handle_read] relay_in6 not found" << std::endl; } break; default: { }; } } catch (rofl::eSocketRxAgain& e) { rofcore::logging::debug << "[cgtprelay][handle_read] eSocketRxAgain: no further data available on socket" << std::endl; delete mem; } catch (rofl::eSysCall& e) { rofcore::logging::warn << "[cgtprelay][handle_read] failed to read from socket: " << e << std::endl; delete mem; } catch (rofl::RoflException& e) { rofcore::logging::warn << "[cgtprelay][handle_read] dropping invalid message: " << e << std::endl; delete mem; } } <|endoftext|>
<commit_before>#include "process.h" #include <stdexcept> #include <cerrno> #include <cstring> #include <unistd.h> #include <sys/wait.h> #include "unidirectional_pipe.h" string Process::binary_path_only(const string &argv0, const string &this_program_name) { if (argv0.length() > this_program_name.length() && argv0[argv0.length() - this_program_name.length() - 1] == '/' && argv0.substr(argv0.length() - this_program_name.length(), this_program_name.length()) == this_program_name) { return argv0.substr(0, argv0.length() - this_program_name.length()); } else { return ""; } } pid_t Process::fork_and_exec(const string &binary, const char *args[]) { pid_t child = fork(); if (child < 0) { // hit the process limit throw runtime_error("Couldn't fork to start binary: " + string(strerror(errno))); } else if (child == 0) { // we are the child; run the binary if (execvp(binary.c_str(), (char * const *)args) < 0) { throw runtime_error("Couldn't exec " + binary + ": " + string(strerror(errno))); } throw logic_error("execv returned"); } else { return child; } } pid_t Process::fork_and_exec(const string &binary, const char *args[], UnidirectionalPipe &stdin_pipe, UnidirectionalPipe &stdout_pipe) { pid_t child = fork(); if (child < 0) { // hit the process limit throw runtime_error("Couldn't fork to start binary: " + string(strerror(errno))); } else if (child == 0) { // we are the child; close the ends of the pipe that we won't use (as otherwise we'd not see the pipes close when the other end is done) stdin_pipe.close_write(); stdout_pipe.close_read(); // attach our stdin stdin_pipe.dup_read_to(STDIN_FILENO); stdin_pipe.close_read(); // attach our stdout stdout_pipe.dup_write_to(STDOUT_FILENO); stdout_pipe.close_write(); // run the binary if (execvp(binary.c_str(), (char * const *)args) < 0) { throw runtime_error("Couldn't exec " + binary + ": " + string(strerror(errno))); } throw logic_error("execv returned"); } else { return child; } } bool Process::wait_for_and_check(pid_t child) { int status; while (true) { if (waitpid(child, &status, 0) < 0) { throw runtime_error("Couldn't wait for child: " + string(strerror(errno))); } return WIFEXITED(status) && WEXITSTATUS(status) == 0; } } <commit_msg>more detailed message if the execvp fails with a 'No such file or directory' error (#46)<commit_after>#include "process.h" #include <stdexcept> #include <cerrno> #include <cstring> #include <unistd.h> #include <sys/wait.h> #include "unidirectional_pipe.h" string Process::binary_path_only(const string &argv0, const string &this_program_name) { if (argv0.length() > this_program_name.length() && argv0[argv0.length() - this_program_name.length() - 1] == '/' && argv0.substr(argv0.length() - this_program_name.length(), this_program_name.length()) == this_program_name) { return argv0.substr(0, argv0.length() - this_program_name.length()); } else { return ""; } } string describe_error(const string &binary, int err) { string suffix; if (err == ENOENT) suffix = ". This usually means Kitchen Sync was not compiled with support for that database."; return "Couldn't exec " + binary + ": " + string(strerror(err)) + suffix; } pid_t Process::fork_and_exec(const string &binary, const char *args[]) { pid_t child = fork(); if (child < 0) { // hit the process limit throw runtime_error("Couldn't fork to start binary: " + string(strerror(errno))); } else if (child == 0) { // we are the child; run the binary if (execvp(binary.c_str(), (char * const *)args) < 0) { throw runtime_error(describe_error(binary, errno)); } throw logic_error("execv returned"); } else { return child; } } pid_t Process::fork_and_exec(const string &binary, const char *args[], UnidirectionalPipe &stdin_pipe, UnidirectionalPipe &stdout_pipe) { pid_t child = fork(); if (child < 0) { // hit the process limit throw runtime_error("Couldn't fork to start binary: " + string(strerror(errno))); } else if (child == 0) { // we are the child; close the ends of the pipe that we won't use (as otherwise we'd not see the pipes close when the other end is done) stdin_pipe.close_write(); stdout_pipe.close_read(); // attach our stdin stdin_pipe.dup_read_to(STDIN_FILENO); stdin_pipe.close_read(); // attach our stdout stdout_pipe.dup_write_to(STDOUT_FILENO); stdout_pipe.close_write(); // run the binary if (execvp(binary.c_str(), (char * const *)args) < 0) { throw runtime_error(describe_error(binary, errno)); } throw logic_error("execv returned"); } else { return child; } } bool Process::wait_for_and_check(pid_t child) { int status; while (true) { if (waitpid(child, &status, 0) < 0) { throw runtime_error("Couldn't wait for child: " + string(strerror(errno))); } return WIFEXITED(status) && WEXITSTATUS(status) == 0; } } <|endoftext|>
<commit_before>#include "robobo.h" int main(int argc, char** argv) { std::string confDir = "."; // look in current directory by default std::string confName = "robobo.conf"; // look for robobo.conf by default unsigned short debug = 0; if (argc > 1) { // analyze arguments bool exitAfter = false; for (int i = 1; i < argc; i++) { // iterate through all arguments if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) { std::cout << "RoBoBo-IRC-BoBo IRC Bot Help" << std::endl; std::cout << std::endl; std::cout << "RoBoBo can connect to IRC servers. All of its functionality outside of" << std::endl << "connecting to servers is provided by loaded modules." << std::endl; std::cout << "See the README file for more information." << std::endl; std::cout << std::endl; std::cout << "Some command line arguments are provided to perform certain actions. With no" << std::endl << "parameters, the bot will run as a bot. With some command line arguments, the" << std::endl << "functionality of the bot can be changed." << std::endl; std::cout << "Command Line Arguments:" << std::endl; std::cout << "\t--help: display this help and exit" << std::endl; std::cout << "\t\t-h: same as --help" << std::endl; std::cout << "\t\t-?: same as --help" << std::endl; std::cout << "\t--version: display RoBoBo's version and exit" << std::endl; std::cout << "\t\t-v: same as --version" << std::endl; std::cout << "\t--confdir <directory>: make RoBoBo look in the specified directory for the configuration instead of current directory" << std::endl; std::cout << "\t--confname <filename>: make RoBoBo look for the specified file in the conf directory for configuration information" << std::endl; std::cout << "\t--debug: make RoBoBo enter debug mode" << std::endl; std::cout << "\t\t-d: same as --debug" << std::endl; exitAfter = true; } else if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) { std::cout << "RoBoBo-IRC-BoBo Pre-alpha Development Version" << std::endl; exitAfter = true; } else if (strcmp(argv[i], "--confdir") == 0) { if (++i >= argc) { std::cout << "An argument was not specified for the --confdir argument." << std::endl; return 0; } confDir = argv[i]; std::cout << "Looking for the configuration file in " << confDir << std::endl; } else if (strcmp(argv[i], "--confname") == 0) { if (++i >= argc) { std::cout << "An argument was not specified for the --confname argument." << std::endl; return 0; } confName = argv[i]; std::cout << "Looking for a configuration file named " << confName << std::endl; } else if (strcmp(argv[i], "--debug") == 0 || strcmp(argv[i], "-d") == 0) { if (i+1 >= argc || !(strcmp(argv[i+1], "0") == 0 || strcmp(argv[i+1], "1") == 0 || strcmp(argv[i+1], "2") == 0 || strcmp(argv[i+1], "3") == 0 || strcmp(argv[i+1], "4") == 0 || strcmp(argv[i+1], "5") == 0)) debug = 1; else { std::istringstream debugNum (argv[++i]); debugNum >> debug; } std::cout << "Setting debug mode with level " << debug << std::endl; } std::cout << std::endl; // add a newline after a parameter's output } if (exitAfter) return 0; } new ModuleInterface (confDir, confName, debug); //run actual bot pthread_exit(NULL); }<commit_msg>Change the version as defined by the --version command line argument.<commit_after>#include "robobo.h" int main(int argc, char** argv) { std::string confDir = "."; // look in current directory by default std::string confName = "robobo.conf"; // look for robobo.conf by default unsigned short debug = 0; if (argc > 1) { // analyze arguments bool exitAfter = false; for (int i = 1; i < argc; i++) { // iterate through all arguments if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) { std::cout << "RoBoBo-IRC-BoBo IRC Bot Help" << std::endl; std::cout << std::endl; std::cout << "RoBoBo can connect to IRC servers. All of its functionality outside of" << std::endl << "connecting to servers is provided by loaded modules." << std::endl; std::cout << "See the README file for more information." << std::endl; std::cout << std::endl; std::cout << "Some command line arguments are provided to perform certain actions. With no" << std::endl << "parameters, the bot will run as a bot. With some command line arguments, the" << std::endl << "functionality of the bot can be changed." << std::endl; std::cout << "Command Line Arguments:" << std::endl; std::cout << "\t--help: display this help and exit" << std::endl; std::cout << "\t\t-h: same as --help" << std::endl; std::cout << "\t\t-?: same as --help" << std::endl; std::cout << "\t--version: display RoBoBo's version and exit" << std::endl; std::cout << "\t\t-v: same as --version" << std::endl; std::cout << "\t--confdir <directory>: make RoBoBo look in the specified directory for the configuration instead of current directory" << std::endl; std::cout << "\t--confname <filename>: make RoBoBo look for the specified file in the conf directory for configuration information" << std::endl; std::cout << "\t--debug: make RoBoBo enter debug mode" << std::endl; std::cout << "\t\t-d: same as --debug" << std::endl; exitAfter = true; } else if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) { std::cout << "RoBoBo-IRC-BoBo Version 1.0.0 Alpha 1" << std::endl; exitAfter = true; } else if (strcmp(argv[i], "--confdir") == 0) { if (++i >= argc) { std::cout << "An argument was not specified for the --confdir argument." << std::endl; return 0; } confDir = argv[i]; std::cout << "Looking for the configuration file in " << confDir << std::endl; } else if (strcmp(argv[i], "--confname") == 0) { if (++i >= argc) { std::cout << "An argument was not specified for the --confname argument." << std::endl; return 0; } confName = argv[i]; std::cout << "Looking for a configuration file named " << confName << std::endl; } else if (strcmp(argv[i], "--debug") == 0 || strcmp(argv[i], "-d") == 0) { if (i+1 >= argc || !(strcmp(argv[i+1], "0") == 0 || strcmp(argv[i+1], "1") == 0 || strcmp(argv[i+1], "2") == 0 || strcmp(argv[i+1], "3") == 0 || strcmp(argv[i+1], "4") == 0 || strcmp(argv[i+1], "5") == 0)) debug = 1; else { std::istringstream debugNum (argv[++i]); debugNum >> debug; } std::cout << "Setting debug mode with level " << debug << std::endl; } std::cout << std::endl; // add a newline after a parameter's output } if (exitAfter) return 0; } new ModuleInterface (confDir, confName, debug); //run actual bot pthread_exit(NULL); }<|endoftext|>
<commit_before>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <QtCore/QString> #include <QtCore/QFileInfo> #include <QTextStream> #include <QAbstractItemView> #include "copasi.h" #include "qtUtilities.h" #include "CQMessageBox.h" #include "utilities/CCopasiParameterGroup.h" #include "utilities/CDirEntry.h" #include "copasiWidget.h" #include "CQCopasiApplication.h" #include "copasiui3window.h" #include "DataModelGUI.h" #include "listviews.h" #ifdef DEBUG_UI #include <QtCore/QtDebug> #endif bool updateGUI(C_INT32 objectType, C_INT32 action, const std::string & key /*= ""*/) { CQCopasiApplication* app = dynamic_cast<CQCopasiApplication*>(qApp->instance()); if (app == NULL) return false; CopasiUI3Window* win = app->getMainWindow(); if (win == NULL) return false; DataModelGUI* dm = win->getDataModel(); if (dm == NULL) return false; return dm->notify((ListViews::ObjectType)objectType, (ListViews::Action)action, key); } void switchToWidget(size_t id, const std::string & key /*= ""*/) { CQCopasiApplication* app = dynamic_cast<CQCopasiApplication*>(qApp->instance()); if (app == NULL) return; CopasiUI3Window* win = app->getMainWindow(); if (win == NULL) return; ListViews *lv = win->getMainWidget(); if (lv == NULL) return; if (lv->getCurrentItemId() != id || (id == C_INVALID_INDEX && !key.empty())) lv->switchToOtherWidget(id, key); } void updateCurrentWidget() { CQCopasiApplication* app = dynamic_cast<CQCopasiApplication*>(qApp->instance()); if (app == NULL) return; CopasiUI3Window* win = app->getMainWindow(); if (win == NULL) return; ListViews *lv = win->getMainWidget(); if (lv == NULL) return; CopasiWidget* currentWidget = lv->getCurrentWidget(); if (currentWidget == NULL) return; currentWidget->refresh(); } QVariant getParameterValue(const CCopasiParameter * pParameter) { if (pParameter == NULL) return false; switch (pParameter->getType()) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: return QVariant(pParameter->getValue< C_FLOAT64 >()); break; case CCopasiParameter::INT: return QVariant(pParameter->getValue< C_INT32 >()); break; case CCopasiParameter::UINT: return QVariant(pParameter->getValue< unsigned C_INT32 >()); break; case CCopasiParameter::BOOL:; return QVariant(pParameter->getValue< bool >()); break; case CCopasiParameter::STRING: case CCopasiParameter::KEY: case CCopasiParameter::FILE: case CCopasiParameter::EXPRESSION: case CCopasiParameter::CN: return QVariant(FROM_UTF8(pParameter->getValue< std::string >())); break; case CCopasiParameter::GROUP: case CCopasiParameter::INVALID: break; } return QVariant(); } QVariant getParameterValue(const CCopasiParameterGroup * pGroup, const size_t & index) { return getParameterValue(pGroup->getParameter(index)); } QVariant getParameterValue(const CCopasiParameterGroup * pGroup, const std::string & name) { return getParameterValue(pGroup->getParameter(name)); } QList< QPair < QVariant, QVariant > > getParameterValidValues(const CCopasiParameter * pParameter) { QList< QPair < QVariant, QVariant > > ValidValues; if (pParameter == NULL || !pParameter->hasValidValues()) return ValidValues; switch (pParameter->getType()) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: { std::vector<std::pair< C_FLOAT64, C_FLOAT64 > >::const_iterator it = pParameter->getValidValues< C_FLOAT64 >().begin(); std::vector<std::pair< C_FLOAT64, C_FLOAT64 > >::const_iterator end = pParameter->getValidValues< C_FLOAT64 >().end(); for (; it != end; ++it) ValidValues.append( QPair<QVariant, QVariant>(QVariant(it->first), QVariant(it->second))); } break; case CCopasiParameter::INT: { std::vector< std::pair < C_INT32, C_INT32 > >::const_iterator it = pParameter->getValidValues< C_INT32 >().begin(); std::vector< std::pair < C_INT32, C_INT32 > >::const_iterator end = pParameter->getValidValues< C_INT32 >().end(); for (; it != end; ++it) ValidValues.append(QPair< QVariant, QVariant >(QVariant(it->first), QVariant(it->second))); } break; case CCopasiParameter::UINT: { std::vector< std::pair < unsigned C_INT32, unsigned C_INT32 > >::const_iterator it = pParameter->getValidValues< unsigned C_INT32 >().begin(); std::vector< std::pair < unsigned C_INT32, unsigned C_INT32 > >::const_iterator end = pParameter->getValidValues< unsigned C_INT32 >().end(); for (; it != end; ++it) ValidValues.append(QPair< QVariant, QVariant >(QVariant(it->first), QVariant(it->second))); } break; case CCopasiParameter::BOOL:; { std::vector< std::pair < bool, bool > >::const_iterator it = pParameter->getValidValues< bool >().begin(); std::vector< std::pair < bool, bool > >::const_iterator end = pParameter->getValidValues< bool >().end(); for (; it != end; ++it) ValidValues.append(QPair< QVariant, QVariant >(QVariant(it->first), QVariant(it->second))); } break; case CCopasiParameter::STRING: case CCopasiParameter::KEY: case CCopasiParameter::FILE: case CCopasiParameter::EXPRESSION: case CCopasiParameter::CN: { std::vector< std::pair < std::string, std::string > >::const_iterator it = pParameter->getValidValues< std::string >().begin(); std::vector< std::pair < std::string, std::string > >::const_iterator end = pParameter->getValidValues< std::string >().end(); for (; it != end; ++it) ValidValues.append(QPair< QVariant, QVariant >(QVariant(FROM_UTF8(it->first)), QVariant(FROM_UTF8(it->second)))); } break; case CCopasiParameter::GROUP: case CCopasiParameter::INVALID: break; } return ValidValues; } bool setParameterValue(CCopasiParameter * pParameter, const QVariant & value) { if (pParameter == NULL) return false; switch (pParameter->getType()) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: return pParameter->setValue< C_FLOAT64 >(value.toDouble()); break; case CCopasiParameter::INT: return pParameter->setValue< C_INT32 >(value.toInt()); break; case CCopasiParameter::UINT: return pParameter->setValue< unsigned C_INT32 >(value.toUInt()); break; case CCopasiParameter::BOOL:; return pParameter->setValue< bool >(value.toBool()); break; case CCopasiParameter::STRING: case CCopasiParameter::KEY: case CCopasiParameter::FILE: case CCopasiParameter::EXPRESSION: return pParameter->setValue< std::string >(TO_UTF8(value.toString())); break; case CCopasiParameter::CN: return pParameter->setValue< CCommonName >(std::string(TO_UTF8(value.toString()))); break; case CCopasiParameter::GROUP: case CCopasiParameter::INVALID: break; } return false; } bool setParameterValue(CCopasiParameterGroup * pGroup, const size_t & index, const QVariant & value) { return setParameterValue(pGroup->getParameter(index), value); } bool setParameterValue(CCopasiParameterGroup * pGroup, const size_t & index, const QString & value) { return setParameterValue(pGroup->getParameter(index), QVariant(value)); } bool setParameterValue(CCopasiParameterGroup * pGroup, const std::string & name, const QString & value) { return setParameterValue(pGroup->getParameter(name), QVariant(value)); } bool setParameterValue(CCopasiParameterGroup * pGroup, const std::string & name, const QVariant & value) { return setParameterValue(pGroup->getParameter(name), value); } C_INT32 checkSelection(const QString & file) { #ifdef DEBUG_UI qDebug() << "Filename on checkSelection = " << file; #endif if (QFileInfo(file).exists()) { if (CDirEntry::isWritable(TO_UTF8(file))) return CQMessageBox::question(NULL, "File exists!", "Overwrite existing file " + file + "?", QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); else { CQMessageBox::information(NULL, "File read-only", "The file is read-only. Please select another file!", QMessageBox::Ok, QMessageBox::Ok); return QMessageBox::Cancel; } } else return QMessageBox::Ok; } void vectorOfStrings2QStringList(std::vector<std::string> vs, QStringList & qsl) { qsl.clear(); size_t i, imax = vs.size(); for (i = 0; i < imax; ++i) qsl += FROM_UTF8(vs[i]); } const CopasiWidget * GetCopasiWidget(const QObject * pObject) { const QObject * pParent = pObject; const CopasiWidget * pCopasiWidget = NULL; while (pParent != NULL && pCopasiWidget == NULL) { pCopasiWidget = dynamic_cast< const CopasiWidget * >(pParent); pParent = pParent->parent(); } return pCopasiWidget; } QString toTsvString(QAbstractItemModel* pModel, bool writeColumnHeaders /*= true*/, bool writeRowHeaders /*= true*/) { QString text; QTextStream stream(&text); if (writeColumnHeaders) { if (writeRowHeaders) stream << '\t'; for (int j = 0; j <= pModel->columnCount(); ++j) { stream << pModel->headerData(j, Qt::Horizontal).toString().replace('\n', ' '); if (j + 1 < pModel->columnCount()) stream << '\t'; } stream << '\n'; } for (int i = 0; i < pModel->rowCount(); ++i) { if (writeRowHeaders) stream << pModel->headerData(i, Qt::Vertical).toString().replace('\n', ' ') << '\t'; for (int j = 0; j <= pModel->columnCount(); ++j) { stream << pModel->index(i, j).data().toString(); if (j + 1 < pModel->columnCount()) stream << '\t'; } stream << '\n'; } return text; } QString toTsvString(QAbstractItemView* pWidget, bool writeColumnHeaders /*= true*/, bool writeRowHeaders /*= true*/) { if (pWidget == NULL) return QString(); QAbstractItemModel* pModel = pWidget->model(); return toTsvString(pModel, writeColumnHeaders, writeRowHeaders); } <commit_msg>- issue 2527: correct comparison<commit_after>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <QtCore/QString> #include <QtCore/QFileInfo> #include <QTextStream> #include <QAbstractItemView> #include "copasi.h" #include "qtUtilities.h" #include "CQMessageBox.h" #include "utilities/CCopasiParameterGroup.h" #include "utilities/CDirEntry.h" #include "copasiWidget.h" #include "CQCopasiApplication.h" #include "copasiui3window.h" #include "DataModelGUI.h" #include "listviews.h" #ifdef DEBUG_UI #include <QtCore/QtDebug> #endif bool updateGUI(C_INT32 objectType, C_INT32 action, const std::string & key /*= ""*/) { CQCopasiApplication* app = dynamic_cast<CQCopasiApplication*>(qApp->instance()); if (app == NULL) return false; CopasiUI3Window* win = app->getMainWindow(); if (win == NULL) return false; DataModelGUI* dm = win->getDataModel(); if (dm == NULL) return false; return dm->notify((ListViews::ObjectType)objectType, (ListViews::Action)action, key); } void switchToWidget(size_t id, const std::string & key /*= ""*/) { CQCopasiApplication* app = dynamic_cast<CQCopasiApplication*>(qApp->instance()); if (app == NULL) return; CopasiUI3Window* win = app->getMainWindow(); if (win == NULL) return; ListViews *lv = win->getMainWidget(); if (lv == NULL) return; if (lv->getCurrentItemId() != id || (id == C_INVALID_INDEX && !key.empty())) lv->switchToOtherWidget(id, key); } void updateCurrentWidget() { CQCopasiApplication* app = dynamic_cast<CQCopasiApplication*>(qApp->instance()); if (app == NULL) return; CopasiUI3Window* win = app->getMainWindow(); if (win == NULL) return; ListViews *lv = win->getMainWidget(); if (lv == NULL) return; CopasiWidget* currentWidget = lv->getCurrentWidget(); if (currentWidget == NULL) return; currentWidget->refresh(); } QVariant getParameterValue(const CCopasiParameter * pParameter) { if (pParameter == NULL) return false; switch (pParameter->getType()) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: return QVariant(pParameter->getValue< C_FLOAT64 >()); break; case CCopasiParameter::INT: return QVariant(pParameter->getValue< C_INT32 >()); break; case CCopasiParameter::UINT: return QVariant(pParameter->getValue< unsigned C_INT32 >()); break; case CCopasiParameter::BOOL:; return QVariant(pParameter->getValue< bool >()); break; case CCopasiParameter::STRING: case CCopasiParameter::KEY: case CCopasiParameter::FILE: case CCopasiParameter::EXPRESSION: case CCopasiParameter::CN: return QVariant(FROM_UTF8(pParameter->getValue< std::string >())); break; case CCopasiParameter::GROUP: case CCopasiParameter::INVALID: break; } return QVariant(); } QVariant getParameterValue(const CCopasiParameterGroup * pGroup, const size_t & index) { return getParameterValue(pGroup->getParameter(index)); } QVariant getParameterValue(const CCopasiParameterGroup * pGroup, const std::string & name) { return getParameterValue(pGroup->getParameter(name)); } QList< QPair < QVariant, QVariant > > getParameterValidValues(const CCopasiParameter * pParameter) { QList< QPair < QVariant, QVariant > > ValidValues; if (pParameter == NULL || !pParameter->hasValidValues()) return ValidValues; switch (pParameter->getType()) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: { std::vector<std::pair< C_FLOAT64, C_FLOAT64 > >::const_iterator it = pParameter->getValidValues< C_FLOAT64 >().begin(); std::vector<std::pair< C_FLOAT64, C_FLOAT64 > >::const_iterator end = pParameter->getValidValues< C_FLOAT64 >().end(); for (; it != end; ++it) ValidValues.append( QPair<QVariant, QVariant>(QVariant(it->first), QVariant(it->second))); } break; case CCopasiParameter::INT: { std::vector< std::pair < C_INT32, C_INT32 > >::const_iterator it = pParameter->getValidValues< C_INT32 >().begin(); std::vector< std::pair < C_INT32, C_INT32 > >::const_iterator end = pParameter->getValidValues< C_INT32 >().end(); for (; it != end; ++it) ValidValues.append(QPair< QVariant, QVariant >(QVariant(it->first), QVariant(it->second))); } break; case CCopasiParameter::UINT: { std::vector< std::pair < unsigned C_INT32, unsigned C_INT32 > >::const_iterator it = pParameter->getValidValues< unsigned C_INT32 >().begin(); std::vector< std::pair < unsigned C_INT32, unsigned C_INT32 > >::const_iterator end = pParameter->getValidValues< unsigned C_INT32 >().end(); for (; it != end; ++it) ValidValues.append(QPair< QVariant, QVariant >(QVariant(it->first), QVariant(it->second))); } break; case CCopasiParameter::BOOL:; { std::vector< std::pair < bool, bool > >::const_iterator it = pParameter->getValidValues< bool >().begin(); std::vector< std::pair < bool, bool > >::const_iterator end = pParameter->getValidValues< bool >().end(); for (; it != end; ++it) ValidValues.append(QPair< QVariant, QVariant >(QVariant(it->first), QVariant(it->second))); } break; case CCopasiParameter::STRING: case CCopasiParameter::KEY: case CCopasiParameter::FILE: case CCopasiParameter::EXPRESSION: case CCopasiParameter::CN: { std::vector< std::pair < std::string, std::string > >::const_iterator it = pParameter->getValidValues< std::string >().begin(); std::vector< std::pair < std::string, std::string > >::const_iterator end = pParameter->getValidValues< std::string >().end(); for (; it != end; ++it) ValidValues.append(QPair< QVariant, QVariant >(QVariant(FROM_UTF8(it->first)), QVariant(FROM_UTF8(it->second)))); } break; case CCopasiParameter::GROUP: case CCopasiParameter::INVALID: break; } return ValidValues; } bool setParameterValue(CCopasiParameter * pParameter, const QVariant & value) { if (pParameter == NULL) return false; switch (pParameter->getType()) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: return pParameter->setValue< C_FLOAT64 >(value.toDouble()); break; case CCopasiParameter::INT: return pParameter->setValue< C_INT32 >(value.toInt()); break; case CCopasiParameter::UINT: return pParameter->setValue< unsigned C_INT32 >(value.toUInt()); break; case CCopasiParameter::BOOL:; return pParameter->setValue< bool >(value.toBool()); break; case CCopasiParameter::STRING: case CCopasiParameter::KEY: case CCopasiParameter::FILE: case CCopasiParameter::EXPRESSION: return pParameter->setValue< std::string >(TO_UTF8(value.toString())); break; case CCopasiParameter::CN: return pParameter->setValue< CCommonName >(std::string(TO_UTF8(value.toString()))); break; case CCopasiParameter::GROUP: case CCopasiParameter::INVALID: break; } return false; } bool setParameterValue(CCopasiParameterGroup * pGroup, const size_t & index, const QVariant & value) { return setParameterValue(pGroup->getParameter(index), value); } bool setParameterValue(CCopasiParameterGroup * pGroup, const size_t & index, const QString & value) { return setParameterValue(pGroup->getParameter(index), QVariant(value)); } bool setParameterValue(CCopasiParameterGroup * pGroup, const std::string & name, const QString & value) { return setParameterValue(pGroup->getParameter(name), QVariant(value)); } bool setParameterValue(CCopasiParameterGroup * pGroup, const std::string & name, const QVariant & value) { return setParameterValue(pGroup->getParameter(name), value); } C_INT32 checkSelection(const QString & file) { #ifdef DEBUG_UI qDebug() << "Filename on checkSelection = " << file; #endif if (QFileInfo(file).exists()) { if (CDirEntry::isWritable(TO_UTF8(file))) return CQMessageBox::question(NULL, "File exists!", "Overwrite existing file " + file + "?", QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); else { CQMessageBox::information(NULL, "File read-only", "The file is read-only. Please select another file!", QMessageBox::Ok, QMessageBox::Ok); return QMessageBox::Cancel; } } else return QMessageBox::Ok; } void vectorOfStrings2QStringList(std::vector<std::string> vs, QStringList & qsl) { qsl.clear(); size_t i, imax = vs.size(); for (i = 0; i < imax; ++i) qsl += FROM_UTF8(vs[i]); } const CopasiWidget * GetCopasiWidget(const QObject * pObject) { const QObject * pParent = pObject; const CopasiWidget * pCopasiWidget = NULL; while (pParent != NULL && pCopasiWidget == NULL) { pCopasiWidget = dynamic_cast< const CopasiWidget * >(pParent); pParent = pParent->parent(); } return pCopasiWidget; } QString toTsvString(QAbstractItemModel* pModel, bool writeColumnHeaders /*= true*/, bool writeRowHeaders /*= true*/) { QString text; QTextStream stream(&text); if (writeColumnHeaders) { if (writeRowHeaders) stream << '\t'; for (int j = 0; j < pModel->columnCount(); ++j) { stream << pModel->headerData(j, Qt::Horizontal).toString().replace('\n', ' '); if (j + 1 < pModel->columnCount()) stream << '\t'; } stream << '\n'; } for (int i = 0; i < pModel->rowCount(); ++i) { if (writeRowHeaders) stream << pModel->headerData(i, Qt::Vertical).toString().replace('\n', ' ') << '\t'; for (int j = 0; j < pModel->columnCount(); ++j) { stream << pModel->index(i, j).data().toString(); if (j + 1 < pModel->columnCount()) stream << '\t'; } stream << '\n'; } return text; } QString toTsvString(QAbstractItemView* pWidget, bool writeColumnHeaders /*= true*/, bool writeRowHeaders /*= true*/) { if (pWidget == NULL) return QString(); QAbstractItemModel* pModel = pWidget->model(); return toTsvString(pModel, writeColumnHeaders, writeRowHeaders); } <|endoftext|>
<commit_before>/* Generated from orogen/lib/orogen/templates/typekit/Types.hpp */ #ifndef __OROGEN_GENERATED_<%= typekit.name.upcase %>_TYPES_HPP #define __OROGEN_GENERATED_<%= typekit.name.upcase %>_TYPES_HPP <%= typekit.opaques.map { |opaque_def| opaque_def.includes }. flatten.map { |p| "#include <#{p}>" }.join("\n") %> <% typekit.external_loads.each do |file| %> #include <<%= file %>> <% end %> <% typekit.local_headers(false).each do |path, dest_path| %> #include "<%= typekit.name %>/types/<%= typekit.name %>/<%= dest_path %>" <% end %> <% typekit.used_typekits.each do |tk| %> <% next if tk.virtual? %> #include <<%= tk.name %>/Types.hpp> <% end %> // This is a hack. We include it unconditionally as it may be required by some // typekits *and* it is a standard header. Ideally, we would actually check if // some of the types need std::vector. #include <vector> #include <boost/cstdint.hpp> #include <boost/serialization/serialization.hpp> #include <boost/serialization/array.hpp> #include <boost/serialization/vector.hpp> <%= typekit.m_types_code %> <% interface_types.each do |type| %> #ifdef CORELIB_DATASOURCE_HPP extern template class RTT::internal::DataSource< <%= type.cxx_name %> >; extern template class RTT::internal::AssignableDataSource< <%= type.cxx_name %> >; #endif #ifdef ORO_CORELIB_DATASOURCES_HPP extern template class RTT::internal::ValueDataSource< <%= type.cxx_name %> >; extern template class RTT::internal::ConstantDataSource< <%= type.cxx_name %> >; extern template class RTT::internal::ReferenceDataSource< <%= type.cxx_name %> >; #endif #ifdef ORO_INPUT_PORT_HPP extern template class RTT::OutputPort< <%= type.cxx_name %> >; #endif #ifdef ORO_OUTPUT_PORT_HPP extern template class RTT::InputPort< <%= type.cxx_name %> >; #endif #ifdef ORO_PROPERTY_HPP extern template class RTT::Property< <%= type.cxx_name %> >; #endif #ifdef ORO_CORELIB_ATTRIBUTE_HPP extern template class RTT::Attribute< <%= type.cxx_name %> >; #endif <% end %> <% boost_serialize_types = converted_types. find_all do |t| t.boost_serialization_compatible? && t.respond_to?(:to_boost_serialization) end %> <% if !boost_serialize_types.empty? %> namespace boost { namespace serialization { <% boost_serialize_types.each do |type| %> template<typename Archive> void serialize(Archive& a, <%= type.cxx_name %>& b, unsigned int version) { using boost::serialization::make_nvp; <%= type.to_boost_serialization %> } <% end %> } } <% end %> #endif <commit_msg>typegen: include boost serialization headers for all stl types.<commit_after>/* Generated from orogen/lib/orogen/templates/typekit/Types.hpp */ #ifndef __OROGEN_GENERATED_<%= typekit.name.upcase %>_TYPES_HPP #define __OROGEN_GENERATED_<%= typekit.name.upcase %>_TYPES_HPP <%= typekit.opaques.map { |opaque_def| opaque_def.includes }. flatten.map { |p| "#include <#{p}>" }.join("\n") %> <% typekit.external_loads.each do |file| %> #include <<%= file %>> <% end %> <% typekit.local_headers(false).each do |path, dest_path| %> #include "<%= typekit.name %>/types/<%= typekit.name %>/<%= dest_path %>" <% end %> <% typekit.used_typekits.each do |tk| %> <% next if tk.virtual? %> #include <<%= tk.name %>/Types.hpp> <% end %> // This is a hack. We include it unconditionally as it may be required by some // typekits *and* it is a standard header. Ideally, we would actually check if // some of the types need std::vector. #include <vector> #include <boost/cstdint.hpp> #include <boost/serialization/serialization.hpp> #include <boost/serialization/array.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/list.hpp> #include <boost/serialization/deque.hpp> #include <boost/serialization/utility.hpp> <%= typekit.m_types_code %> <% interface_types.each do |type| %> #ifdef CORELIB_DATASOURCE_HPP extern template class RTT::internal::DataSource< <%= type.cxx_name %> >; extern template class RTT::internal::AssignableDataSource< <%= type.cxx_name %> >; #endif #ifdef ORO_CORELIB_DATASOURCES_HPP extern template class RTT::internal::ValueDataSource< <%= type.cxx_name %> >; extern template class RTT::internal::ConstantDataSource< <%= type.cxx_name %> >; extern template class RTT::internal::ReferenceDataSource< <%= type.cxx_name %> >; #endif #ifdef ORO_INPUT_PORT_HPP extern template class RTT::OutputPort< <%= type.cxx_name %> >; #endif #ifdef ORO_OUTPUT_PORT_HPP extern template class RTT::InputPort< <%= type.cxx_name %> >; #endif #ifdef ORO_PROPERTY_HPP extern template class RTT::Property< <%= type.cxx_name %> >; #endif #ifdef ORO_CORELIB_ATTRIBUTE_HPP extern template class RTT::Attribute< <%= type.cxx_name %> >; #endif <% end %> <% boost_serialize_types = converted_types. find_all do |t| t.boost_serialization_compatible? && t.respond_to?(:to_boost_serialization) end %> <% if !boost_serialize_types.empty? %> namespace boost { namespace serialization { <% boost_serialize_types.each do |type| %> template<typename Archive> void serialize(Archive& a, <%= type.cxx_name %>& b, unsigned int version) { using boost::serialization::make_nvp; <%= type.to_boost_serialization %> } <% end %> } } <% end %> #endif <|endoftext|>
<commit_before> #include "CReportDefinition.h" #include "CReportBody.h" #include "CReport.h" #include "CCopasiContainer.h" ////////////////////////////////////////////////// // //class CReport // ////////////////////////////////////////////////// CReport::CReport(): CCopasiObject("Report", NULL, "Report", CCopasiObject::Container), mpReportDef(NULL), mAppend(true) //,mKey(CKeyFactory::add("Report", this)) {} CReport::~CReport() {cleanup();} void CReport::cleanup() { objectList.clear(); // CKeyFactory::remove(mKey); // mpReportDef pointer shall be dealt outside, where it is created // pdelete(mpReportDef); } CReportDefinition* CReport::getReportDefinition() {return mpReportDef;} void CReport::setReportDefinition(CReportDefinition* reportDef) {mpReportDef = reportDef;} const std::string& CReport::getTarget() {return mTarget;} void CReport::setTarget(std::string target) {mTarget = target;} bool CReport::append() {return mAppend;} void CReport::setAppend(bool append) {mAppend = append;} void CReport::printHeader() { // for loop print out mpReportDef->getHeader() } void CReport::printBody() { // for loop print out mpReportDef->getBody() } void CReport::printFooter() { // for loop print out mpReportDef->getFooter() } void CReport::compile() { CCopasiContainer* pCopasiObject; int i; for (i = 0; i < mpReportDef->getBodyAddr()->size(); i++) { CCopasiObject* pSelected = (CCopasiObject*)CCopasiContainer::Root->getObject((*(mpReportDef->getBodyAddr()))[i]); objectList.push_back(pSelected); } } void CReport::printBody(CReport * pReport) {if (pReport) pReport->printBody();} <commit_msg>fixed the error due to erasing the objects twice,<commit_after> #include "CReportDefinition.h" #include "CReportBody.h" #include "CReport.h" #include "CCopasiContainer.h" ////////////////////////////////////////////////// // //class CReport // ////////////////////////////////////////////////// CReport::CReport(): CCopasiObject("Report", NULL, "Report", CCopasiObject::Container), mpReportDef(NULL), mAppend(true) //,mKey(CKeyFactory::add("Report", this)) {} CReport::~CReport() {cleanup();} void CReport::cleanup() { // Please Dont clear the objectList, as all pointers are also referred swh else int i; for (i = 0; i < objectList.size(); i++) { objectList[i] = NULL; } objectList.clear(); // CKeyFactory::remove(mKey); // mpReportDef pointer shall be dealt outside, where it is created // pdelete(mpReportDef); } CReportDefinition* CReport::getReportDefinition() {return mpReportDef;} void CReport::setReportDefinition(CReportDefinition* reportDef) {mpReportDef = reportDef;} const std::string& CReport::getTarget() {return mTarget;} void CReport::setTarget(std::string target) {mTarget = target;} bool CReport::append() {return mAppend;} void CReport::setAppend(bool append) {mAppend = append;} void CReport::printHeader() { // for loop print out mpReportDef->getHeader() } void CReport::printBody() { // for loop print out mpReportDef->getBody() } void CReport::printFooter() { // for loop print out mpReportDef->getFooter() } void CReport::compile() { CCopasiContainer* pCopasiObject; int i; for (i = 0; i < mpReportDef->getBodyAddr()->size(); i++) { CCopasiObject* pSelected = (CCopasiObject*)CCopasiContainer::Root->getObject((*(mpReportDef->getBodyAddr()))[i]); objectList.push_back(pSelected); } } void CReport::printBody(CReport * pReport) {if (pReport) pReport->printBody();} <|endoftext|>
<commit_before>#include "rtkfdk_ggo.h" #include "rtkGgoFunctions.h" #include "rtkConfiguration.h" #include "itkThreeDCircularProjectionGeometryXMLFile.h" #include "itkProjectionsReader.h" #include "itkFFTRampImageFilter.h" #include "itkFDKWeightProjectionFilter.h" #include "itkFDKBackProjectionImageFilter.h" #if CUDA_FOUND # include "itkCudaFDKBackProjectionImageFilter.h" #endif #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkTimeProbe.h> #include <itkStreamingImageFilter.h> int main(int argc, char * argv[]) { GGO(rtkfdk, args_info); typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(args_info.path_arg); names->SetNumericSort(false); names->SetRegularExpression(args_info.regexp_arg); names->SetSubMatch(0); if(args_info.verbose_flag) std::cout << "Regular expression matches " << names->GetFileNames().size() << " file(s)..." << std::endl; // Projections reader typedef itk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( names->GetFileNames() ); reader->GenerateOutputInformation(); itk::TimeProbe readerProbe; if(!args_info.lowmem_flag) { if(args_info.verbose_flag) std::cout << "Reading... " << std::flush; try { readerProbe.Start(); reader->Update(); readerProbe.Stop(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } if(args_info.verbose_flag) std::cout << "It took " << readerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl; } // Geometry if(args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; itk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader = itk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); geometryReader->GenerateOutputInformation(); // Weight projections according to fdk algorithm typedef itk::FDKWeightProjectionFilter< OutputImageType > WeightFilterType; WeightFilterType::Pointer weightFilter = WeightFilterType::New(); weightFilter->SetInput( reader->GetOutput() ); weightFilter->SetSourceToDetectorDistance( geometryReader->GetOutputObject()->GetSourceToDetectorDistance() ); weightFilter->SetInPlace(false); //SR: there seems to be a bug in ITK: incompatibility between InPlace and streaming? // Ramp filter typedef itk::FFTRampImageFilter<OutputImageType> RampFilterType; RampFilterType::Pointer rampFilter = RampFilterType::New(); rampFilter->SetInput( weightFilter->GetOutput() ); rampFilter->SetTruncationCorrection(args_info.pad_arg); rampFilter->SetHannCutFrequency(args_info.hann_arg); // Streaming filter typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType; StreamerType::Pointer streamer = StreamerType::New(); streamer->SetInput( rampFilter->GetOutput() ); streamer->SetNumberOfStreamDivisions( 1 + reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() / (1024*1024*4) ); // Try to do all 2D pre-processing itk::TimeProbe streamerProbe; if(!args_info.lowmem_flag) { try { if(args_info.verbose_flag) std::cout << "Weighting and filtering projections... " << std::flush; streamerProbe.Start(); streamer->Update(); streamerProbe.Stop(); if(args_info.verbose_flag) std::cout << "It took " << streamerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl; } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } } // Create reconstructed volume OutputImageType::Pointer tomography = rtk::CreateImageFromGgo<OutputImageType>(args_info); if(args_info.verbose_flag) std::cout << "Backprojecting using " << args_info.hardware_arg << "... " << std::flush; // Backprojection typedef itk::FDKBackProjectionImageFilter<OutputImageType, OutputImageType> BackProjectionFilterType; BackProjectionFilterType::Pointer bpFilter; if(!strcmp(args_info.hardware_arg, "cpu")) bpFilter = BackProjectionFilterType::New(); else if(!strcmp(args_info.hardware_arg, "cuda")) { #if CUDA_FOUND bpFilter = itk::CudaFDKBackProjectionImageFilter::New(); #else std::cerr << "The program has not been compiled with cuda option" << std::endl; return EXIT_FAILURE; #endif } bpFilter->SetInput( 0, tomography ); if(args_info.lowmem_flag) bpFilter->SetInput( 1, rampFilter->GetOutput() ); else bpFilter->SetInput( 1, streamer->GetOutput() ); bpFilter->SetGeometry( geometryReader->GetOutputObject() ); bpFilter->SetInPlace( true ); itk::TimeProbe bpProbe; try { bpProbe.Start(); bpFilter->Update(); bpProbe.Stop(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } if(args_info.verbose_flag) std::cout << "It took " << bpProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl << "Writing... " << std::flush; // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( bpFilter->GetOutput() ); itk::TimeProbe writerProbe; try { writerProbe.Start(); writer->Update(); writerProbe.Stop(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } if(args_info.verbose_flag) std::cout << "It took " << writerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl; return EXIT_SUCCESS; } <commit_msg>Setting up NumberOfStreamDivisions to number of projections to obtain numerically equivalent results with or without --lowmem.<commit_after>#include "rtkfdk_ggo.h" #include "rtkGgoFunctions.h" #include "rtkConfiguration.h" #include "itkThreeDCircularProjectionGeometryXMLFile.h" #include "itkProjectionsReader.h" #include "itkFFTRampImageFilter.h" #include "itkFDKWeightProjectionFilter.h" #include "itkFDKBackProjectionImageFilter.h" #if CUDA_FOUND # include "itkCudaFDKBackProjectionImageFilter.h" #endif #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkTimeProbe.h> #include <itkStreamingImageFilter.h> int main(int argc, char * argv[]) { GGO(rtkfdk, args_info); typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // Generate file names itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New(); names->SetDirectory(args_info.path_arg); names->SetNumericSort(false); names->SetRegularExpression(args_info.regexp_arg); names->SetSubMatch(0); if(args_info.verbose_flag) std::cout << "Regular expression matches " << names->GetFileNames().size() << " file(s)..." << std::endl; // Projections reader typedef itk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( names->GetFileNames() ); reader->GenerateOutputInformation(); itk::TimeProbe readerProbe; if(!args_info.lowmem_flag) { if(args_info.verbose_flag) std::cout << "Reading... " << std::flush; try { readerProbe.Start(); reader->Update(); readerProbe.Stop(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } if(args_info.verbose_flag) std::cout << "It took " << readerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl; } // Geometry if(args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; itk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader = itk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); geometryReader->GenerateOutputInformation(); // Weight projections according to fdk algorithm typedef itk::FDKWeightProjectionFilter< OutputImageType > WeightFilterType; WeightFilterType::Pointer weightFilter = WeightFilterType::New(); weightFilter->SetInput( reader->GetOutput() ); weightFilter->SetSourceToDetectorDistance( geometryReader->GetOutputObject()->GetSourceToDetectorDistance() ); weightFilter->SetInPlace(false); //SR: there seems to be a bug in ITK: incompatibility between InPlace and streaming? // Ramp filter typedef itk::FFTRampImageFilter<OutputImageType> RampFilterType; RampFilterType::Pointer rampFilter = RampFilterType::New(); rampFilter->SetInput( weightFilter->GetOutput() ); rampFilter->SetTruncationCorrection(args_info.pad_arg); rampFilter->SetHannCutFrequency(args_info.hann_arg); // Streaming filter typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType; StreamerType::Pointer streamer = StreamerType::New(); streamer->SetInput( rampFilter->GetOutput() ); streamer->SetNumberOfStreamDivisions( geometryReader->GetOutputObject()->GetMatrices().size() ); // Try to do all 2D pre-processing itk::TimeProbe streamerProbe; if(!args_info.lowmem_flag) { try { if(args_info.verbose_flag) std::cout << "Weighting and filtering projections... " << std::flush; streamerProbe.Start(); streamer->Update(); streamerProbe.Stop(); if(args_info.verbose_flag) std::cout << "It took " << streamerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl; } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } } // Create reconstructed volume OutputImageType::Pointer tomography = rtk::CreateImageFromGgo<OutputImageType>(args_info); if(args_info.verbose_flag) std::cout << "Backprojecting using " << args_info.hardware_arg << "... " << std::flush; // Backprojection typedef itk::FDKBackProjectionImageFilter<OutputImageType, OutputImageType> BackProjectionFilterType; BackProjectionFilterType::Pointer bpFilter; if(!strcmp(args_info.hardware_arg, "cpu")) bpFilter = BackProjectionFilterType::New(); else if(!strcmp(args_info.hardware_arg, "cuda")) { #if CUDA_FOUND bpFilter = itk::CudaFDKBackProjectionImageFilter::New(); #else std::cerr << "The program has not been compiled with cuda option" << std::endl; return EXIT_FAILURE; #endif } bpFilter->SetInput( 0, tomography ); if(args_info.lowmem_flag) bpFilter->SetInput( 1, rampFilter->GetOutput() ); else bpFilter->SetInput( 1, streamer->GetOutput() ); bpFilter->SetGeometry( geometryReader->GetOutputObject() ); bpFilter->SetInPlace( true ); itk::TimeProbe bpProbe; try { bpProbe.Start(); bpFilter->Update(); bpProbe.Stop(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } if(args_info.verbose_flag) std::cout << "It took " << bpProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl << "Writing... " << std::flush; // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( bpFilter->GetOutput() ); itk::TimeProbe writerProbe; try { writerProbe.Start(); writer->Update(); writerProbe.Stop(); } catch( itk::ExceptionObject & err ) { std::cerr << "ExceptionObject caught !" << std::endl; std::cerr << err << std::endl; return EXIT_FAILURE; } if(args_info.verbose_flag) std::cout << "It took " << writerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <Axel.Naumann@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Utils/SourceNormalization.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/Lexer.h" #include <utility> using namespace clang; namespace { ///\brief A Lexer that exposes preprocessor directives. class MinimalPPLexer: public Lexer { ///\brief Jump to last Identifier in a scope chain A::B::C::D /// bool SkipScopes(Token& Tok) { if (getLangOpts().CPlusPlus) { while (Tok.is(tok::coloncolon)) { if (!LexClean(Tok) || Identifier(Tok).empty()) return false; if (!LexClean(Tok)) return false; } } return true; } ///\brief Skips all contiguous '*' '&' tokens /// bool SkipPointerRefs(Token& Tok) { while (Tok.isNot(tok::raw_identifier)) { if (!Tok.isOneOf(tok::star, tok::amp)) return false; if (!LexClean(Tok)) return false; } return true; } ///\brief Test if a given token is a valid identifier for the current language /// /// \param Tok - Token, advanced to first token to test /// \return - The valid identifier or empty llvm::StringRef llvm::StringRef Identifier(Token& Tok) const { if (Tok.is(tok::raw_identifier)) { StringRef Id(Tok.getRawIdentifier()); if (Lexer::isIdentifierBodyChar(Id.front(), getLangOpts())) return Id; } return llvm::StringRef(); } public: ///\brief Construct a Lexer from LangOpts and source. MinimalPPLexer(const LangOptions &LangOpts, llvm::StringRef source): Lexer(SourceLocation(), LangOpts, source.begin(), source.begin(), source.end()) {} bool inPPDirective() const { return ParsingPreprocessorDirective; } ///\brief Lex, forwarding to Lexer::LexFromRawLexer, and keeping track of /// preprocessor directives to provide a tok::eod corresponding to a /// tok::hash. bool Lex(Token& Tok) { bool ret = LexFromRawLexer(Tok); if (inPPDirective()) { // Saw a PP directive; probe for eod to end PP parsing mode. if (Tok.is(tok::eod)) ParsingPreprocessorDirective = false; } else { if (Tok.is(tok::hash)) { // Found a PP directive, request tok::eod to be generated. ParsingPreprocessorDirective = true; } } return ret; } ///\brief Advance to token with given token kind. /// /// \param Tok - Token to advance. /// \param kind - Token kind where to stop lexing. /// \return - Result of most recent call to Lex(). bool AdvanceTo(Token& Tok, tok::TokenKind kind) { while (!Lex(Tok)) { if (Tok.is(kind)) return false; } return true; } ///\brief Lex a token that requires no cleaning /// /// \return - Result of the lex and whether the token is clean. bool LexClean(Token& Tok) { if (!LexFromRawLexer(Tok)) return !Tok.needsCleaning(); return false; } ///\brief Make sure a token is closed/balanced properly /// bool CheckBalance(Token& Tok) { const tok::TokenKind In = Tok.getKind(); const tok::TokenKind Out = In == tok::less ? tok::greater : tok::TokenKind(In + 1); assert((In == tok::l_paren || In == tok::l_brace || In == tok::l_square || In == tok::less) && "Invalid balance token"); bool atEOF = false; int unBalanced = 1; while (unBalanced && !atEOF) { atEOF = !LexClean(Tok); if (Tok.is(Out)) --unBalanced; else if (Tok.is(In)) ++unBalanced; } return unBalanced == 0; } enum DefinitionType { kNONE, ///< Neither a function or class defintion kFunction, ///< Function, method, constructor, or destructor definition kClass ///< Class definition }; ///\brief Test if the given input is a function or class definition /// /// \param Tok - Token, advanced to first token to test /// \param First - First token identifier. /// \return - Typeof definition, function/method or class DefinitionType IsClassOrFunction(Token& Tok, llvm::StringRef First) { /// ###TODO: Allow preprocessor expansion if (!Lexer::isIdentifierBodyChar(First.front(), getLangOpts())) return kNONE; // Early out calling a function/macro Ident() if (!LexClean(Tok) || Tok.is(tok::l_paren)) return kNONE; bool Ctor = false; if (getLangOpts().CPlusPlus && Tok.is(tok::coloncolon)) { // CLASS::CLASS() or CLASS::~CLASS() // CLASS::NESTED::NESTED() // CLASS::type func() // CLASS::NESTED::type Var(); llvm::StringRef Ident; do { if (!LexClean(Tok)) return kNONE; if (Tok.is(tok::raw_identifier)) { if (!Ident.empty()) First = Ident; Ident = Identifier(Tok); if (!LexClean(Tok)) return kNONE; if (Tok.is(tok::less)) { // A template: Ident < if (!CheckBalance(Tok)) return kNONE; if (!LexClean(Tok)) return kNONE; } } } while (Tok.is(tok::coloncolon)); if (Tok.is(tok::tilde)) { if (!LexClean(Tok)) return kNONE; if (!Ident.empty()) First = Ident; Ident = Identifier(Tok); // Advance to argument list if (Ident.empty() || !LexClean(Tok)) return kNONE; } else Ctor = true; // Constructor and Destructor identifiers must match if (!First.equals(Ident)) { if (!SkipPointerRefs(Tok)) return kNONE; // Advance to argument list, or next scope if (!LexClean(Tok)) return kNONE; // Function name should be last on scope chain if (!SkipScopes(Tok)) return kNONE; Ctor = false; } } else { if (First.equals("struct") || First.equals("class")) { do { // Identifier(Tok).empty() is redundant 1st time, but simplifies code if (Identifier(Tok).empty() || !LexClean(Tok)) return kNONE; } while (getLangOpts().CPlusPlus && Tok.is(tok::coloncolon) && LexClean(Tok)); // 'class T {' 'struct T {' 'class T :' if (Tok.is(tok::l_brace)) return kClass; if (Tok.is(tok::colon)) return !AdvanceTo(Tok, tok::l_brace) ? kClass : kNONE; } else if (First.equals("static") || First.equals("constexpr") || First.equals("inline") || First.equals("const")) { // Advance past keyword for below if (!LexClean(Tok)) return kNONE; } if (Tok.isNot(tok::raw_identifier)) { // If we're not at an identifier, we might be still be in return value: // A::B::C funcname() or int * funcname() if (!SkipScopes(Tok)) return kNONE; if (!SkipPointerRefs(Tok)) return kNONE; } // Function or class name should be in Tok now if (Identifier(Tok).empty()) return kNONE; // Advance to argument list or method name if (!LexClean(Tok)) return kNONE; if (!SkipScopes(Tok)) return kNONE; } // Argument list if (Tok.isNot(tok::l_paren)) return kNONE; // ##TODO // Lex the argument identifiers so we can know if this is a declaration // RVAL IDENT(A,B,C) -> could be: // // T inst(a,b,c); -> class instance // T func(T0 a, T1 b, T2 c); -> func declaration // // Without macro expansion it's difficult to distinguish cases, but as the // detection can fail because of macros already, would it be enough to check // that there are two idents not separated by commas between parenthesis? // It still wouldn't work for RVAL IDENT(), but -Wno-vexing-parse could be // passed to clang in initialization. // // Maybe the best would be to lookup the Decl IDENT to see if its a class? if (!CheckBalance(Tok)) return kNONE; if (!LexClean(Tok)) return kNONE; // 'int func() {' or 'CLASS::method() {' if (Tok.is(tok::l_brace)) return kFunction; if (getLangOpts().CPlusPlus) { // constructor initialization 'CLASS::CLASS() :' if (Ctor && Tok.is(tok::colon)) return !AdvanceTo(Tok, tok::l_brace) ? kFunction : kNONE; // class const method 'CLASS::method() const {' if (!Ctor && Identifier(Tok).equals("const")) { if (LexClean(Tok) && Tok.is(tok::l_brace)) return kFunction; } } return kNONE; } }; size_t getFileOffset(const Token& Tok) { return Tok.getLocation().getRawEncoding(); } } size_t cling::utils::isUnnamedMacro(llvm::StringRef source, clang::LangOptions& LangOpts) { // Find the first token that is not a non-cpp directive nor a comment. // If that token is a '{' we have an unnamed macro. MinimalPPLexer Lex(LangOpts, source); Token Tok; bool AfterHash = false; while (true) { bool atEOF = Lex.Lex(Tok); if (atEOF) return std::string::npos; if (Lex.inPPDirective() || Tok.is(tok::eod)) { if (AfterHash) { if (Tok.is(tok::raw_identifier)) { StringRef keyword(Tok.getRawIdentifier()); if (keyword.startswith("if")) { // This could well be // #if FOO // { // where we would determine this to be an unnamed macro and replace // '{' by ' ', whether FOO is #defined or not. Instead, assume that // this is not an unnamed macro and we need to parse it as is. return std::string::npos; } } AfterHash = false; } else AfterHash = Tok.is(tok::hash); continue; // Skip PP directives. } if (Tok.is(tok::l_brace)) return getFileOffset(Tok); if (Tok.is(tok::comment)) continue; // ignore comments return std::string::npos; } // Empty file? return std::string::npos; } size_t cling::utils::getWrapPoint(std::string& source, const clang::LangOptions& LangOpts) { // TODO: For future reference. // Parser* P = const_cast<clang::Parser*>(m_IncrParser->getParser()); // Parser::TentativeParsingAction TA(P); // TPResult result = P->isCXXDeclarationSpecifier(); // TA.Revert(); // return result == TPResult::True(); MinimalPPLexer Lex(LangOpts, source); Token Tok; while (true) { bool atEOF = Lex.Lex(Tok); if (Lex.inPPDirective() || Tok.is(tok::eod)) { if (atEOF) break; continue; // Skip PP directives; they just move the wrap point. } if (Tok.is(tok::eof)) { // Reached EOF before seeing a non-preproc token. // Nothing to wrap. return std::string::npos; } const tok::TokenKind kind = Tok.getKind(); // Prior behavior was to return getFileOffset, which was only used as an // in a test against std::string::npos. By returning 0 we preserve prior // behavior to pass the test against std::string::npos and wrap everything const size_t offset = 0; if (kind == tok::raw_identifier && !Tok.needsCleaning()) { StringRef keyword(Tok.getRawIdentifier()); if (keyword.equals("using")) { // FIXME: Using definitions and declarations should be decl extracted. // Until we have that, don't wrap them if they are the only input. if (Lex.AdvanceTo(Tok, tok::semi)) { // EOF while looking for semi. Don't wrap. return std::string::npos; } // There is "more" - let's assume this input consists of a using // declaration or definition plus some code that should be wrapped. // // We need to include the ';' in the offset as this will be a // non-wrapped statement. return getFileOffset(Tok) + 1; } if (keyword.equals("extern")) return std::string::npos; if (keyword.equals("namespace")) return std::string::npos; if (keyword.equals("template")) return std::string::npos; if (const MinimalPPLexer::DefinitionType T = Lex.IsClassOrFunction(Tok, keyword)) { assert(Tok.is(tok::l_brace) && "Lexer begin location invalid"); if (!Lex.CheckBalance(Tok)) return offset; assert(Tok.is(tok::r_brace) && "Lexer end location invalid"); const size_t rBrace = getFileOffset(Tok); // Wrap everything after '}' bool atEOF = !Lex.LexClean(Tok); bool hadSemi = Tok.is(tok::semi); size_t wrapPoint = getFileOffset(Tok); if (!atEOF) { if (hadSemi) { atEOF = !Lex.LexClean(Tok); if (!atEOF) { // Wrap everything after ';' wrapPoint = getFileOffset(Tok); } } else if (T == MinimalPPLexer::kClass) { // 'struct T {} t ' // 'struct E {} t = {}' // Value print: We want to preserve Tok.is(tok::raw_identifier) // unless the statement was terminated by a semi-colon anyway. Token Tok2; atEOF = Lex.AdvanceTo(Tok2, tok::semi); if ((hadSemi = Tok2.is(tok::semi))) Tok = Tok2; } } // If nothing left to lex, then don't wrap any of it if (atEOF) { if (T == MinimalPPLexer::kClass) { if (!hadSemi) { // Support lack of semi-colon value printing 'struct T {} t' if (Tok.is(tok::raw_identifier)) return 0; if (!LangOpts.HeinousExtensions) { // Let's fix 'class NoTerminatingSemi { ... }' for them! // ### TODO DiagnosticOptions.ShowFixits might be better source.insert(rBrace+1, ";"); return source.size(); } } } return std::string::npos; } return wrapPoint; } // There is something else here that needs to be wrapped. return offset; } // FIXME: in the future, continue lexing to extract relevant PP directives; // return wrapPoint // There is something else here that needs to be wrapped. return offset; } // We have only had PP directives; no need to wrap. return std::string::npos; } <commit_msg>Added function to detect c++ attributes at function definition.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <Axel.Naumann@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Utils/SourceNormalization.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/Lexer.h" #include <utility> using namespace clang; namespace { ///\brief A Lexer that exposes preprocessor directives. class MinimalPPLexer: public Lexer { ///\brief Jump to last Identifier in a scope chain A::B::C::D /// bool SkipScopes(Token& Tok) { if (getLangOpts().CPlusPlus) { while (Tok.is(tok::coloncolon)) { if (!LexClean(Tok) || Identifier(Tok).empty()) return false; if (!LexClean(Tok)) return false; } } return true; } ///\brief Skips all contiguous '*' '&' tokens /// bool SkipPointerRefs(Token& Tok) { while (Tok.isNot(tok::raw_identifier)) { if (!Tok.isOneOf(tok::star, tok::amp)) return false; if (!LexClean(Tok)) return false; } return true; } ///\brief Test if a given token is a valid identifier for the current language /// /// \param Tok - Token, advanced to first token to test /// \return - The valid identifier or empty llvm::StringRef llvm::StringRef Identifier(Token& Tok) const { if (Tok.is(tok::raw_identifier)) { StringRef Id(Tok.getRawIdentifier()); if (Lexer::isIdentifierBodyChar(Id.front(), getLangOpts())) return Id; } return llvm::StringRef(); } public: ///\brief Construct a Lexer from LangOpts and source. MinimalPPLexer(const LangOptions &LangOpts, llvm::StringRef source): Lexer(SourceLocation(), LangOpts, source.begin(), source.begin(), source.end()) {} bool inPPDirective() const { return ParsingPreprocessorDirective; } ///\brief Lex, forwarding to Lexer::LexFromRawLexer, and keeping track of /// preprocessor directives to provide a tok::eod corresponding to a /// tok::hash. bool Lex(Token& Tok) { bool ret = LexFromRawLexer(Tok); if (inPPDirective()) { // Saw a PP directive; probe for eod to end PP parsing mode. if (Tok.is(tok::eod)) ParsingPreprocessorDirective = false; } else { if (Tok.is(tok::hash)) { // Found a PP directive, request tok::eod to be generated. ParsingPreprocessorDirective = true; } } return ret; } ///\brief Advance to token with given token kind. /// /// \param Tok - Token to advance. /// \param kind - Token kind where to stop lexing. /// \return - Result of most recent call to Lex(). bool AdvanceTo(Token& Tok, tok::TokenKind kind) { while (!Lex(Tok)) { if (Tok.is(kind)) return false; } return true; } ///\brief Lex a token that requires no cleaning /// /// \return - Result of the lex and whether the token is clean. bool LexClean(Token& Tok) { if (!LexFromRawLexer(Tok)) return !Tok.needsCleaning(); return false; } ///\brief Make sure a token is closed/balanced properly /// bool CheckBalance(Token& Tok) { const tok::TokenKind In = Tok.getKind(); const tok::TokenKind Out = In == tok::less ? tok::greater : tok::TokenKind(In + 1); assert((In == tok::l_paren || In == tok::l_brace || In == tok::l_square || In == tok::less) && "Invalid balance token"); bool atEOF = false; int unBalanced = 1; while (unBalanced && !atEOF) { atEOF = !LexClean(Tok); if (Tok.is(Out)) --unBalanced; else if (Tok.is(In)) ++unBalanced; } return unBalanced == 0; } enum DefinitionType { kNONE, ///< Neither a function or class defintion kFunction, ///< Function, method, constructor, or destructor definition kClass ///< Class definition }; ///\brief Test if the given input is a function or class definition /// /// \param Tok - Token, advanced to first token to test /// \param First - First token identifier. /// \return - Typeof definition, function/method or class DefinitionType IsClassOrFunction(Token& Tok, llvm::StringRef First) { /// ###TODO: Allow preprocessor expansion if (!Lexer::isIdentifierBodyChar(First.front(), getLangOpts())) return kNONE; // Early out calling a function/macro Ident() if (!LexClean(Tok) || Tok.is(tok::l_paren)) return kNONE; bool Ctor = false; if (getLangOpts().CPlusPlus && Tok.is(tok::coloncolon)) { // CLASS::CLASS() or CLASS::~CLASS() // CLASS::NESTED::NESTED() // CLASS::type func() // CLASS::NESTED::type Var(); llvm::StringRef Ident; do { if (!LexClean(Tok)) return kNONE; if (Tok.is(tok::raw_identifier)) { if (!Ident.empty()) First = Ident; Ident = Identifier(Tok); if (!LexClean(Tok)) return kNONE; if (Tok.is(tok::less)) { // A template: Ident < if (!CheckBalance(Tok)) return kNONE; if (!LexClean(Tok)) return kNONE; } } } while (Tok.is(tok::coloncolon)); if (Tok.is(tok::tilde)) { if (!LexClean(Tok)) return kNONE; if (!Ident.empty()) First = Ident; Ident = Identifier(Tok); // Advance to argument list if (Ident.empty() || !LexClean(Tok)) return kNONE; } else Ctor = true; // Constructor and Destructor identifiers must match if (!First.equals(Ident)) { if (!SkipPointerRefs(Tok)) return kNONE; // Advance to argument list, or next scope if (!LexClean(Tok)) return kNONE; // Function name should be last on scope chain if (!SkipScopes(Tok)) return kNONE; Ctor = false; } } else { if (First.equals("struct") || First.equals("class")) { do { // Identifier(Tok).empty() is redundant 1st time, but simplifies code if (Identifier(Tok).empty() || !LexClean(Tok)) return kNONE; } while (getLangOpts().CPlusPlus && Tok.is(tok::coloncolon) && LexClean(Tok)); // 'class T {' 'struct T {' 'class T :' if (Tok.is(tok::l_brace)) return kClass; if (Tok.is(tok::colon)) return !AdvanceTo(Tok, tok::l_brace) ? kClass : kNONE; } else if (First.equals("static") || First.equals("constexpr") || First.equals("inline") || First.equals("const")) { // Advance past keyword for below if (!LexClean(Tok)) return kNONE; } if (Tok.isNot(tok::raw_identifier)) { // If we're not at an identifier, we might be still be in return value: // A::B::C funcname() or int * funcname() if (!SkipScopes(Tok)) return kNONE; if (!SkipPointerRefs(Tok)) return kNONE; } // Function or class name should be in Tok now if (Identifier(Tok).empty()) return kNONE; // Advance to argument list or method name if (!LexClean(Tok)) return kNONE; if (!SkipScopes(Tok)) return kNONE; } // Argument list if (Tok.isNot(tok::l_paren)) return kNONE; // ##TODO // Lex the argument identifiers so we can know if this is a declaration // RVAL IDENT(A,B,C) -> could be: // // T inst(a,b,c); -> class instance // T func(T0 a, T1 b, T2 c); -> func declaration // // Without macro expansion it's difficult to distinguish cases, but as the // detection can fail because of macros already, would it be enough to check // that there are two idents not separated by commas between parenthesis? // It still wouldn't work for RVAL IDENT(), but -Wno-vexing-parse could be // passed to clang in initialization. // // Maybe the best would be to lookup the Decl IDENT to see if its a class? if (!CheckBalance(Tok)) return kNONE; if (!LexClean(Tok)) return kNONE; // 'int func() {' or 'CLASS::method() {' if (Tok.is(tok::l_brace)) return kFunction; if (getLangOpts().CPlusPlus) { // constructor initialization 'CLASS::CLASS() :' if (Ctor && Tok.is(tok::colon)) return !AdvanceTo(Tok, tok::l_brace) ? kFunction : kNONE; // class const method 'CLASS::method() const {' if (!Ctor && Identifier(Tok).equals("const")) { if (LexClean(Tok) && Tok.is(tok::l_brace)) return kFunction; } } return kNONE; } }; size_t getFileOffset(const Token& Tok) { return Tok.getLocation().getRawEncoding(); } } size_t cling::utils::isUnnamedMacro(llvm::StringRef source, clang::LangOptions& LangOpts) { // Find the first token that is not a non-cpp directive nor a comment. // If that token is a '{' we have an unnamed macro. MinimalPPLexer Lex(LangOpts, source); Token Tok; bool AfterHash = false; while (true) { bool atEOF = Lex.Lex(Tok); if (atEOF) return std::string::npos; if (Lex.inPPDirective() || Tok.is(tok::eod)) { if (AfterHash) { if (Tok.is(tok::raw_identifier)) { StringRef keyword(Tok.getRawIdentifier()); if (keyword.startswith("if")) { // This could well be // #if FOO // { // where we would determine this to be an unnamed macro and replace // '{' by ' ', whether FOO is #defined or not. Instead, assume that // this is not an unnamed macro and we need to parse it as is. return std::string::npos; } } AfterHash = false; } else AfterHash = Tok.is(tok::hash); continue; // Skip PP directives. } if (Tok.is(tok::l_brace)) return getFileOffset(Tok); if (Tok.is(tok::comment)) continue; // ignore comments return std::string::npos; } // Empty file? return std::string::npos; } size_t cling::utils::getWrapPoint(std::string& source, const clang::LangOptions& LangOpts) { // TODO: For future reference. // Parser* P = const_cast<clang::Parser*>(m_IncrParser->getParser()); // Parser::TentativeParsingAction TA(P); // TPResult result = P->isCXXDeclarationSpecifier(); // TA.Revert(); // return result == TPResult::True(); MinimalPPLexer Lex(LangOpts, source); Token Tok; while (true) { bool atEOF = Lex.Lex(Tok); if (Lex.inPPDirective() || Tok.is(tok::eod)) { if (atEOF) break; continue; // Skip PP directives; they just move the wrap point. } if (Tok.is(tok::eof)) { // Reached EOF before seeing a non-preproc token. // Nothing to wrap. return std::string::npos; } // Prior behavior was to return getFileOffset, which was only used as an // in a test against std::string::npos. By returning 0 we preserve prior // behavior to pass the test against std::string::npos and wrap everything const size_t offset = 0; // Check, if a function with c++ attributes should be defined. while (Tok.getKind() == tok::l_square) { Lex.Lex(Tok); // Check, if attribute starts with '[[' if (Tok.getKind() != tok::l_square) { return offset; } // Check, if the second '[' is closing. if (!Lex.CheckBalance(Tok)) { return offset; } Lex.Lex(Tok); // Check, if the first '[' is closing. if (Tok.getKind() != tok::r_square) { return offset; } Lex.Lex(Tok); } const tok::TokenKind kind = Tok.getKind(); if (kind == tok::raw_identifier && !Tok.needsCleaning()) { StringRef keyword(Tok.getRawIdentifier()); if (keyword.equals("using")) { // FIXME: Using definitions and declarations should be decl extracted. // Until we have that, don't wrap them if they are the only input. if (Lex.AdvanceTo(Tok, tok::semi)) { // EOF while looking for semi. Don't wrap. return std::string::npos; } // There is "more" - let's assume this input consists of a using // declaration or definition plus some code that should be wrapped. // // We need to include the ';' in the offset as this will be a // non-wrapped statement. return getFileOffset(Tok) + 1; } if (keyword.equals("extern")) return std::string::npos; if (keyword.equals("namespace")) return std::string::npos; if (keyword.equals("template")) return std::string::npos; if (const MinimalPPLexer::DefinitionType T = Lex.IsClassOrFunction(Tok, keyword)) { assert(Tok.is(tok::l_brace) && "Lexer begin location invalid"); if (!Lex.CheckBalance(Tok)) return offset; assert(Tok.is(tok::r_brace) && "Lexer end location invalid"); const size_t rBrace = getFileOffset(Tok); // Wrap everything after '}' bool atEOF = !Lex.LexClean(Tok); bool hadSemi = Tok.is(tok::semi); size_t wrapPoint = getFileOffset(Tok); if (!atEOF) { if (hadSemi) { atEOF = !Lex.LexClean(Tok); if (!atEOF) { // Wrap everything after ';' wrapPoint = getFileOffset(Tok); } } else if (T == MinimalPPLexer::kClass) { // 'struct T {} t ' // 'struct E {} t = {}' // Value print: We want to preserve Tok.is(tok::raw_identifier) // unless the statement was terminated by a semi-colon anyway. Token Tok2; atEOF = Lex.AdvanceTo(Tok2, tok::semi); if ((hadSemi = Tok2.is(tok::semi))) Tok = Tok2; } } // If nothing left to lex, then don't wrap any of it if (atEOF) { if (T == MinimalPPLexer::kClass) { if (!hadSemi) { // Support lack of semi-colon value printing 'struct T {} t' if (Tok.is(tok::raw_identifier)) return 0; if (!LangOpts.HeinousExtensions) { // Let's fix 'class NoTerminatingSemi { ... }' for them! // ### TODO DiagnosticOptions.ShowFixits might be better source.insert(rBrace+1, ";"); return source.size(); } } } return std::string::npos; } return wrapPoint; } // There is something else here that needs to be wrapped. return offset; } // FIXME: in the future, continue lexing to extract relevant PP directives; // return wrapPoint // There is something else here that needs to be wrapped. return offset; } // We have only had PP directives; no need to wrap. return std::string::npos; } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/make_config_option.hpp" #include "caf/config_value.hpp" #include "caf/optional.hpp" #define DEFAULT_META(type) \ config_option::meta_state type##_meta_state { \ check_impl<type>, store_impl<type>, get_impl<type>, \ detail::type_name<type>() \ }; \ using std::string; namespace caf { namespace { using meta_state = config_option::meta_state; template <class T> error check_impl(const config_value& x) { if (holds_alternative<T>(x)) return none; return make_error(pec::type_mismatch); } template <class T> void store_impl(void* ptr, const config_value& x) { CAF_ASSERT(ptr != nullptr); *static_cast<T*>(ptr) = get<T>(x); } template <class T> config_value get_impl(const void* ptr) { CAF_ASSERT(ptr != nullptr); return config_value{*static_cast<const T*>(ptr)}; } error bool_check(const config_value& x) { if (holds_alternative<bool>(x)) return none; return make_error(pec::type_mismatch); } void bool_store(void* ptr, const config_value& x) { *static_cast<bool*>(ptr) = get<bool>(x); } void bool_store_neg(void* ptr, const config_value& x) { *static_cast<bool*>(ptr) = !get<bool>(x); } config_value bool_get(const void* ptr) { return config_value{*static_cast<const bool*>(ptr)}; } config_value bool_get_neg(const void* ptr) { return config_value{!*static_cast<const bool*>(ptr)}; } meta_state bool_neg_meta{bool_check, bool_store_neg, bool_get_neg, detail::type_name<bool>()}; meta_state us_res_meta{ [](const config_value& x) -> error { if (holds_alternative<timespan>(x)) return none; return make_error(pec::type_mismatch); }, [](void* ptr, const config_value& x) { *static_cast<size_t*>(ptr) = get<timespan>(x).count() / 1000; }, [](const void* ptr) -> config_value { auto ival = static_cast<int64_t>(*static_cast<const size_t*>(ptr)); timespan val{ival / 1000}; return config_value{val}; }, detail::type_name<timespan>() }; meta_state ms_res_meta{ [](const config_value& x) -> error { if (holds_alternative<timespan>(x)) return none; return make_error(pec::type_mismatch); }, [](void* ptr, const config_value& x) { *static_cast<size_t*>(ptr) = get<timespan>(x).count() / 1000000; }, [](const void* ptr) -> config_value { auto ival = static_cast<int64_t>(*static_cast<const size_t*>(ptr)); timespan val{ival / 1000000}; return config_value{val}; }, detail::type_name<timespan>() }; } // namespace namespace detail { DEFAULT_META(atom_value); DEFAULT_META(size_t); DEFAULT_META(string); config_option::meta_state bool_meta_state{ bool_check, bool_store, bool_get, detail::type_name<bool>() }; } // namespace detail config_option make_negated_config_option(bool& storage, string_view category, string_view name, string_view description) { return {category, name, description, &bool_neg_meta, &storage}; } config_option make_us_resolution_config_option(size_t& storage, string_view category, string_view name, string_view description) { return {category, name, description, &us_res_meta, &storage}; } config_option make_ms_resolution_config_option(size_t& storage, string_view category, string_view name, string_view description) { return {category, name, description, &ms_res_meta, &storage}; } } // namespace caf <commit_msg>Fix conversion warning<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/make_config_option.hpp" #include "caf/config_value.hpp" #include "caf/optional.hpp" #define DEFAULT_META(type) \ config_option::meta_state type##_meta_state { \ check_impl<type>, store_impl<type>, get_impl<type>, \ detail::type_name<type>() \ }; \ using std::string; namespace caf { namespace { using meta_state = config_option::meta_state; template <class T> error check_impl(const config_value& x) { if (holds_alternative<T>(x)) return none; return make_error(pec::type_mismatch); } template <class T> void store_impl(void* ptr, const config_value& x) { CAF_ASSERT(ptr != nullptr); *static_cast<T*>(ptr) = get<T>(x); } template <class T> config_value get_impl(const void* ptr) { CAF_ASSERT(ptr != nullptr); return config_value{*static_cast<const T*>(ptr)}; } error bool_check(const config_value& x) { if (holds_alternative<bool>(x)) return none; return make_error(pec::type_mismatch); } void bool_store(void* ptr, const config_value& x) { *static_cast<bool*>(ptr) = get<bool>(x); } void bool_store_neg(void* ptr, const config_value& x) { *static_cast<bool*>(ptr) = !get<bool>(x); } config_value bool_get(const void* ptr) { return config_value{*static_cast<const bool*>(ptr)}; } config_value bool_get_neg(const void* ptr) { return config_value{!*static_cast<const bool*>(ptr)}; } meta_state bool_neg_meta{bool_check, bool_store_neg, bool_get_neg, detail::type_name<bool>()}; meta_state us_res_meta{ [](const config_value& x) -> error { if (holds_alternative<timespan>(x)) return none; return make_error(pec::type_mismatch); }, [](void* ptr, const config_value& x) { *static_cast<size_t*>(ptr) = static_cast<size_t>(get<timespan>(x).count()) / 1000; }, [](const void* ptr) -> config_value { auto ival = static_cast<int64_t>(*static_cast<const size_t*>(ptr)); timespan val{ival / 1000}; return config_value{val}; }, detail::type_name<timespan>() }; meta_state ms_res_meta{ [](const config_value& x) -> error { if (holds_alternative<timespan>(x)) return none; return make_error(pec::type_mismatch); }, [](void* ptr, const config_value& x) { *static_cast<size_t*>(ptr) = get<timespan>(x).count() / 1000000; }, [](const void* ptr) -> config_value { auto ival = static_cast<int64_t>(*static_cast<const size_t*>(ptr)); timespan val{ival / 1000000}; return config_value{val}; }, detail::type_name<timespan>() }; } // namespace namespace detail { DEFAULT_META(atom_value); DEFAULT_META(size_t); DEFAULT_META(string); config_option::meta_state bool_meta_state{ bool_check, bool_store, bool_get, detail::type_name<bool>() }; } // namespace detail config_option make_negated_config_option(bool& storage, string_view category, string_view name, string_view description) { return {category, name, description, &bool_neg_meta, &storage}; } config_option make_us_resolution_config_option(size_t& storage, string_view category, string_view name, string_view description) { return {category, name, description, &us_res_meta, &storage}; } config_option make_ms_resolution_config_option(size_t& storage, string_view category, string_view name, string_view description) { return {category, name, description, &ms_res_meta, &storage}; } } // namespace caf <|endoftext|>
<commit_before>/* kopeteplugindataobject.cpp - Kopete Plugin Data Object Copyright (c) 2003-2005 by Olivier Goffart <ogoffart @ kde.org> Copyright (c) 2003 by Martijn Klingens <klingens@kde.org> Copyright (c) 2004 by Richard Smith <kde@metafoo.co.uk> Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "kopetecontactlistelement.h" #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include "kopeteplugin.h" namespace Kopete { class ContactListElement::Private { public: QMap<QString, QMap<QString, QString> > pluginData; QMap<ContactListElement::IconState, QString> icons; bool useCustomIcon; }; ContactListElement::ContactListElement( QObject *parent ) : QObject( parent ) { d = new Private; 0 d->useCustomIcon = false; #if 0 //TODO connect( Kopete::Global::onlineStatusIconCache(), SIGNAL( iconsChanged() ), SIGNAL( iconAppearanceChanged() ) ); #endif } ContactListElement::~ContactListElement() { delete d; } void ContactListElement::setPluginData( Plugin *plugin, const QMap<QString, QString> &pluginData ) { if ( pluginData.isEmpty() ) { d->pluginData.remove( plugin->pluginId() ); return; } d->pluginData[ plugin->pluginId() ] = pluginData; emit pluginDataChanged(); } void ContactListElement::setPluginData( Plugin *p, const QString &key, const QString &value ) { d->pluginData[ p->pluginId() ][ key ] = value; emit pluginDataChanged(); } QMap<QString, QString> ContactListElement::pluginData( Plugin *plugin ) const { if ( !d->pluginData.contains( plugin->pluginId() ) ) return QMap<QString, QString>(); return d->pluginData[ plugin->pluginId() ]; } QString ContactListElement::pluginData( Plugin *plugin, const QString &key ) const { if ( !d->pluginData.contains( plugin->pluginId() ) || !d->pluginData[ plugin->pluginId() ].contains( key ) ) return QString::null; return d->pluginData[ plugin->pluginId() ][ key ]; } const QList<QDomElement> ContactListElement::toXML() { QDomDocument pluginData; QList<QDomElement> pluginNodes; pluginData.appendChild( pluginData.createElement( QString::fromLatin1( "plugin-data" ) ) ); if ( !d->pluginData.isEmpty() ) { QMap<QString, QMap<QString, QString> >::ConstIterator pluginIt; for ( pluginIt = d->pluginData.begin(); pluginIt != d->pluginData.end(); ++pluginIt ) { QDomElement pluginElement = pluginData.createElement( QString::fromLatin1( "plugin-data" ) ); pluginElement.setAttribute( QString::fromLatin1( "plugin-id" ), pluginIt.key() ); QMap<QString, QString>::ConstIterator it; for ( it = pluginIt.value().begin(); it != pluginIt.value().end(); ++it ) { QDomElement pluginDataField = pluginData.createElement( QString::fromLatin1( "plugin-data-field" ) ); pluginDataField.setAttribute( QString::fromLatin1( "key" ), it.key() ); pluginDataField.appendChild( pluginData.createTextNode( it.value() ) ); pluginElement.appendChild( pluginDataField ); } pluginData.documentElement().appendChild( pluginElement ); pluginNodes.append( pluginElement ); } } if ( !d->icons.isEmpty() ) { QDomElement iconsElement = pluginData.createElement( QString::fromLatin1( "custom-icons" ) ); iconsElement.setAttribute( QString::fromLatin1( "use" ), d->useCustomIcon ? QString::fromLatin1( "1" ) : QString::fromLatin1( "0" ) ); for ( QMap<IconState, QString >::ConstIterator it = d->icons.begin(); it != d->icons.end(); ++it ) { QDomElement iconElement = pluginData.createElement( QString::fromLatin1( "icon" ) ); QString stateStr; switch ( it.key() ) { case Open: stateStr = QString::fromLatin1( "open" ); break; case Closed: stateStr = QString::fromLatin1( "closed" ); break; case Online: stateStr = QString::fromLatin1( "online" ); break; case Away: stateStr = QString::fromLatin1( "away" ); break; case Offline: stateStr = QString::fromLatin1( "offline" ); break; case Unknown: stateStr = QString::fromLatin1( "unknown" ); break; case None: default: stateStr = QString::fromLatin1( "none" ); break; } iconElement.setAttribute( QString::fromLatin1( "state" ), stateStr ); iconElement.appendChild( pluginData.createTextNode( it.value() ) ); iconsElement.appendChild( iconElement ); } pluginData.documentElement().appendChild( iconsElement ); pluginNodes.append( iconsElement ); } return pluginNodes; } bool ContactListElement::fromXML( const QDomElement& element ) { if ( element.tagName() == QString::fromLatin1( "plugin-data" ) ) { QMap<QString, QString> pluginData; QString pluginId = element.attribute( QString::fromLatin1( "plugin-id" ), QString::null ); //in kopete 0.6 the AIM protocol was called OSCAR if ( pluginId == QString::fromLatin1( "OscarProtocol" ) ) pluginId = QString::fromLatin1( "AIMProtocol" ); QDomNode field = element.firstChild(); while( !field.isNull() ) { QDomElement fieldElement = field.toElement(); if ( fieldElement.tagName() == QString::fromLatin1( "plugin-data-field" ) ) { pluginData.insert( fieldElement.attribute( QString::fromLatin1( "key" ), QString::fromLatin1( "undefined-key" ) ), fieldElement.text() ); } field = field.nextSibling(); } d->pluginData.insert( pluginId, pluginData ); } else if ( element.tagName() == QString::fromLatin1( "custom-icons" ) ) { d->useCustomIcon= element.attribute( QString::fromLatin1( "use" ), QString::fromLatin1( "1" ) ) == QString::fromLatin1( "1" ); QDomNode ic = element.firstChild(); while( !ic.isNull() ) { QDomElement iconElement = ic.toElement(); if ( iconElement.tagName() == QString::fromLatin1( "icon" ) ) { QString stateStr = iconElement.attribute( QString::fromLatin1( "state" ), QString::null ); QString icon = iconElement.text(); IconState state = None; if ( stateStr == QString::fromLatin1( "open" ) ) state = Open; if ( stateStr == QString::fromLatin1( "closed" ) ) state = Closed; if ( stateStr == QString::fromLatin1( "online" ) ) state = Online; if ( stateStr == QString::fromLatin1( "offline" ) ) state = Offline; if ( stateStr == QString::fromLatin1( "away" ) ) state = Away; if ( stateStr == QString::fromLatin1( "unknown" ) ) state = Unknown; d->icons[ state ] = icon; } ic = ic.nextSibling(); } } else { return false; } return true; } QString ContactListElement::icon( ContactListElement::IconState state ) const { if ( d->icons.contains( state ) ) return d->icons[state]; return d->icons[ None ]; } void ContactListElement::setIcon( const QString& icon , ContactListElement::IconState state ) { if ( icon.isNull() ) d->icons.remove( state ); else d->icons[ state ] = icon; emit iconChanged( state, icon ); emit iconAppearanceChanged(); } bool ContactListElement::useCustomIcon() const { return d->useCustomIcon; } void ContactListElement::setUseCustomIcon( bool useCustomIcon ) { if ( d->useCustomIcon != useCustomIcon ) { d->useCustomIcon = useCustomIcon; emit useCustomIconChanged( useCustomIcon ); } } } //END namespace Kopete #include "kopetecontactlistelement.moc" <commit_msg>SVN_SILENT: Fix compilation<commit_after>/* kopeteplugindataobject.cpp - Kopete Plugin Data Object Copyright (c) 2003-2005 by Olivier Goffart <ogoffart @ kde.org> Copyright (c) 2003 by Martijn Klingens <klingens@kde.org> Copyright (c) 2004 by Richard Smith <kde@metafoo.co.uk> Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "kopetecontactlistelement.h" #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include "kopeteplugin.h" namespace Kopete { class ContactListElement::Private { public: QMap<QString, QMap<QString, QString> > pluginData; QMap<ContactListElement::IconState, QString> icons; bool useCustomIcon; }; ContactListElement::ContactListElement( QObject *parent ) : QObject( parent ) { d = new Private; d->useCustomIcon = false; #if 0 //TODO connect( Kopete::Global::onlineStatusIconCache(), SIGNAL( iconsChanged() ), SIGNAL( iconAppearanceChanged() ) ); #endif } ContactListElement::~ContactListElement() { delete d; } void ContactListElement::setPluginData( Plugin *plugin, const QMap<QString, QString> &pluginData ) { if ( pluginData.isEmpty() ) { d->pluginData.remove( plugin->pluginId() ); return; } d->pluginData[ plugin->pluginId() ] = pluginData; emit pluginDataChanged(); } void ContactListElement::setPluginData( Plugin *p, const QString &key, const QString &value ) { d->pluginData[ p->pluginId() ][ key ] = value; emit pluginDataChanged(); } QMap<QString, QString> ContactListElement::pluginData( Plugin *plugin ) const { if ( !d->pluginData.contains( plugin->pluginId() ) ) return QMap<QString, QString>(); return d->pluginData[ plugin->pluginId() ]; } QString ContactListElement::pluginData( Plugin *plugin, const QString &key ) const { if ( !d->pluginData.contains( plugin->pluginId() ) || !d->pluginData[ plugin->pluginId() ].contains( key ) ) return QString::null; return d->pluginData[ plugin->pluginId() ][ key ]; } const QList<QDomElement> ContactListElement::toXML() { QDomDocument pluginData; QList<QDomElement> pluginNodes; pluginData.appendChild( pluginData.createElement( QString::fromLatin1( "plugin-data" ) ) ); if ( !d->pluginData.isEmpty() ) { QMap<QString, QMap<QString, QString> >::ConstIterator pluginIt; for ( pluginIt = d->pluginData.begin(); pluginIt != d->pluginData.end(); ++pluginIt ) { QDomElement pluginElement = pluginData.createElement( QString::fromLatin1( "plugin-data" ) ); pluginElement.setAttribute( QString::fromLatin1( "plugin-id" ), pluginIt.key() ); QMap<QString, QString>::ConstIterator it; for ( it = pluginIt.value().begin(); it != pluginIt.value().end(); ++it ) { QDomElement pluginDataField = pluginData.createElement( QString::fromLatin1( "plugin-data-field" ) ); pluginDataField.setAttribute( QString::fromLatin1( "key" ), it.key() ); pluginDataField.appendChild( pluginData.createTextNode( it.value() ) ); pluginElement.appendChild( pluginDataField ); } pluginData.documentElement().appendChild( pluginElement ); pluginNodes.append( pluginElement ); } } if ( !d->icons.isEmpty() ) { QDomElement iconsElement = pluginData.createElement( QString::fromLatin1( "custom-icons" ) ); iconsElement.setAttribute( QString::fromLatin1( "use" ), d->useCustomIcon ? QString::fromLatin1( "1" ) : QString::fromLatin1( "0" ) ); for ( QMap<IconState, QString >::ConstIterator it = d->icons.begin(); it != d->icons.end(); ++it ) { QDomElement iconElement = pluginData.createElement( QString::fromLatin1( "icon" ) ); QString stateStr; switch ( it.key() ) { case Open: stateStr = QString::fromLatin1( "open" ); break; case Closed: stateStr = QString::fromLatin1( "closed" ); break; case Online: stateStr = QString::fromLatin1( "online" ); break; case Away: stateStr = QString::fromLatin1( "away" ); break; case Offline: stateStr = QString::fromLatin1( "offline" ); break; case Unknown: stateStr = QString::fromLatin1( "unknown" ); break; case None: default: stateStr = QString::fromLatin1( "none" ); break; } iconElement.setAttribute( QString::fromLatin1( "state" ), stateStr ); iconElement.appendChild( pluginData.createTextNode( it.value() ) ); iconsElement.appendChild( iconElement ); } pluginData.documentElement().appendChild( iconsElement ); pluginNodes.append( iconsElement ); } return pluginNodes; } bool ContactListElement::fromXML( const QDomElement& element ) { if ( element.tagName() == QString::fromLatin1( "plugin-data" ) ) { QMap<QString, QString> pluginData; QString pluginId = element.attribute( QString::fromLatin1( "plugin-id" ), QString::null ); //in kopete 0.6 the AIM protocol was called OSCAR if ( pluginId == QString::fromLatin1( "OscarProtocol" ) ) pluginId = QString::fromLatin1( "AIMProtocol" ); QDomNode field = element.firstChild(); while( !field.isNull() ) { QDomElement fieldElement = field.toElement(); if ( fieldElement.tagName() == QString::fromLatin1( "plugin-data-field" ) ) { pluginData.insert( fieldElement.attribute( QString::fromLatin1( "key" ), QString::fromLatin1( "undefined-key" ) ), fieldElement.text() ); } field = field.nextSibling(); } d->pluginData.insert( pluginId, pluginData ); } else if ( element.tagName() == QString::fromLatin1( "custom-icons" ) ) { d->useCustomIcon= element.attribute( QString::fromLatin1( "use" ), QString::fromLatin1( "1" ) ) == QString::fromLatin1( "1" ); QDomNode ic = element.firstChild(); while( !ic.isNull() ) { QDomElement iconElement = ic.toElement(); if ( iconElement.tagName() == QString::fromLatin1( "icon" ) ) { QString stateStr = iconElement.attribute( QString::fromLatin1( "state" ), QString::null ); QString icon = iconElement.text(); IconState state = None; if ( stateStr == QString::fromLatin1( "open" ) ) state = Open; if ( stateStr == QString::fromLatin1( "closed" ) ) state = Closed; if ( stateStr == QString::fromLatin1( "online" ) ) state = Online; if ( stateStr == QString::fromLatin1( "offline" ) ) state = Offline; if ( stateStr == QString::fromLatin1( "away" ) ) state = Away; if ( stateStr == QString::fromLatin1( "unknown" ) ) state = Unknown; d->icons[ state ] = icon; } ic = ic.nextSibling(); } } else { return false; } return true; } QString ContactListElement::icon( ContactListElement::IconState state ) const { if ( d->icons.contains( state ) ) return d->icons[state]; return d->icons[ None ]; } void ContactListElement::setIcon( const QString& icon , ContactListElement::IconState state ) { if ( icon.isNull() ) d->icons.remove( state ); else d->icons[ state ] = icon; emit iconChanged( state, icon ); emit iconAppearanceChanged(); } bool ContactListElement::useCustomIcon() const { return d->useCustomIcon; } void ContactListElement::setUseCustomIcon( bool useCustomIcon ) { if ( d->useCustomIcon != useCustomIcon ) { d->useCustomIcon = useCustomIcon; emit useCustomIconChanged( useCustomIcon ); } } } //END namespace Kopete #include "kopetecontactlistelement.moc" <|endoftext|>
<commit_before>#pragma once #include <algorithm> #include "linesearch.h" #include "linesearch_step.hpp" #include "linesearch_cubic.hpp" namespace ncv { namespace optimize { /// /// \brief zoom-in in the bracketed interval, /// see "Numerical optimization", Nocedal & Wright, 2nd edition, p.60 /// template < typename tstep, typename tscalar = typename tstep::tscalar, typename tsize = typename tstep::tsize > tstep ls_zoom( const ls_strategy strategy, const tscalar c1, const tscalar c2, const tstep& step0, tstep steplo, tstep stephi, const tsize max_iters = 64) { tstep stept(step0); tscalar t; for ( size_t i = 1; i <= max_iters && std::fabs(steplo.alpha() - stephi.alpha()) > stept.minimum(); i ++) { const tscalar tmin = std::min(steplo.alpha(), stephi.alpha()); const tscalar tmax = std::max(steplo.alpha(), stephi.alpha()); const tscalar teps = stept.minimum(); switch (strategy) { case ls_strategy::interpolation_cubic: t = ls_cubic(steplo, stephi); if (std::isfinite(t) && tmin + teps < t && t < tmax - teps) { break; } // fallthrough! case ls_strategy::interpolation_bisection: default: t = 0.33 * tmin + 0.67 * tmax; break; } // check sufficient decrease if (!stept.reset_with_grad(t)) { return step0; } if (!stept.has_armijo(c1) || stept.phi() >= steplo.phi()) { stephi = stept; } // check curvature else { if (stept.has_strong_wolfe(c2)) { return stept.setup(); } if (stept.gphi() * (stephi.alpha() - steplo.alpha()) >= 0) { stephi = steplo; } steplo = stept; } } // NOK, give up return std::min(stept, step0); } } } <commit_msg>simplify bisection<commit_after>#pragma once #include <algorithm> #include "linesearch.h" #include "linesearch_step.hpp" #include "linesearch_cubic.hpp" namespace ncv { namespace optimize { /// /// \brief zoom-in in the bracketed interval, /// see "Numerical optimization", Nocedal & Wright, 2nd edition, p.60 /// template < typename tstep, typename tscalar = typename tstep::tscalar, typename tsize = typename tstep::tsize > tstep ls_zoom( const ls_strategy strategy, const tscalar c1, const tscalar c2, const tstep& step0, tstep steplo, tstep stephi, const tsize max_iters = 64) { tstep stept(step0); tscalar t; for ( size_t i = 1; i <= max_iters && std::fabs(steplo.alpha() - stephi.alpha()) > stept.minimum(); i ++) { const tscalar tmin = std::min(steplo.alpha(), stephi.alpha()); const tscalar tmax = std::max(steplo.alpha(), stephi.alpha()); const tscalar teps = stept.minimum(); switch (strategy) { case ls_strategy::interpolation_cubic: t = ls_cubic(steplo, stephi); if (std::isfinite(t) && tmin + teps < t && t < tmax - teps) { break; } // fallthrough! case ls_strategy::interpolation_bisection: default: t = (steplo.alpha() + stephi.alpha()) / 2; break; } // check sufficient decrease if (!stept.reset_with_grad(t)) { return step0; } if (!stept.has_armijo(c1) || stept.phi() >= steplo.phi()) { stephi = stept; } // check curvature else { if (stept.has_strong_wolfe(c2)) { return stept.setup(); } if (stept.gphi() * (stephi.alpha() - steplo.alpha()) >= 0) { stephi = steplo; } steplo = stept; } } // NOK, give up return std::min(stept, step0); } } } <|endoftext|>
<commit_before>/** * @file reader.hpp * @author Robin Dietrich <me (at) invokr (dot) org> * @version 1.0 * * @par License * Alice Replay Parser * Copyright 2014 Robin Dietrich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _DOTA_READER_HPP_ #define _DOTA_READER_HPP_ #include <fstream> #include <string> #include <utility> #include <type_traits> #include <alice/exception.hpp> #include <alice/handler.hpp> #include <alice/gamestate.hpp> #include <alice/config.hpp> /// Defines the first 7 bytes to check as the header ID #define DOTA_DEMHEADERID "PBUFDEM" /// Defines a fixed amount of memory to allocate for the internal buffer #define DOTA_BUFSIZE 0x60000 namespace dota { /// @defgroup EXCEPTIONS Exceptions /// @{ /// Thrown when the file in inaccesible (e.g. wrong permissions or wrong path) CREATE_EXCEPTION( demFileNotAccessible, "Unable to open file." ) /// Thrown when the file has an unlikely small file size CREATE_EXCEPTION( demFileTooSmall, "Filesize is too small." ) /// Thrown when the header of the file is not matching #DOTA_DEMHEADERID CREATE_EXCEPTION( demHeaderMismatch, "Header ID is not matching." ) /// Thrown if the end of the file is reached before an operation is completed CREATE_EXCEPTION( demUnexpectedEOF, "Unexpected end of file." ) /// Thrown when the file is likely corrupted CREATE_EXCEPTION( demCorrupted, "Demo file appears to be corruped." ) /// Thrown when snappy fails to decompress content CREATE_EXCEPTION( demInvalidCompression, "Data uncompression failed." ) /// Thrown when protobuf fails to parse a message CREATE_EXCEPTION( demParsingError, "Parsing protouf message failed." ) /// Thrown when the size of a single messages would cause a buffer overflow CREATE_EXCEPTION( demMessageToBig, "Messagesize is to big." ) /// @} /// @defgroup CORE Core /// @{ /** This class reads all messages for a given replay and reports them to the registered handlers and the gamestate. */ class reader { public: /** Reading status, announces when certain parts of the replay become available */ enum status { REPLAY_START = 0, // Parsing started REPLAY_FLATTABLES, // Flattables are available REPLAY_FINISH // Parsing finished }; /** Constructor, takes path to the replay as a first argument. */ reader(const std::string& file); /** Destructor, closed file and resets handler */ ~reader() { if (fstream.is_open()) fstream.close(); delete h; delete[] buffer; delete[] bufferCmp; } /** Returns pointer to handler */ handler_t* getHandler() { return h; } /** Returns reference to gamestate */ gamestate& getState() { return db; } /** Reads a single message */ void readMessage(bool skip = false); /** Returns true if there are still messages left to read */ inline bool good() { return (fstream.good() && (state != 2)); } /** Reads until the next tick and returns */ inline void readUntilNextTick() { const uint32_t tTick = cTick; while (cTick == tTick && good()) { readMessage(); } } /** Reads all messages and returns */ inline void readAll() { while (good()) { readMessage(); } } /** Returns current tick */ inline uint32_t getTick() { return cTick; } private: /** File header for verification purposes */ struct demheader_t { char headerid[ 8 ]; // needs to equal DOTA_HEADERID int32_t offset; }; /** Path to file */ std::string file; /** Filestream for the demo file in question */ std::ifstream fstream; /** Parsing state: 0 = normal, 1 = STOP reached, 2 = finished */ uint8_t state; /** Equals the last tick read */ uint32_t cTick; /** Buffer for messages, reused to omit calling new for every message */ char* buffer; /** Buffer the uncompressed messages, reused to omit calling new for every message */ char* bufferCmp; /** The handler object for this reader */ handler_t* h; /** Initialized in the reader to make sure a valid gamestate is available for all accessors */ gamestate db; /** Private copy constructor, dont allow copying */ reader(const reader&) = delete; /** Reads single 32 bit integer from the file stream */ int32_t readVarInt(std::ifstream &stream, const std::string& file); /** Reads single 32 bit integer from a string */ int32_t readVarInt(stringWrapper &s, const std::string& file); /** Registers all known types with their object counterparts */ void registerTypes(); /** * Directly returns a callback object from the data provided. * * MSVC chokes on the resolution of the return type if we specify it correctly. * To fix this, we provide if with the fixed return type of msgDem. This works * because currently all protobuf objects forwarded to the handler have the same * callback signature. * * This function is definitly broken for entities though. */ template <typename HandlerType, typename Object> typename std::remove_pointer<handlerCbType(msgDem)>::type getCallbackObject(stringWrapper str, uint32_t tick) { Object* msg = new Object; if (!msg->ParseFromArray(str.str, str.size)) BOOST_THROW_EXCEPTION((handlerParserError())); typedef typename std::remove_pointer<typename handler_t::type<HandlerType::id>::callbackObj_t>::type cbObj; return cbObj(msg, tick, 0); } /** Forwards all entries in the message as specified type */ template <typename Type> void forwardMessageContainer(stringWrapper str, uint32_t tick) { while (str.size) { uint32_t type = readVarInt(str, file); uint32_t size = readVarInt(str, file); if (size > str.size) { BOOST_THROW_EXCEPTION((demUnexpectedEOF() << EArg<1>::info(file) << EArgT<2, uint32_t>::info(str.size) << EArgT<3, uint32_t>::info(size) << EArgT<4, uint32_t>::info(type) )); } // remove data from the original buffer stringWrapper message{str.str, size}; str.str = str.str+size; str.size = (str.size - size); // directly parse entities to omit calling the handler to often if (std::is_same<Type, msgNet>{}) { switch (type) { case svc_PacketEntities: { auto e = getCallbackObject<msgNet, CSVCMsg_PacketEntities>(std::move(message), tick); db.handleEntity(&e); } break; case svc_ServerInfo: { auto e = getCallbackObject<msgNet, CSVCMsg_ServerInfo>(std::move(message), tick); db.handleServerInfo(&e); } break; case svc_SendTable: { auto e = getCallbackObject<msgNet, CSVCMsg_SendTable>(std::move(message), tick); db.handleSendTable(&e); } break; case svc_CreateStringTable: { auto e = getCallbackObject<msgNet, CSVCMsg_CreateStringTable>(std::move(message), tick); db.handleCreateStringtable(&e); } break; case svc_UpdateStringTable: { auto e = getCallbackObject<msgNet, CSVCMsg_UpdateStringTable>(std::move(message), tick); db.handleUpdateStringtable(&e); } break; default: h->forward<Type>(type, std::move(message), tick); } } else { h->forward<Type>(type, std::move(message), tick); } } } /** Handle packets */ inline void handlePacket(handlerCbType(msgDem) msg) { CDemoPacket* m = msg->get<CDemoPacket>(); const std::string &data = m->data(); forwardMessageContainer<msgNet>(stringWrapper{data.c_str(), data.size()}, msg->tick); // forward as Net Message } /** Handle user message */ inline void handleUserMessage(handlerCbType(msgNet) msg) { CSVCMsg_UserMessage* m = msg->get<CSVCMsg_UserMessage>(); const std::string &data = m->msg_data(); h->forward<msgUser>(static_cast<uint32_t>(m->msg_type()), stringWrapper{data.c_str(), data.size()}, msg->tick); } /** Handle send tables forwarded from DEM */ inline void handleSendTablesDem(handlerCbType(msgDem) msg) { CDemoSendTables* m = msg->get<CDemoSendTables>(); const std::string &data = m->data(); forwardMessageContainer<msgNet>(stringWrapper{data.c_str(), data.size()}, msg->tick); // forward as Net Message } }; /// @} } #endif /* _DOTA_READER_HPP_ */<commit_msg>catch user message in reader<commit_after>/** * @file reader.hpp * @author Robin Dietrich <me (at) invokr (dot) org> * @version 1.0 * * @par License * Alice Replay Parser * Copyright 2014 Robin Dietrich * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _DOTA_READER_HPP_ #define _DOTA_READER_HPP_ #include <fstream> #include <string> #include <utility> #include <type_traits> #include <alice/exception.hpp> #include <alice/handler.hpp> #include <alice/gamestate.hpp> #include <alice/config.hpp> /// Defines the first 7 bytes to check as the header ID #define DOTA_DEMHEADERID "PBUFDEM" /// Defines a fixed amount of memory to allocate for the internal buffer #define DOTA_BUFSIZE 0x60000 namespace dota { /// @defgroup EXCEPTIONS Exceptions /// @{ /// Thrown when the file in inaccesible (e.g. wrong permissions or wrong path) CREATE_EXCEPTION( demFileNotAccessible, "Unable to open file." ) /// Thrown when the file has an unlikely small file size CREATE_EXCEPTION( demFileTooSmall, "Filesize is too small." ) /// Thrown when the header of the file is not matching #DOTA_DEMHEADERID CREATE_EXCEPTION( demHeaderMismatch, "Header ID is not matching." ) /// Thrown if the end of the file is reached before an operation is completed CREATE_EXCEPTION( demUnexpectedEOF, "Unexpected end of file." ) /// Thrown when the file is likely corrupted CREATE_EXCEPTION( demCorrupted, "Demo file appears to be corruped." ) /// Thrown when snappy fails to decompress content CREATE_EXCEPTION( demInvalidCompression, "Data uncompression failed." ) /// Thrown when protobuf fails to parse a message CREATE_EXCEPTION( demParsingError, "Parsing protouf message failed." ) /// Thrown when the size of a single messages would cause a buffer overflow CREATE_EXCEPTION( demMessageToBig, "Messagesize is to big." ) /// @} /// @defgroup CORE Core /// @{ /** This class reads all messages for a given replay and reports them to the registered handlers and the gamestate. */ class reader { public: /** Reading status, announces when certain parts of the replay become available */ enum status { REPLAY_START = 0, // Parsing started REPLAY_FLATTABLES, // Flattables are available REPLAY_FINISH // Parsing finished }; /** Constructor, takes path to the replay as a first argument. */ reader(const std::string& file); /** Destructor, closed file and resets handler */ ~reader() { if (fstream.is_open()) fstream.close(); delete h; delete[] buffer; delete[] bufferCmp; } /** Returns pointer to handler */ handler_t* getHandler() { return h; } /** Returns reference to gamestate */ gamestate& getState() { return db; } /** Reads a single message */ void readMessage(bool skip = false); /** Returns true if there are still messages left to read */ inline bool good() { return (fstream.good() && (state != 2)); } /** Reads until the next tick and returns */ inline void readUntilNextTick() { const uint32_t tTick = cTick; while (cTick == tTick && good()) { readMessage(); } } /** Reads all messages and returns */ inline void readAll() { while (good()) { readMessage(); } } /** Returns current tick */ inline uint32_t getTick() { return cTick; } private: /** File header for verification purposes */ struct demheader_t { char headerid[ 8 ]; // needs to equal DOTA_HEADERID int32_t offset; }; /** Path to file */ std::string file; /** Filestream for the demo file in question */ std::ifstream fstream; /** Parsing state: 0 = normal, 1 = STOP reached, 2 = finished */ uint8_t state; /** Equals the last tick read */ uint32_t cTick; /** Buffer for messages, reused to omit calling new for every message */ char* buffer; /** Buffer the uncompressed messages, reused to omit calling new for every message */ char* bufferCmp; /** The handler object for this reader */ handler_t* h; /** Initialized in the reader to make sure a valid gamestate is available for all accessors */ gamestate db; /** Private copy constructor, dont allow copying */ reader(const reader&) = delete; /** Reads single 32 bit integer from the file stream */ int32_t readVarInt(std::ifstream &stream, const std::string& file); /** Reads single 32 bit integer from a string */ int32_t readVarInt(stringWrapper &s, const std::string& file); /** Registers all known types with their object counterparts */ void registerTypes(); /** * Directly returns a callback object from the data provided. * * MSVC chokes on the resolution of the return type if we specify it correctly. * To fix this, we provide if with the fixed return type of msgDem. This works * because currently all protobuf objects forwarded to the handler have the same * callback signature. * * Returning by value here is a hack that is possible because the compiler optimizes * this function in a way that, instead of creating a copy, the original value is used. * The destructor is therefor triggered when the value leaves the return scope. * * @todo: Check if all recent compilers support this. * Works on MSVC >= 2013 / Clang >= 3.2 / G++ >= 4.7 so far. */ template <typename HandlerType, typename Object> inline typename std::remove_pointer<handlerCbType(msgDem)>::type getCallbackObject(stringWrapper str, uint32_t tick) { Object* msg = new Object; if (!msg->ParseFromArray(str.str, str.size)) BOOST_THROW_EXCEPTION((handlerParserError())); typedef typename std::remove_pointer<typename handler_t::type<HandlerType::id>::callbackObj_t>::type cbObj; return cbObj(msg, tick, 0); } /** Forwards all entries in the message as specified type */ template <typename Type> void forwardMessageContainer(stringWrapper str, uint32_t tick) { while (str.size) { uint32_t type = readVarInt(str, file); uint32_t size = readVarInt(str, file); if (size > str.size) { BOOST_THROW_EXCEPTION((demUnexpectedEOF() << EArg<1>::info(file) << EArgT<2, uint32_t>::info(str.size) << EArgT<3, uint32_t>::info(size) << EArgT<4, uint32_t>::info(type) )); } // remove data from the original buffer stringWrapper message{str.str, size}; str.str = str.str+size; str.size = (str.size - size); // directly parse entities to omit calling the handler to often if (std::is_same<Type, msgNet>{}) { switch (type) { case svc_PacketEntities: { auto e = getCallbackObject<msgNet, CSVCMsg_PacketEntities>(std::move(message), tick); db.handleEntity(&e); } break; case svc_ServerInfo: { auto e = getCallbackObject<msgNet, CSVCMsg_ServerInfo>(std::move(message), tick); db.handleServerInfo(&e); } break; case svc_SendTable: { auto e = getCallbackObject<msgNet, CSVCMsg_SendTable>(std::move(message), tick); db.handleSendTable(&e); } break; case svc_CreateStringTable: { auto e = getCallbackObject<msgNet, CSVCMsg_CreateStringTable>(std::move(message), tick); db.handleCreateStringtable(&e); } break; case svc_UpdateStringTable: { auto e = getCallbackObject<msgNet, CSVCMsg_UpdateStringTable>(std::move(message), tick); db.handleUpdateStringtable(&e); } break; case svc_UserMessage: { auto e = getCallbackObject<msgNet, CSVCMsg_UserMessage>(std::move(message), tick); handleUserMessage(&e); } break; default: h->forward<Type>(type, std::move(message), tick); } } else { h->forward<Type>(type, std::move(message), tick); } } } /** Handle packets */ inline void handlePacket(handlerCbType(msgDem) msg) { CDemoPacket* m = msg->get<CDemoPacket>(); const std::string &data = m->data(); forwardMessageContainer<msgNet>(stringWrapper{data.c_str(), data.size()}, msg->tick); // forward as Net Message } /** Handle user message */ inline void handleUserMessage(handlerCbType(msgNet) msg) { CSVCMsg_UserMessage* m = msg->get<CSVCMsg_UserMessage>(); const std::string &data = m->msg_data(); h->forward<msgUser>(static_cast<uint32_t>(m->msg_type()), stringWrapper{data.c_str(), data.size()}, msg->tick); } /** Handle send tables forwarded from DEM */ inline void handleSendTablesDem(handlerCbType(msgDem) msg) { CDemoSendTables* m = msg->get<CDemoSendTables>(); const std::string &data = m->data(); forwardMessageContainer<msgNet>(stringWrapper{data.c_str(), data.size()}, msg->tick); // forward as Net Message } }; /// @} } #endif /* _DOTA_READER_HPP_ */<|endoftext|>
<commit_before>/** * Copyright (c) 2013, Timothy Stack * * 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 Timothy Stack 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 REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file ansi_scrubber.cc */ #include "config.h" #include <vector> #include "base/opt_util.hh" #include "view_curses.hh" #include "pcrepp/pcrepp.hh" #include "ansi_scrubber.hh" using namespace std; static pcrepp &ansi_regex() { static pcrepp retval("\x1b\\[([\\d=;\\?]*)([a-zA-Z])"); return retval; } void scrub_ansi_string(std::string &str, string_attrs_t &sa) { pcre_context_static<60> context; pcrepp & regex = ansi_regex(); pcre_input pi(str); replace(str.begin(), str.end(), '\0', ' '); while (regex.match(context, pi)) { pcre_context::capture_t *caps = context.all(); struct line_range lr; bool has_attrs = false; attr_t attrs = 0; auto bg = nonstd::optional<int>(); auto fg = nonstd::optional<int>(); auto role = nonstd::optional<int>(); size_t lpc; switch (pi.get_substr_start(&caps[2])[0]) { case 'm': for (lpc = caps[1].c_begin; lpc != string::npos && lpc < (size_t) caps[1].c_end;) { int ansi_code = 0; if (sscanf(&(str[lpc]), "%d", &ansi_code) == 1) { if (90 <= ansi_code && ansi_code <= 97) { ansi_code -= 60; attrs |= A_STANDOUT; } if (30 <= ansi_code && ansi_code <= 37) { fg = ansi_code - 30; } if (40 <= ansi_code && ansi_code <= 47) { bg = ansi_code - 40; } switch (ansi_code) { case 1: attrs |= A_BOLD; break; case 2: attrs |= A_DIM; break; case 4: attrs |= A_UNDERLINE; break; case 7: attrs |= A_REVERSE; break; } } lpc = str.find(';', lpc); if (lpc != string::npos) { lpc += 1; } } has_attrs = true; break; case 'C': { unsigned int spaces = 0; if (sscanf(&(str[caps[1].c_begin]), "%u", &spaces) == 1 && spaces > 0) { str.insert((unsigned long) caps[0].c_end, spaces, ' '); } break; } case 'H': { unsigned int row = 0, spaces = 0; if (sscanf(&(str[caps[1].c_begin]), "%u;%u", &row, &spaces) == 2 && spaces > 1) { int ispaces = spaces - 1; if (ispaces > caps[0].c_begin) { str.insert((unsigned long) caps[0].c_end, ispaces - caps[0].c_begin, ' '); } } break; } case 'O': { int role_int; if (sscanf(&(str[caps[1].c_begin]), "%d", &role_int) == 1) { if (role_int >= 0 && role_int < view_colors::VCR__MAX) { role = role_int; has_attrs = true; } } break; } } str.erase(str.begin() + caps[0].c_begin, str.begin() + caps[0].c_end); if (has_attrs) { for (auto rit = sa.rbegin(); rit != sa.rend(); rit++) { if (rit->sa_range.lr_end != -1) { break; } rit->sa_range.lr_end = caps[0].c_begin; } lr.lr_start = caps[0].c_begin; lr.lr_end = -1; if (attrs) { sa.emplace_back(lr, &view_curses::VC_STYLE, attrs); } role | [&lr, &sa](int r) { sa.emplace_back(lr, &view_curses::VC_ROLE, r); }; fg | [&lr, &sa](int color) { sa.emplace_back(lr, &view_curses::VC_FOREGROUND, color); }; bg | [&lr, &sa](int color) { sa.emplace_back(lr, &view_curses::VC_BACKGROUND, color); }; } pi.reset(str); } } void add_ansi_vars(std::map<std::string, std::string> &vars) { vars["ansi_csi"] = ANSI_CSI; vars["ansi_norm"] = ANSI_NORM; vars["ansi_bold"] = ANSI_BOLD_START; vars["ansi_underline"] = ANSI_UNDERLINE_START; vars["ansi_black"] = ANSI_COLOR(COLOR_BLACK); vars["ansi_red"] = ANSI_COLOR(COLOR_RED); vars["ansi_green"] = ANSI_COLOR(COLOR_GREEN); vars["ansi_yellow"] = ANSI_COLOR(COLOR_YELLOW); vars["ansi_blue"] = ANSI_COLOR(COLOR_BLUE); vars["ansi_magenta"] = ANSI_COLOR(COLOR_MAGENTA); vars["ansi_cyan"] = ANSI_COLOR(COLOR_CYAN); vars["ansi_white"] = ANSI_COLOR(COLOR_WHITE); } <commit_msg>[build] missing algo inc<commit_after>/** * Copyright (c) 2013, Timothy Stack * * 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 Timothy Stack 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 REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file ansi_scrubber.cc */ #include "config.h" #include <vector> #include <algorithm> #include "base/opt_util.hh" #include "view_curses.hh" #include "pcrepp/pcrepp.hh" #include "ansi_scrubber.hh" using namespace std; static pcrepp &ansi_regex() { static pcrepp retval("\x1b\\[([\\d=;\\?]*)([a-zA-Z])"); return retval; } void scrub_ansi_string(std::string &str, string_attrs_t &sa) { pcre_context_static<60> context; pcrepp & regex = ansi_regex(); pcre_input pi(str); replace(str.begin(), str.end(), '\0', ' '); while (regex.match(context, pi)) { pcre_context::capture_t *caps = context.all(); struct line_range lr; bool has_attrs = false; attr_t attrs = 0; auto bg = nonstd::optional<int>(); auto fg = nonstd::optional<int>(); auto role = nonstd::optional<int>(); size_t lpc; switch (pi.get_substr_start(&caps[2])[0]) { case 'm': for (lpc = caps[1].c_begin; lpc != string::npos && lpc < (size_t) caps[1].c_end;) { int ansi_code = 0; if (sscanf(&(str[lpc]), "%d", &ansi_code) == 1) { if (90 <= ansi_code && ansi_code <= 97) { ansi_code -= 60; attrs |= A_STANDOUT; } if (30 <= ansi_code && ansi_code <= 37) { fg = ansi_code - 30; } if (40 <= ansi_code && ansi_code <= 47) { bg = ansi_code - 40; } switch (ansi_code) { case 1: attrs |= A_BOLD; break; case 2: attrs |= A_DIM; break; case 4: attrs |= A_UNDERLINE; break; case 7: attrs |= A_REVERSE; break; } } lpc = str.find(';', lpc); if (lpc != string::npos) { lpc += 1; } } has_attrs = true; break; case 'C': { unsigned int spaces = 0; if (sscanf(&(str[caps[1].c_begin]), "%u", &spaces) == 1 && spaces > 0) { str.insert((unsigned long) caps[0].c_end, spaces, ' '); } break; } case 'H': { unsigned int row = 0, spaces = 0; if (sscanf(&(str[caps[1].c_begin]), "%u;%u", &row, &spaces) == 2 && spaces > 1) { int ispaces = spaces - 1; if (ispaces > caps[0].c_begin) { str.insert((unsigned long) caps[0].c_end, ispaces - caps[0].c_begin, ' '); } } break; } case 'O': { int role_int; if (sscanf(&(str[caps[1].c_begin]), "%d", &role_int) == 1) { if (role_int >= 0 && role_int < view_colors::VCR__MAX) { role = role_int; has_attrs = true; } } break; } } str.erase(str.begin() + caps[0].c_begin, str.begin() + caps[0].c_end); if (has_attrs) { for (auto rit = sa.rbegin(); rit != sa.rend(); rit++) { if (rit->sa_range.lr_end != -1) { break; } rit->sa_range.lr_end = caps[0].c_begin; } lr.lr_start = caps[0].c_begin; lr.lr_end = -1; if (attrs) { sa.emplace_back(lr, &view_curses::VC_STYLE, attrs); } role | [&lr, &sa](int r) { sa.emplace_back(lr, &view_curses::VC_ROLE, r); }; fg | [&lr, &sa](int color) { sa.emplace_back(lr, &view_curses::VC_FOREGROUND, color); }; bg | [&lr, &sa](int color) { sa.emplace_back(lr, &view_curses::VC_BACKGROUND, color); }; } pi.reset(str); } } void add_ansi_vars(std::map<std::string, std::string> &vars) { vars["ansi_csi"] = ANSI_CSI; vars["ansi_norm"] = ANSI_NORM; vars["ansi_bold"] = ANSI_BOLD_START; vars["ansi_underline"] = ANSI_UNDERLINE_START; vars["ansi_black"] = ANSI_COLOR(COLOR_BLACK); vars["ansi_red"] = ANSI_COLOR(COLOR_RED); vars["ansi_green"] = ANSI_COLOR(COLOR_GREEN); vars["ansi_yellow"] = ANSI_COLOR(COLOR_YELLOW); vars["ansi_blue"] = ANSI_COLOR(COLOR_BLUE); vars["ansi_magenta"] = ANSI_COLOR(COLOR_MAGENTA); vars["ansi_cyan"] = ANSI_COLOR(COLOR_CYAN); vars["ansi_white"] = ANSI_COLOR(COLOR_WHITE); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: indexentrysupplier_default.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2005-02-25 10:08:50 $ * * 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): _______________________________________ * * ************************************************************************/ #include <indexentrysupplier_default.hxx> #include <localedata.hxx> #include <i18nutil/unicode.hxx> #include <com/sun/star/i18n/CollatorOptions.hpp> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { IndexEntrySupplier_Unicode::IndexEntrySupplier_Unicode( const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& rxMSF ) : IndexEntrySupplier_Common(rxMSF) { implementationName = "com.sun.star.i18n.IndexEntrySupplier_Unicode"; index = new Index(collator); } IndexEntrySupplier_Unicode::~IndexEntrySupplier_Unicode() { delete index; } sal_Bool SAL_CALL IndexEntrySupplier_Unicode::loadAlgorithm( const lang::Locale& rLocale, const OUString& rAlgorithm, sal_Int32 collatorOptions ) throw (RuntimeException) { index->init(rLocale, rAlgorithm); return IndexEntrySupplier_Common::loadAlgorithm(rLocale, rAlgorithm, collatorOptions); } OUString SAL_CALL IndexEntrySupplier_Unicode::getIndexKey( const OUString& rIndexEntry, const OUString& rPhoneticEntry, const lang::Locale& rLocale ) throw (RuntimeException) { return index->getIndexDescription(getEntry(rIndexEntry, rPhoneticEntry, rLocale)); } sal_Int16 SAL_CALL IndexEntrySupplier_Unicode::compareIndexEntry( const OUString& rIndexEntry1, const OUString& rPhoneticEntry1, const lang::Locale& rLocale1, const OUString& rIndexEntry2, const OUString& rPhoneticEntry2, const lang::Locale& rLocale2 ) throw (RuntimeException) { sal_Int16 result = index->getIndexWeight(getEntry(rIndexEntry1, rPhoneticEntry1, rLocale1)) - index->getIndexWeight(getEntry(rIndexEntry2, rPhoneticEntry2, rLocale2)); if (result == 0) return IndexEntrySupplier_Common::compareIndexEntry( rIndexEntry1, rPhoneticEntry1, rLocale1, rIndexEntry2, rPhoneticEntry2, rLocale2); return result > 0 ? 1 : -1; } OUString SAL_CALL IndexEntrySupplier_Unicode::getIndexCharacter( const OUString& rIndexEntry, const lang::Locale& rLocale, const OUString& rAlgorithm ) throw (RuntimeException) { if (loadAlgorithm( rLocale, rAlgorithm, CollatorOptions::CollatorOptions_IGNORE_CASE)) return index->getIndexDescription(rIndexEntry); else return IndexEntrySupplier_Common::getIndexCharacter(rIndexEntry, rLocale, rAlgorithm); } IndexTable::IndexTable() { table = NULL; } IndexTable::~IndexTable() { if (table) free(table); } void IndexTable::init(sal_Unicode start_, sal_Unicode end_, IndexKey *keys, sal_Int16 key_count, Index *index) { start=start_; end=end_; table = (sal_uInt8*) malloc((end-start+1)*sizeof(sal_uInt8)); for (sal_Unicode i = start; i <= end; i++) { sal_Int16 j; for (j = 0; j < key_count; j++) { if (i == keys[j].key || index->compare(i, keys[j].key) == 0) { table[i-start] = j; break; } } if (j == key_count) table[i-start] = 0xFF; } } Index::Index(CollatorImpl *col) { collator = col; } sal_Int16 Index::compare(sal_Unicode c1, sal_Unicode c2) { return collator->compareString(OUString(&c1, 1), OUString(&c2, 1)); } sal_Int16 Index::getIndexWeight(const OUString& rIndexEntry) { sal_Unicode code = rIndexEntry[0]; for (sal_Int16 i = 0; i < table_count; i++) { if (tables[i].start <= code && code <= tables[i].end) return tables[i].table[code-tables[i].start]; } return 0xFF; } OUString Index::getIndexDescription(const OUString& rIndexEntry) { sal_Int16 wgt = getIndexWeight(rIndexEntry); if (wgt < MAX_KEYS) { if (keys[wgt].desc.getLength()) return keys[wgt].desc; else return OUString(&keys[wgt].key, 1); } return rIndexEntry.copy(0, 1); } #define LOCALE_EN lang::Locale(OUString::createFromAscii("en"), OUString(), OUString()) void Index::makeIndexKeys(const lang::Locale &rLocale, const OUString &algorithm) throw (RuntimeException) { OUString keyStr = LocaleData().getIndexKeysByAlgorithm(rLocale, algorithm); if (!keyStr.getLength()) { keyStr = LocaleData().getIndexKeysByAlgorithm(LOCALE_EN, LocaleData().getDefaultIndexAlgorithm(LOCALE_EN)); if (!keyStr) throw RuntimeException(); } sal_Int16 j = 0, len = keyStr.getLength(); for (sal_Int16 i = 0; i < len && j < MAX_KEYS; i++) { sal_Unicode curr = keyStr[i]; if (unicode::isWhiteSpace(curr)) continue; switch(curr) { case sal_Unicode('-'): if (j > 0 && i + 1 < len ) { for (curr = keyStr[++i]; j < MAX_KEYS && keys[j-1].key < curr; j++) { keys[j].key = keys[j-1].key+1; keys[j].desc = OUString(); } } else throw RuntimeException(); break; case sal_Unicode('('): if (j > 0) { sal_Int16 end = i+1; while (end < len && keyStr[end] != sal_Unicode(')')) end++; if (end >= len) // no found throw RuntimeException(); keys[j-1].desc = keyStr.copy(i+1, end-i-1); i=end+1; } else throw RuntimeException(); break; default: keys[j].key = curr; keys[j++].desc = OUString(); break; } } key_count = j; } void Index::init(const lang::Locale &rLocale, const OUString& algorithm) throw (RuntimeException) { makeIndexKeys(rLocale, algorithm); Sequence< UnicodeScript > scriptList = LocaleData().getUnicodeScripts( rLocale ); if (scriptList.getLength() == 0) { scriptList = LocaleData().getUnicodeScripts(LOCALE_EN); if (scriptList.getLength() == 0) throw RuntimeException(); } table_count = scriptList.getLength(); if (table_count > MAX_TABLES) throw RuntimeException(); collator->loadCollatorAlgorithm(algorithm, rLocale, CollatorOptions::CollatorOptions_IGNORE_CASE); sal_Int16 j=0; sal_Unicode start = unicode::getUnicodeScriptStart((UnicodeScript)0); sal_Unicode end = unicode::getUnicodeScriptEnd((UnicodeScript)0); for (sal_Int16 i= (scriptList[0] == (UnicodeScript)0) ? 1 : 0; i< scriptList.getLength(); i++) { if (unicode::getUnicodeScriptStart(scriptList[i]) != end+1) { tables[j++].init(start, end, keys, key_count, this); start = unicode::getUnicodeScriptStart(scriptList[i]); } end = unicode::getUnicodeScriptEnd(scriptList[i]); } tables[j++].init(start, end, keys, key_count, this); table_count = j; } } } } } <commit_msg>INTEGRATION: CWS ooo19126 (1.7.34); FILE MERGED 2005/09/05 17:47:38 rt 1.7.34.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: indexentrysupplier_default.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:09:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <indexentrysupplier_default.hxx> #include <localedata.hxx> #include <i18nutil/unicode.hxx> #include <com/sun/star/i18n/CollatorOptions.hpp> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { IndexEntrySupplier_Unicode::IndexEntrySupplier_Unicode( const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& rxMSF ) : IndexEntrySupplier_Common(rxMSF) { implementationName = "com.sun.star.i18n.IndexEntrySupplier_Unicode"; index = new Index(collator); } IndexEntrySupplier_Unicode::~IndexEntrySupplier_Unicode() { delete index; } sal_Bool SAL_CALL IndexEntrySupplier_Unicode::loadAlgorithm( const lang::Locale& rLocale, const OUString& rAlgorithm, sal_Int32 collatorOptions ) throw (RuntimeException) { index->init(rLocale, rAlgorithm); return IndexEntrySupplier_Common::loadAlgorithm(rLocale, rAlgorithm, collatorOptions); } OUString SAL_CALL IndexEntrySupplier_Unicode::getIndexKey( const OUString& rIndexEntry, const OUString& rPhoneticEntry, const lang::Locale& rLocale ) throw (RuntimeException) { return index->getIndexDescription(getEntry(rIndexEntry, rPhoneticEntry, rLocale)); } sal_Int16 SAL_CALL IndexEntrySupplier_Unicode::compareIndexEntry( const OUString& rIndexEntry1, const OUString& rPhoneticEntry1, const lang::Locale& rLocale1, const OUString& rIndexEntry2, const OUString& rPhoneticEntry2, const lang::Locale& rLocale2 ) throw (RuntimeException) { sal_Int16 result = index->getIndexWeight(getEntry(rIndexEntry1, rPhoneticEntry1, rLocale1)) - index->getIndexWeight(getEntry(rIndexEntry2, rPhoneticEntry2, rLocale2)); if (result == 0) return IndexEntrySupplier_Common::compareIndexEntry( rIndexEntry1, rPhoneticEntry1, rLocale1, rIndexEntry2, rPhoneticEntry2, rLocale2); return result > 0 ? 1 : -1; } OUString SAL_CALL IndexEntrySupplier_Unicode::getIndexCharacter( const OUString& rIndexEntry, const lang::Locale& rLocale, const OUString& rAlgorithm ) throw (RuntimeException) { if (loadAlgorithm( rLocale, rAlgorithm, CollatorOptions::CollatorOptions_IGNORE_CASE)) return index->getIndexDescription(rIndexEntry); else return IndexEntrySupplier_Common::getIndexCharacter(rIndexEntry, rLocale, rAlgorithm); } IndexTable::IndexTable() { table = NULL; } IndexTable::~IndexTable() { if (table) free(table); } void IndexTable::init(sal_Unicode start_, sal_Unicode end_, IndexKey *keys, sal_Int16 key_count, Index *index) { start=start_; end=end_; table = (sal_uInt8*) malloc((end-start+1)*sizeof(sal_uInt8)); for (sal_Unicode i = start; i <= end; i++) { sal_Int16 j; for (j = 0; j < key_count; j++) { if (i == keys[j].key || index->compare(i, keys[j].key) == 0) { table[i-start] = j; break; } } if (j == key_count) table[i-start] = 0xFF; } } Index::Index(CollatorImpl *col) { collator = col; } sal_Int16 Index::compare(sal_Unicode c1, sal_Unicode c2) { return collator->compareString(OUString(&c1, 1), OUString(&c2, 1)); } sal_Int16 Index::getIndexWeight(const OUString& rIndexEntry) { sal_Unicode code = rIndexEntry[0]; for (sal_Int16 i = 0; i < table_count; i++) { if (tables[i].start <= code && code <= tables[i].end) return tables[i].table[code-tables[i].start]; } return 0xFF; } OUString Index::getIndexDescription(const OUString& rIndexEntry) { sal_Int16 wgt = getIndexWeight(rIndexEntry); if (wgt < MAX_KEYS) { if (keys[wgt].desc.getLength()) return keys[wgt].desc; else return OUString(&keys[wgt].key, 1); } return rIndexEntry.copy(0, 1); } #define LOCALE_EN lang::Locale(OUString::createFromAscii("en"), OUString(), OUString()) void Index::makeIndexKeys(const lang::Locale &rLocale, const OUString &algorithm) throw (RuntimeException) { OUString keyStr = LocaleData().getIndexKeysByAlgorithm(rLocale, algorithm); if (!keyStr.getLength()) { keyStr = LocaleData().getIndexKeysByAlgorithm(LOCALE_EN, LocaleData().getDefaultIndexAlgorithm(LOCALE_EN)); if (!keyStr) throw RuntimeException(); } sal_Int16 j = 0, len = keyStr.getLength(); for (sal_Int16 i = 0; i < len && j < MAX_KEYS; i++) { sal_Unicode curr = keyStr[i]; if (unicode::isWhiteSpace(curr)) continue; switch(curr) { case sal_Unicode('-'): if (j > 0 && i + 1 < len ) { for (curr = keyStr[++i]; j < MAX_KEYS && keys[j-1].key < curr; j++) { keys[j].key = keys[j-1].key+1; keys[j].desc = OUString(); } } else throw RuntimeException(); break; case sal_Unicode('('): if (j > 0) { sal_Int16 end = i+1; while (end < len && keyStr[end] != sal_Unicode(')')) end++; if (end >= len) // no found throw RuntimeException(); keys[j-1].desc = keyStr.copy(i+1, end-i-1); i=end+1; } else throw RuntimeException(); break; default: keys[j].key = curr; keys[j++].desc = OUString(); break; } } key_count = j; } void Index::init(const lang::Locale &rLocale, const OUString& algorithm) throw (RuntimeException) { makeIndexKeys(rLocale, algorithm); Sequence< UnicodeScript > scriptList = LocaleData().getUnicodeScripts( rLocale ); if (scriptList.getLength() == 0) { scriptList = LocaleData().getUnicodeScripts(LOCALE_EN); if (scriptList.getLength() == 0) throw RuntimeException(); } table_count = scriptList.getLength(); if (table_count > MAX_TABLES) throw RuntimeException(); collator->loadCollatorAlgorithm(algorithm, rLocale, CollatorOptions::CollatorOptions_IGNORE_CASE); sal_Int16 j=0; sal_Unicode start = unicode::getUnicodeScriptStart((UnicodeScript)0); sal_Unicode end = unicode::getUnicodeScriptEnd((UnicodeScript)0); for (sal_Int16 i= (scriptList[0] == (UnicodeScript)0) ? 1 : 0; i< scriptList.getLength(); i++) { if (unicode::getUnicodeScriptStart(scriptList[i]) != end+1) { tables[j++].init(start, end, keys, key_count, this); start = unicode::getUnicodeScriptStart(scriptList[i]); } end = unicode::getUnicodeScriptEnd(scriptList[i]); } tables[j++].init(start, end, keys, key_count, this); table_count = j; } } } } } <|endoftext|>