text
stringlengths
54
60.6k
<commit_before>#include "template.h" #include <simlib/time.h> Template::TemplateEnder Template::baseTemplate(const StringView& title, const StringView& styles, const StringView& scripts) { resp.headers["Content-Type"] = "text/html; charset=utf-8"; resp.content = ""; append("<!DOCTYPE html>\n" "<html lang=\"en\">\n" "<head>\n" "<meta charset=\"utf-8\">\n" "<title>", htmlSpecialChars(title), "</title>\n" "<link rel=\"stylesheet\" href=\"/kit/styles.css\">\n" "<script src=\"/kit/jquery.js\"></script>\n" "<script src=\"/kit/scripts.js\"></script>\n" "<link rel=\"shortcut icon\" href=\"/kit/img/favicon.png\">\n"); if (scripts.size()) append("<script>", scripts, "</script>\n"); if (styles.size()) append("<style>", styles, "</style>\n"); append("</head>\n" "<body>\n" "<div class=\"navbar\">\n" "<a href=\"/\" class=\"brand\">SIM</a>\n" "<a href=\"/c/\">Contests</a>\n"); if (Session::open() && Session::user_type < UTYPE_NORMAL) { append("<a href=\"/u\">Users</a>\n"); if (Session::user_type == UTYPE_ADMIN) append("<a href=\"/logs\">Logs</a>\n"); } append("<div class=\"rightbar\">\n" "<time id=\"clock\">", date("%H:%M:%S"), " UTC</time>"); if (Session::isOpen()) append("<div class=\"dropdown\">\n" "<a class=\"user dropdown-toggle\">" "<strong>", htmlSpecialChars(Session::username), "</strong>" "</a>\n" "<ul>\n" "<a href=\"/u/", Session::user_id, "\">Edit profile</a>\n" "<a href=\"/u/", Session::user_id, "/change-password\">Change password</a>\n" "<a href=\"/logout\">Logout</a>\n" "</ul>\n" "</div>"); else append("<a href=\"/login\"><strong>Log in</strong></a>\n" "<a href=\"/signup\">Sign up</a>"); append("</div>\n" "</div>\n" "<div class=\"body\">\n"); return TemplateEnder(*this); } void Template::endTemplate() { append("</div>\n" "<script>var start_time=", toString(microtime() / 1000), ";</script>\n" "</body>\n" "</html>\n"); } <commit_msg>Added protection form clickjacking and XSS attack<commit_after>#include "template.h" #include <simlib/time.h> Template::TemplateEnder Template::baseTemplate(const StringView& title, const StringView& styles, const StringView& scripts) { // Protect from clickjacking resp.headers["X-Frame-Options"] = "DENY"; resp.headers["Content-Security-Policy"] = "frame-ancestors 'none'"; // Protect from XSS attack resp.headers["X-XSS-Protection"] = "1; mode=block"; resp.headers["Content-Type"] = "text/html; charset=utf-8"; resp.content = ""; append("<!DOCTYPE html>\n" "<html lang=\"en\">\n" "<head>\n" "<meta charset=\"utf-8\">\n" "<title>", htmlSpecialChars(title), "</title>\n" "<link rel=\"stylesheet\" href=\"/kit/styles.css\">\n" "<script src=\"/kit/jquery.js\"></script>\n" "<script src=\"/kit/scripts.js\"></script>\n" "<link rel=\"shortcut icon\" href=\"/kit/img/favicon.png\">\n"); if (scripts.size()) append("<script>", scripts, "</script>\n"); if (styles.size()) append("<style>", styles, "</style>\n"); append("</head>\n" "<body>\n" "<div class=\"navbar\">\n" "<a href=\"/\" class=\"brand\">SIM</a>\n" "<a href=\"/c/\">Contests</a>\n"); if (Session::open() && Session::user_type < UTYPE_NORMAL) { append("<a href=\"/u\">Users</a>\n"); if (Session::user_type == UTYPE_ADMIN) append("<a href=\"/logs\">Logs</a>\n"); } append("<div class=\"rightbar\">\n" "<time id=\"clock\">", date("%H:%M:%S"), " UTC</time>"); if (Session::isOpen()) append("<div class=\"dropdown\">\n" "<a class=\"user dropdown-toggle\">" "<strong>", htmlSpecialChars(Session::username), "</strong>" "</a>\n" "<ul>\n" "<a href=\"/u/", Session::user_id, "\">Edit profile</a>\n" "<a href=\"/u/", Session::user_id, "/change-password\">Change password</a>\n" "<a href=\"/logout\">Logout</a>\n" "</ul>\n" "</div>"); else append("<a href=\"/login\"><strong>Log in</strong></a>\n" "<a href=\"/signup\">Sign up</a>"); append("</div>\n" "</div>\n" "<div class=\"body\">\n"); return TemplateEnder(*this); } void Template::endTemplate() { append("</div>\n" "<script>var start_time=", toString(microtime() / 1000), ";</script>\n" "</body>\n" "</html>\n"); } <|endoftext|>
<commit_before><commit_msg>range support in globs<commit_after><|endoftext|>
<commit_before>#include "euclidean_dist_grad.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/register_types.h" // Not available for user made kernels //#include "tensorflow/core/kernels/fill_functor.h" #include <cmath> #include <thread> namespace tensorflow { template <typename T> static void threadcompute(OpKernelContext* context, Tensor* xoutput_tensor, Tensor* coutput_tensor, int i, int numThreads){ const Tensor& input_tensor1 = context->input(0); const Tensor& input_tensor2 = context->input(1); const Tensor& input_tensor3 = context->input(2); const Tensor& input_tensor4 = context->input(3); const int r1=input_tensor1.shape().dim_size(0); //num of data = n const int c1=input_tensor1.shape().dim_size(1); //dimensions = d const int c2=input_tensor2.shape().dim_size(1); //clusters = k auto in1 = input_tensor1.shaped<double, 2>({r1,c1}); auto in2 = input_tensor2.shaped<double, 2>({c1,c2}); auto in3 = input_tensor3.shaped<double, 2>({r1,c2}); auto in4 = input_tensor4.shaped<double, 2>({r1,c2}); auto xgrad = xoutput_tensor->shaped<double, 2>({r1,c1}); auto cgrad = coutput_tensor->shaped<double, 2>({c1,c2}); //printf("i: %d r1: %d numThreads: %d \n",i,r1,numThreads); for(int in=i*r1/float(numThreads); in<(i+1)*r1/float(numThreads); in++){ for (int id=0; id<c1; id++){ xgrad(in,id) = 0; } } for(int ik=i*c2/float(numThreads); ik<(i+1)*c2/float(numThreads); ik++){ for (int id=0; id<c1; id++){ cgrad(id,ik) = 0; } } //printf("%f\n",(double)gradients(0,0)); //printf("%f\n",(double)output(0,0)); if (numThreads == 1) { for(int in=0; in<r1; in++){ for (int ik=0; ik<c2; ik++){ // Points where x==c cannot be differentiated. // Often those are points that don't want to be // moved anyway, since that's typically the "best" // cluster representative input. if (in3(in,ik)!=0){ auto tempMultiplicand = in4(in,ik)/in3(in,ik); for (int id=0; id<c1; id++){ auto temp = (in1(in,id)-in2(id,ik))*tempMultiplicand; xgrad(in,id) += temp; cgrad(id,ik) -= temp; } } } } } else { // In multithreading, the two gradients have to be computed apart. for(int in=i*r1/float(numThreads); in<(i+1)*r1/float(numThreads); in++){ for (int ik=0; ik<c2; ik++){ if (in3(in,ik)!=0){ auto tempMultiplicand = in4(in,ik)/in3(in,ik); for (int id=0; id<c1; id++){ xgrad(in,id) += (in1(in,id)-in2(id,ik))*tempMultiplicand; } } } } for(int ik=i*c2/float(numThreads); ik<(i+1)*c2/float(numThreads); ik++){ for (int in=0; in<r1; in++){ if (in3(in,ik)!=0){ auto tempMultiplicand = in4(in,ik)/in3(in,ik); for (int id=0; id<c1; id++){ cgrad(id,ik) -= (in1(in,id)-in2(id,ik))*tempMultiplicand; } } } } } } template <typename Device, typename T> class EuclideanDistGradOp; template <typename T> struct LaunchEuclideanDistGradCPU { static void launch( OpKernelContext* ctx, OpKernel* kernel, const Tensor& a, const Tensor& b, const Tensor& d, const Tensor& g, Tensor* xout, Tensor* cout) { int numThreads = (( EuclideanDistGradOp<CPUDevice, T>*) kernel)->get_number_of_threads(); std::thread myThreads[numThreads-1]; for (int id=0;id<numThreads-1;id++){ myThreads[id]=std::thread(threadcompute<T>, ctx, xout, cout, id, numThreads); } // Remember that the thread launching these threads is a usuable thread as well. threadcompute<T>(ctx, xout, cout, numThreads-1, numThreads); for (int id=1; id<numThreads-1; id++){ myThreads[id].join(); } } }; template <typename T> struct LaunchEuclideanDistGrad<CPUDevice, T> : public LaunchEuclideanDistGradCPU<T> {}; template <typename T> struct LaunchEuclideanDistGrad<GPUDevice, T> : public LaunchEuclideanDistGradGPU<T> {}; REGISTER_OP("EuclideanDistGrad") .Input("data: T") .Input("clusters: T") .Input("distances: T") .Input("gradients: T") .Output("xgrad: T") .Output("cgrad: T") .Attr("number_of_threads: int >= 1 = 1") .Attr("T: {half, float, double, int32, int64, complex64, complex128}") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { ::tensorflow::shape_inference::ShapeHandle a; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &a)); ::tensorflow::shape_inference::ShapeHandle b; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &b)); ::tensorflow::shape_inference::ShapeHandle d; TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &d)); ::tensorflow::shape_inference::ShapeHandle g; TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &g)); ::tensorflow::shape_inference::DimensionHandle xoutput_rows = c->Dim(a, 0); ::tensorflow::shape_inference::DimensionHandle xoutput_cols = c->Dim(a, 1); ::tensorflow::shape_inference::DimensionHandle coutput_rows = c->Dim(b, 0); ::tensorflow::shape_inference::DimensionHandle coutput_cols = c->Dim(b, 1); // Validate that the inner shapes are compatible. ::tensorflow::shape_inference::DimensionHandle inner_a = c->Dim(a, 1); ::tensorflow::shape_inference::DimensionHandle inner_b = c->Dim(b, 0); ::tensorflow::shape_inference::DimensionHandle merged; TF_RETURN_IF_ERROR(c->Merge(inner_a, inner_b, &merged)); // I actually don't know how to check the shapes of d and g here. // I don't know if that's necessary. // Documentation on shape_inference is sparse. c->set_output(0, c->Matrix(xoutput_rows, xoutput_cols)); c->set_output(1, c->Matrix(coutput_rows, coutput_cols)); return Status::OK(); }) .Doc(R"doc( Computes the gradient of the pairwise Euclidean distance calculation in the euclidean distance op with respect to the original inputs, the ouput, and the backpropagated gradients. The inputs must be two-dimensional matrices, the inner dimension of "data" must match the inner dimension of "clusters", the outer dimensions of "data" and "clusters" must match the dimensions of both "distances" and "gradients". )doc"); template <typename Device, typename T> class EuclideanDistGradOp : public OpKernel { public: EuclideanDistGradOp(OpKernelConstruction* context) : OpKernel(context) { // Get the number of the threads to use OP_REQUIRES_OK(context, context->GetAttr("number_of_threads", &number_of_threads_)); // Check that number_of_threads is strictly positive OP_REQUIRES(context, number_of_threads_ >= 1, errors::InvalidArgument("Need number_of_threads >= 1, got ", number_of_threads_)); } void Compute(OpKernelContext* ctx) override { const Tensor& a = ctx->input(0); const Tensor& b = ctx->input(1); const Tensor& d = ctx->input(2); const Tensor& g = ctx->input(3); // Check that the dimensions of the four matrices are valid. OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a.shape()), errors::InvalidArgument("In[0] is not a matrix")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b.shape()), errors::InvalidArgument("In[1] is not a matrix")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(d.shape()), errors::InvalidArgument("In[2] is not a matrix")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(g.shape()), errors::InvalidArgument("In[3] is not a matrix")); OP_REQUIRES(ctx, a.dim_size(1) == b.dim_size(0), errors::InvalidArgument("Matrix size-incompatible: In[0]: ", a.shape().DebugString(), ", In[1]: ", b.shape().DebugString())); OP_REQUIRES(ctx, a.dim_size(0) == d.dim_size(0), errors::InvalidArgument("Matrix size-incompatible: In[0]: ", a.shape().DebugString(), ", In[2]: ", d.shape().DebugString())); OP_REQUIRES(ctx, b.dim_size(1) == d.dim_size(1), errors::InvalidArgument("Matrix size-incompatible: In[1]: ", b.shape().DebugString(), ", In[2]: ", d.shape().DebugString())); OP_REQUIRES(ctx, a.dim_size(0) == g.dim_size(0), errors::InvalidArgument("Matrix size-incompatible: In[0]: ", a.shape().DebugString(), ", In[3]: ", g.shape().DebugString())); OP_REQUIRES(ctx, b.dim_size(1) == g.dim_size(1), errors::InvalidArgument("Matrix size-incompatible: In[1]: ", b.shape().DebugString(), ", In[3]: ", g.shape().DebugString())); TensorShape xout_shape({a.dim_size(0), a.dim_size(1)}); TensorShape cout_shape({b.dim_size(0), b.dim_size(1)}); Tensor* xout = nullptr; Tensor* cout = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, xout_shape, &xout)); OP_REQUIRES_OK(ctx, ctx->allocate_output(1, cout_shape, &cout)); if (a.NumElements() == 0) { // If a has zero elements, the first output shape is // a 0-element matrix, so there is nothing to do for it. if (b.NumElements() != 0) { // But if b has non-zero elements, we have to // set all of the second output to zero. auto output = cout->shaped<T, 2>({b.shape().dim_size(0),b.shape().dim_size(1)}); // Not available for user made kernels //functor::SetZeroFunctor<Device, T> f; //f(ctx->eigen_device<Device>(), out->flat<T>()); for (int k=0; k<b.dim_size(1); k++){ for(int n=0; n<b.dim_size(0); n++){ output(n,k) = 0; } } } return; } if (b.NumElements() == 0) { // If b has zero elements, and a doesn't then we // have to set all of the first output to zero. auto output = xout->shaped<T, 2>({a.shape().dim_size(0),a.shape().dim_size(1)}); // Not available for user made kernels //functor::SetZeroFunctor<Device, T> f; //f(ctx->eigen_device<Device>(), out->flat<T>()); for (int k=0; k<a.dim_size(1); k++){ for(int n=0; n<a.dim_size(0); n++){ output(n,k) = 0; } } return; } LaunchEuclideanDistGrad<Device, T>::launch(ctx, this, a, b, d, g, xout, cout); } int get_number_of_threads() { return number_of_threads_; } private: int number_of_threads_; }; #define REGISTER_KERNEL(type) \ REGISTER_KERNEL_BUILDER( \ Name("EuclideanDistGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ EuclideanDistGradOp<CPUDevice, type>); \ REGISTER_KERNEL_BUILDER( \ Name("EuclideanDistGrad") \ .Device(DEVICE_GPU) \ .TypeConstraint<type>("T"), \ EuclideanDistGradOp<GPUDevice, type>); REGISTER_KERNEL(int32); REGISTER_KERNEL(float); REGISTER_KERNEL(double); #undef REGISTER_KERNEL } // namespace tensorflow <commit_msg>I forgot to add some templating. TensorFlow will fatal crash without this fix.<commit_after>#include "euclidean_dist_grad.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/register_types.h" // Not available for user made kernels //#include "tensorflow/core/kernels/fill_functor.h" #include <cmath> #include <thread> namespace tensorflow { template <typename T> static void threadcompute(OpKernelContext* context, Tensor* xoutput_tensor, Tensor* coutput_tensor, int i, int numThreads){ const Tensor& input_tensor1 = context->input(0); const Tensor& input_tensor2 = context->input(1); const Tensor& input_tensor3 = context->input(2); const Tensor& input_tensor4 = context->input(3); const int r1=input_tensor1.shape().dim_size(0); //num of data = n const int c1=input_tensor1.shape().dim_size(1); //dimensions = d const int c2=input_tensor2.shape().dim_size(1); //clusters = k auto in1 = input_tensor1.shaped<T, 2>({r1,c1}); auto in2 = input_tensor2.shaped<T, 2>({c1,c2}); auto in3 = input_tensor3.shaped<T, 2>({r1,c2}); auto in4 = input_tensor4.shaped<T, 2>({r1,c2}); auto xgrad = xoutput_tensor->shaped<T, 2>({r1,c1}); auto cgrad = coutput_tensor->shaped<T, 2>({c1,c2}); //printf("i: %d r1: %d numThreads: %d \n",i,r1,numThreads); for(int in=i*r1/float(numThreads); in<(i+1)*r1/float(numThreads); in++){ for (int id=0; id<c1; id++){ xgrad(in,id) = 0; } } for(int ik=i*c2/float(numThreads); ik<(i+1)*c2/float(numThreads); ik++){ for (int id=0; id<c1; id++){ cgrad(id,ik) = 0; } } //printf("%f\n",(double)gradients(0,0)); //printf("%f\n",(double)output(0,0)); if (numThreads == 1) { for(int in=0; in<r1; in++){ for (int ik=0; ik<c2; ik++){ // Points where x==c cannot be differentiated. // Often those are points that don't want to be // moved anyway, since that's typically the "best" // cluster representative input. if (in3(in,ik)!=0){ auto tempMultiplicand = in4(in,ik)/in3(in,ik); for (int id=0; id<c1; id++){ auto temp = (in1(in,id)-in2(id,ik))*tempMultiplicand; xgrad(in,id) += temp; cgrad(id,ik) -= temp; } } } } } else { // In multithreading, the two gradients have to be computed apart. for(int in=i*r1/float(numThreads); in<(i+1)*r1/float(numThreads); in++){ for (int ik=0; ik<c2; ik++){ if (in3(in,ik)!=0){ auto tempMultiplicand = in4(in,ik)/in3(in,ik); for (int id=0; id<c1; id++){ xgrad(in,id) += (in1(in,id)-in2(id,ik))*tempMultiplicand; } } } } for(int ik=i*c2/float(numThreads); ik<(i+1)*c2/float(numThreads); ik++){ for (int in=0; in<r1; in++){ if (in3(in,ik)!=0){ auto tempMultiplicand = in4(in,ik)/in3(in,ik); for (int id=0; id<c1; id++){ cgrad(id,ik) -= (in1(in,id)-in2(id,ik))*tempMultiplicand; } } } } } } template <typename Device, typename T> class EuclideanDistGradOp; template <typename T> struct LaunchEuclideanDistGradCPU { static void launch( OpKernelContext* ctx, OpKernel* kernel, const Tensor& a, const Tensor& b, const Tensor& d, const Tensor& g, Tensor* xout, Tensor* cout) { int numThreads = (( EuclideanDistGradOp<CPUDevice, T>*) kernel)->get_number_of_threads(); std::thread myThreads[numThreads-1]; for (int id=0;id<numThreads-1;id++){ myThreads[id]=std::thread(threadcompute<T>, ctx, xout, cout, id, numThreads); } // Remember that the thread launching these threads is a usuable thread as well. threadcompute<T>(ctx, xout, cout, numThreads-1, numThreads); for (int id=1; id<numThreads-1; id++){ myThreads[id].join(); } } }; template <typename T> struct LaunchEuclideanDistGrad<CPUDevice, T> : public LaunchEuclideanDistGradCPU<T> {}; template <typename T> struct LaunchEuclideanDistGrad<GPUDevice, T> : public LaunchEuclideanDistGradGPU<T> {}; REGISTER_OP("EuclideanDistGrad") .Input("data: T") .Input("clusters: T") .Input("distances: T") .Input("gradients: T") .Output("xgrad: T") .Output("cgrad: T") .Attr("number_of_threads: int >= 1 = 1") .Attr("T: {half, float, double, int32, int64, complex64, complex128}") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { ::tensorflow::shape_inference::ShapeHandle a; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &a)); ::tensorflow::shape_inference::ShapeHandle b; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &b)); ::tensorflow::shape_inference::ShapeHandle d; TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &d)); ::tensorflow::shape_inference::ShapeHandle g; TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &g)); ::tensorflow::shape_inference::DimensionHandle xoutput_rows = c->Dim(a, 0); ::tensorflow::shape_inference::DimensionHandle xoutput_cols = c->Dim(a, 1); ::tensorflow::shape_inference::DimensionHandle coutput_rows = c->Dim(b, 0); ::tensorflow::shape_inference::DimensionHandle coutput_cols = c->Dim(b, 1); // Validate that the inner shapes are compatible. ::tensorflow::shape_inference::DimensionHandle inner_a = c->Dim(a, 1); ::tensorflow::shape_inference::DimensionHandle inner_b = c->Dim(b, 0); ::tensorflow::shape_inference::DimensionHandle merged; TF_RETURN_IF_ERROR(c->Merge(inner_a, inner_b, &merged)); // I actually don't know how to check the shapes of d and g here. // I don't know if that's necessary. // Documentation on shape_inference is sparse. c->set_output(0, c->Matrix(xoutput_rows, xoutput_cols)); c->set_output(1, c->Matrix(coutput_rows, coutput_cols)); return Status::OK(); }) .Doc(R"doc( Computes the gradient of the pairwise Euclidean distance calculation in the euclidean distance op with respect to the original inputs, the ouput, and the backpropagated gradients. The inputs must be two-dimensional matrices, the inner dimension of "data" must match the inner dimension of "clusters", the outer dimensions of "data" and "clusters" must match the dimensions of both "distances" and "gradients". )doc"); template <typename Device, typename T> class EuclideanDistGradOp : public OpKernel { public: EuclideanDistGradOp(OpKernelConstruction* context) : OpKernel(context) { // Get the number of the threads to use OP_REQUIRES_OK(context, context->GetAttr("number_of_threads", &number_of_threads_)); // Check that number_of_threads is strictly positive OP_REQUIRES(context, number_of_threads_ >= 1, errors::InvalidArgument("Need number_of_threads >= 1, got ", number_of_threads_)); } void Compute(OpKernelContext* ctx) override { const Tensor& a = ctx->input(0); const Tensor& b = ctx->input(1); const Tensor& d = ctx->input(2); const Tensor& g = ctx->input(3); // Check that the dimensions of the four matrices are valid. OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a.shape()), errors::InvalidArgument("In[0] is not a matrix")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b.shape()), errors::InvalidArgument("In[1] is not a matrix")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(d.shape()), errors::InvalidArgument("In[2] is not a matrix")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(g.shape()), errors::InvalidArgument("In[3] is not a matrix")); OP_REQUIRES(ctx, a.dim_size(1) == b.dim_size(0), errors::InvalidArgument("Matrix size-incompatible: In[0]: ", a.shape().DebugString(), ", In[1]: ", b.shape().DebugString())); OP_REQUIRES(ctx, a.dim_size(0) == d.dim_size(0), errors::InvalidArgument("Matrix size-incompatible: In[0]: ", a.shape().DebugString(), ", In[2]: ", d.shape().DebugString())); OP_REQUIRES(ctx, b.dim_size(1) == d.dim_size(1), errors::InvalidArgument("Matrix size-incompatible: In[1]: ", b.shape().DebugString(), ", In[2]: ", d.shape().DebugString())); OP_REQUIRES(ctx, a.dim_size(0) == g.dim_size(0), errors::InvalidArgument("Matrix size-incompatible: In[0]: ", a.shape().DebugString(), ", In[3]: ", g.shape().DebugString())); OP_REQUIRES(ctx, b.dim_size(1) == g.dim_size(1), errors::InvalidArgument("Matrix size-incompatible: In[1]: ", b.shape().DebugString(), ", In[3]: ", g.shape().DebugString())); TensorShape xout_shape({a.dim_size(0), a.dim_size(1)}); TensorShape cout_shape({b.dim_size(0), b.dim_size(1)}); Tensor* xout = nullptr; Tensor* cout = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, xout_shape, &xout)); OP_REQUIRES_OK(ctx, ctx->allocate_output(1, cout_shape, &cout)); if (a.NumElements() == 0) { // If a has zero elements, the first output shape is // a 0-element matrix, so there is nothing to do for it. if (b.NumElements() != 0) { // But if b has non-zero elements, we have to // set all of the second output to zero. auto output = cout->shaped<T, 2>({b.shape().dim_size(0),b.shape().dim_size(1)}); // Not available for user made kernels //functor::SetZeroFunctor<Device, T> f; //f(ctx->eigen_device<Device>(), out->flat<T>()); for (int k=0; k<b.dim_size(1); k++){ for(int n=0; n<b.dim_size(0); n++){ output(n,k) = 0; } } } return; } if (b.NumElements() == 0) { // If b has zero elements, and a doesn't then we // have to set all of the first output to zero. auto output = xout->shaped<T, 2>({a.shape().dim_size(0),a.shape().dim_size(1)}); // Not available for user made kernels //functor::SetZeroFunctor<Device, T> f; //f(ctx->eigen_device<Device>(), out->flat<T>()); for (int k=0; k<a.dim_size(1); k++){ for(int n=0; n<a.dim_size(0); n++){ output(n,k) = 0; } } return; } LaunchEuclideanDistGrad<Device, T>::launch(ctx, this, a, b, d, g, xout, cout); } int get_number_of_threads() { return number_of_threads_; } private: int number_of_threads_; }; #define REGISTER_KERNEL(type) \ REGISTER_KERNEL_BUILDER( \ Name("EuclideanDistGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ EuclideanDistGradOp<CPUDevice, type>); \ REGISTER_KERNEL_BUILDER( \ Name("EuclideanDistGrad") \ .Device(DEVICE_GPU) \ .TypeConstraint<type>("T"), \ EuclideanDistGradOp<GPUDevice, type>); REGISTER_KERNEL(int32); REGISTER_KERNEL(float); REGISTER_KERNEL(double); #undef REGISTER_KERNEL } // namespace tensorflow <|endoftext|>
<commit_before> #include <stdio.h> #include "eudaq/FileReader.hh" #include "eudaq/PluginManager.hh" #include "eudaq/OptionParser.hh" #include "eudaq/StandardEvent.hh" #include <iostream> #include <vector> #include <map> #ifndef WIN32 #include <inttypes.h> #endif #include "cfunc.h" using namespace eudaq; void eudaq_data_map(const std::string & filename, unsigned int begin, unsigned int end, std::map<std::string, std::vector<data_row> > & data_map) { // Create a reader for this iframele eudaq::FileReader reader(filename); eudaq::PluginManager::Initialize(reader.GetDetectorEvent()); // Display the actual iframelename (argument could have been a run number) //std::cout << "Opened file: " << reader.Filename() << std::endl; while (reader.NextEvent()) { if (reader.GetDetectorEvent().IsEORE()) { //std::cout << "End of run detected" << std::endl; // Don't try to process if it is an EORE break; } unsigned int eventnumber=reader.GetDetectorEvent().GetEventNumber(); if (eventnumber<begin){ continue; } if (eventnumber>=end){ break; } try { unsigned int eventnumber=reader.GetDetectorEvent().GetEventNumber(); eudaq::StandardEvent sev = eudaq::PluginManager::ConvertToStandard(reader.GetDetectorEvent()); //std::cout << sev << std::endl; for(unsigned int iplane = 0; iplane < sev.NumPlanes(); iplane++){ const StandardPlane & plane = sev.GetPlane(iplane); //std::cout<< " sensor=" << plane.Sensor() << " type=" << plane.Type() << "" << std::endl; for(unsigned int iframe = 0; iframe < plane.NumFrames(); iframe++){ const std::vector<double> & xv = plane.XVector(iframe); const std::vector<double> & yv = plane.YVector(iframe); const std::vector<double> & pix = plane.PixVector(iframe); for(unsigned int ipix = 0; ipix < pix.size(); ipix++){ data_row data_pix = {eventnumber,plane.TLUEvent(), iplane, iframe, xv[ipix], yv[ipix], pix[ipix]}; data_map[plane.Type()].push_back(data_pix); } } } } catch (const eudaq::Exception & e) { //std::cout << "No " << type << " subevent in event " << reader.GetDetectorEvent().GetEventNumber() << std::endl; } } } <commit_msg>add eventnumber in return, add begin and end<commit_after> #include <stdio.h> #include "eudaq/FileReader.hh" #include "eudaq/PluginManager.hh" #include "eudaq/OptionParser.hh" #include "eudaq/StandardEvent.hh" #include <iostream> #include <vector> #include <map> #ifndef WIN32 #include <inttypes.h> #endif #include "cfunc.h" using namespace eudaq; void eudaq_data_map(const std::string & filename, unsigned int begin, unsigned int end, std::map<std::string, std::vector<data_row> > & data_map) { // Create a reader for this iframele eudaq::FileReader reader(filename); eudaq::PluginManager::Initialize(reader.GetDetectorEvent()); // Display the actual iframelename (argument could have been a run number) //std::cout << "Opened file: " << reader.Filename() << std::endl; while (reader.NextEvent()) { if (reader.GetDetectorEvent().IsEORE()) { //std::cout << "End of run detected" << std::endl; // Don't try to process if it is an EORE break; } unsigned int eventnumber=reader.GetDetectorEvent().GetEventNumber(); if (eventnumber<begin){ continue; } if (eventnumber>=end){ break; } try { unsigned int eventnumber=reader.GetDetectorEvent().GetEventNumber(); eudaq::StandardEvent sev = eudaq::PluginManager::ConvertToStandard(reader.GetDetectorEvent()); //std::cout << sev << std::endl; for(unsigned int iplane = 0; iplane < sev.NumPlanes(); iplane++){ const StandardPlane & plane = sev.GetPlane(iplane); //std::cout<< " sensor=" << plane.Sensor() << " type=" << plane.Type() << "" << std::endl; for(unsigned int iframe = 0; iframe < plane.NumFrames(); iframe++){ const std::vector<double> & xv = plane.XVector(iframe); const std::vector<double> & yv = plane.YVector(iframe); const std::vector<double> & pix = plane.PixVector(iframe); for(unsigned int ipix = 0; ipix < pix.size(); ipix++){ data_row data_pix = {eventnumber,plane.TLUEvent(), iplane, iframe, xv[ipix], yv[ipix], pix[ipix]}; data_map[plane.Type()].push_back(data_pix); } } } } catch (const eudaq::Exception & e) { //std::cout << "No " << type << " subevent in event " << reader.GetDetectorEvent().GetEventNumber() << std::endl; } } } <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/external/external_delegate.h" #include <string> #include <locale> #include <vector> #include "tensorflow/lite/minimal_logging.h" #include "tensorflow/lite/shared_library.h" namespace tflite { namespace { // External delegate library construct struct ExternalLib { using CreateDelegatePtr = std::add_pointer<TfLiteDelegate*( const char**, const char**, size_t, void (*report_error)(const char*))>::type; using DestroyDelegatePtr = std::add_pointer<void(TfLiteDelegate*)>::type; struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {}; std::wstring_convert<wchar_codecvt> converter; // Open a given delegate library and load the create/destroy symbols bool load(const std::string library) { void* handle = SharedLibrary::LoadLibrary(converter.from_bytes(library.c_str()).c_str()); if (handle == nullptr) { TFLITE_LOG(TFLITE_LOG_INFO, "Unable to load external delegate from : %s", library.c_str()); } else { create = reinterpret_cast<decltype(create)>(SharedLibrary::GetLibrarySymbol( handle, "tflite_plugin_create_delegate")); destroy = reinterpret_cast<decltype(destroy)>(SharedLibrary::GetLibrarySymbol( handle, "tflite_plugin_destroy_delegate")); return create && destroy; } return false; } CreateDelegatePtr create{nullptr}; DestroyDelegatePtr destroy{nullptr}; }; // An ExternalDelegateWrapper is responsibile to manage a TFLite delegate // initialized from a shared library. It creates a delegate from the given // option and storages it to external_delegate_ member variable. On the // destruction, it conducts necessary clean up process. class ExternalDelegateWrapper { public: explicit ExternalDelegateWrapper( const TfLiteExternalDelegateOptions* options); ~ExternalDelegateWrapper(); // Return a TfLiteDelegate which is created from // tflite_plugin_create_delegate() of an external delegate logic. TfLiteDelegate* tflite_external_delegate() { return external_delegate_; } // Return a TfLiteDelegate which is convertibile to this class. TfLiteDelegate* tflite_wrapper_delegate() { return &wrapper_delegate_; } private: ExternalLib external_lib_; // external delegate instance owned by external delegate logic. // It's created by "tflite_plugin_destroy_delegate()" function in the external // delegate logic And it should be released by // "tflite_plugin_destroy_delegate()" function. TfLiteDelegate* external_delegate_; // TfLiteDelegate representation of this ExternalDelegateWrapper object. TfLiteDelegate wrapper_delegate_; }; // Converts the given TfLiteDelegate to an ExternalDelegateWrapper instance. inline ExternalDelegateWrapper* GetExternalDelegateWrapper( TfLiteDelegate* delegate) { return reinterpret_cast<ExternalDelegateWrapper*>(delegate->data_); } // Relay Prepare() call to the associated external TfLiteDelegate object. TfLiteStatus DelegatePrepare(TfLiteContext* context, TfLiteDelegate* delegate) { auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate); TfLiteDelegate* external_delegate = external_delegate_wrapper->tflite_external_delegate(); return external_delegate->Prepare(context, external_delegate); } // Relay CopyFromBufferHandle() call to the associated external TfLiteDelegate // object. TfLiteStatus DelegateCopyFromBufferHandle(TfLiteContext* context, struct TfLiteDelegate* delegate, TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) { auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate); TfLiteDelegate* external_delegate = external_delegate_wrapper->tflite_external_delegate(); return external_delegate->CopyFromBufferHandle(context, delegate, buffer_handle, tensor); } // Relay CopyToBufferHandle() call to the associated external TfLiteDelegate // object. TfLiteStatus DelegateCopyToBufferHandle(TfLiteContext* context, struct TfLiteDelegate* delegate, TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) { auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate); TfLiteDelegate* external_delegate = external_delegate_wrapper->tflite_external_delegate(); return external_delegate->CopyToBufferHandle(context, delegate, buffer_handle, tensor); } // Relay FreeBufferHandle() call to the associated external TfLiteDelegate // object. void DelegateFreeBufferHandle(TfLiteContext* context, struct TfLiteDelegate* delegate, TfLiteBufferHandle* handle) { auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate); TfLiteDelegate* external_delegate = external_delegate_wrapper->tflite_external_delegate(); return external_delegate->FreeBufferHandle(context, delegate, handle); } ExternalDelegateWrapper::ExternalDelegateWrapper( const TfLiteExternalDelegateOptions* options) { external_delegate_ = nullptr; if (external_lib_.load(options->lib_path)) { std::vector<const char*> ckeys, cvalues; for (int i = 0; i < options->count; i++) { ckeys.push_back(options->keys[i]); cvalues.push_back(options->values[i]); } external_delegate_ = external_lib_.create(ckeys.data(), cvalues.data(), ckeys.size(), nullptr); if (external_delegate_) { wrapper_delegate_ = { .data_ = reinterpret_cast<void*>(this), .Prepare = DelegatePrepare, .CopyFromBufferHandle = nullptr, .CopyToBufferHandle = nullptr, .FreeBufferHandle = nullptr, .flags = external_delegate_->flags, }; if (external_delegate_->CopyFromBufferHandle) { wrapper_delegate_.CopyFromBufferHandle = DelegateCopyFromBufferHandle; } if (external_delegate_->CopyToBufferHandle) { wrapper_delegate_.CopyToBufferHandle = DelegateCopyToBufferHandle; } if (external_delegate_->FreeBufferHandle) { wrapper_delegate_.FreeBufferHandle = DelegateFreeBufferHandle; } } } } ExternalDelegateWrapper::~ExternalDelegateWrapper() { if (external_delegate_ != nullptr) { external_lib_.destroy(external_delegate_); } } } // namespace } // namespace tflite // TfLiteExternalDelegateOptionsInsert adds key/value to the given // TfLiteExternalDelegateOptions instance. TfLiteStatus TfLiteExternalDelegateOptionsInsert( TfLiteExternalDelegateOptions* options, const char* key, const char* value) { if (options->count >= kMaxOptions) { return kTfLiteError; } options->keys[options->count] = key; options->values[options->count] = value; options->count++; return kTfLiteOk; } TfLiteExternalDelegateOptions TfLiteExternalDelegateOptionsDefault( const char* lib_path) { // As 'keys' and 'values' don't need to be set here, using designated // initializers may cause a compiling error as "non-trivial designated // initializers not supported" by some compiler. TfLiteExternalDelegateOptions options; options.lib_path = lib_path; options.count = 0; options.insert = TfLiteExternalDelegateOptionsInsert; return options; } TfLiteDelegate* TfLiteExternalDelegateCreate( const TfLiteExternalDelegateOptions* options) { auto* external_delegate_wrapper = new tflite::ExternalDelegateWrapper(options); if (external_delegate_wrapper) { return external_delegate_wrapper->tflite_wrapper_delegate(); } return nullptr; } void TfLiteExternalDelegateDelete(TfLiteDelegate* delegate) { delete tflite::GetExternalDelegateWrapper(delegate); } <commit_msg>Convert string only for Windows<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/external/external_delegate.h" #include <string> #include <locale> #include <vector> #include "tensorflow/lite/minimal_logging.h" #include "tensorflow/lite/shared_library.h" namespace tflite { namespace { // External delegate library construct struct ExternalLib { using CreateDelegatePtr = std::add_pointer<TfLiteDelegate*( const char**, const char**, size_t, void (*report_error)(const char*))>::type; using DestroyDelegatePtr = std::add_pointer<void(TfLiteDelegate*)>::type; struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {}; std::wstring_convert<wchar_codecvt> converter; // Open a given delegate library and load the create/destroy symbols bool load(const std::string library) { #if defined(_WIN32) void* handle = SharedLibrary::LoadLibrary(converter.from_bytes(library.c_str()).c_str()); #else void* handle = SharedLibrary::LoadLibrary(library.c_str()); #endif // defined(_WIN32) if (handle == nullptr) { TFLITE_LOG(TFLITE_LOG_INFO, "Unable to load external delegate from : %s", library.c_str()); } else { create = reinterpret_cast<decltype(create)>(SharedLibrary::GetLibrarySymbol( handle, "tflite_plugin_create_delegate")); destroy = reinterpret_cast<decltype(destroy)>(SharedLibrary::GetLibrarySymbol( handle, "tflite_plugin_destroy_delegate")); return create && destroy; } return false; } CreateDelegatePtr create{nullptr}; DestroyDelegatePtr destroy{nullptr}; }; // An ExternalDelegateWrapper is responsibile to manage a TFLite delegate // initialized from a shared library. It creates a delegate from the given // option and storages it to external_delegate_ member variable. On the // destruction, it conducts necessary clean up process. class ExternalDelegateWrapper { public: explicit ExternalDelegateWrapper( const TfLiteExternalDelegateOptions* options); ~ExternalDelegateWrapper(); // Return a TfLiteDelegate which is created from // tflite_plugin_create_delegate() of an external delegate logic. TfLiteDelegate* tflite_external_delegate() { return external_delegate_; } // Return a TfLiteDelegate which is convertibile to this class. TfLiteDelegate* tflite_wrapper_delegate() { return &wrapper_delegate_; } private: ExternalLib external_lib_; // external delegate instance owned by external delegate logic. // It's created by "tflite_plugin_destroy_delegate()" function in the external // delegate logic And it should be released by // "tflite_plugin_destroy_delegate()" function. TfLiteDelegate* external_delegate_; // TfLiteDelegate representation of this ExternalDelegateWrapper object. TfLiteDelegate wrapper_delegate_; }; // Converts the given TfLiteDelegate to an ExternalDelegateWrapper instance. inline ExternalDelegateWrapper* GetExternalDelegateWrapper( TfLiteDelegate* delegate) { return reinterpret_cast<ExternalDelegateWrapper*>(delegate->data_); } // Relay Prepare() call to the associated external TfLiteDelegate object. TfLiteStatus DelegatePrepare(TfLiteContext* context, TfLiteDelegate* delegate) { auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate); TfLiteDelegate* external_delegate = external_delegate_wrapper->tflite_external_delegate(); return external_delegate->Prepare(context, external_delegate); } // Relay CopyFromBufferHandle() call to the associated external TfLiteDelegate // object. TfLiteStatus DelegateCopyFromBufferHandle(TfLiteContext* context, struct TfLiteDelegate* delegate, TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) { auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate); TfLiteDelegate* external_delegate = external_delegate_wrapper->tflite_external_delegate(); return external_delegate->CopyFromBufferHandle(context, delegate, buffer_handle, tensor); } // Relay CopyToBufferHandle() call to the associated external TfLiteDelegate // object. TfLiteStatus DelegateCopyToBufferHandle(TfLiteContext* context, struct TfLiteDelegate* delegate, TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) { auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate); TfLiteDelegate* external_delegate = external_delegate_wrapper->tflite_external_delegate(); return external_delegate->CopyToBufferHandle(context, delegate, buffer_handle, tensor); } // Relay FreeBufferHandle() call to the associated external TfLiteDelegate // object. void DelegateFreeBufferHandle(TfLiteContext* context, struct TfLiteDelegate* delegate, TfLiteBufferHandle* handle) { auto external_delegate_wrapper = GetExternalDelegateWrapper(delegate); TfLiteDelegate* external_delegate = external_delegate_wrapper->tflite_external_delegate(); return external_delegate->FreeBufferHandle(context, delegate, handle); } ExternalDelegateWrapper::ExternalDelegateWrapper( const TfLiteExternalDelegateOptions* options) { external_delegate_ = nullptr; if (external_lib_.load(options->lib_path)) { std::vector<const char*> ckeys, cvalues; for (int i = 0; i < options->count; i++) { ckeys.push_back(options->keys[i]); cvalues.push_back(options->values[i]); } external_delegate_ = external_lib_.create(ckeys.data(), cvalues.data(), ckeys.size(), nullptr); if (external_delegate_) { wrapper_delegate_ = { .data_ = reinterpret_cast<void*>(this), .Prepare = DelegatePrepare, .CopyFromBufferHandle = nullptr, .CopyToBufferHandle = nullptr, .FreeBufferHandle = nullptr, .flags = external_delegate_->flags, }; if (external_delegate_->CopyFromBufferHandle) { wrapper_delegate_.CopyFromBufferHandle = DelegateCopyFromBufferHandle; } if (external_delegate_->CopyToBufferHandle) { wrapper_delegate_.CopyToBufferHandle = DelegateCopyToBufferHandle; } if (external_delegate_->FreeBufferHandle) { wrapper_delegate_.FreeBufferHandle = DelegateFreeBufferHandle; } } } } ExternalDelegateWrapper::~ExternalDelegateWrapper() { if (external_delegate_ != nullptr) { external_lib_.destroy(external_delegate_); } } } // namespace } // namespace tflite // TfLiteExternalDelegateOptionsInsert adds key/value to the given // TfLiteExternalDelegateOptions instance. TfLiteStatus TfLiteExternalDelegateOptionsInsert( TfLiteExternalDelegateOptions* options, const char* key, const char* value) { if (options->count >= kMaxOptions) { return kTfLiteError; } options->keys[options->count] = key; options->values[options->count] = value; options->count++; return kTfLiteOk; } TfLiteExternalDelegateOptions TfLiteExternalDelegateOptionsDefault( const char* lib_path) { // As 'keys' and 'values' don't need to be set here, using designated // initializers may cause a compiling error as "non-trivial designated // initializers not supported" by some compiler. TfLiteExternalDelegateOptions options; options.lib_path = lib_path; options.count = 0; options.insert = TfLiteExternalDelegateOptionsInsert; return options; } TfLiteDelegate* TfLiteExternalDelegateCreate( const TfLiteExternalDelegateOptions* options) { auto* external_delegate_wrapper = new tflite::ExternalDelegateWrapper(options); if (external_delegate_wrapper) { return external_delegate_wrapper->tflite_wrapper_delegate(); } return nullptr; } void TfLiteExternalDelegateDelete(TfLiteDelegate* delegate) { delete tflite::GetExternalDelegateWrapper(delegate); } <|endoftext|>
<commit_before>#ifndef TOPPRA_CONST_ACCEL_HPP #define TOPPRA_CONST_ACCEL_HPP #include <toppra/parametrizer.hpp> #include <toppra/toppra.hpp> namespace toppra { namespace parametrizer { /** \brief A path parametrizer with constant acceleration assumption. * * We assume that in each segment, the path acceleration is constant. */ class ConstAccel : public Parametrizer { public: ConstAccel(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared); const Vector get_m_ts() {return m_ts;} private: /** Return joint derivatives at specified times. */ Vectors eval_impl(const Vector &times, int order = 0) const override; bool validate_impl() const override; Bound pathInterval_impl() const override; /** \brief Evaluate path variables ss, vs, and us at the input time instances. * * For each t, a starting gridpoint will be selected. The selected * path position, velocity and acceleration is then used to compute * the corresponding output quantities. * * \param[in] ts Time instances to be evaluated, starting from zero seconds. * \param[out] ss Path positions at the given time instances. * \param[out] vs Path velocities at the given time instances. * \param[out] us Path accelerations at the given time instances. * */ bool evalParams(const Vector &ts, Vector &ss, Vector &vs, Vector &us) const; // Compute times and acclerations from given data (path, velocities) void process_internals(); // Vector of time instances (corresponded to gridpoints) Vector m_ts; // Vector of accelerations (corresponded to gridpoints). Should have size // shorter than m_ts and m_vs by 1. Vector m_us; }; } // namespace parametrizer } // namespace toppra #endif <commit_msg>Fixed function name, made return reference.<commit_after>#ifndef TOPPRA_CONST_ACCEL_HPP #define TOPPRA_CONST_ACCEL_HPP #include <toppra/parametrizer.hpp> #include <toppra/toppra.hpp> namespace toppra { namespace parametrizer { /** \brief A path parametrizer with constant acceleration assumption. * * We assume that in each segment, the path acceleration is constant. */ class ConstAccel : public Parametrizer { public: ConstAccel(GeometricPathPtr path, const Vector &gridpoints, const Vector &vsquared); const Vector& getTs() { return m_ts; } private: /** Return joint derivatives at specified times. */ Vectors eval_impl(const Vector &times, int order = 0) const override; bool validate_impl() const override; Bound pathInterval_impl() const override; /** \brief Evaluate path variables ss, vs, and us at the input time instances. * * For each t, a starting gridpoint will be selected. The selected * path position, velocity and acceleration is then used to compute * the corresponding output quantities. * * \param[in] ts Time instances to be evaluated, starting from zero seconds. * \param[out] ss Path positions at the given time instances. * \param[out] vs Path velocities at the given time instances. * \param[out] us Path accelerations at the given time instances. * */ bool evalParams(const Vector &ts, Vector &ss, Vector &vs, Vector &us) const; // Compute times and acclerations from given data (path, velocities) void process_internals(); // Vector of time instances (corresponded to gridpoints) Vector m_ts; // Vector of accelerations (corresponded to gridpoints). Should have size // shorter than m_ts and m_vs by 1. Vector m_us; }; } // namespace parametrizer } // namespace toppra #endif <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> #include <cstring> #include <stdio.h> #include <stdlib.h> #include <cstring> #include "testdriverconfig.h" // SRC and BIN dir definitions #include "testuriresolver.h" #include "specification.h" // parsing spec files #include "common/common.h" #include <zorba/zorba.h> #include <zorba/error_handler.h> #include <zorba/exception.h> #include <zorba/zorbastring.h> #include <zorba/util/file.h> #include <zorba/static_context_consts.h> #include <zorbautils/strutil.h> #include <simplestore/simplestore.h> #include "util/properties.h" #include "testdriver_comparator.h" bool isErrorExpected(zorba::ZorbaException& e, State* aState) { if ( aState->hasErrors) { std::vector<std::string>::const_iterator lIter = aState->theErrors.begin(); std::vector<std::string>::const_iterator lEnd = aState->theErrors.end(); zorba::String lError = zorba::ZorbaException::getErrorCodeAsString(e.getErrorCode()); for(;lIter!=lEnd;++lIter) { zorba::String lSpecError = *lIter; if (lError.compare(lSpecError) == 0) { return true; } } } return false; } Zorba_CompilerHints getCompilerHints() { Zorba_CompilerHints lHints; // ZORBA_OPTLEVEL=O0 | O1 char* lOptLevel = getenv("ZORBA_OPTLEVEL"); if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) { lHints.opt_level = ZORBA_OPT_LEVEL_O0; std::cout << "testdriver is using optimization level O0" << std::endl; } else { lHints.opt_level = ZORBA_OPT_LEVEL_O1; std::cout << "testdriver is using optimization level O1" << std::endl; } return lHints; } // set a variable in the dynamic context // inlineFile specifies whether the given parameter is a file and it's value should // be inlined or not void set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext* dctx) { zorba::str_replace_all(val, "$UPDATE_SRC_DIR", zorba::UPDATE_SRC_DIR); zorba::ItemFactory* lFactory = zorba::Zorba::getInstance(NULL)->getItemFactory(); if (!inlineFile) { zorba::Item lItem = lFactory->createString(val); if(name != ".") dctx->setVariable (name, lItem); else dctx->setContextItem (lItem); } else { std::ifstream* is = new std::ifstream(val.c_str ()); if ( *is==NULL ) std::cout << "Error: Location not found: " << val.c_str() << std::endl; assert (*is); if(name != ".") { dctx->setVariableAsDocument(name, val.c_str(), std::auto_ptr<std::istream>(is), validate_lax); } else { dctx->setContextItemAsDocument (val.c_str(), std::auto_ptr<std::istream>(is)); } } } int #ifdef _WIN32_WCE _tmain(int argc, _TCHAR* argv[]) #else main(int argc, char** argv) #endif { if (argc != 2) { std::cout << "\nusage: testdriver [testfile]" << std::endl; return 1; } zorba::Properties::load (NULL, NULL); zorba::Zorba* engine = zorba::Zorba::getInstance(zorba::simplestore::SimpleStoreManager::getStore()); Specification lSpec; int flags = zorba::file::CONVERT_SLASHES | zorba::file::RESOLVE; std::string srcDir = zorba::UPDATE_SRC_DIR; std::string binDir = zorba::UPDATE_BINARY_DIR; std::string argString = std::string(argv[1]); std::string lSpecNoSuffix = argString.substr(0, argString.size()-5); std::string lSpecFileString = srcDir + "/Queries/" + argv[1]; zorba::file lSpecFile(lSpecFileString, flags); zorba::filesystem_path lSpecPath(lSpecFile.branch_path()); if ( (! lSpecFile.exists ()) || lSpecFile.is_directory () ) { std::cout << "\n spec file " << lSpecFile.get_path() << " does not exist or is not a file" << std::endl; return 2; } std::cout << "test " << lSpecNoSuffix << std::endl; std::string lResultFileString = binDir+"/QueryResults/"+lSpecNoSuffix+".res"; zorba::file lResultFile(lResultFileString, flags); if (!lResultFile.exists()) zorba::file(lResultFile.branch_path()).deep_mkdir(); std::string lRefFileString = srcDir+"/ExpectedTestResults/"+lSpecNoSuffix+".xml.res"; zorba::file lRefFile(lRefFileString, flags); zorba::filesystem_path lRefPath(lRefFile.branch_path()); // read the xargs and errors if the spec file exists lSpec.parseFile(lSpecFile.get_path()); Zorba_SerializerOptions lSerOptions; lSerOptions.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES; int lRun = 0; std::vector<State*>::const_iterator lIter = lSpec.statesBegin(); std::vector<State*>::const_iterator lEnd = lSpec.statesEnd(); std::vector<zorba::XQuery_t> lQueries; for(; lIter != lEnd; ++lIter) { State* lState = *lIter; std::string qname_str; if(lSpecPath.get_path().find("XQueryX") == std::string::npos) qname_str = (*lIter)->theName + ".xq"; else qname_str = (*lIter)->theName + ".xqx"; std::cout << "qname_str " << qname_str << std::endl; zorba::filesystem_path lQueryName(qname_str, zorba::file::CONVERT_SLASHES); zorba::filesystem_path lQueryFile(lSpecPath, lQueryName); std::cout << std::endl << "Query (Run " << ++lRun << "):" << std::endl; std::cout << "Query file " << lQueryFile << ": " << std::endl; zorba::printFile(std::cout, lQueryFile); std::cout << std::endl; std::ifstream lQueryStream(lQueryFile.c_str()); try { zorba::StaticContext_t lContext = engine->createStaticContext(); std::string path = lQueryFile.get_path(); std::auto_ptr<zorba::TestSchemaURIResolver> resolver; if ( path.find ( "w3c_update_testsuite" ) != std::string::npos ) { std::string uri_map_file = srcDir + "/Queries/w3c_update_testsuite/TestSources/uri.txt"; resolver.reset(new zorba::TestSchemaURIResolver ( uri_map_file.c_str() )); lContext->setSchemaURIResolver ( resolver.get() ); if (path.find("ValSkip") != std::string::npos || path.find("ValLax") != std::string::npos) lContext->setBoundarySpacePolicy(preserve_space); zorba::String lProlog = zorba::String(std::string("import schema 'http://www.w3.org/XML/1998/namespace';\n")); lContext->loadProlog(lProlog, getCompilerHints()); } zorba::XQuery_t lQuery = engine->createQuery(); lQuery->setFileName (lQueryFile.c_str()); lQuery->compile(lQueryStream, lContext, getCompilerHints()); lQueries.push_back(lQuery); } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected compiler error:\n" << e << std::endl; std::cout << "updtestdriver: success" << std::endl; return 0; } else { std::cout << "Unexpected compiler error:\n" << e << std::endl; return 3; } } try { zorba::DynamicContext* lDynCtx = lQueries.back()->getDynamicContext(); if (lState->hasDate) { std::string lDateTime = lState->theDate; if (lDateTime.find("T") == std::string::npos) { lDateTime += "T00:00:00"; } lDynCtx->setCurrentDateTime(engine->getItemFactory()->createDateTime(lDateTime)); } std::vector<Variable*>::const_iterator lVarIter = (*lIter)->varsBegin(); std::vector<Variable*>::const_iterator lVarEnd = (*lIter)->varsEnd(); for(; lVarIter != lVarEnd; ++lVarIter) { Variable* lVar = *lVarIter; set_var(lVar->theInline, lVar->theName, lVar->theValue, lDynCtx); } } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected execution error:\n" << e << std::endl; continue; } else { std::cout << "Unexpected execution error:\n" << e << std::endl; return 6; } } try { if (lQueries.back()->isUpdateQuery()) { zorba::XQuery_t query = lQueries.back(); query->applyUpdates(); std::cout << "Updating Query -> no Result" << std::endl; } else { if ( lResultFile.exists ()) lResultFile.remove(); std::ofstream lResFileStream(lResultFile.get_path().c_str()); lQueries.back()->serialize(lResFileStream, &lSerOptions); lResFileStream.flush(); if (lState->hasCompare) { bool lRes = false; bool anyMatch = false; ulong numRefs = lState->theCompares.size(); for (ulong i = 0; i < numRefs && !lRes; i++) { std::string lRefFileTmpString = lRefPath; // the ref file is the same for xqueryx and xquery tests // hence, we remove the string xqueryx or xquery from the path size_t lPosOfW3C = lRefPath.get_path().find("w3c_update_testsuite"); if (lPosOfW3C != std::string::npos) { if (lRefPath.get_path().find("XQueryX", lPosOfW3C) != std::string::npos) lRefFileTmpString = lRefFileTmpString.erase(lPosOfW3C + 21, 8); else lRefFileTmpString = lRefFileTmpString.erase(lPosOfW3C + 21, 7); } zorba::filesystem_path lRefFile(lRefFileTmpString, zorba::filesystem_path(lState->theCompares[i], zorba::file::CONVERT_SLASHES)); std::cout << std::endl << "Ref " << lRefFile.get_path() << std::endl; int lLine, lCol, lPos; std::string lRefLine, lResultLine; lRes = zorba::fileEquals(lRefFile.get_path().c_str(), lResultFile.get_path().c_str(), lLine, lCol, lPos, lRefLine, lResultLine); // if the simple comparison doesn't work, we do the full-fledged // xml canonical comparison if (lRes) { std::cout << "updtestdriver: success (non-canonical result matches)" << std::endl; anyMatch = true; break; } else { std::cout << "Actual and Reference results are not identical" << std::endl << std::endl << "Actual Result " << lResultFile.get_path() << ": " << std::endl << std::endl; zorba::printFile(std::cout, lResultFile.get_path()); std::cout << "Reference Result " << lRefFile.get_path() << ": " << std::endl << std::endl; zorba::printFile(std::cout, lRefFile.get_path()); std::cout << std::endl << std::endl; int lCanonicalRes = zorba::canonicalizeAndCompare(State::compareTypeStr(lState->theCompareTypes[i]), lRefFile.get_path().c_str(), lResultFile.get_path().c_str(), zorba::UPDATE_BINARY_DIR.c_str()); if (lCanonicalRes == 0) { anyMatch = true; break; } } } // multiple compare possible if (!anyMatch) { return 4; } } else if (lState->hasErrors) { std::cout << "Query must throw an error!" << std::endl; return 5; } else { std::cout << "Query returns result but no expected result defined!" << std::endl; } } // if non-updating query } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected execution error:\n" << e << std::endl; continue; } else { std::cout << "Unexpected execution error:\n" << e << std::endl; return 6; } } } // for each query described in the spec file std::cout << "updtestdriver: success" << std::endl; return 0; } <commit_msg>temporarily disabled the loadProlog to make CDash tests pass<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> #include <cstring> #include <stdio.h> #include <stdlib.h> #include <cstring> #include "testdriverconfig.h" // SRC and BIN dir definitions #include "testuriresolver.h" #include "specification.h" // parsing spec files #include "common/common.h" #include <zorba/zorba.h> #include <zorba/error_handler.h> #include <zorba/exception.h> #include <zorba/zorbastring.h> #include <zorba/util/file.h> #include <zorba/static_context_consts.h> #include <zorbautils/strutil.h> #include <simplestore/simplestore.h> #include "util/properties.h" #include "testdriver_comparator.h" bool isErrorExpected(zorba::ZorbaException& e, State* aState) { if ( aState->hasErrors) { std::vector<std::string>::const_iterator lIter = aState->theErrors.begin(); std::vector<std::string>::const_iterator lEnd = aState->theErrors.end(); zorba::String lError = zorba::ZorbaException::getErrorCodeAsString(e.getErrorCode()); for(;lIter!=lEnd;++lIter) { zorba::String lSpecError = *lIter; if (lError.compare(lSpecError) == 0) { return true; } } } return false; } Zorba_CompilerHints getCompilerHints() { Zorba_CompilerHints lHints; // ZORBA_OPTLEVEL=O0 | O1 char* lOptLevel = getenv("ZORBA_OPTLEVEL"); if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) { lHints.opt_level = ZORBA_OPT_LEVEL_O0; std::cout << "testdriver is using optimization level O0" << std::endl; } else { lHints.opt_level = ZORBA_OPT_LEVEL_O1; std::cout << "testdriver is using optimization level O1" << std::endl; } return lHints; } // set a variable in the dynamic context // inlineFile specifies whether the given parameter is a file and it's value should // be inlined or not void set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext* dctx) { zorba::str_replace_all(val, "$UPDATE_SRC_DIR", zorba::UPDATE_SRC_DIR); zorba::ItemFactory* lFactory = zorba::Zorba::getInstance(NULL)->getItemFactory(); if (!inlineFile) { zorba::Item lItem = lFactory->createString(val); if(name != ".") dctx->setVariable (name, lItem); else dctx->setContextItem (lItem); } else { std::ifstream* is = new std::ifstream(val.c_str ()); if ( *is==NULL ) std::cout << "Error: Location not found: " << val.c_str() << std::endl; assert (*is); if(name != ".") { dctx->setVariableAsDocument(name, val.c_str(), std::auto_ptr<std::istream>(is), validate_lax); } else { dctx->setContextItemAsDocument (val.c_str(), std::auto_ptr<std::istream>(is)); } } } int #ifdef _WIN32_WCE _tmain(int argc, _TCHAR* argv[]) #else main(int argc, char** argv) #endif { if (argc != 2) { std::cout << "\nusage: testdriver [testfile]" << std::endl; return 1; } zorba::Properties::load (NULL, NULL); zorba::Zorba* engine = zorba::Zorba::getInstance(zorba::simplestore::SimpleStoreManager::getStore()); Specification lSpec; int flags = zorba::file::CONVERT_SLASHES | zorba::file::RESOLVE; std::string srcDir = zorba::UPDATE_SRC_DIR; std::string binDir = zorba::UPDATE_BINARY_DIR; std::string argString = std::string(argv[1]); std::string lSpecNoSuffix = argString.substr(0, argString.size()-5); std::string lSpecFileString = srcDir + "/Queries/" + argv[1]; zorba::file lSpecFile(lSpecFileString, flags); zorba::filesystem_path lSpecPath(lSpecFile.branch_path()); if ( (! lSpecFile.exists ()) || lSpecFile.is_directory () ) { std::cout << "\n spec file " << lSpecFile.get_path() << " does not exist or is not a file" << std::endl; return 2; } std::cout << "test " << lSpecNoSuffix << std::endl; std::string lResultFileString = binDir+"/QueryResults/"+lSpecNoSuffix+".res"; zorba::file lResultFile(lResultFileString, flags); if (!lResultFile.exists()) zorba::file(lResultFile.branch_path()).deep_mkdir(); std::string lRefFileString = srcDir+"/ExpectedTestResults/"+lSpecNoSuffix+".xml.res"; zorba::file lRefFile(lRefFileString, flags); zorba::filesystem_path lRefPath(lRefFile.branch_path()); // read the xargs and errors if the spec file exists lSpec.parseFile(lSpecFile.get_path()); Zorba_SerializerOptions lSerOptions; lSerOptions.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES; int lRun = 0; std::vector<State*>::const_iterator lIter = lSpec.statesBegin(); std::vector<State*>::const_iterator lEnd = lSpec.statesEnd(); std::vector<zorba::XQuery_t> lQueries; for(; lIter != lEnd; ++lIter) { State* lState = *lIter; std::string qname_str; if(lSpecPath.get_path().find("XQueryX") == std::string::npos) qname_str = (*lIter)->theName + ".xq"; else qname_str = (*lIter)->theName + ".xqx"; std::cout << "qname_str " << qname_str << std::endl; zorba::filesystem_path lQueryName(qname_str, zorba::file::CONVERT_SLASHES); zorba::filesystem_path lQueryFile(lSpecPath, lQueryName); std::cout << std::endl << "Query (Run " << ++lRun << "):" << std::endl; std::cout << "Query file " << lQueryFile << ": " << std::endl; zorba::printFile(std::cout, lQueryFile); std::cout << std::endl; std::ifstream lQueryStream(lQueryFile.c_str()); try { zorba::StaticContext_t lContext = engine->createStaticContext(); std::string path = lQueryFile.get_path(); std::auto_ptr<zorba::TestSchemaURIResolver> resolver; if ( path.find ( "w3c_update_testsuite" ) != std::string::npos ) { std::string uri_map_file = srcDir + "/Queries/w3c_update_testsuite/TestSources/uri.txt"; resolver.reset(new zorba::TestSchemaURIResolver ( uri_map_file.c_str() )); lContext->setSchemaURIResolver ( resolver.get() ); if (path.find("ValSkip") != std::string::npos || path.find("ValLax") != std::string::npos) lContext->setBoundarySpacePolicy(preserve_space); #if 0 zorba::String lProlog = zorba::String(std::string("import schema 'http://www.w3.org/XML/1998/namespace';\n")); lContext->loadProlog(lProlog, getCompilerHints()); #endif } zorba::XQuery_t lQuery = engine->createQuery(); lQuery->setFileName (lQueryFile.c_str()); lQuery->compile(lQueryStream, lContext, getCompilerHints()); lQueries.push_back(lQuery); } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected compiler error:\n" << e << std::endl; std::cout << "updtestdriver: success" << std::endl; return 0; } else { std::cout << "Unexpected compiler error:\n" << e << std::endl; return 3; } } try { zorba::DynamicContext* lDynCtx = lQueries.back()->getDynamicContext(); if (lState->hasDate) { std::string lDateTime = lState->theDate; if (lDateTime.find("T") == std::string::npos) { lDateTime += "T00:00:00"; } lDynCtx->setCurrentDateTime(engine->getItemFactory()->createDateTime(lDateTime)); } std::vector<Variable*>::const_iterator lVarIter = (*lIter)->varsBegin(); std::vector<Variable*>::const_iterator lVarEnd = (*lIter)->varsEnd(); for(; lVarIter != lVarEnd; ++lVarIter) { Variable* lVar = *lVarIter; set_var(lVar->theInline, lVar->theName, lVar->theValue, lDynCtx); } } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected execution error:\n" << e << std::endl; continue; } else { std::cout << "Unexpected execution error:\n" << e << std::endl; return 6; } } try { if (lQueries.back()->isUpdateQuery()) { zorba::XQuery_t query = lQueries.back(); query->applyUpdates(); std::cout << "Updating Query -> no Result" << std::endl; } else { if ( lResultFile.exists ()) lResultFile.remove(); std::ofstream lResFileStream(lResultFile.get_path().c_str()); lQueries.back()->serialize(lResFileStream, &lSerOptions); lResFileStream.flush(); if (lState->hasCompare) { bool lRes = false; bool anyMatch = false; ulong numRefs = lState->theCompares.size(); for (ulong i = 0; i < numRefs && !lRes; i++) { std::string lRefFileTmpString = lRefPath; // the ref file is the same for xqueryx and xquery tests // hence, we remove the string xqueryx or xquery from the path size_t lPosOfW3C = lRefPath.get_path().find("w3c_update_testsuite"); if (lPosOfW3C != std::string::npos) { if (lRefPath.get_path().find("XQueryX", lPosOfW3C) != std::string::npos) lRefFileTmpString = lRefFileTmpString.erase(lPosOfW3C + 21, 8); else lRefFileTmpString = lRefFileTmpString.erase(lPosOfW3C + 21, 7); } zorba::filesystem_path lRefFile(lRefFileTmpString, zorba::filesystem_path(lState->theCompares[i], zorba::file::CONVERT_SLASHES)); std::cout << std::endl << "Ref " << lRefFile.get_path() << std::endl; int lLine, lCol, lPos; std::string lRefLine, lResultLine; lRes = zorba::fileEquals(lRefFile.get_path().c_str(), lResultFile.get_path().c_str(), lLine, lCol, lPos, lRefLine, lResultLine); // if the simple comparison doesn't work, we do the full-fledged // xml canonical comparison if (lRes) { std::cout << "updtestdriver: success (non-canonical result matches)" << std::endl; anyMatch = true; break; } else { std::cout << "Actual and Reference results are not identical" << std::endl << std::endl << "Actual Result " << lResultFile.get_path() << ": " << std::endl << std::endl; zorba::printFile(std::cout, lResultFile.get_path()); std::cout << "Reference Result " << lRefFile.get_path() << ": " << std::endl << std::endl; zorba::printFile(std::cout, lRefFile.get_path()); std::cout << std::endl << std::endl; int lCanonicalRes = zorba::canonicalizeAndCompare(State::compareTypeStr(lState->theCompareTypes[i]), lRefFile.get_path().c_str(), lResultFile.get_path().c_str(), zorba::UPDATE_BINARY_DIR.c_str()); if (lCanonicalRes == 0) { anyMatch = true; break; } } } // multiple compare possible if (!anyMatch) { return 4; } } else if (lState->hasErrors) { std::cout << "Query must throw an error!" << std::endl; return 5; } else { std::cout << "Query returns result but no expected result defined!" << std::endl; } } // if non-updating query } catch (zorba::ZorbaException &e) { if (isErrorExpected(e, lState)) { std::cout << "Expected execution error:\n" << e << std::endl; continue; } else { std::cout << "Unexpected execution error:\n" << e << std::endl; return 6; } } } // for each query described in the spec file std::cout << "updtestdriver: success" << std::endl; return 0; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> using namespace View; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); undoButton = new QPushButton(this); undoButton->setText("Undo"); undoButton->move(50, 600); connect(undoButton, SIGNAL(clicked()), this, SIGNAL(onUndo())); redoButton = new QPushButton(this); redoButton->setText("Redo"); redoButton->move(150, 600); connect(redoButton, SIGNAL(clicked()), this, SIGNAL(onRedo())); loadPuzzleButton = new QPushButton(this); loadPuzzleButton->setText("Load Puzzle"); loadPuzzleButton->move(250, 600); connect(loadPuzzleButton, SIGNAL(clicked()), this, SIGNAL(onLoadPuzzlePressed())); savePuzzleButton = new QPushButton(this); savePuzzleButton->setText("Save Puzzle"); savePuzzleButton->move(350, 600); connect(savePuzzleButton, SIGNAL(clicked()), this, SIGNAL(onSavePuzzlePressed())); loadProgressButton = new QPushButton(this); loadProgressButton->setText("Load Progress"); loadProgressButton->move(450, 600); connect(loadProgressButton, SIGNAL(clicked()), this, SIGNAL(onLoadProgressPressed())); saveProgressButton = new QPushButton(this); saveProgressButton->setText("Save Progress"); saveProgressButton->move(550, 600); connect(saveProgressButton, SIGNAL(clicked()), this, SIGNAL(onSaveProgressPressed())); for (int i = 1; i < 10; i++) { for (int j = 1; j < 10; j++) { //Creating and formatting each QLineEdit field. fields[i][j] = new QLineEdit(); QValidator *val = new QIntValidator(1,9,fields[i][j]); fields[i][j]->setValidator(val); // fields[i][j]->setInputMask("D"); fields[i][j]->setObjectName(QString::number(i) + "_" + QString::number(j)); fields[i][j]->setFixedHeight(31); fields[i][j]->setFixedWidth(41); fields[i][j]->setAlignment(Qt::AlignCenter); fields[i][j]->setStyleSheet("font: 18pt;"); connect(fields[i][j], SIGNAL(textChanged(QString)),this,SLOT(fieldChanged(QString))); } } createLayout(); } MainWindow::~MainWindow() { //buttons are deleted when ui is deleted since it is parent, see Qt documentation delete ui; } void MainWindow::fieldChanged(QString text) { //Will eventually parse the object name '1_1' (row 1, col 1) into a position array, //and pass the position and values to the Controller, for now just update label to display Value/Field. QLineEdit *field = (QLineEdit *)sender(); emit onMakeMove(QString("Value: " + text + " Field: " + field->objectName())); } void MainWindow::createLayout() { ui->gridLayout->setMargin(6); ui->gridLayout->setSpacing(6); for(int i = 1; i < 10; i++) { for(int j = 1; j < 10; j++) { ui->gridLayout->addWidget(fields[i][j], i, j); } } } <commit_msg>Forgot to uncomment some stuff.<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> using namespace View; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); undoButton = new QPushButton(this); undoButton->setText("Undo"); undoButton->move(50, 600); connect(undoButton, SIGNAL(clicked()), this, SIGNAL(onUndo())); redoButton = new QPushButton(this); redoButton->setText("Redo"); redoButton->move(150, 600); connect(redoButton, SIGNAL(clicked()), this, SIGNAL(onRedo())); loadPuzzleButton = new QPushButton(this); loadPuzzleButton->setText("Load Puzzle"); loadPuzzleButton->move(250, 600); connect(loadPuzzleButton, SIGNAL(clicked()), this, SIGNAL(onLoadPuzzlePressed())); savePuzzleButton = new QPushButton(this); savePuzzleButton->setText("Save Puzzle"); savePuzzleButton->move(350, 600); connect(savePuzzleButton, SIGNAL(clicked()), this, SIGNAL(onSavePuzzlePressed())); loadProgressButton = new QPushButton(this); loadProgressButton->setText("Load Progress"); loadProgressButton->move(450, 600); connect(loadProgressButton, SIGNAL(clicked()), this, SIGNAL(onLoadProgressPressed())); saveProgressButton = new QPushButton(this); saveProgressButton->setText("Save Progress"); saveProgressButton->move(550, 600); connect(saveProgressButton, SIGNAL(clicked()), this, SIGNAL(onSaveProgressPressed())); for (int i = 1; i < 10; i++) { for (int j = 1; j < 10; j++) { //Creating and formatting each QLineEdit field. fields[i][j] = new QLineEdit(); QValidator *val = new QIntValidator(1,9,fields[i][j]); fields[i][j]->setValidator(val); fields[i][j]->setObjectName(QString::number(i) + "_" + QString::number(j)); fields[i][j]->setFixedHeight(31); fields[i][j]->setFixedWidth(41); fields[i][j]->setAlignment(Qt::AlignCenter); fields[i][j]->setStyleSheet("font: 18pt;"); connect(fields[i][j], SIGNAL(textChanged(QString)),this,SLOT(fieldChanged(QString))); } } createLayout(); } MainWindow::~MainWindow() { //buttons are deleted when ui is deleted since it is parent, see Qt documentation delete ui; } void MainWindow::fieldChanged(QString text) { //Will eventually parse the object name '1_1' (row 1, col 1) into a position array, //and pass the position and values to the Controller, for now just update label to display Value/Field. QLineEdit *field = (QLineEdit *)sender(); emit onMakeMove(QString("Value: " + text + " Field: " + field->objectName())); } void MainWindow::createLayout() { ui->gridLayout->setMargin(6); ui->gridLayout->setSpacing(6); for(int i = 1; i < 10; i++) { for(int j = 1; j < 10; j++) { ui->gridLayout->addWidget(fields[i][j], i, j); } } } <|endoftext|>
<commit_before>#include <bits/stdc++.h> using namespace std; // ---- Start ---- template<typename T, typename Cmp=less<T> > void quick_sort(T *beg, T *end, const Cmp &cmp = Cmp()){ if(beg == end || beg+1==end)return; T mid = *beg; T *l = beg+1, *r = end-1; while(l != r+1){ if(cmp(mid, *r))r--; else if(cmp(*l, mid))l++; else swap(*l,*r); } swap(*beg, *r); quick_sort(beg,r,cmp); quick_sort(r+1,end,cmp); } // ---- End ---- // ---- Demo ---- const int N = 10; int A[N]; void print(){ cout<<"A: "; for(int i=0;i<N;i++){ cout<<A[i]<<' '; } cout<<endl; } int main(){ for(int i=0;i<N;i++){ A[i] = i; } random_shuffle(A,A+N); print(); quick_sort(A,A+N); print(); while(1); }<commit_msg>fix quick sort bug<commit_after>#include <bits/stdc++.h> using namespace std; // ---- Start ---- template<typename T, typename Cmp=less<T> > void quick_sort(T *beg, T *end, const Cmp &cmp = Cmp()){ if(beg == end || beg+1==end)return; T mid = *beg; T *l = beg+1, *r = end-1; while(l != r+1){ if(cmp(mid, *r))r--; else if(!cmp(mid, *l))l++; else swap(*l,*r); } swap(*beg, *r); quick_sort(beg,r,cmp); quick_sort(r+1,end,cmp); } // ---- End ---- // ---- Demo ---- const int N = 10; int A[N]; void print(){ cout<<"A: "; for(int i=0;i<N;i++){ cout<<A[i]<<' '; } cout<<endl; } int main(){ for(int i=0;i<N;i++){ A[i] = rand()%(i+1); } random_shuffle(A,A+N); print(); quick_sort(A,A+N); print(); while(1); }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optupdt.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: ihi $ $Date: 2006-08-04 09:48:19 $ * * 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 * ************************************************************************/ #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #include "optupdt.hxx" #include "optupdt.hrc" #include "dialmgr.hxx" #include "dialogs.hrc" #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFolderPicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_ #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_ #include <com/sun/star/frame/XDispatchProvider.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_ #include <com/sun/star/util/XChangesBatch.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #include <osl/file.hxx> #include <osl/security.hxx> namespace beans = ::com::sun::star::beans; namespace container = ::com::sun::star::container; namespace dialogs = ::com::sun::star::ui::dialogs; namespace frame = ::com::sun::star::frame; namespace lang = ::com::sun::star::lang; namespace uno = ::com::sun::star::uno; namespace util = ::com::sun::star::util; // define ---------------------------------------------------------------- #define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s)) // class SvxOnlineUpdateTabPage -------------------------------------------------- SvxOnlineUpdateTabPage::SvxOnlineUpdateTabPage( Window* pParent, const SfxItemSet& rSet ) : SfxTabPage( pParent, SVX_RES( RID_SVXPAGE_ONLINEUPDATE ), rSet ), m_aOptionsLine( this, ResId( FL_OPTIONS ) ), m_aAutoCheckCheckBox( this, ResId( CB_AUTOCHECK ) ), m_aEveryDayButton( this, ResId( RB_EVERYDAY ) ), m_aEveryWeekButton( this, ResId( RB_EVERYWEEK ) ), m_aEveryMonthButton( this, ResId( RB_EVERYMONTH ) ), m_aCheckNowButton( this, ResId( PB_CHECKNOW ) ), m_aAutoDownloadCheckBox( this, ResId( CB_AUTODOWNLOAD ) ), m_aDestPathLabel( this, ResId( FT_DESTPATHLABEL ) ), m_aDestPath( this, ResId( FT_DESTPATH ) ), m_aChangePathButton( this, ResId( PB_CHANGEPATH ) ) { FreeResource(); m_aAutoCheckCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoCheckHdl_Impl ) ); m_aCheckNowButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, CheckNowHdl_Impl ) ); m_aAutoDownloadCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl ) ); m_aChangePathButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, FileDialogHdl_Impl ) ); uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); m_xUpdateAccess = uno::Reference < container::XNameReplace >( xFactory->createInstance( UNISTRING( "com.sun.star.setup.UpdateCheckConfig" ) ), uno::UNO_QUERY_THROW ); sal_Bool bDownloadSupported; m_xUpdateAccess->getByName( UNISTRING( "DownloadSupported") ) >>= bDownloadSupported; WinBits nStyle = m_aDestPath.GetStyle(); nStyle |= WB_PATHELLIPSIS; m_aDestPath.SetStyle(nStyle); m_aAutoDownloadCheckBox.Show(bDownloadSupported); m_aDestPathLabel.Show(bDownloadSupported); m_aDestPath.Show(bDownloadSupported); m_aChangePathButton.Show(bDownloadSupported); } // ----------------------------------------------------------------------- SvxOnlineUpdateTabPage::~SvxOnlineUpdateTabPage() { } // ----------------------------------------------------------------------- SfxTabPage* SvxOnlineUpdateTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet ) { return new SvxOnlineUpdateTabPage( pParent, rAttrSet ); } // ----------------------------------------------------------------------- BOOL SvxOnlineUpdateTabPage::FillItemSet( SfxItemSet& ) { BOOL bModified = FALSE; sal_Bool bValue; sal_Int64 nValue; if( m_aAutoCheckCheckBox.GetSavedValue() != m_aAutoCheckCheckBox.IsChecked() ) { bValue = (TRUE == m_aAutoCheckCheckBox.IsChecked()); m_xUpdateAccess->replaceByName( UNISTRING("AutoCheckEnabled"), uno::makeAny( bValue ) ); bModified = TRUE; } nValue = 0; if( TRUE == m_aEveryDayButton.IsChecked() ) { if( FALSE == m_aEveryDayButton.GetSavedValue() ) nValue = 86400; } else if( TRUE == m_aEveryWeekButton.IsChecked() ) { if( FALSE == m_aEveryWeekButton.GetSavedValue() ) nValue = 604800; } else if( TRUE == m_aEveryMonthButton.IsChecked() ) { if( FALSE == m_aEveryMonthButton.GetSavedValue() ) nValue = 2592000; } if( nValue > 0 ) { m_xUpdateAccess->replaceByName( UNISTRING("CheckInterval"), uno::makeAny( nValue ) ); bModified = TRUE; } if( m_aAutoDownloadCheckBox.GetSavedValue() != m_aAutoDownloadCheckBox.IsChecked() ) { bValue = (TRUE == m_aAutoDownloadCheckBox.IsChecked()); m_xUpdateAccess->replaceByName( UNISTRING("AutoDownloadEnabled"), uno::makeAny( bValue ) ); bModified = TRUE; } rtl::OUString sValue, aURL; m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue; if( ( osl::FileBase::E_None == osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) ) && ( ! aURL.equals( sValue ) ) ) { m_xUpdateAccess->replaceByName( UNISTRING("DownloadDestination"), uno::makeAny( aURL ) ); bModified = TRUE; } uno::Reference< util::XChangesBatch > xChangesBatch(m_xUpdateAccess, uno::UNO_QUERY); if( xChangesBatch.is() && xChangesBatch->hasPendingChanges() ) xChangesBatch->commitChanges(); return bModified; } // ----------------------------------------------------------------------- void SvxOnlineUpdateTabPage::Reset( const SfxItemSet& ) { sal_Bool bValue; m_xUpdateAccess->getByName( UNISTRING("AutoCheckEnabled") ) >>= bValue; m_aAutoCheckCheckBox.Check(bValue); m_aEveryDayButton.Enable(bValue); m_aEveryWeekButton.Enable(bValue); m_aEveryMonthButton.Enable(bValue); sal_Int64 nValue; m_xUpdateAccess->getByName( UNISTRING("CheckInterval") ) >>= nValue; if( nValue == 86400 ) m_aEveryDayButton.Check(); else if( nValue == 604800 ) m_aEveryWeekButton.Check(); else m_aEveryMonthButton.Check(); m_aAutoCheckCheckBox.SaveValue(); m_aEveryDayButton.SaveValue(); m_aEveryWeekButton.SaveValue(); m_aEveryMonthButton.SaveValue(); m_xUpdateAccess->getByName( UNISTRING("AutoDownloadEnabled") ) >>= bValue; m_aAutoDownloadCheckBox.Check(bValue); m_aDestPathLabel.Enable(bValue); m_aDestPath.Enable(bValue); m_aChangePathButton.Enable(bValue); rtl::OUString sValue, aPath; m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue; if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(sValue, aPath) ) m_aDestPath.SetText(aPath); m_aAutoDownloadCheckBox.SaveValue(); } // ----------------------------------------------------------------------- void SvxOnlineUpdateTabPage::FillUserData() { } // ----------------------------------------------------------------------- IMPL_LINK( SvxOnlineUpdateTabPage, AutoCheckHdl_Impl, CheckBox *, pBox ) { BOOL bEnabled = pBox->IsChecked(); m_aEveryDayButton.Enable(bEnabled); m_aEveryWeekButton.Enable(bEnabled); m_aEveryMonthButton.Enable(bEnabled); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl, CheckBox *, pBox ) { BOOL bEnabled = pBox->IsChecked(); m_aDestPathLabel.Enable(bEnabled); m_aDestPath.Enable(bEnabled); m_aChangePathButton.Enable(bEnabled); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxOnlineUpdateTabPage, FileDialogHdl_Impl, PushButton *, EMPTYARG ) { uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); uno::Reference < dialogs::XFolderPicker > xFolderPicker( xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) ) ), uno::UNO_QUERY ); rtl::OUString aURL; if( osl::FileBase::E_None != osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) ) osl::Security().getHomeDir(aURL); xFolderPicker->setDisplayDirectory( aURL ); sal_Int16 nRet = xFolderPicker->execute(); if ( dialogs::ExecutableDialogResults::OK == nRet ) { rtl::OUString aFolder; if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(xFolderPicker->getDirectory(), aFolder)) m_aDestPath.SetText( aFolder ); } return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxOnlineUpdateTabPage, CheckNowHdl_Impl, PushButton *, EMPTYARG ) { uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); try { uno::Reference< lang::XMultiServiceFactory > xConfigProvider( xFactory->createInstance( UNISTRING( "com.sun.star.configuration.ConfigurationProvider" )), uno::UNO_QUERY_THROW); beans::PropertyValue aProperty; aProperty.Name = UNISTRING( "nodepath" ); aProperty.Value = uno::makeAny( UNISTRING("org.openoffice.Office.Addons/AddonUI/OfficeHelp/UpdateCheckJob") ); uno::Sequence< uno::Any > aArgumentList( 1 ); aArgumentList[0] = uno::makeAny( aProperty ); uno::Reference< container::XNameAccess > xNameAccess( xConfigProvider->createInstanceWithArguments( UNISTRING("com.sun.star.configuration.ConfigurationAccess"), aArgumentList ), uno::UNO_QUERY_THROW ); util::URL aURL; xNameAccess->getByName(UNISTRING("URL")) >>= aURL.Complete; uno::Reference < util::XURLTransformer > xTransformer( xFactory->createInstance( UNISTRING( "com.sun.star.util.URLTransformer" ) ), uno::UNO_QUERY_THROW ); xTransformer->parseStrict(aURL); uno::Reference < frame::XDesktop > xDesktop( xFactory->createInstance( UNISTRING( "com.sun.star.frame.Desktop" ) ), uno::UNO_QUERY_THROW ); uno::Reference< frame::XDispatchProvider > xDispatchProvider( xDesktop->getCurrentFrame(), uno::UNO_QUERY ); uno::Reference< frame::XDispatch > xDispatch = xDispatchProvider->queryDispatch(aURL, rtl::OUString(), 0); if( xDispatch.is() ) xDispatch->dispatch(aURL, uno::Sequence< beans::PropertyValue > ()); } catch( const uno::Exception& e ) { OSL_TRACE( "Caught exception: %s\n thread terminated.\n", rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr()); } return 0; } <commit_msg>INTEGRATION: CWS pchfix02 (1.2.16); FILE MERGED 2006/09/01 17:46:20 kaib 1.2.16.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optupdt.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 04:32:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifdef SVX_DLLIMPLEMENTATION #undef SVX_DLLIMPLEMENTATION #endif // include --------------------------------------------------------------- #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #include "optupdt.hxx" #include "optupdt.hrc" #include "dialmgr.hxx" #include "dialogs.hrc" #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFolderPicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_ #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_ #include <com/sun/star/frame/XDispatchProvider.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_ #include <com/sun/star/util/XChangesBatch.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #include <osl/file.hxx> #include <osl/security.hxx> namespace beans = ::com::sun::star::beans; namespace container = ::com::sun::star::container; namespace dialogs = ::com::sun::star::ui::dialogs; namespace frame = ::com::sun::star::frame; namespace lang = ::com::sun::star::lang; namespace uno = ::com::sun::star::uno; namespace util = ::com::sun::star::util; // define ---------------------------------------------------------------- #define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s)) // class SvxOnlineUpdateTabPage -------------------------------------------------- SvxOnlineUpdateTabPage::SvxOnlineUpdateTabPage( Window* pParent, const SfxItemSet& rSet ) : SfxTabPage( pParent, SVX_RES( RID_SVXPAGE_ONLINEUPDATE ), rSet ), m_aOptionsLine( this, ResId( FL_OPTIONS ) ), m_aAutoCheckCheckBox( this, ResId( CB_AUTOCHECK ) ), m_aEveryDayButton( this, ResId( RB_EVERYDAY ) ), m_aEveryWeekButton( this, ResId( RB_EVERYWEEK ) ), m_aEveryMonthButton( this, ResId( RB_EVERYMONTH ) ), m_aCheckNowButton( this, ResId( PB_CHECKNOW ) ), m_aAutoDownloadCheckBox( this, ResId( CB_AUTODOWNLOAD ) ), m_aDestPathLabel( this, ResId( FT_DESTPATHLABEL ) ), m_aDestPath( this, ResId( FT_DESTPATH ) ), m_aChangePathButton( this, ResId( PB_CHANGEPATH ) ) { FreeResource(); m_aAutoCheckCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoCheckHdl_Impl ) ); m_aCheckNowButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, CheckNowHdl_Impl ) ); m_aAutoDownloadCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl ) ); m_aChangePathButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, FileDialogHdl_Impl ) ); uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); m_xUpdateAccess = uno::Reference < container::XNameReplace >( xFactory->createInstance( UNISTRING( "com.sun.star.setup.UpdateCheckConfig" ) ), uno::UNO_QUERY_THROW ); sal_Bool bDownloadSupported; m_xUpdateAccess->getByName( UNISTRING( "DownloadSupported") ) >>= bDownloadSupported; WinBits nStyle = m_aDestPath.GetStyle(); nStyle |= WB_PATHELLIPSIS; m_aDestPath.SetStyle(nStyle); m_aAutoDownloadCheckBox.Show(bDownloadSupported); m_aDestPathLabel.Show(bDownloadSupported); m_aDestPath.Show(bDownloadSupported); m_aChangePathButton.Show(bDownloadSupported); } // ----------------------------------------------------------------------- SvxOnlineUpdateTabPage::~SvxOnlineUpdateTabPage() { } // ----------------------------------------------------------------------- SfxTabPage* SvxOnlineUpdateTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet ) { return new SvxOnlineUpdateTabPage( pParent, rAttrSet ); } // ----------------------------------------------------------------------- BOOL SvxOnlineUpdateTabPage::FillItemSet( SfxItemSet& ) { BOOL bModified = FALSE; sal_Bool bValue; sal_Int64 nValue; if( m_aAutoCheckCheckBox.GetSavedValue() != m_aAutoCheckCheckBox.IsChecked() ) { bValue = (TRUE == m_aAutoCheckCheckBox.IsChecked()); m_xUpdateAccess->replaceByName( UNISTRING("AutoCheckEnabled"), uno::makeAny( bValue ) ); bModified = TRUE; } nValue = 0; if( TRUE == m_aEveryDayButton.IsChecked() ) { if( FALSE == m_aEveryDayButton.GetSavedValue() ) nValue = 86400; } else if( TRUE == m_aEveryWeekButton.IsChecked() ) { if( FALSE == m_aEveryWeekButton.GetSavedValue() ) nValue = 604800; } else if( TRUE == m_aEveryMonthButton.IsChecked() ) { if( FALSE == m_aEveryMonthButton.GetSavedValue() ) nValue = 2592000; } if( nValue > 0 ) { m_xUpdateAccess->replaceByName( UNISTRING("CheckInterval"), uno::makeAny( nValue ) ); bModified = TRUE; } if( m_aAutoDownloadCheckBox.GetSavedValue() != m_aAutoDownloadCheckBox.IsChecked() ) { bValue = (TRUE == m_aAutoDownloadCheckBox.IsChecked()); m_xUpdateAccess->replaceByName( UNISTRING("AutoDownloadEnabled"), uno::makeAny( bValue ) ); bModified = TRUE; } rtl::OUString sValue, aURL; m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue; if( ( osl::FileBase::E_None == osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) ) && ( ! aURL.equals( sValue ) ) ) { m_xUpdateAccess->replaceByName( UNISTRING("DownloadDestination"), uno::makeAny( aURL ) ); bModified = TRUE; } uno::Reference< util::XChangesBatch > xChangesBatch(m_xUpdateAccess, uno::UNO_QUERY); if( xChangesBatch.is() && xChangesBatch->hasPendingChanges() ) xChangesBatch->commitChanges(); return bModified; } // ----------------------------------------------------------------------- void SvxOnlineUpdateTabPage::Reset( const SfxItemSet& ) { sal_Bool bValue; m_xUpdateAccess->getByName( UNISTRING("AutoCheckEnabled") ) >>= bValue; m_aAutoCheckCheckBox.Check(bValue); m_aEveryDayButton.Enable(bValue); m_aEveryWeekButton.Enable(bValue); m_aEveryMonthButton.Enable(bValue); sal_Int64 nValue; m_xUpdateAccess->getByName( UNISTRING("CheckInterval") ) >>= nValue; if( nValue == 86400 ) m_aEveryDayButton.Check(); else if( nValue == 604800 ) m_aEveryWeekButton.Check(); else m_aEveryMonthButton.Check(); m_aAutoCheckCheckBox.SaveValue(); m_aEveryDayButton.SaveValue(); m_aEveryWeekButton.SaveValue(); m_aEveryMonthButton.SaveValue(); m_xUpdateAccess->getByName( UNISTRING("AutoDownloadEnabled") ) >>= bValue; m_aAutoDownloadCheckBox.Check(bValue); m_aDestPathLabel.Enable(bValue); m_aDestPath.Enable(bValue); m_aChangePathButton.Enable(bValue); rtl::OUString sValue, aPath; m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue; if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(sValue, aPath) ) m_aDestPath.SetText(aPath); m_aAutoDownloadCheckBox.SaveValue(); } // ----------------------------------------------------------------------- void SvxOnlineUpdateTabPage::FillUserData() { } // ----------------------------------------------------------------------- IMPL_LINK( SvxOnlineUpdateTabPage, AutoCheckHdl_Impl, CheckBox *, pBox ) { BOOL bEnabled = pBox->IsChecked(); m_aEveryDayButton.Enable(bEnabled); m_aEveryWeekButton.Enable(bEnabled); m_aEveryMonthButton.Enable(bEnabled); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl, CheckBox *, pBox ) { BOOL bEnabled = pBox->IsChecked(); m_aDestPathLabel.Enable(bEnabled); m_aDestPath.Enable(bEnabled); m_aChangePathButton.Enable(bEnabled); return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxOnlineUpdateTabPage, FileDialogHdl_Impl, PushButton *, EMPTYARG ) { uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); uno::Reference < dialogs::XFolderPicker > xFolderPicker( xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) ) ), uno::UNO_QUERY ); rtl::OUString aURL; if( osl::FileBase::E_None != osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) ) osl::Security().getHomeDir(aURL); xFolderPicker->setDisplayDirectory( aURL ); sal_Int16 nRet = xFolderPicker->execute(); if ( dialogs::ExecutableDialogResults::OK == nRet ) { rtl::OUString aFolder; if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(xFolderPicker->getDirectory(), aFolder)) m_aDestPath.SetText( aFolder ); } return 0; } // ----------------------------------------------------------------------- IMPL_LINK( SvxOnlineUpdateTabPage, CheckNowHdl_Impl, PushButton *, EMPTYARG ) { uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); try { uno::Reference< lang::XMultiServiceFactory > xConfigProvider( xFactory->createInstance( UNISTRING( "com.sun.star.configuration.ConfigurationProvider" )), uno::UNO_QUERY_THROW); beans::PropertyValue aProperty; aProperty.Name = UNISTRING( "nodepath" ); aProperty.Value = uno::makeAny( UNISTRING("org.openoffice.Office.Addons/AddonUI/OfficeHelp/UpdateCheckJob") ); uno::Sequence< uno::Any > aArgumentList( 1 ); aArgumentList[0] = uno::makeAny( aProperty ); uno::Reference< container::XNameAccess > xNameAccess( xConfigProvider->createInstanceWithArguments( UNISTRING("com.sun.star.configuration.ConfigurationAccess"), aArgumentList ), uno::UNO_QUERY_THROW ); util::URL aURL; xNameAccess->getByName(UNISTRING("URL")) >>= aURL.Complete; uno::Reference < util::XURLTransformer > xTransformer( xFactory->createInstance( UNISTRING( "com.sun.star.util.URLTransformer" ) ), uno::UNO_QUERY_THROW ); xTransformer->parseStrict(aURL); uno::Reference < frame::XDesktop > xDesktop( xFactory->createInstance( UNISTRING( "com.sun.star.frame.Desktop" ) ), uno::UNO_QUERY_THROW ); uno::Reference< frame::XDispatchProvider > xDispatchProvider( xDesktop->getCurrentFrame(), uno::UNO_QUERY ); uno::Reference< frame::XDispatch > xDispatch = xDispatchProvider->queryDispatch(aURL, rtl::OUString(), 0); if( xDispatch.is() ) xDispatch->dispatch(aURL, uno::Sequence< beans::PropertyValue > ()); } catch( const uno::Exception& e ) { OSL_TRACE( "Caught exception: %s\n thread terminated.\n", rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr()); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tabline.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: pb $ $Date: 2000-09-26 06:37:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // include --------------------------------------------------------------- #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #pragma hdrstop #define _SVX_TABLINE_CXX #include "dialogs.hrc" #include "tabline.hrc" #include "dlgname.hrc" #define ITEMID_COLOR_TABLE SID_COLOR_TABLE #define ITEMID_DASH_LIST SID_DASH_LIST #define ITEMID_LINEEND_LIST SID_LINEEND_LIST #include "tabline.hxx" #include "dlgname.hxx" #include "dialmgr.hxx" #include "svdmodel.hxx" #include "xtable.hxx" #include "drawitem.hxx" #define DLGWIN this->GetParent()->GetParent() #define BITMAP_WIDTH 32 #define BITMAP_HEIGHT 12 #define XOUT_WIDTH 150 /************************************************************************* |* |* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu |* \************************************************************************/ SvxLineTabDialog::SvxLineTabDialog ( Window* pParent, const SfxItemSet* pAttr, SdrModel* pModel, const SdrObject* pSdrObj, BOOL bHasObj ) : SfxTabDialog ( pParent, SVX_RES( RID_SVXDLG_LINE ), pAttr ), pDrawModel ( pModel ), pObj ( pSdrObj ), bObjSelected ( bHasObj ), pColorTab ( pModel->GetColorTable() ), pDashList ( pModel->GetDashList() ), pLineEndList ( pModel->GetLineEndList() ), pNewDashList ( pModel->GetDashList() ), pNewLineEndList ( pModel->GetLineEndList() ), rOutAttrs ( *pAttr ) { FreeResource(); AddTabPage( RID_SVXPAGE_LINE, SvxLineTabPage::Create, 0); AddTabPage( RID_SVXPAGE_LINE_DEF, SvxLineDefTabPage::Create, 0); AddTabPage( RID_SVXPAGE_LINEEND_DEF, SvxLineEndDefTabPage::Create, 0); nLineEndListState = CT_NONE; nDashListState = CT_NONE; nDlgType = 0; nPageType = 0; // wird hier in erster Linie benutzt, um mit FillItemSet // die richtigen Attribute zu erhalten ( noch Fragen? ) nPosDashLb = 0; nPosLineEndLb = 0; SetCurPageId( RID_SVXPAGE_LINE ); CancelButton& rBtnCancel = GetCancelButton(); rBtnCancel.SetClickHdl( LINK( this, SvxLineTabDialog, CancelHdl ) ); //! rBtnCancel.SetText( SVX_RESSTR( RID_SVXSTR_CLOSE ) ); } // ----------------------------------------------------------------------- SvxLineTabDialog::~SvxLineTabDialog() { } // ----------------------------------------------------------------------- void SvxLineTabDialog::SavePalettes() { if( pNewDashList != pDrawModel->GetDashList() ) { delete pDrawModel->GetDashList(); pDrawModel->SetDashList( pNewDashList ); SfxObjectShell::Current()->PutItem( SvxDashListItem( pNewDashList ) ); pDashList = pDrawModel->GetDashList(); } if( pNewLineEndList != pDrawModel->GetLineEndList() ) { delete pDrawModel->GetLineEndList(); pDrawModel->SetLineEndList( pNewLineEndList ); SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pNewLineEndList ) ); pLineEndList = pDrawModel->GetLineEndList(); } // Speichern der Tabellen, wenn sie geaendert wurden. const String aPath( SvtPathOptions().GetPalettePath() ); if( nDashListState & CT_MODIFIED ) { pDashList->SetPath( aPath ); pDashList->Save(); // ToolBoxControls werden benachrichtigt: SfxObjectShell::Current()->PutItem( SvxDashListItem( pDashList ) ); } if( nLineEndListState & CT_MODIFIED ) { pLineEndList->SetPath( aPath ); pLineEndList->Save(); // ToolBoxControls werden benachrichtigt: SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pLineEndList ) ); } } // ----------------------------------------------------------------------- short SvxLineTabDialog::Ok() { SavePalettes(); // Es wird RET_OK zurueckgeliefert, wenn wenigstens eine // TabPage in FillItemSet() TRUE zurueckliefert. Dieses // geschieht z.Z. standardmaessig. return( SfxTabDialog::Ok() ); } // ----------------------------------------------------------------------- IMPL_LINK_INLINE_START( SvxLineTabDialog, CancelHdl, void *, p ) { SavePalettes(); EndDialog( RET_CANCEL ); return 0; } IMPL_LINK_INLINE_END( SvxLineTabDialog, CancelHdl, void *, p ) // ----------------------------------------------------------------------- void SvxLineTabDialog::PageCreated( USHORT nId, SfxTabPage &rPage ) { switch( nId ) { case RID_SVXPAGE_LINE: ( (SvxLineTabPage&) rPage ).SetColorTable( pColorTab ); ( (SvxLineTabPage&) rPage ).SetDashList( pDashList ); ( (SvxLineTabPage&) rPage ).SetLineEndList( pLineEndList ); ( (SvxLineTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineTabPage&) rPage ).SetPosDashLb( &nPosDashLb ); ( (SvxLineTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb ); ( (SvxLineTabPage&) rPage ).SetDashChgd( &nDashListState ); ( (SvxLineTabPage&) rPage ).SetLineEndChgd( &nLineEndListState ); ( (SvxLineTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineTabPage&) rPage ).Construct(); // ActivatePage() wird das erste mal nicht gerufen ( (SvxLineTabPage&) rPage ).ActivatePage( rOutAttrs ); break; case RID_SVXPAGE_LINE_DEF: ( (SvxLineDefTabPage&) rPage ).SetDashList( pDashList ); ( (SvxLineDefTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineDefTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineDefTabPage&) rPage ).SetPosDashLb( &nPosDashLb ); ( (SvxLineDefTabPage&) rPage ).SetDashChgd( &nDashListState ); ( (SvxLineDefTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineDefTabPage&) rPage ).Construct(); break; case RID_SVXPAGE_LINEEND_DEF: ( (SvxLineEndDefTabPage&) rPage ).SetLineEndList( pLineEndList ); ( (SvxLineEndDefTabPage&) rPage ).SetPolyObj( pObj ); ( (SvxLineEndDefTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineEndDefTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineEndDefTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb ); ( (SvxLineEndDefTabPage&) rPage ).SetLineEndChgd( &nLineEndListState ); ( (SvxLineEndDefTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineEndDefTabPage&) rPage ).Construct(); break; } } <commit_msg>INTEGRATION: CWS dialogdiet (1.2.528); FILE MERGED 2004/01/17 01:45:18 mwu 1.2.528.1: DialogDiet 2004_01_17<commit_after>/************************************************************************* * * $RCSfile: tabline.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-02-03 18:53:05 $ * * 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 --------------------------------------------------------------- #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #pragma hdrstop #define _SVX_TABLINE_CXX #include "dialogs.hrc" #include "tabline.hrc" #include "dlgname.hrc" #define ITEMID_COLOR_TABLE SID_COLOR_TABLE #define ITEMID_DASH_LIST SID_DASH_LIST #define ITEMID_LINEEND_LIST SID_LINEEND_LIST #include "cuitabline.hxx" #include "dlgname.hxx" #include "dialmgr.hxx" #include "svdmodel.hxx" #include "xtable.hxx" #include "drawitem.hxx" #define DLGWIN this->GetParent()->GetParent() #define BITMAP_WIDTH 32 #define BITMAP_HEIGHT 12 #define XOUT_WIDTH 150 /************************************************************************* |* |* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu |* \************************************************************************/ SvxLineTabDialog::SvxLineTabDialog ( Window* pParent, const SfxItemSet* pAttr, SdrModel* pModel, const SdrObject* pSdrObj, BOOL bHasObj ) : SfxTabDialog ( pParent, SVX_RES( RID_SVXDLG_LINE ), pAttr ), pDrawModel ( pModel ), pObj ( pSdrObj ), bObjSelected ( bHasObj ), pColorTab ( pModel->GetColorTable() ), pDashList ( pModel->GetDashList() ), pLineEndList ( pModel->GetLineEndList() ), pNewDashList ( pModel->GetDashList() ), pNewLineEndList ( pModel->GetLineEndList() ), rOutAttrs ( *pAttr ) { FreeResource(); AddTabPage( RID_SVXPAGE_LINE, SvxLineTabPage::Create, 0); AddTabPage( RID_SVXPAGE_LINE_DEF, SvxLineDefTabPage::Create, 0); AddTabPage( RID_SVXPAGE_LINEEND_DEF, SvxLineEndDefTabPage::Create, 0); nLineEndListState = CT_NONE; nDashListState = CT_NONE; nDlgType = 0; nPageType = 0; // wird hier in erster Linie benutzt, um mit FillItemSet // die richtigen Attribute zu erhalten ( noch Fragen? ) nPosDashLb = 0; nPosLineEndLb = 0; SetCurPageId( RID_SVXPAGE_LINE ); CancelButton& rBtnCancel = GetCancelButton(); rBtnCancel.SetClickHdl( LINK( this, SvxLineTabDialog, CancelHdl ) ); //! rBtnCancel.SetText( SVX_RESSTR( RID_SVXSTR_CLOSE ) ); } // ----------------------------------------------------------------------- SvxLineTabDialog::~SvxLineTabDialog() { } // ----------------------------------------------------------------------- void SvxLineTabDialog::SavePalettes() { if( pNewDashList != pDrawModel->GetDashList() ) { delete pDrawModel->GetDashList(); pDrawModel->SetDashList( pNewDashList ); SfxObjectShell::Current()->PutItem( SvxDashListItem( pNewDashList ) ); pDashList = pDrawModel->GetDashList(); } if( pNewLineEndList != pDrawModel->GetLineEndList() ) { delete pDrawModel->GetLineEndList(); pDrawModel->SetLineEndList( pNewLineEndList ); SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pNewLineEndList ) ); pLineEndList = pDrawModel->GetLineEndList(); } // Speichern der Tabellen, wenn sie geaendert wurden. const String aPath( SvtPathOptions().GetPalettePath() ); if( nDashListState & CT_MODIFIED ) { pDashList->SetPath( aPath ); pDashList->Save(); // ToolBoxControls werden benachrichtigt: SfxObjectShell::Current()->PutItem( SvxDashListItem( pDashList ) ); } if( nLineEndListState & CT_MODIFIED ) { pLineEndList->SetPath( aPath ); pLineEndList->Save(); // ToolBoxControls werden benachrichtigt: SfxObjectShell::Current()->PutItem( SvxLineEndListItem( pLineEndList ) ); } } // ----------------------------------------------------------------------- short SvxLineTabDialog::Ok() { SavePalettes(); // Es wird RET_OK zurueckgeliefert, wenn wenigstens eine // TabPage in FillItemSet() TRUE zurueckliefert. Dieses // geschieht z.Z. standardmaessig. return( SfxTabDialog::Ok() ); } // ----------------------------------------------------------------------- IMPL_LINK_INLINE_START( SvxLineTabDialog, CancelHdl, void *, p ) { SavePalettes(); EndDialog( RET_CANCEL ); return 0; } IMPL_LINK_INLINE_END( SvxLineTabDialog, CancelHdl, void *, p ) // ----------------------------------------------------------------------- void SvxLineTabDialog::PageCreated( USHORT nId, SfxTabPage &rPage ) { switch( nId ) { case RID_SVXPAGE_LINE: ( (SvxLineTabPage&) rPage ).SetColorTable( pColorTab ); ( (SvxLineTabPage&) rPage ).SetDashList( pDashList ); ( (SvxLineTabPage&) rPage ).SetLineEndList( pLineEndList ); ( (SvxLineTabPage&) rPage ).SetDlgType( nDlgType );//CHINA001 ( (SvxLineTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineTabPage&) rPage ).SetPageType( nPageType );//CHINA001 ( (SvxLineTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineTabPage&) rPage ).SetPosDashLb( &nPosDashLb ); ( (SvxLineTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb ); ( (SvxLineTabPage&) rPage ).SetDashChgd( &nDashListState ); ( (SvxLineTabPage&) rPage ).SetLineEndChgd( &nLineEndListState ); ( (SvxLineTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineTabPage&) rPage ).Construct(); // ActivatePage() wird das erste mal nicht gerufen ( (SvxLineTabPage&) rPage ).ActivatePage( rOutAttrs ); break; case RID_SVXPAGE_LINE_DEF: ( (SvxLineDefTabPage&) rPage ).SetDashList( pDashList ); ( (SvxLineDefTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineDefTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineDefTabPage&) rPage ).SetPosDashLb( &nPosDashLb ); ( (SvxLineDefTabPage&) rPage ).SetDashChgd( &nDashListState ); ( (SvxLineDefTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineDefTabPage&) rPage ).Construct(); break; case RID_SVXPAGE_LINEEND_DEF: ( (SvxLineEndDefTabPage&) rPage ).SetLineEndList( pLineEndList ); ( (SvxLineEndDefTabPage&) rPage ).SetPolyObj( pObj ); ( (SvxLineEndDefTabPage&) rPage ).SetDlgType( &nDlgType ); ( (SvxLineEndDefTabPage&) rPage ).SetPageType( &nPageType ); ( (SvxLineEndDefTabPage&) rPage ).SetPosLineEndLb( &nPosLineEndLb ); ( (SvxLineEndDefTabPage&) rPage ).SetLineEndChgd( &nLineEndListState ); ( (SvxLineEndDefTabPage&) rPage ).SetObjSelected( bObjSelected ); ( (SvxLineEndDefTabPage&) rPage ).Construct(); break; } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <tools/stream.hxx> #include <com/sun/star/table/BorderLine.hpp> #include <com/sun/star/table/CellVertJustify2.hpp> #include <com/sun/star/table/ShadowLocation.hpp> #include <com/sun/star/table/TableBorder.hpp> #include <com/sun/star/table/ShadowFormat.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #include <com/sun/star/table/CellContentType.hpp> #include <com/sun/star/table/TableOrientation.hpp> #include <com/sun/star/util/SortField.hpp> #include <com/sun/star/util/SortFieldType.hpp> #include <com/sun/star/table/CellOrientation.hpp> #include <com/sun/star/table/CellAddress.hpp> #include "rotmodit.hxx" using namespace ::rtl; using namespace ::com::sun::star; // STATIC DATA ----------------------------------------------------------- TYPEINIT1_FACTORY(SvxRotateModeItem, SfxEnumItem, new SvxRotateModeItem(SVX_ROTATE_MODE_STANDARD, 0)); //----------------------------------------------------------------------- // SvxRotateModeItem - Ausrichtung bei gedrehtem Text //----------------------------------------------------------------------- SvxRotateModeItem::SvxRotateModeItem( SvxRotateMode eMode, USHORT _nWhich ) : SfxEnumItem( _nWhich, (USHORT)eMode ) { } SvxRotateModeItem::SvxRotateModeItem( const SvxRotateModeItem& rItem ) : SfxEnumItem( rItem ) { } SvxRotateModeItem::~SvxRotateModeItem() { } SfxPoolItem* SvxRotateModeItem::Create( SvStream& rStream, USHORT ) const { USHORT nVal; rStream >> nVal; return new SvxRotateModeItem( (SvxRotateMode) nVal,Which() ); } SfxItemPresentation SvxRotateModeItem::GetPresentation( SfxItemPresentation ePres, SfxMapUnit /*eCoreUnit*/, SfxMapUnit /*ePresUnit*/, String& rText, const IntlWrapper * ) const { rText.Erase(); switch ( ePres ) { case SFX_ITEM_PRESENTATION_COMPLETE: rText.AppendAscii("..."); rText.AppendAscii(": "); // break; // DURCHFALLEN!!! case SFX_ITEM_PRESENTATION_NAMELESS: rText += UniString::CreateFromInt32( GetValue() ); break; default: ;//prevent warning } return ePres; } String SvxRotateModeItem::GetValueText( USHORT nVal ) const { String aText; switch ( nVal ) { case SVX_ROTATE_MODE_STANDARD: case SVX_ROTATE_MODE_TOP: case SVX_ROTATE_MODE_CENTER: case SVX_ROTATE_MODE_BOTTOM: aText.AppendAscii("..."); break; default: DBG_ERROR("SvxRotateModeItem: falscher enum"); break; } return aText; } USHORT SvxRotateModeItem::GetValueCount() const { return 4; // STANDARD, TOP, CENTER, BOTTOM } SfxPoolItem* SvxRotateModeItem::Clone( SfxItemPool* ) const { return new SvxRotateModeItem( *this ); } USHORT SvxRotateModeItem::GetVersion( USHORT /*nFileVersion*/ ) const { return 0; } bool SvxRotateModeItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const { sal_Int32 nUno = table::CellVertJustify2::STANDARD; switch ( (SvxRotateMode)GetValue() ) { case SVX_ROTATE_MODE_STANDARD: nUno = table::CellVertJustify2::STANDARD; break; case SVX_ROTATE_MODE_TOP: nUno = table::CellVertJustify2::TOP; break; case SVX_ROTATE_MODE_CENTER: nUno = table::CellVertJustify2::CENTER; break; case SVX_ROTATE_MODE_BOTTOM: nUno = table::CellVertJustify2::BOTTOM; break; } rVal <<= nUno; return true; } bool SvxRotateModeItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ ) { sal_Int32 nUno; if(!(rVal >>= nUno)) { nUno = table::CellVertJustify2::STANDARD; } SvxRotateMode eSvx = SVX_ROTATE_MODE_STANDARD; switch (nUno) { case table::CellVertJustify2::STANDARD: eSvx = SVX_ROTATE_MODE_STANDARD; break; case table::CellVertJustify2::TOP: eSvx = SVX_ROTATE_MODE_TOP; break; case table::CellVertJustify2::CENTER: eSvx = SVX_ROTATE_MODE_CENTER; break; case table::CellVertJustify2::BOTTOM: eSvx = SVX_ROTATE_MODE_BOTTOM; break; default: ;//prevent warning } SetValue( (USHORT)eSvx ); return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fix a compile time warning: un-initialized variable.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <tools/stream.hxx> #include <com/sun/star/table/BorderLine.hpp> #include <com/sun/star/table/CellVertJustify2.hpp> #include <com/sun/star/table/ShadowLocation.hpp> #include <com/sun/star/table/TableBorder.hpp> #include <com/sun/star/table/ShadowFormat.hpp> #include <com/sun/star/table/CellRangeAddress.hpp> #include <com/sun/star/table/CellContentType.hpp> #include <com/sun/star/table/TableOrientation.hpp> #include <com/sun/star/util/SortField.hpp> #include <com/sun/star/util/SortFieldType.hpp> #include <com/sun/star/table/CellOrientation.hpp> #include <com/sun/star/table/CellAddress.hpp> #include "rotmodit.hxx" using namespace ::rtl; using namespace ::com::sun::star; // STATIC DATA ----------------------------------------------------------- TYPEINIT1_FACTORY(SvxRotateModeItem, SfxEnumItem, new SvxRotateModeItem(SVX_ROTATE_MODE_STANDARD, 0)); //----------------------------------------------------------------------- // SvxRotateModeItem - Ausrichtung bei gedrehtem Text //----------------------------------------------------------------------- SvxRotateModeItem::SvxRotateModeItem( SvxRotateMode eMode, USHORT _nWhich ) : SfxEnumItem( _nWhich, (USHORT)eMode ) { } SvxRotateModeItem::SvxRotateModeItem( const SvxRotateModeItem& rItem ) : SfxEnumItem( rItem ) { } SvxRotateModeItem::~SvxRotateModeItem() { } SfxPoolItem* SvxRotateModeItem::Create( SvStream& rStream, USHORT ) const { USHORT nVal; rStream >> nVal; return new SvxRotateModeItem( (SvxRotateMode) nVal,Which() ); } SfxItemPresentation SvxRotateModeItem::GetPresentation( SfxItemPresentation ePres, SfxMapUnit /*eCoreUnit*/, SfxMapUnit /*ePresUnit*/, String& rText, const IntlWrapper * ) const { rText.Erase(); switch ( ePres ) { case SFX_ITEM_PRESENTATION_COMPLETE: rText.AppendAscii("..."); rText.AppendAscii(": "); // break; // DURCHFALLEN!!! case SFX_ITEM_PRESENTATION_NAMELESS: rText += UniString::CreateFromInt32( GetValue() ); break; default: ;//prevent warning } return ePres; } String SvxRotateModeItem::GetValueText( USHORT nVal ) const { String aText; switch ( nVal ) { case SVX_ROTATE_MODE_STANDARD: case SVX_ROTATE_MODE_TOP: case SVX_ROTATE_MODE_CENTER: case SVX_ROTATE_MODE_BOTTOM: aText.AppendAscii("..."); break; default: DBG_ERROR("SvxRotateModeItem: falscher enum"); break; } return aText; } USHORT SvxRotateModeItem::GetValueCount() const { return 4; // STANDARD, TOP, CENTER, BOTTOM } SfxPoolItem* SvxRotateModeItem::Clone( SfxItemPool* ) const { return new SvxRotateModeItem( *this ); } USHORT SvxRotateModeItem::GetVersion( USHORT /*nFileVersion*/ ) const { return 0; } bool SvxRotateModeItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const { sal_Int32 nUno = table::CellVertJustify2::STANDARD; switch ( (SvxRotateMode)GetValue() ) { case SVX_ROTATE_MODE_STANDARD: nUno = table::CellVertJustify2::STANDARD; break; case SVX_ROTATE_MODE_TOP: nUno = table::CellVertJustify2::TOP; break; case SVX_ROTATE_MODE_CENTER: nUno = table::CellVertJustify2::CENTER; break; case SVX_ROTATE_MODE_BOTTOM: nUno = table::CellVertJustify2::BOTTOM; break; } rVal <<= nUno; return true; } bool SvxRotateModeItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ ) { sal_Int32 nUno(0); if(!(rVal >>= nUno)) { nUno = table::CellVertJustify2::STANDARD; } SvxRotateMode eSvx = SVX_ROTATE_MODE_STANDARD; switch (nUno) { case table::CellVertJustify2::STANDARD: eSvx = SVX_ROTATE_MODE_STANDARD; break; case table::CellVertJustify2::TOP: eSvx = SVX_ROTATE_MODE_TOP; break; case table::CellVertJustify2::CENTER: eSvx = SVX_ROTATE_MODE_CENTER; break; case table::CellVertJustify2::BOTTOM: eSvx = SVX_ROTATE_MODE_BOTTOM; break; default: ;//prevent warning } SetValue( (USHORT)eSvx ); return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlcnitm.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-10-12 12:56:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _COM_SUN_STAR_XML_ATTRIBUTEDATA_HPP_ #include <com/sun/star/xml/AttributeData.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ #include <com/sun/star/lang/XUnoTunnel.hpp> #endif #ifndef _XMLOFF_XMLCNIMP_HXX #include <xmloff/xmlcnimp.hxx> #endif #ifndef _XMLOFF_XMLCNITM_HXX #include <xmloff/unoatrcn.hxx> #endif #include "xmlcnitm.hxx" using namespace rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::xml; // ------------------------------------------------------------------------ TYPEINIT1(SvXMLAttrContainerItem, SfxPoolItem); SvXMLAttrContainerItem::SvXMLAttrContainerItem( USHORT _nWhich ) : SfxPoolItem( _nWhich ) { pImpl = new SvXMLAttrContainerData; } SvXMLAttrContainerItem::SvXMLAttrContainerItem( const SvXMLAttrContainerItem& rItem ) : SfxPoolItem( rItem ) { pImpl = new SvXMLAttrContainerData( *rItem.pImpl ); } SvXMLAttrContainerItem::~SvXMLAttrContainerItem() { delete pImpl; } int SvXMLAttrContainerItem::operator==( const SfxPoolItem& rItem ) const { DBG_ASSERT( rItem.ISA(SvXMLAttrContainerItem), "SvXMLAttrContainerItem::operator ==(): Bad type"); return *pImpl == *((const SvXMLAttrContainerItem&)rItem).pImpl; } int SvXMLAttrContainerItem::Compare( const SfxPoolItem &/*rWith*/ ) const { DBG_ASSERT( !this, "not yet implemented" ); return 0; } SfxItemPresentation SvXMLAttrContainerItem::GetPresentation( SfxItemPresentation /*ePresentation*/, SfxMapUnit /*eCoreMetric*/, SfxMapUnit /*ePresentationMetric*/, XubString &/*rText*/, const IntlWrapper * /*pIntlWrapper*/ ) const { return SFX_ITEM_PRESENTATION_NONE; } USHORT SvXMLAttrContainerItem::GetVersion( USHORT /*nFileFormatVersion*/ ) const { // This item should never be stored return USHRT_MAX; } BOOL SvXMLAttrContainerItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ ) const { Reference<XNameContainer> xContainer = new SvUnoAttributeContainer( new SvXMLAttrContainerData( *pImpl ) ); rVal.setValue( &xContainer, ::getCppuType((Reference<XNameContainer>*)0) ); return TRUE; } BOOL SvXMLAttrContainerItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ ) { Reference<XInterface> xRef; SvUnoAttributeContainer* pContainer = NULL; if( rVal.getValue() != NULL && rVal.getValueType().getTypeClass() == TypeClass_INTERFACE ) { xRef = *(Reference<XInterface>*)rVal.getValue(); Reference<XUnoTunnel> xTunnel(xRef, UNO_QUERY); if( xTunnel.is() ) pContainer = (SvUnoAttributeContainer*)(ULONG)xTunnel->getSomething(SvUnoAttributeContainer::getUnoTunnelId()); } if( pContainer ) { delete pImpl; pImpl = new SvXMLAttrContainerData( * pContainer->GetContainerImpl() ); } else { SvXMLAttrContainerData* pNewImpl = new SvXMLAttrContainerData; try { Reference<XNameContainer> xContainer( xRef, UNO_QUERY ); if( !xContainer.is() ) return FALSE; const Sequence< OUString > aNameSequence( xContainer->getElementNames() ); const OUString* pNames = aNameSequence.getConstArray(); const INT32 nCount = aNameSequence.getLength(); Any aAny; AttributeData* pData; INT32 nAttr; for( nAttr = 0; nAttr < nCount; nAttr++ ) { const OUString aName( *pNames++ ); aAny = xContainer->getByName( aName ); if( aAny.getValue() == NULL || aAny.getValueType() != ::getCppuType((AttributeData*)0) ) return FALSE; pData = (AttributeData*)aAny.getValue(); sal_Int32 pos = aName.indexOf( sal_Unicode(':') ); if( pos != -1 ) { const OUString aPrefix( aName.copy( 0, pos )); const OUString aLName( aName.copy( pos+1 )); if( pData->Namespace.getLength() == 0 ) { if( !pNewImpl->AddAttr( aPrefix, aLName, pData->Value ) ) break; } else { if( !pNewImpl->AddAttr( aPrefix, pData->Namespace, aLName, pData->Value ) ) break; } } else { if( !pNewImpl->AddAttr( aName, pData->Value ) ) break; } } if( nAttr == nCount ) { delete pImpl; pImpl = pNewImpl; } else { delete pNewImpl; return FALSE; } } catch(...) { delete pNewImpl; return FALSE; } } return TRUE; } BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rLName, const OUString& rValue ) { return pImpl->AddAttr( rLName, rValue ); } BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rPrefix, const OUString& rNamespace, const OUString& rLName, const OUString& rValue ) { return pImpl->AddAttr( rPrefix, rNamespace, rLName, rValue ); } USHORT SvXMLAttrContainerItem::GetAttrCount() const { return (USHORT)pImpl->GetAttrCount(); } OUString SvXMLAttrContainerItem::GetAttrNamespace( USHORT i ) const { return pImpl->GetAttrNamespace( i ); } OUString SvXMLAttrContainerItem::GetAttrPrefix( USHORT i ) const { return pImpl->GetAttrPrefix( i ); } const OUString& SvXMLAttrContainerItem::GetAttrLName( USHORT i ) const { return pImpl->GetAttrLName( i ); } const OUString& SvXMLAttrContainerItem::GetAttrValue( USHORT i ) const { return pImpl->GetAttrValue( i ); } USHORT SvXMLAttrContainerItem::GetFirstNamespaceIndex() const { return pImpl->GetFirstNamespaceIndex(); } USHORT SvXMLAttrContainerItem::GetNextNamespaceIndex( USHORT nIdx ) const { return pImpl->GetNextNamespaceIndex( nIdx ); } const OUString& SvXMLAttrContainerItem::GetNamespace( USHORT i ) const { return pImpl->GetNamespace( i ); } const OUString& SvXMLAttrContainerItem::GetPrefix( USHORT i ) const { return pImpl->GetPrefix( i ); } <commit_msg>INTEGRATION: CWS changefileheader (1.8.698); FILE MERGED 2008/04/01 15:51:19 thb 1.8.698.3: #i85898# Stripping all external header guards 2008/04/01 12:49:16 thb 1.8.698.2: #i85898# Stripping all external header guards 2008/03/31 14:22:39 rt 1.8.698.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlcnitm.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <com/sun/star/xml/AttributeData.hpp> #include <com/sun/star/lang/XUnoTunnel.hpp> #include <xmloff/xmlcnimp.hxx> #ifndef _XMLOFF_XMLCNITM_HXX #include <xmloff/unoatrcn.hxx> #endif #include "xmlcnitm.hxx" using namespace rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::xml; // ------------------------------------------------------------------------ TYPEINIT1(SvXMLAttrContainerItem, SfxPoolItem); SvXMLAttrContainerItem::SvXMLAttrContainerItem( USHORT _nWhich ) : SfxPoolItem( _nWhich ) { pImpl = new SvXMLAttrContainerData; } SvXMLAttrContainerItem::SvXMLAttrContainerItem( const SvXMLAttrContainerItem& rItem ) : SfxPoolItem( rItem ) { pImpl = new SvXMLAttrContainerData( *rItem.pImpl ); } SvXMLAttrContainerItem::~SvXMLAttrContainerItem() { delete pImpl; } int SvXMLAttrContainerItem::operator==( const SfxPoolItem& rItem ) const { DBG_ASSERT( rItem.ISA(SvXMLAttrContainerItem), "SvXMLAttrContainerItem::operator ==(): Bad type"); return *pImpl == *((const SvXMLAttrContainerItem&)rItem).pImpl; } int SvXMLAttrContainerItem::Compare( const SfxPoolItem &/*rWith*/ ) const { DBG_ASSERT( !this, "not yet implemented" ); return 0; } SfxItemPresentation SvXMLAttrContainerItem::GetPresentation( SfxItemPresentation /*ePresentation*/, SfxMapUnit /*eCoreMetric*/, SfxMapUnit /*ePresentationMetric*/, XubString &/*rText*/, const IntlWrapper * /*pIntlWrapper*/ ) const { return SFX_ITEM_PRESENTATION_NONE; } USHORT SvXMLAttrContainerItem::GetVersion( USHORT /*nFileFormatVersion*/ ) const { // This item should never be stored return USHRT_MAX; } BOOL SvXMLAttrContainerItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ ) const { Reference<XNameContainer> xContainer = new SvUnoAttributeContainer( new SvXMLAttrContainerData( *pImpl ) ); rVal.setValue( &xContainer, ::getCppuType((Reference<XNameContainer>*)0) ); return TRUE; } BOOL SvXMLAttrContainerItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ ) { Reference<XInterface> xRef; SvUnoAttributeContainer* pContainer = NULL; if( rVal.getValue() != NULL && rVal.getValueType().getTypeClass() == TypeClass_INTERFACE ) { xRef = *(Reference<XInterface>*)rVal.getValue(); Reference<XUnoTunnel> xTunnel(xRef, UNO_QUERY); if( xTunnel.is() ) pContainer = (SvUnoAttributeContainer*)(ULONG)xTunnel->getSomething(SvUnoAttributeContainer::getUnoTunnelId()); } if( pContainer ) { delete pImpl; pImpl = new SvXMLAttrContainerData( * pContainer->GetContainerImpl() ); } else { SvXMLAttrContainerData* pNewImpl = new SvXMLAttrContainerData; try { Reference<XNameContainer> xContainer( xRef, UNO_QUERY ); if( !xContainer.is() ) return FALSE; const Sequence< OUString > aNameSequence( xContainer->getElementNames() ); const OUString* pNames = aNameSequence.getConstArray(); const INT32 nCount = aNameSequence.getLength(); Any aAny; AttributeData* pData; INT32 nAttr; for( nAttr = 0; nAttr < nCount; nAttr++ ) { const OUString aName( *pNames++ ); aAny = xContainer->getByName( aName ); if( aAny.getValue() == NULL || aAny.getValueType() != ::getCppuType((AttributeData*)0) ) return FALSE; pData = (AttributeData*)aAny.getValue(); sal_Int32 pos = aName.indexOf( sal_Unicode(':') ); if( pos != -1 ) { const OUString aPrefix( aName.copy( 0, pos )); const OUString aLName( aName.copy( pos+1 )); if( pData->Namespace.getLength() == 0 ) { if( !pNewImpl->AddAttr( aPrefix, aLName, pData->Value ) ) break; } else { if( !pNewImpl->AddAttr( aPrefix, pData->Namespace, aLName, pData->Value ) ) break; } } else { if( !pNewImpl->AddAttr( aName, pData->Value ) ) break; } } if( nAttr == nCount ) { delete pImpl; pImpl = pNewImpl; } else { delete pNewImpl; return FALSE; } } catch(...) { delete pNewImpl; return FALSE; } } return TRUE; } BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rLName, const OUString& rValue ) { return pImpl->AddAttr( rLName, rValue ); } BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rPrefix, const OUString& rNamespace, const OUString& rLName, const OUString& rValue ) { return pImpl->AddAttr( rPrefix, rNamespace, rLName, rValue ); } USHORT SvXMLAttrContainerItem::GetAttrCount() const { return (USHORT)pImpl->GetAttrCount(); } OUString SvXMLAttrContainerItem::GetAttrNamespace( USHORT i ) const { return pImpl->GetAttrNamespace( i ); } OUString SvXMLAttrContainerItem::GetAttrPrefix( USHORT i ) const { return pImpl->GetAttrPrefix( i ); } const OUString& SvXMLAttrContainerItem::GetAttrLName( USHORT i ) const { return pImpl->GetAttrLName( i ); } const OUString& SvXMLAttrContainerItem::GetAttrValue( USHORT i ) const { return pImpl->GetAttrValue( i ); } USHORT SvXMLAttrContainerItem::GetFirstNamespaceIndex() const { return pImpl->GetFirstNamespaceIndex(); } USHORT SvXMLAttrContainerItem::GetNextNamespaceIndex( USHORT nIdx ) const { return pImpl->GetNextNamespaceIndex( nIdx ); } const OUString& SvXMLAttrContainerItem::GetNamespace( USHORT i ) const { return pImpl->GetNamespace( i ); } const OUString& SvXMLAttrContainerItem::GetPrefix( USHORT i ) const { return pImpl->GetPrefix( i ); } <|endoftext|>
<commit_before>#include <stan/math/prim/scal.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> TEST(MathFunctions, falling_factorial) { using stan::math::falling_factorial; EXPECT_FLOAT_EQ(24, falling_factorial(4.0,3)); EXPECT_FLOAT_EQ(120, falling_factorial(5.0,4)); EXPECT_FLOAT_EQ(144.8261, falling_factorial(6.1,3.1)); EXPECT_THROW(falling_factorial(1, -4), std::domain_error); } TEST(MathFunctions, falling_factorial_nan) { double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(4.0, nan)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(nan, 4.0)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(nan, nan)); } <commit_msg>Tests using real n, only defined for integer n<commit_after>#include <stan/math/prim/scal.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> TEST(MathFunctions, falling_factorial) { using stan::math::falling_factorial; EXPECT_FLOAT_EQ(24, falling_factorial(4.0,3)); EXPECT_FLOAT_EQ(120, falling_factorial(5.0,4)); EXPECT_THROW(falling_factorial(1, -4), std::domain_error); } TEST(MathFunctions, falling_factorial_nan) { double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(4.0, nan)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(nan, 4.0)); EXPECT_PRED1(boost::math::isnan<double>, stan::math::falling_factorial(nan, nan)); } <|endoftext|>
<commit_before>#define GURKE_STEP_NAME_PREFIX TestSteps #include "gurkenlaeufer/Step.h" #include "gtest/gtest.h" #include <iostream> #include <vector> struct Calculator { std::vector<int> values; }; STEP(".*have entered (\\d+) into the calculator$") { // This step uses the gurkenlaeufer native API auto calc = getFixture<Calculator>(); calc->values.push_back(getNextParam<int>()); } STEP(".*press (\\w+)") { std::cout << getNextParam<std::string>() << std::endl; } STEP(".*nostep") { } STEP(".*the result should be (\\d+) on the screen$") { // This step uses the cucumber-cpp adaption layer auto calc = getFixture<Calculator>(); int sum = 0; for (auto& n : calc->values) sum += n; auto result = getParam<int>(0u); std::cout << "Sum=" << sum << " " << result << std::endl; EXPECT_EQ(result, sum); } STEP(".*nobody should know") { auto docString = getNextParam<std::string>(); std::cout << docString << std::endl; } BEFORE("@Print") { std::cout << "ctrl + p" << std::endl; } AFTER("@Echo") { std::cout << "echo ho ho ho" << std::endl; } <commit_msg>Remove misleading comments<commit_after>#define GURKE_STEP_NAME_PREFIX TestSteps #include "gurkenlaeufer/Step.h" #include "gtest/gtest.h" #include <iostream> #include <vector> struct Calculator { std::vector<int> values; }; STEP(".*have entered (\\d+) into the calculator$") { auto calc = getFixture<Calculator>(); calc->values.push_back(getNextParam<int>()); } STEP(".*press (\\w+)") { std::cout << getNextParam<std::string>() << std::endl; } STEP(".*nostep") { } STEP(".*the result should be (\\d+) on the screen$") { auto calc = getFixture<Calculator>(); int sum = 0; for (auto& n : calc->values) sum += n; auto result = getParam<int>(0u); std::cout << "Sum=" << sum << " " << result << std::endl; EXPECT_EQ(result, sum); } STEP(".*nobody should know") { auto docString = getNextParam<std::string>(); std::cout << docString << std::endl; } BEFORE("@Print") { std::cout << "ctrl + p" << std::endl; } AFTER("@Echo") { std::cout << "echo ho ho ho" << std::endl; } <|endoftext|>
<commit_before>/* Copyright (c) 2008 Eric Scott Albright * * 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 <UnitTest++.h> #include "../unittest_enchant_providers.h" #include <vector> #include <map> #include <assert.h> #include <string.h> struct DictionaryCheck_TestFixture : Provider_TestFixture { typedef std::multimap<EnchantDict*, std::string> AddedWordsByDict; EnchantDict* _dict; const char *_provider_name; AddedWordsByDict _addedWordsByDict; //Setup DictionaryCheck_TestFixture():_dict(NULL) { _dict = GetFirstAvailableDictionary(); /* FIXME: hspell does not consider non-Hebrew letters to be valid letters */ if (_dict) { _provider_name = _provider->identify(_provider); if (strcmp(_provider_name, "hspell") == 0) _dict = NULL; } } //Teardown ~DictionaryCheck_TestFixture() { ReleaseDictionary(_dict); } virtual void ReleaseDictionary(EnchantDict* dict){ std::pair<AddedWordsByDict::const_iterator, AddedWordsByDict::const_iterator> addedWords = _addedWordsByDict.equal_range(dict); AddedWordsByDict::const_iterator it; for(it = addedWords.first; it != addedWords.second; ++it) { if(dict->add_to_exclude) { (*dict->add_to_exclude)(dict, it->second.c_str(), it->second.length()); } } _addedWordsByDict.erase(dict); Provider_TestFixture::ReleaseDictionary(dict); } bool IsWordInDictionary(const std::string& word) { return IsWordInDictionary(_dict, word); } static bool IsWordInDictionary(EnchantDict* dict, const std::string& word) { assert(dict && dict->check); // tests must check this before calling return (*dict->check)(dict, word.c_str(), word.length()) == 0; //check returns 0 when successful and 1 when not successful } bool AddWordToDictionary(const std::string& word) { return AddWordToDictionary(_dict, word); } bool AddWordToDictionary(EnchantDict* dict, const std::string& word) { if(dict == NULL) { return false; } if(IsWordInDictionary(word)) { return true; } // prefer adding it to the session so it will get automatically removed if(dict->add_to_session) { (*dict->add_to_session) (dict, word.c_str(), word.length()); if(IsWordInDictionary(word)) { return true; } } if(dict->add_to_personal) { _addedWordsByDict.insert(std::pair<EnchantDict*, std::string>(dict,word)); (*dict->add_to_personal) (dict, word.c_str(), word.length()); if(IsWordInDictionary(word)) { return true; } } return false; } }; ///////////////////////////////////////////////////////////////////////////////////////////////// // Unicode normalization TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_AddedComposed_SuccessfulCheckWithComposedAndDecomposed) { if(_dict && _dict->check) { if(AddWordToDictionary(Convert(L"fianc\x00e9" L"deleteme"))) // u00e9 = Latin small letter e with acute { CHECK( IsWordInDictionary(Convert(L"fianc\x00e9" L"deleteme")) ); //NFC // FIXME: This test times out on macOS >= 10.12 with "findMisspelledWordInString timed out" #if !(defined(__APPLE__) && defined(__MACH__)) CHECK( IsWordInDictionary(Convert(L"fiance\x0301" L"deleteme")) ); //NFD u0301 = Combining acute accent #endif } } } TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_AddedDecomposed_SuccessfulCheckWithComposedAndDecomposed) { if(_dict && _dict->check) { if(AddWordToDictionary(Convert(L"fiance\x0301" L"deletethis"))) // u0301 = Combining acute accent { CHECK( IsWordInDictionary(Convert(L"fianc\x00e9" L"deletethis")) ); //NFC CHECK( IsWordInDictionary(Convert(L"fiance\x0301" L"deletethis")) ); //NFD } } } TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_SuccessfulCheckWithComposedAndDecomposed) { EnchantDict* dict = GetDictionary("fr_FR"); if(dict && dict->check) { CHECK( IsWordInDictionary(dict, Convert(L"Fran\x00e7" L"ais")) ); //NFC latin small letter c with cedilla CHECK( IsWordInDictionary(dict, Convert(L"Franc\x0327" L"ais")) ); //NFD combining cedilla } ReleaseDictionary(dict); } ///////////////////////////////////////////////////////////////////////////////////////////////// // Capitalization TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_AddedAllCaps_OnlyAllCapsSuccessful) { if(_dict && _dict->check) { if(AddWordToDictionary("ZYX")) { CHECK( IsWordInDictionary("ZYX") ); CHECK(!IsWordInDictionary("ZYx") ); CHECK(!IsWordInDictionary("Zyx") ); CHECK(!IsWordInDictionary("zyx") ); if (strcmp(_provider_name, "AppleSpell") != 0) /* FIXME: This fails on AppleSpell */ CHECK(!IsWordInDictionary("zYx") ); } } } TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_AddedTitle_lowerCaseAndMixedCaseNotSuccessful) { if(_dict && _dict->check) { if(AddWordToDictionary("Zxyz")) { CHECK( IsWordInDictionary("ZXYZ") ); CHECK(!IsWordInDictionary("ZXyz") ); CHECK( IsWordInDictionary("Zxyz") ); CHECK(!IsWordInDictionary("zxyz") ); CHECK(!IsWordInDictionary("zXyz") ); } } } TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_Addedlower_MixedCaseNotSuccessful) { if(_dict && _dict->check) { if(AddWordToDictionary("zyxz")) { CHECK( IsWordInDictionary("ZYXZ") ); CHECK(!IsWordInDictionary("ZYxz") ); CHECK( IsWordInDictionary("Zyxz") ); CHECK( IsWordInDictionary("zyxz") ); CHECK(!IsWordInDictionary("zYxz") ); } } } <commit_msg>Comment out another test failing on macOS >= 10.12<commit_after>/* Copyright (c) 2008 Eric Scott Albright * * 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 <UnitTest++.h> #include "../unittest_enchant_providers.h" #include <vector> #include <map> #include <assert.h> #include <string.h> struct DictionaryCheck_TestFixture : Provider_TestFixture { typedef std::multimap<EnchantDict*, std::string> AddedWordsByDict; EnchantDict* _dict; const char *_provider_name; AddedWordsByDict _addedWordsByDict; //Setup DictionaryCheck_TestFixture():_dict(NULL) { _dict = GetFirstAvailableDictionary(); /* FIXME: hspell does not consider non-Hebrew letters to be valid letters */ if (_dict) { _provider_name = _provider->identify(_provider); if (strcmp(_provider_name, "hspell") == 0) _dict = NULL; } } //Teardown ~DictionaryCheck_TestFixture() { ReleaseDictionary(_dict); } virtual void ReleaseDictionary(EnchantDict* dict){ std::pair<AddedWordsByDict::const_iterator, AddedWordsByDict::const_iterator> addedWords = _addedWordsByDict.equal_range(dict); AddedWordsByDict::const_iterator it; for(it = addedWords.first; it != addedWords.second; ++it) { if(dict->add_to_exclude) { (*dict->add_to_exclude)(dict, it->second.c_str(), it->second.length()); } } _addedWordsByDict.erase(dict); Provider_TestFixture::ReleaseDictionary(dict); } bool IsWordInDictionary(const std::string& word) { return IsWordInDictionary(_dict, word); } static bool IsWordInDictionary(EnchantDict* dict, const std::string& word) { assert(dict && dict->check); // tests must check this before calling return (*dict->check)(dict, word.c_str(), word.length()) == 0; //check returns 0 when successful and 1 when not successful } bool AddWordToDictionary(const std::string& word) { return AddWordToDictionary(_dict, word); } bool AddWordToDictionary(EnchantDict* dict, const std::string& word) { if(dict == NULL) { return false; } if(IsWordInDictionary(word)) { return true; } // prefer adding it to the session so it will get automatically removed if(dict->add_to_session) { (*dict->add_to_session) (dict, word.c_str(), word.length()); if(IsWordInDictionary(word)) { return true; } } if(dict->add_to_personal) { _addedWordsByDict.insert(std::pair<EnchantDict*, std::string>(dict,word)); (*dict->add_to_personal) (dict, word.c_str(), word.length()); if(IsWordInDictionary(word)) { return true; } } return false; } }; ///////////////////////////////////////////////////////////////////////////////////////////////// // Unicode normalization TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_AddedComposed_SuccessfulCheckWithComposedAndDecomposed) { if(_dict && _dict->check) { if(AddWordToDictionary(Convert(L"fianc\x00e9" L"deleteme"))) // u00e9 = Latin small letter e with acute { // FIXME: These tests time out on macOS >= 10.12 with "findMisspelledWordInString timed out" #if !(defined(__APPLE__) && defined(__MACH__)) CHECK( IsWordInDictionary(Convert(L"fianc\x00e9" L"deleteme")) ); //NFC CHECK( IsWordInDictionary(Convert(L"fiance\x0301" L"deleteme")) ); //NFD u0301 = Combining acute accent #endif } } } TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_AddedDecomposed_SuccessfulCheckWithComposedAndDecomposed) { if(_dict && _dict->check) { if(AddWordToDictionary(Convert(L"fiance\x0301" L"deletethis"))) // u0301 = Combining acute accent { CHECK( IsWordInDictionary(Convert(L"fianc\x00e9" L"deletethis")) ); //NFC CHECK( IsWordInDictionary(Convert(L"fiance\x0301" L"deletethis")) ); //NFD } } } TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_SuccessfulCheckWithComposedAndDecomposed) { EnchantDict* dict = GetDictionary("fr_FR"); if(dict && dict->check) { CHECK( IsWordInDictionary(dict, Convert(L"Fran\x00e7" L"ais")) ); //NFC latin small letter c with cedilla CHECK( IsWordInDictionary(dict, Convert(L"Franc\x0327" L"ais")) ); //NFD combining cedilla } ReleaseDictionary(dict); } ///////////////////////////////////////////////////////////////////////////////////////////////// // Capitalization TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_AddedAllCaps_OnlyAllCapsSuccessful) { if(_dict && _dict->check) { if(AddWordToDictionary("ZYX")) { CHECK( IsWordInDictionary("ZYX") ); CHECK(!IsWordInDictionary("ZYx") ); CHECK(!IsWordInDictionary("Zyx") ); CHECK(!IsWordInDictionary("zyx") ); if (strcmp(_provider_name, "AppleSpell") != 0) /* FIXME: This fails on AppleSpell */ CHECK(!IsWordInDictionary("zYx") ); } } } TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_AddedTitle_lowerCaseAndMixedCaseNotSuccessful) { if(_dict && _dict->check) { if(AddWordToDictionary("Zxyz")) { CHECK( IsWordInDictionary("ZXYZ") ); CHECK(!IsWordInDictionary("ZXyz") ); CHECK( IsWordInDictionary("Zxyz") ); CHECK(!IsWordInDictionary("zxyz") ); CHECK(!IsWordInDictionary("zXyz") ); } } } TEST_FIXTURE(DictionaryCheck_TestFixture, IsWordInDictionary_Addedlower_MixedCaseNotSuccessful) { if(_dict && _dict->check) { if(AddWordToDictionary("zyxz")) { CHECK( IsWordInDictionary("ZYXZ") ); CHECK(!IsWordInDictionary("ZYxz") ); CHECK( IsWordInDictionary("Zyxz") ); CHECK( IsWordInDictionary("zyxz") ); CHECK(!IsWordInDictionary("zYxz") ); } } } <|endoftext|>
<commit_before>/* level.cpp Contains functions for loading and saving level data. This code is released under the terms of the MIT license. See COPYING.txt for details. */ #include "compress.h" #include "romfile.h" #include "level.h" #include <algorithm> #include <cstring> #include <cstdlib> #include <cstdint> #include <list> #include <iostream> #include <stdexcept> #include <QMessageBox> #include <QString> #include <QCoreApplication> #define MAP_DATA_SIZE 0xCDA //Locations of chunk data in ROM (using CPU addressing.) //currently assumes table locations are constant in all versions, // may need to change this later to use version arrays like kdceditor //... const romaddr_t ptrMapDataL = {0x12, 0x88a6}; const romaddr_t ptrMapDataH = {0x12, 0x875f}; const romaddr_t ptrMapDataB = {0x12, 0x84d1}; const romaddr_t mapTilesets = {0x12, 0x8618}; const romaddr_t ptrSpritesL = {0x12, 0x8d0e}; const romaddr_t ptrSpritesH = {0x12, 0x8bc7}; const romaddr_t ptrSpritesB = {0x12, 0x8a80}; const romaddr_t ptrExitsL = {0x12, 0x8f82}; const romaddr_t ptrExitsH = {0x12, 0x90cb}; const uint ptrExitsB = 0x12; const romaddr_t bossExits = {0x12, 0x9c4a}; /* Load a level by number. Returns pointer to the level data as a struct. Returns null if a level failed and the user decided not to continue. */ leveldata_t* loadLevel (ROMFile& file, uint num) { //invalid data should at least be able to decompress fully uint8_t buf[DATA_SIZE] = {0}; header_t *header = (header_t*)buf + 0; uint8_t *screens = buf + 8; uint8_t *tiles = buf + 0xDA; size_t result = file.readFromPointer(ptrMapDataL, ptrMapDataH, ptrMapDataB, 0, buf, num); // TODO: "error reading level, attempt to continue?" if (result == 0) return NULL; leveldata_t *level; try { level = new leveldata_t; } catch (std::bad_alloc) { QMessageBox::critical(0, "Load ROM", QString("Unable to allocate memory for room %1").arg(num), QMessageBox::Ok); return NULL; } memcpy(&level->header, header, sizeof(header_t)); // make sure the level size is valid if (header->screensH * header->screensV > 16 || header->screensH == 0 || header->screensV == 0) { QMessageBox::critical(0, "Load ROM", QString("Unable to load room %1 because it has an invalid size.\n\n" "The ROM may be corrupt.").arg(num), QMessageBox::Ok); delete level; return NULL; } // kinda slow, but eh for (uint y = 0; y < SCREEN_HEIGHT * header->screensV; y++) { for (uint x = 0; x < SCREEN_WIDTH * header->screensH; x++) { uint idx = (y / SCREEN_HEIGHT * header->screensH) + (x / SCREEN_WIDTH); uint8_t screen = screens[idx]; level->tiles[y][x] = tiles[(screen * SCREEN_SIZE) + (y % SCREEN_HEIGHT * 16) + (x % SCREEN_WIDTH)]; } } // get tileset from table level->tileset = file.readByte(mapTilesets + num); // get "don't return on death" flag // (which is the highest bit of the level pointer's bank byte) level->noReturn = file.readByte(ptrMapDataB + num) & 0x80; // get sprite data romaddr_t spritePtr = file.readPointer(ptrSpritesL, ptrSpritesH, ptrSpritesB, num); // true number of screens (this may differ in levels more than 2 screens tall) uint sprScreens = file.readByte(spritePtr); // last # of sprite on each screen romaddr_t spriteCounts = spritePtr + 2; uint numSprites = file.readByte(spriteCounts + (sprScreens - 1)); // position of each sprite romaddr_t spritePos = spriteCounts + sprScreens; // type of each sprite romaddr_t spriteTypes = spritePos + numSprites; uint sprNum = 0; for (uint i = 0; i < sprScreens; i++) { // number of sprites on this screen numSprites = file.readByte(spriteCounts + i); while (sprNum < numSprites) { sprite_t *sprite = new sprite_t; sprite->type = file.readByte(spriteTypes + sprNum); uint8_t pos = file.readByte(spritePos + sprNum); // calculate normal x/y positions sprite->x = (i % header->screensH * SCREEN_WIDTH) + (pos >> 4); // for some stupid reason, HAL designed the sprite data so that // sprite coords / screen positions are based on screens being // 16 tiles tall instead of 12. changing this should put sprites // in the correct place all the time on vertical levels. // (fixes issue #2) sprite->y = (i / header->screensH * (SCREEN_HEIGHT + 4)) + (pos & 0xF); level->sprites.push_back(sprite); sprNum++; } } // get exit data romaddr_t exits = file.readShortPointer(ptrExitsL, ptrExitsH, ptrExitsB, num); romaddr_t nextExits = file.readShortPointer(ptrExitsL, ptrExitsH, ptrExitsB, num+1); // the game subtracts consecutive pointers to calculate # of exits in current level uint numExits = (nextExits.addr - exits.addr) / 5; for (uint i = 0; i < numExits; i++) { exit_t *exit = new exit_t; romaddr_t thisExit = exits + (i * 5); uint8_t byte; // byte 0: exit type / screen byte = file.readByte(thisExit); uint screen = byte & 0xF; exit->type = byte >> 4; // byte 1: coordinates byte = file.readByte(thisExit + 1); exit->x = (screen % header->screensH * SCREEN_WIDTH) + (byte >> 4); exit->y = (screen / header->screensH * SCREEN_HEIGHT) + (byte & 0xF); // byte 2: LSB of destination exit->dest = file.readByte(thisExit + 2); // byte 3: MSB of destination / type / dest screen byte = file.readByte(thisExit + 3); if (byte & 0x80) exit->dest |= 0x100; exit->type |= (byte & 0x70); exit->destScreen = byte & 0xF; // byte 4: dest coordinates byte = file.readByte(thisExit + 4); exit->destX = byte >> 4; exit->destY = byte & 0xF; // if this is a "next level/boss" door, get that info too if (num < 8 && exit->type == 0x1F) { exit->bossLevel = file.readByte(bossExits + (num * 3)); byte = file.readByte(bossExits + (num * 3) + 1); if (byte & 0x80) exit->bossLevel |= 0x100; exit->bossScreen = byte & 0xF; byte = file.readByte(bossExits + (num * 3) + 2); exit->bossX = byte >> 4; exit->bossY = byte & 0xF; } else { exit->bossLevel = 0; exit->bossScreen = 0; exit->bossX = 0; exit->bossY = 0; } level->exits.push_back(exit); } level->modified = false; return level; } /* * Returns a compressed data chunk based on level data (tile map only). * This is inserted into the big list of data chunks and then * later passed back to saveLevel in order to save it to the ROM * (and add it to the pointer table). */ DataChunk packLevel(const leveldata_t *level, uint num) { uint8_t buf[MAP_DATA_SIZE] = {0}; header_t *header = (header_t*)buf + 0; uint8_t *screens = buf + 8; uint8_t *tiles = buf + 0xDA; *header = level->header; uint numScreens = level->header.screensV * level->header.screensH; // all current unique screens uint8_t uniques[16][SCREEN_SIZE] = {{0}}; uint unique = 0; for (uint i = 0; i < numScreens; i++) { // temporary screen uint8_t tempScreen[SCREEN_SIZE] = {0}; // write tile data for screen uint h = i % header->screensH; uint v = i / header->screensH; for (uint y = 0; y < SCREEN_HEIGHT; y++) { memcpy(tempScreen + (y * SCREEN_WIDTH), &level->tiles[v * SCREEN_HEIGHT + y][h * SCREEN_WIDTH], SCREEN_WIDTH); } // does an identical screen already exist? bool found = false; for (uint s = 0; s < unique; s++) { if (!memcmp(uniques[s], tempScreen, SCREEN_SIZE)) { // reuse the same screen index screens[i] = s; found = true; break; } } if (found) continue; // write the new unique screen uint8_t *newScreen = tiles + (SCREEN_SIZE * unique); // to the level data memcpy(newScreen, tempScreen, SCREEN_SIZE); // and to the unique screens memcpy(uniques[unique], tempScreen, SCREEN_SIZE); // use a new screen index screens[i] = unique++; } // pack and return return DataChunk(buf, 0xDA + (SCREEN_SIZE * numScreens), DataChunk::level, num); } DataChunk packSprites(const leveldata_t *level, uint num) { uint8_t buf[DATA_SIZE] = {0}; // sort sprites by screen std::list<sprite_t> sprites; for (std::list<sprite_t*>::const_iterator i = level->sprites.begin(); i != level->sprites.end(); i++) { sprite_t sprite = *(*i); // which screen is this sprite on? // (treat screens as 16 tiles tall instead of 12 - fixes issue #2) sprite.screen = (sprite.y / (SCREEN_HEIGHT + 4) * level->header.screensH) + (sprite.x / SCREEN_WIDTH); sprites.push_back(sprite); } sprites.sort(); uint numScreens = level->header.screensH * level->header.screensV; uint numSprites = sprites.size(); uint8_t *screens = buf + 2; uint8_t *positions = screens + numScreens; uint8_t *types = positions + numSprites; // write screen count bytes buf[0] = numScreens; buf[1] = level->header.screensV; uint sprNum = 0; for (std::list<sprite_t>::const_iterator i = sprites.begin(); i != sprites.end(); i++) { sprite_t sprite = *i; // update sprites-per-screen counts for (uint j = sprite.screen; j < numScreens; j++) screens[j]++; // sprite position and type positions[sprNum] = ((sprite.x % SCREEN_WIDTH) << 4) + (sprite.y % (SCREEN_HEIGHT + 4)); types[sprNum] = sprite.type; sprNum++; } // pack and return return DataChunk(buf, 2 + numScreens + numSprites + numSprites, DataChunk::enemy, num); } /* Save a level back to the ROM and update the pointer table. Takes both a compressed data chunk for the tilemap (used to sort by size beforehand) and a pointer to the editor's own level struct for saving exits and other stuff. */ void saveLevel(ROMFile& file, const DataChunk &chunk, const leveldata_t *level, romaddr_t addr) { // level data banks mapped to A000-BFFF addr.addr %= BANK_SIZE; addr.addr += 0xA000; if (level->noReturn) addr.bank |= 0x80; // save compressed data chunk, update pointer table uint num = chunk.num; file.writeToPointer(ptrMapDataL, ptrMapDataH, ptrMapDataB, addr, chunk.size, chunk.data, num); // write tileset number file.writeByte(mapTilesets + num, level->tileset); } void saveExits(ROMFile& file, const leveldata_t *level, uint num) { romaddr_t addr = file.readShortPointer(ptrExitsL, ptrExitsH, ptrExitsB, num); for (std::list<exit_t*>::const_iterator i = level->exits.begin(); i != level->exits.end(); i++) { exit_t *exit = *i; uint8_t bytes[5]; // byte 0: upper 4 = exit type & 0xF, lower 4 = screen exit is on bytes[0] = exit->type << 4; // calculate screen number bytes[0] |= (exit->y / SCREEN_HEIGHT * level->header.screensH) + (exit->x / SCREEN_WIDTH); // byte 1: upper 4 = x, lower 4 = y bytes[1] = ((exit->x % SCREEN_WIDTH) << 4) | (exit->y % SCREEN_HEIGHT); // byte 2: level number lsb bytes[2] = exit->dest & 0xFF; // byte 3: upper bit = level number msbit, rest of upper = exit type & 0x70, // lower = destination screen number bytes[3] = (exit->type & 0x70) | exit->destScreen; if (exit->dest >= 0x100) bytes[3] |= 0x80; // byte 4: destination x/y bytes[4] = (exit->destX << 4) | exit->destY; file.writeBytes(addr, 5, bytes); addr.addr += 5; // if this is a "next level/boss" door, save that info if (num < 8 && exit->type == 0x1F) { bytes[0] = exit->bossLevel & 0xFF; bytes[1] = exit->bossScreen; if (exit->bossLevel >= 0x100) bytes[1] |= 0x80; bytes[2] = (exit->bossX << 4) | exit->bossY; file.writeBytes(bossExits + (num * 3), 3, bytes); } } // write pointer for NEXT level file.writeByte(ptrExitsL + num + 1, addr.addr & 0xFF); file.writeByte(ptrExitsH + num + 1, addr.addr >> 8); } void saveSprites(ROMFile& file, const DataChunk& chunk, romaddr_t addr) { // level data banks mapped to A000-BFFF addr.addr %= BANK_SIZE; addr.addr += 0xA000; // save compressed data chunk, update pointer table uint num = chunk.num; file.writeToPointer(ptrSpritesL, ptrSpritesH, ptrSpritesB, addr, chunk.size, chunk.data, num); } <commit_msg>only merge identical screens for rot. towers<commit_after>/* level.cpp Contains functions for loading and saving level data. This code is released under the terms of the MIT license. See COPYING.txt for details. */ #include "compress.h" #include "romfile.h" #include "level.h" #include <algorithm> #include <cstring> #include <cstdlib> #include <cstdint> #include <list> #include <iostream> #include <stdexcept> #include <QMessageBox> #include <QString> #include <QCoreApplication> #define MAP_DATA_SIZE 0xCDA //Locations of chunk data in ROM (using CPU addressing.) //currently assumes table locations are constant in all versions, // may need to change this later to use version arrays like kdceditor //... const romaddr_t ptrMapDataL = {0x12, 0x88a6}; const romaddr_t ptrMapDataH = {0x12, 0x875f}; const romaddr_t ptrMapDataB = {0x12, 0x84d1}; const romaddr_t mapTilesets = {0x12, 0x8618}; const romaddr_t ptrSpritesL = {0x12, 0x8d0e}; const romaddr_t ptrSpritesH = {0x12, 0x8bc7}; const romaddr_t ptrSpritesB = {0x12, 0x8a80}; const romaddr_t ptrExitsL = {0x12, 0x8f82}; const romaddr_t ptrExitsH = {0x12, 0x90cb}; const uint ptrExitsB = 0x12; const romaddr_t bossExits = {0x12, 0x9c4a}; /* Load a level by number. Returns pointer to the level data as a struct. Returns null if a level failed and the user decided not to continue. */ leveldata_t* loadLevel (ROMFile& file, uint num) { //invalid data should at least be able to decompress fully uint8_t buf[DATA_SIZE] = {0}; header_t *header = (header_t*)buf + 0; uint8_t *screens = buf + 8; uint8_t *tiles = buf + 0xDA; size_t result = file.readFromPointer(ptrMapDataL, ptrMapDataH, ptrMapDataB, 0, buf, num); // TODO: "error reading level, attempt to continue?" if (result == 0) return NULL; leveldata_t *level; try { level = new leveldata_t; } catch (std::bad_alloc) { QMessageBox::critical(0, "Load ROM", QString("Unable to allocate memory for room %1").arg(num), QMessageBox::Ok); return NULL; } memcpy(&level->header, header, sizeof(header_t)); // make sure the level size is valid if (header->screensH * header->screensV > 16 || header->screensH == 0 || header->screensV == 0) { QMessageBox::critical(0, "Load ROM", QString("Unable to load room %1 because it has an invalid size.\n\n" "The ROM may be corrupt.").arg(num), QMessageBox::Ok); delete level; return NULL; } // kinda slow, but eh for (uint y = 0; y < SCREEN_HEIGHT * header->screensV; y++) { for (uint x = 0; x < SCREEN_WIDTH * header->screensH; x++) { uint idx = (y / SCREEN_HEIGHT * header->screensH) + (x / SCREEN_WIDTH); uint8_t screen = screens[idx]; level->tiles[y][x] = tiles[(screen * SCREEN_SIZE) + (y % SCREEN_HEIGHT * 16) + (x % SCREEN_WIDTH)]; } } // get tileset from table level->tileset = file.readByte(mapTilesets + num); // get "don't return on death" flag // (which is the highest bit of the level pointer's bank byte) level->noReturn = file.readByte(ptrMapDataB + num) & 0x80; // get sprite data romaddr_t spritePtr = file.readPointer(ptrSpritesL, ptrSpritesH, ptrSpritesB, num); // true number of screens (this may differ in levels more than 2 screens tall) uint sprScreens = file.readByte(spritePtr); // last # of sprite on each screen romaddr_t spriteCounts = spritePtr + 2; uint numSprites = file.readByte(spriteCounts + (sprScreens - 1)); // position of each sprite romaddr_t spritePos = spriteCounts + sprScreens; // type of each sprite romaddr_t spriteTypes = spritePos + numSprites; uint sprNum = 0; for (uint i = 0; i < sprScreens; i++) { // number of sprites on this screen numSprites = file.readByte(spriteCounts + i); while (sprNum < numSprites) { sprite_t *sprite = new sprite_t; sprite->type = file.readByte(spriteTypes + sprNum); uint8_t pos = file.readByte(spritePos + sprNum); // calculate normal x/y positions sprite->x = (i % header->screensH * SCREEN_WIDTH) + (pos >> 4); // for some stupid reason, HAL designed the sprite data so that // sprite coords / screen positions are based on screens being // 16 tiles tall instead of 12. changing this should put sprites // in the correct place all the time on vertical levels. // (fixes issue #2) sprite->y = (i / header->screensH * (SCREEN_HEIGHT + 4)) + (pos & 0xF); level->sprites.push_back(sprite); sprNum++; } } // get exit data romaddr_t exits = file.readShortPointer(ptrExitsL, ptrExitsH, ptrExitsB, num); romaddr_t nextExits = file.readShortPointer(ptrExitsL, ptrExitsH, ptrExitsB, num+1); // the game subtracts consecutive pointers to calculate # of exits in current level uint numExits = (nextExits.addr - exits.addr) / 5; for (uint i = 0; i < numExits; i++) { exit_t *exit = new exit_t; romaddr_t thisExit = exits + (i * 5); uint8_t byte; // byte 0: exit type / screen byte = file.readByte(thisExit); uint screen = byte & 0xF; exit->type = byte >> 4; // byte 1: coordinates byte = file.readByte(thisExit + 1); exit->x = (screen % header->screensH * SCREEN_WIDTH) + (byte >> 4); exit->y = (screen / header->screensH * SCREEN_HEIGHT) + (byte & 0xF); // byte 2: LSB of destination exit->dest = file.readByte(thisExit + 2); // byte 3: MSB of destination / type / dest screen byte = file.readByte(thisExit + 3); if (byte & 0x80) exit->dest |= 0x100; exit->type |= (byte & 0x70); exit->destScreen = byte & 0xF; // byte 4: dest coordinates byte = file.readByte(thisExit + 4); exit->destX = byte >> 4; exit->destY = byte & 0xF; // if this is a "next level/boss" door, get that info too if (num < 8 && exit->type == 0x1F) { exit->bossLevel = file.readByte(bossExits + (num * 3)); byte = file.readByte(bossExits + (num * 3) + 1); if (byte & 0x80) exit->bossLevel |= 0x100; exit->bossScreen = byte & 0xF; byte = file.readByte(bossExits + (num * 3) + 2); exit->bossX = byte >> 4; exit->bossY = byte & 0xF; } else { exit->bossLevel = 0; exit->bossScreen = 0; exit->bossX = 0; exit->bossY = 0; } level->exits.push_back(exit); } level->modified = false; return level; } /* * Returns a compressed data chunk based on level data (tile map only). * This is inserted into the big list of data chunks and then * later passed back to saveLevel in order to save it to the ROM * (and add it to the pointer table). */ DataChunk packLevel(const leveldata_t *level, uint num) { uint8_t buf[MAP_DATA_SIZE] = {0}; header_t *header = (header_t*)buf + 0; uint8_t *screens = buf + 8; uint8_t *tiles = buf + 0xDA; *header = level->header; uint numScreens = level->header.screensV * level->header.screensH; // all current unique screens uint8_t uniques[16][SCREEN_SIZE] = {{0}}; uint unique = 0; for (uint i = 0; i < numScreens; i++) { // temporary screen uint8_t tempScreen[SCREEN_SIZE] = {0}; // write tile data for screen uint h = i % header->screensH; uint v = i / header->screensH; for (uint y = 0; y < SCREEN_HEIGHT; y++) { memcpy(tempScreen + (y * SCREEN_WIDTH), &level->tiles[v * SCREEN_HEIGHT + y][h * SCREEN_WIDTH], SCREEN_WIDTH); } // combine unique screens instead of writing multiple copies of them. // this is currently only done for rotating tower rooms (0CD, 0D4, 0DF, 0E6) // because they require this in order for their exits to work correctly. // doing it anywhere else can cause destroyable tiles to inadvertedly // affect more than one part of the level at the same time. if (num == 0xCD || num == 0xD4 || num == 0xDF || num == 0xE6) { // does an identical screen already exist? bool found = false; for (uint s = 0; !found && s < unique; s++) { if (!memcmp(uniques[s], tempScreen, SCREEN_SIZE)) { // reuse the same screen index screens[i] = s; found = true; } } if (found) continue; // add this screen to the unique screens memcpy(uniques[unique], tempScreen, SCREEN_SIZE); } // write the new unique screen to the level data uint8_t *newScreen = tiles + (SCREEN_SIZE * unique); memcpy(newScreen, tempScreen, SCREEN_SIZE); // use a new screen index screens[i] = unique++; } // pack and return return DataChunk(buf, 0xDA + (SCREEN_SIZE * numScreens), DataChunk::level, num); } DataChunk packSprites(const leveldata_t *level, uint num) { uint8_t buf[DATA_SIZE] = {0}; // sort sprites by screen std::list<sprite_t> sprites; for (std::list<sprite_t*>::const_iterator i = level->sprites.begin(); i != level->sprites.end(); i++) { sprite_t sprite = *(*i); // which screen is this sprite on? // (treat screens as 16 tiles tall instead of 12 - fixes issue #2) sprite.screen = (sprite.y / (SCREEN_HEIGHT + 4) * level->header.screensH) + (sprite.x / SCREEN_WIDTH); sprites.push_back(sprite); } sprites.sort(); uint numScreens = level->header.screensH * level->header.screensV; uint numSprites = sprites.size(); uint8_t *screens = buf + 2; uint8_t *positions = screens + numScreens; uint8_t *types = positions + numSprites; // write screen count bytes buf[0] = numScreens; buf[1] = level->header.screensV; uint sprNum = 0; for (std::list<sprite_t>::const_iterator i = sprites.begin(); i != sprites.end(); i++) { sprite_t sprite = *i; // update sprites-per-screen counts for (uint j = sprite.screen; j < numScreens; j++) screens[j]++; // sprite position and type positions[sprNum] = ((sprite.x % SCREEN_WIDTH) << 4) + (sprite.y % (SCREEN_HEIGHT + 4)); types[sprNum] = sprite.type; sprNum++; } // pack and return return DataChunk(buf, 2 + numScreens + numSprites + numSprites, DataChunk::enemy, num); } /* Save a level back to the ROM and update the pointer table. Takes both a compressed data chunk for the tilemap (used to sort by size beforehand) and a pointer to the editor's own level struct for saving exits and other stuff. */ void saveLevel(ROMFile& file, const DataChunk &chunk, const leveldata_t *level, romaddr_t addr) { // level data banks mapped to A000-BFFF addr.addr %= BANK_SIZE; addr.addr += 0xA000; if (level->noReturn) addr.bank |= 0x80; // save compressed data chunk, update pointer table uint num = chunk.num; file.writeToPointer(ptrMapDataL, ptrMapDataH, ptrMapDataB, addr, chunk.size, chunk.data, num); // write tileset number file.writeByte(mapTilesets + num, level->tileset); } void saveExits(ROMFile& file, const leveldata_t *level, uint num) { romaddr_t addr = file.readShortPointer(ptrExitsL, ptrExitsH, ptrExitsB, num); for (std::list<exit_t*>::const_iterator i = level->exits.begin(); i != level->exits.end(); i++) { exit_t *exit = *i; uint8_t bytes[5]; // byte 0: upper 4 = exit type & 0xF, lower 4 = screen exit is on bytes[0] = exit->type << 4; // calculate screen number bytes[0] |= (exit->y / SCREEN_HEIGHT * level->header.screensH) + (exit->x / SCREEN_WIDTH); // byte 1: upper 4 = x, lower 4 = y bytes[1] = ((exit->x % SCREEN_WIDTH) << 4) | (exit->y % SCREEN_HEIGHT); // byte 2: level number lsb bytes[2] = exit->dest & 0xFF; // byte 3: upper bit = level number msbit, rest of upper = exit type & 0x70, // lower = destination screen number bytes[3] = (exit->type & 0x70) | exit->destScreen; if (exit->dest >= 0x100) bytes[3] |= 0x80; // byte 4: destination x/y bytes[4] = (exit->destX << 4) | exit->destY; file.writeBytes(addr, 5, bytes); addr.addr += 5; // if this is a "next level/boss" door, save that info if (num < 8 && exit->type == 0x1F) { bytes[0] = exit->bossLevel & 0xFF; bytes[1] = exit->bossScreen; if (exit->bossLevel >= 0x100) bytes[1] |= 0x80; bytes[2] = (exit->bossX << 4) | exit->bossY; file.writeBytes(bossExits + (num * 3), 3, bytes); } } // write pointer for NEXT level file.writeByte(ptrExitsL + num + 1, addr.addr & 0xFF); file.writeByte(ptrExitsH + num + 1, addr.addr >> 8); } void saveSprites(ROMFile& file, const DataChunk& chunk, romaddr_t addr) { // level data banks mapped to A000-BFFF addr.addr %= BANK_SIZE; addr.addr += 0xA000; // save compressed data chunk, update pointer table uint num = chunk.num; file.writeToPointer(ptrSpritesL, ptrSpritesH, ptrSpritesB, addr, chunk.size, chunk.data, num); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go double ** param_mtx = new double *[num_of_ent]; double ** coord_mtx = new double *[num_of_ent]; for (int i = 0; i < num_of_ent; ++i) { coord_mtx[i] = new double[3*COORDIM]; param_mtx[i] = new double[5]; } // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coord_mtx[i][j*3] >> coord_mtx[i][j*3+1] >> coord_mtx[i][j*3+2] >> a >> b >> c; } mytfp >> param_mtx[i][0] >> param_mtx[i][1] >> param_mtx[i][2] >> param_mtx[i][3] >> param_mtx[i][4]; } mytfp.close(); #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coord_mtx[i][j*3] << " " << coord_mtx[i][j*3+1] << " " << coord_mtx[i][j*3+2] << std::endl; } std::cout << param_mtx[i][0] << " " << param_mtx[i][1] << " " << param_mtx[i][2] << " " << param_mtx[i][3] << " " << param_mtx[i][4] << std::endl; } #endif double sum = 1.0e0; double coordm[3*COORDIM] = {0.0e0}; double hc[3*COORDIM][3*COORDIM] = {0.0e0}; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0); } } } for (int i=0; i<(3*COORDIM); ++i) for (int j=i+1; j<(3*COORDIM); ++j) if (hc[i][j] != hc[j][i]) std::cout << i << " " << j << " " << hc[i][j] << " ERROR" << std::endl;; arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca(i,j) = hc[i][j]; arma::vec eigval; arma::mat eigvec; arma::eig_sym(eigval, eigvec, hca); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); int j = 1; double totvar = 0.0e0; for (int i=(3*COORDIM-1); i>=0; --i) { if (j <= 5) totvar += 100.0e0*(eigval(i)/totval); ++j; std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << std::endl; } std::cout << "5 eigenvalues: " << totvar << std::endl; arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); hcai = hca.i(); std::cout << hca * hcai ; // and so on ... // documento Annovi // calcolo matrice di correlazione traccie HC // diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali) // A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce // simulate. // documento ATLAS // calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione // data C determinare il vettore di traslazione q // c plus q costanti PCA // write constants in a file for (int i = 0; i < num_of_ent; ++i) { delete(coord_mtx[i]); delete(param_mtx[i]); } delete(coord_mtx); delete(param_mtx); return 0; } <commit_msg>add covariane between trace and parameter (just a backup cjheck it)<commit_after>#include <iostream> #include <fstream> #include <string> // Loriano: let's try Armadillo quick code #include <armadillo> #define ENTDIM 8 #define COORDIM (ENTDIM-2) #define PARAMDIM 5 namespace { int numofline (const char * fname) { int number_of_lines = 0; std::string line; std::ifstream myfile(fname); while (std::getline(myfile, line)) ++number_of_lines; myfile.close(); return number_of_lines; } } int main (int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " coordinatesfile " << std::endl; return 1; } int num_of_line = numofline(argv[1]); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << " " << num_of_ent << " entries " << std::endl; // non perfomante ma easy to go double ** param_mtx = new double *[num_of_ent]; double ** coord_mtx = new double *[num_of_ent]; for (int i = 0; i < num_of_ent; ++i) { coord_mtx[i] = new double[3*COORDIM]; param_mtx[i] = new double[PARAMDIM]; } // leggere file coordinate tracce simulate plus parametri std::string line; std::ifstream mytfp; mytfp.open (argv[1], std::ios::in); std::getline (mytfp, line); //std::cout << line << std::endl; for (int i = 0; i < num_of_ent; ++i) { int fake1, fake2; mytfp >> fake1 >> fake2 ; #ifdef DEBUG std::cout << fake1 << " " << fake2 << std::endl; #endif for (int j = 0; j < COORDIM; ++j) { int a, b, c; mytfp >> coord_mtx[i][j*3] >> coord_mtx[i][j*3+1] >> coord_mtx[i][j*3+2] >> a >> b >> c; } mytfp >> param_mtx[i][0] >> param_mtx[i][1] >> param_mtx[i][2] >> param_mtx[i][3] >> param_mtx[i][4]; } mytfp.close(); #ifdef DEBUG for (int i = 0; i < num_of_ent; ++i) { for (int j = 0; j < COORDIM; ++j) { std::cout << coord_mtx[i][j*3] << " " << coord_mtx[i][j*3+1] << " " << coord_mtx[i][j*3+2] << std::endl; } std::cout << param_mtx[i][0] << " " << param_mtx[i][1] << " " << param_mtx[i][2] << " " << param_mtx[i][3] << " " << param_mtx[i][4] << std::endl; } #endif double sum = 1.0e0; double coordm[3*COORDIM] = {0.0e0}; double hc[3*COORDIM][3*COORDIM] = {0.0e0}; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<(3*COORDIM); ++j) { hc[i][j] += ((coord_mtx[l][i] - coordm[i])* (coord_mtx[l][j] - coordm[j])- (sum-1.0e0)*hc[i][j]/sum)/(sum-1.0e0); } } } for (int i=0; i<(3*COORDIM); ++i) for (int j=i+1; j<(3*COORDIM); ++j) if (hc[i][j] != hc[j][i]) std::cout << i << " " << j << " " << hc[i][j] << " ERROR" << std::endl;; arma::mat hca = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); for (int i=0; i<(3*COORDIM); ++i) for (int j=0; j<(3*COORDIM); ++j) hca(i,j) = hc[i][j]; arma::vec eigval; arma::mat eigvec; arma::eig_sym(eigval, eigvec, hca); double totval = 0.0e0; for (int i=0; i<(3*COORDIM); ++i) totval += eigval(i); int j = 1; double totvar = 0.0e0; for (int i=(3*COORDIM-1); i>=0; --i) { if (j <= PARAMDIM) totvar += 100.0e0*(eigval(i)/totval); ++j; std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval) << std::endl; } std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl; arma::mat hcai = arma::zeros<arma::mat>(3*COORDIM,3*COORDIM); hcai = hca.i(); //std::cout << hca * hcai ; // and so on ... std::fill(coordm, &(coordm[3*COORDIM]), 0.0e0 ); double paramm[PARAMDIM] = {0.0e0}; double hcp[3*COORDIM][PARAMDIM] = {0.0e0}; for (int l=0; l<num_of_ent; ++l) { sum += 1.0e0; for (int i=0; i<(3*COORDIM); ++i) coordm[i] += (coord_mtx[l][i]-coordm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) paramm[i] += (param_mtx[l][i]-paramm[i])/sum; for (int i=0; i<(3*COORDIM); ++i) { for (int j=0; j<PARAMDIM; ++j) { hcp[i][j] += ((coord_mtx[l][i] - coordm[i])* (param_mtx[l][j] - paramm[j])- (sum-1.0e0)*hcp[i][j]/sum)/(sum-1.0e0); } } } // documento Annovi // calcolo matrice di correlazione traccie HC // diagonalizzo HC e determino A, matrice 5 autovettori principali (5 componenti pricipali) // A matrice rotazione che mi permette di calcolare la traslazione usando i paamtri di tracce // simulate. // documento ATLAS // calcolare V e data V calcolare inversa V e quindi C, matrice di rotazione // data C determinare il vettore di traslazione q // c plus q costanti PCA // write constants in a file for (int i = 0; i < num_of_ent; ++i) { delete(coord_mtx[i]); delete(param_mtx[i]); } delete(coord_mtx); delete(param_mtx); return 0; } <|endoftext|>
<commit_before>#include "lexer.hpp" #include <cctype> #include <algorithm> #include <iterator> #include <vector> namespace klang { namespace { using const_iterator = std::string::const_iterator; } Token::Token() : type_(TokenType::UNKNOWN), str_(), line_(-1) {} Token::Token(TokenType type, const std::string& str, int line) : type_(type), str_(str), line_(line) {} TokenType Token::type() const { return type_; } std::string Token::str() const { return str_; } int Token::line() const { return line_; } bool alphabet(char c) { return std::isalpha(c); } bool alphabet_or_bar(char c) { return (c == '_' || alphabet(c)); } bool nonzero_digit(char c) { return (c >= '1' && c <= '9'); } bool decimal_digit(char c) { return std::isdigit(c); } bool identifier(const std::string& str) { if (str.empty() || !alphabet_or_bar(str.front())) { return false; } for (char c : str) { if (!alphabet_or_bar(c) && !decimal_digit(c)) { return false; } } return true; } bool decimal_integer(const std::string& str) { if (str == "0") return true; if (str.empty() || !nonzero_digit(str.front())) { return false; } for (char c : str) { if (!decimal_digit(c)) { return false; } } return true; } bool symbol(const_iterator head, const_iterator tail) { using std::begin; using std::end; std::string const str(head, tail); static std::vector<std::string> const symbol_list = { "~", "+", "-", "*", "/", "%", ":=", ":+=", ":-=", ":*=", ":/=", ":%=", "=", "=/", "<", ">", "<=", ">=", ";", "(", ")", "{", "}", "->", "~}", "and", "or", "not", "int", "def", "var", "if", "else", "while", "for", "break", "continue", "return" }; return (std::find(begin(symbol_list), end(symbol_list), str) != end(symbol_list)); } bool ignore(const std::string& str) { if(str.size() != 1) return false; return std::isspace(str[0]); } bool singleline_comment(const_iterator head, const_iterator tail) { using std::begin; using std::end; if(std::equal(head, std::next(head, 2), "~~")) { return std::find(head, tail, '\n') == std::prev(tail); } return false; } bool multiline_comment(const_iterator head, const_iterator tail) { using std::begin; using std::end; if (std::equal(head, std::next(head, 2), "{~")) { int nest = 0; for(auto it = head; std::next(it) != tail; ++it) { std::string tk(it, std::next(it, 2)); if (tk == "{~") { ++nest; } else if(tk == "~}") { --nest; } } bool closed = nest == 0 && std::equal(std::prev(tail, 2), std::prev(tail), "~}"); return (nest > 0 || closed); } return false; } bool comment(const_iterator head, const_iterator tail) { return (singleline_comment(head, tail) || multiline_comment(head, tail)); } bool string_token(const std::string& str) { using std::begin; using std::end; if (str.front() == '"') { bool escaped = false; for(auto it = std::next(begin(str)); it != end(str); ++it) { if (*it == '\\') { escaped = true; } else if (*it == '"' && (!escaped)) { return std::next(it) == end(str); } else { escaped = false; } } } return false; } TokenType match_type(const_iterator head, const_iterator tail) { if (comment(head, tail)) return TokenType::IGNORE; if (symbol(head, tail)) return TokenType::SYMBOL; if (identifier(head, tail)) return TokenType::IDENTIFIER; if (decimal_integer(head, tail)) return TokenType::NUMBER; if (string_token(head, tail)) return TokenType::STRING; if (ignore(head, tail)) return TokenType::IGNORE; return TokenType::UNKNOWN; } std::string extract_string(const std::string& str) { if (str.front() == '"') { bool escaped = false; std::string new_str; for(auto c : str) { if (escaped) { if(c == '"') new_str.push_back('"'); if(c == 'n') new_str.push_back('\n'); escaped = false; } else if (c == '\\') { escaped = true; } else if (c != '"') { new_str.push_back(c); } } return new_str; } return str; } TokenVector tokenize(std::istream& is) { using std::begin; using std::end; std::string const code(std::string{std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>()} + '\n'); // ファイルの末尾が改行で終わっているほうが処理しやすい。 TokenVector tokens; TokenType prev = TokenType::UNKNOWN; const_iterator head(begin(code)); int line = 1; for (auto it(begin(code)); it != end(code); ++it) { TokenType next = match_type(head, std::next(it)); if (prev != TokenType::UNKNOWN && next == TokenType::UNKNOWN) { if (prev != TokenType::IGNORE) { tokens.push_back(Token(prev, extract_string(head, it), line)); } head = it; prev = match_type(head, std::next(head)); } else { prev = next; } if (*it == '\n') ++line; } return tokens; } bool operator==(Token const& lhs, Token const& rhs) { return lhs.type() == rhs.type() && lhs.str() == rhs.str() && lhs.line() == rhs.line(); } bool operator!=(Token const& lhs, Token const& rhs) { return !( lhs == rhs ); } } // namespace klang <commit_msg>identifier を対応<commit_after>#include "lexer.hpp" #include <cctype> #include <algorithm> #include <iterator> #include <vector> namespace klang { namespace { using const_iterator = std::string::const_iterator; } Token::Token() : type_(TokenType::UNKNOWN), str_(), line_(-1) {} Token::Token(TokenType type, const std::string& str, int line) : type_(type), str_(str), line_(line) {} TokenType Token::type() const { return type_; } std::string Token::str() const { return str_; } int Token::line() const { return line_; } bool alphabet(char c) { return std::isalpha(c); } bool alphabet_or_bar(char c) { return (c == '_' || alphabet(c)); } bool nonzero_digit(char c) { return (c >= '1' && c <= '9'); } bool decimal_digit(char c) { return std::isdigit(c); } bool identifier(const_iterator head, const_iterator tail) { if (head == tail || !alphabet_or_bar(*head)) { return false; } for (auto it(head); it != tail; ++it) { if (!alphabet_or_bar(*it) && !decimal_digit(*it)) { return false; } } return true; } bool decimal_integer(const std::string& str) { if (str == "0") return true; if (str.empty() || !nonzero_digit(str.front())) { return false; } for (char c : str) { if (!decimal_digit(c)) { return false; } } return true; } bool symbol(const_iterator head, const_iterator tail) { using std::begin; using std::end; std::string const str(head, tail); static std::vector<std::string> const symbol_list = { "~", "+", "-", "*", "/", "%", ":=", ":+=", ":-=", ":*=", ":/=", ":%=", "=", "=/", "<", ">", "<=", ">=", ";", "(", ")", "{", "}", "->", "~}", "and", "or", "not", "int", "def", "var", "if", "else", "while", "for", "break", "continue", "return" }; return (std::find(begin(symbol_list), end(symbol_list), str) != end(symbol_list)); } bool ignore(const std::string& str) { if(str.size() != 1) return false; return std::isspace(str[0]); } bool singleline_comment(const_iterator head, const_iterator tail) { using std::begin; using std::end; if(std::equal(head, std::next(head, 2), "~~")) { return std::find(head, tail, '\n') == std::prev(tail); } return false; } bool multiline_comment(const_iterator head, const_iterator tail) { using std::begin; using std::end; if (std::equal(head, std::next(head, 2), "{~")) { int nest = 0; for(auto it = head; std::next(it) != tail; ++it) { std::string tk(it, std::next(it, 2)); if (tk == "{~") { ++nest; } else if(tk == "~}") { --nest; } } bool closed = nest == 0 && std::equal(std::prev(tail, 2), std::prev(tail), "~}"); return (nest > 0 || closed); } return false; } bool comment(const_iterator head, const_iterator tail) { return (singleline_comment(head, tail) || multiline_comment(head, tail)); } bool string_token(const std::string& str) { using std::begin; using std::end; if (str.front() == '"') { bool escaped = false; for(auto it = std::next(begin(str)); it != end(str); ++it) { if (*it == '\\') { escaped = true; } else if (*it == '"' && (!escaped)) { return std::next(it) == end(str); } else { escaped = false; } } } return false; } TokenType match_type(const_iterator head, const_iterator tail) { if (comment(head, tail)) return TokenType::IGNORE; if (symbol(head, tail)) return TokenType::SYMBOL; if (identifier(head, tail)) return TokenType::IDENTIFIER; if (decimal_integer(head, tail)) return TokenType::NUMBER; if (string_token(head, tail)) return TokenType::STRING; if (ignore(head, tail)) return TokenType::IGNORE; return TokenType::UNKNOWN; } std::string extract_string(const std::string& str) { if (str.front() == '"') { bool escaped = false; std::string new_str; for(auto c : str) { if (escaped) { if(c == '"') new_str.push_back('"'); if(c == 'n') new_str.push_back('\n'); escaped = false; } else if (c == '\\') { escaped = true; } else if (c != '"') { new_str.push_back(c); } } return new_str; } return str; } TokenVector tokenize(std::istream& is) { using std::begin; using std::end; std::string const code(std::string{std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>()} + '\n'); // ファイルの末尾が改行で終わっているほうが処理しやすい。 TokenVector tokens; TokenType prev = TokenType::UNKNOWN; const_iterator head(begin(code)); int line = 1; for (auto it(begin(code)); it != end(code); ++it) { TokenType next = match_type(head, std::next(it)); if (prev != TokenType::UNKNOWN && next == TokenType::UNKNOWN) { if (prev != TokenType::IGNORE) { tokens.push_back(Token(prev, extract_string(head, it), line)); } head = it; prev = match_type(head, std::next(head)); } else { prev = next; } if (*it == '\n') ++line; } return tokens; } bool operator==(Token const& lhs, Token const& rhs) { return lhs.type() == rhs.type() && lhs.str() == rhs.str() && lhs.line() == rhs.line(); } bool operator!=(Token const& lhs, Token const& rhs) { return !( lhs == rhs ); } } // namespace klang <|endoftext|>
<commit_before><commit_msg>Use +=<commit_after><|endoftext|>
<commit_before><commit_msg>coverity#1257108 Explicit null dereferenced<commit_after><|endoftext|>
<commit_before>#include "connection_manager.hpp" #include "constants.hpp" #include "filesystem.hpp" #include "grabber_alerts_monitor.hpp" #include "karabiner_version.h" #include "logger.hpp" #include "migration.hpp" #include "process_utility.hpp" #include "spdlog_utility.hpp" #include "thread_utility.hpp" #include "update_utility.hpp" #include "version_monitor.hpp" #include "version_monitor_utility.hpp" #include <spdlog/async.h> #include <spdlog/sinks/rotating_file_sink.h> namespace krbn { class karabiner_console_user_server final { public: karabiner_console_user_server(void) { { auto log_directory = constants::get_user_log_directory(); if (!log_directory.empty()) { filesystem::create_directory_with_intermediate_directories(log_directory, 0700); if (filesystem::is_directory(log_directory)) { std::string log_file_path = log_directory + "/console_user_server.log"; auto l = spdlog::rotating_logger_mt<spdlog::async_factory>("console_user_server", log_file_path.c_str(), 256 * 1024, 3); l->flush_on(spdlog::level::info); l->set_pattern(spdlog_utility::get_pattern()); logger::set_logger(l); } } } logger::get_logger().info("version {0}", karabiner_version); if (!process_utility::lock_single_application_with_user_pid_file("karabiner_console_user_server.pid")) { std::string message("Exit since another process is running."); logger::get_logger().info(message); std::cerr << message << std::endl; exit(0); } // ======================================== grabber_alerts_monitor_ = std::make_unique<grabber_alerts_monitor>(); grabber_alerts_monitor_->alerts_changed.connect([](auto&& alerts) { logger::get_logger().info("karabiner_grabber_alerts.json is updated."); if (!alerts.empty()) { application_launcher::launch_preferences(); } }); grabber_alerts_monitor_->start(constants::get_grabber_alerts_json_file_path()); // ======================================== migration::migrate_v1(); // ======================================== krbn::filesystem::create_directory_with_intermediate_directories(constants::get_user_configuration_directory(), 0700); krbn::filesystem::create_directory_with_intermediate_directories(constants::get_user_complex_modifications_assets_directory(), 0700); connection_manager_ = std::make_unique<connection_manager>(); } ~karabiner_console_user_server(void) { connection_manager_ = nullptr; grabber_alerts_monitor_ = nullptr; } private: std::unique_ptr<grabber_alerts_monitor> grabber_alerts_monitor_; std::unique_ptr<connection_manager> connection_manager_; }; } // namespace krbn int main(int argc, const char* argv[]) { signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); krbn::thread_utility::register_main_thread(); krbn::karabiner_console_user_server karabiner_console_user_server; krbn::update_utility::check_for_updates_on_startup(); krbn::version_monitor_utility::start_monitor_to_stop_main_run_loop_when_version_changed(); CFRunLoopRun(); return 0; } <commit_msg>update for grabber_alerts_monitor interface change<commit_after>#include "connection_manager.hpp" #include "constants.hpp" #include "filesystem.hpp" #include "grabber_alerts_monitor.hpp" #include "karabiner_version.h" #include "logger.hpp" #include "migration.hpp" #include "process_utility.hpp" #include "spdlog_utility.hpp" #include "thread_utility.hpp" #include "update_utility.hpp" #include <spdlog/async.h> #include <spdlog/sinks/rotating_file_sink.h> namespace krbn { class karabiner_console_user_server final { public: karabiner_console_user_server(void) { { auto log_directory = constants::get_user_log_directory(); if (!log_directory.empty()) { filesystem::create_directory_with_intermediate_directories(log_directory, 0700); if (filesystem::is_directory(log_directory)) { std::string log_file_path = log_directory + "/console_user_server.log"; auto l = spdlog::rotating_logger_mt<spdlog::async_factory>("console_user_server", log_file_path.c_str(), 256 * 1024, 3); l->flush_on(spdlog::level::info); l->set_pattern(spdlog_utility::get_pattern()); logger::set_logger(l); } } } logger::get_logger().info("version {0}", karabiner_version); if (!process_utility::lock_single_application_with_user_pid_file("karabiner_console_user_server.pid")) { std::string message("Exit since another process is running."); logger::get_logger().info(message); std::cerr << message << std::endl; exit(0); } // ======================================== grabber_alerts_monitor_ = std::make_unique<grabber_alerts_monitor>(constants::get_grabber_alerts_json_file_path()); grabber_alerts_monitor_->alerts_changed.connect([](auto&& alerts) { logger::get_logger().info("karabiner_grabber_alerts.json is updated."); if (!alerts.empty()) { application_launcher::launch_preferences(); } }); grabber_alerts_monitor_->start(); // ======================================== migration::migrate_v1(); // ======================================== krbn::filesystem::create_directory_with_intermediate_directories(constants::get_user_configuration_directory(), 0700); krbn::filesystem::create_directory_with_intermediate_directories(constants::get_user_complex_modifications_assets_directory(), 0700); connection_manager_ = std::make_unique<connection_manager>(); } ~karabiner_console_user_server(void) { connection_manager_ = nullptr; grabber_alerts_monitor_ = nullptr; } private: std::unique_ptr<grabber_alerts_monitor> grabber_alerts_monitor_; std::unique_ptr<connection_manager> connection_manager_; }; } // namespace krbn int main(int argc, const char* argv[]) { signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); krbn::thread_utility::register_main_thread(); krbn::karabiner_console_user_server karabiner_console_user_server; krbn::update_utility::check_for_updates_on_startup(); CFRunLoopRun(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: swlbox.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-08-12 12:58:39 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #ifndef _UNOTOOLS_CHARCLASS_HXX #include <unotools/charclass.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _SWLBOX_HXX #include <swlbox.hxx> #endif SV_IMPL_PTRARR(SwEntryLst, SwBoxEntry*) /*-------------------------------------------------------------------- Beschreibung: Ein ListboxElement --------------------------------------------------------------------*/ SwBoxEntry::SwBoxEntry() : bModified(FALSE), bNew(FALSE), nId(LISTBOX_APPEND) { } SwBoxEntry::SwBoxEntry(const String& aNam, USHORT nIdx) : bModified(FALSE), bNew(FALSE), aName(aNam), nId(nIdx) { } SwBoxEntry::SwBoxEntry(const SwBoxEntry& rOld) : aName(rOld.aName), nId(rOld.nId), bNew(rOld.bNew), bModified(rOld.bModified) { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ /*SwListBox::SwListBox(Window* pParent, const ResId& rId): ListBox(pParent, rId) { DBG_ASSERT( 0 == (ListBox::GetStyle() & WB_SORT), "NIE sortiert aus der Resource lesen!" ); // falls eine Liste ueber die Resource gelesen wurde, die interne // entsprechend updaten USHORT nCnt = ListBox::GetEntryCount(); for( USHORT n = 0; n < nCnt; ++n ) { const SwBoxEntry* pTmp = new SwBoxEntry( ListBox::GetEntry( n ), n ); aEntryLst.Insert( pTmp, n ); } } /*-------------------------------------------------------------------- Beschreibung: Basisklasse Dtor --------------------------------------------------------------------*/ /*SwListBox::~SwListBox() { } /*-------------------------------------------------------------------- Beschreibung: Listen loeschen und Anzeige loeschen --------------------------------------------------------------------*/ /*void SwListBox::Clear() { ListBox::Clear(); aEntryLst.DeleteAndDestroy( 0, aEntryLst.Count() ); } /*-------------------------------------------------------------------- Beschreibung: Rund um die Entries --------------------------------------------------------------------*/ /*const SwBoxEntry& SwListBox::GetEntry(USHORT nPos) const { if( nPos < aEntryLst.Count() ) return *aEntryLst[ nPos ]; return aDefault; } /*-------------------------------------------------------------------- Beschreibung: aktullen Eintrag zurueckgeben --------------------------------------------------------------------*/ /*const SwBoxEntry& SwListBox::GetSelectEntry() const { USHORT nPos = ListBox::GetSelectEntryPos(); if( nPos < aEntryLst.Count() ) return *aEntryLst[ nPos ]; return aDefault; } void SwListBox::RemoveEntry( USHORT nPos ) { if( nPos < aEntryLst.Count() ) { aEntryLst.DeleteAndDestroy( nPos, 1 ); ListBox::RemoveEntry( nPos ); } } /*-------------------------------------------------------------------- Beschreibung: Eintrag in die ListBox aufnehmen --------------------------------------------------------------------*/ /*void SwListBox::InsertEntry( const SwBoxEntry& rEntry, USHORT nPos ) { if( nPos >= aEntryLst.Count() ) nPos = aEntryLst.Count(); SwBoxEntry* pEntry = new SwBoxEntry( rEntry ); ListBox::InsertEntry( pEntry->aName, nPos ); aEntryLst.C40_INSERT( SwBoxEntry, pEntry, nPos ); } /*-------------------------------------------------------------------- Beschreibung: Sortiert einfuegen --------------------------------------------------------------------*/ /*void SwListBox::InsertEntrySort( const SwBoxEntry& rEntry ) { USHORT nPos; if( !SeekEntry( rEntry, &nPos ) ) { SwBoxEntry* pEntry = new SwBoxEntry( rEntry ); ListBox::InsertEntry( pEntry->aName, nPos ); aEntryLst.C40_INSERT( SwBoxEntry, pEntry, nPos ); } } BOOL SwListBox::SeekEntry( const SwBoxEntry& rEntry, USHORT* pPos ) { register USHORT nO = aEntryLst.Count(), nM, nU = 0; if( nO > 0 ) { nO--; while( nU <= nO ) { nM = nU + ( nO - nU ) / 2; StringCompare eCmp = aEntryLst[ nM ]->aName.ICompare( rEntry.aName ); if( COMPARE_EQUAL == eCmp ) { if( pPos ) *pPos = nM; return TRUE; } else if( COMPARE_GREATER == eCmp ) nU = nM + 1; else if( nM == 0 ) break; else nO = nM - 1; } } if( pPos ) *pPos = nU; return FALSE; } /* */ SwComboBox::SwComboBox(Window* pParent, const ResId& rId, USHORT nStyleBits ): ComboBox(pParent, rId), nStyle(nStyleBits) { // Verwaltung fuer die Stringlist aus der Resource aufbauen USHORT nSize = GetEntryCount(); for( USHORT i=0; i < nSize; ++i ) { const SwBoxEntry* pTmp = new SwBoxEntry(ComboBox::GetEntry(i), i); aEntryLst.Insert(pTmp, aEntryLst.Count() ); } } /*-------------------------------------------------------------------- Beschreibung: Basisklasse Dtor --------------------------------------------------------------------*/ SwComboBox::~SwComboBox() { // das erledigen die Listen doch schon selbst im DTOR! // aEntryLst.DeleteAndDestroy(0, aEntryLst.Count()); // aDelEntryLst.DeleteAndDestroy(0, aDelEntryLst.Count()); } /*-------------------------------------------------------------------- Beschreibung: Eintrag in die ComboBox aufnehmen --------------------------------------------------------------------*/ void SwComboBox::InsertEntry(const SwBoxEntry& rEntry) { InsertSorted(new SwBoxEntry(rEntry)); } /*-------------------------------------------------------------------- Beschreibung: Eintrag aus der Liste loeschen --------------------------------------------------------------------*/ void SwComboBox::RemoveEntry(USHORT nPos) { if(nPos >= aEntryLst.Count()) return; // Altes Element austragen SwBoxEntry* pEntry = aEntryLst[nPos]; aEntryLst.Remove(nPos, 1); ComboBox::RemoveEntry(nPos); // keine neuen Eintraege in die Liste mit aufnehmen if(pEntry->bNew) return; // in DeleteListe eintragen aDelEntryLst.C40_INSERT(SwBoxEntry, pEntry, aDelEntryLst.Count()); } /*-------------------------------------------------------------------- Beschreibung: Position by Name --------------------------------------------------------------------*/ USHORT SwComboBox::GetEntryPos(const SwBoxEntry& rEntry) const { return ComboBox::GetEntryPos(rEntry.aName); } /*-------------------------------------------------------------------- Beschreibung: Rund um die Entries --------------------------------------------------------------------*/ const SwBoxEntry& SwComboBox::GetEntry(USHORT nPos) const { if(nPos < aEntryLst.Count()) return *aEntryLst[nPos]; return aDefault; } /*-------------------------------------------------------------------- Beschreibung: geloeschte Eintraege --------------------------------------------------------------------*/ USHORT SwComboBox::GetRemovedCount() const { return aDelEntryLst.Count(); } const SwBoxEntry& SwComboBox::GetRemovedEntry(USHORT nPos) const { if(nPos < aDelEntryLst.Count()) return *aDelEntryLst[nPos]; return aDefault; } /*-------------------------------------------------------------------- Beschreibung: Sortiert einfuegen --------------------------------------------------------------------*/ void SwComboBox::InsertSorted(SwBoxEntry* pEntry) { ComboBox::InsertEntry(pEntry->aName); USHORT nPos = ComboBox::GetEntryPos(pEntry->aName); aEntryLst.C40_INSERT(SwBoxEntry, pEntry, nPos); } /*-------------------------------------------------------------------- Beschreibung: Je nach Option bestimmte Zeichen ausblenden --------------------------------------------------------------------*/ void SwComboBox::KeyInput( const KeyEvent& rKEvt ) { USHORT nChar = rKEvt.GetCharCode(); if(nStyle & CBS_FILENAME) { #ifdef MAC if(nChar == ':') return; #elif defined UNX if(nChar == '/' || nChar == ' ' ) return; #else if(nChar == ':' || nChar == '\\' || nChar == '.' || nChar == ' ') return; #endif } ComboBox::KeyInput(rKEvt); } /*-------------------------------------------------------------------- Beschreibung: Text nach Option konvertieren --------------------------------------------------------------------*/ String SwComboBox::GetText() const { String aTxt( ComboBox::GetText() ); if(nStyle & CBS_LOWER) GetAppCharClass().toLower( aTxt ); else if( nStyle & CBS_UPPER ) GetAppCharClass().toUpper( aTxt ); return aTxt; } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.600); FILE MERGED 2005/09/05 13:43:11 rt 1.4.600.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: swlbox.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 06:34:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #ifndef _UNOTOOLS_CHARCLASS_HXX #include <unotools/charclass.hxx> #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _SWLBOX_HXX #include <swlbox.hxx> #endif SV_IMPL_PTRARR(SwEntryLst, SwBoxEntry*) /*-------------------------------------------------------------------- Beschreibung: Ein ListboxElement --------------------------------------------------------------------*/ SwBoxEntry::SwBoxEntry() : bModified(FALSE), bNew(FALSE), nId(LISTBOX_APPEND) { } SwBoxEntry::SwBoxEntry(const String& aNam, USHORT nIdx) : bModified(FALSE), bNew(FALSE), aName(aNam), nId(nIdx) { } SwBoxEntry::SwBoxEntry(const SwBoxEntry& rOld) : aName(rOld.aName), nId(rOld.nId), bNew(rOld.bNew), bModified(rOld.bModified) { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ /*SwListBox::SwListBox(Window* pParent, const ResId& rId): ListBox(pParent, rId) { DBG_ASSERT( 0 == (ListBox::GetStyle() & WB_SORT), "NIE sortiert aus der Resource lesen!" ); // falls eine Liste ueber die Resource gelesen wurde, die interne // entsprechend updaten USHORT nCnt = ListBox::GetEntryCount(); for( USHORT n = 0; n < nCnt; ++n ) { const SwBoxEntry* pTmp = new SwBoxEntry( ListBox::GetEntry( n ), n ); aEntryLst.Insert( pTmp, n ); } } /*-------------------------------------------------------------------- Beschreibung: Basisklasse Dtor --------------------------------------------------------------------*/ /*SwListBox::~SwListBox() { } /*-------------------------------------------------------------------- Beschreibung: Listen loeschen und Anzeige loeschen --------------------------------------------------------------------*/ /*void SwListBox::Clear() { ListBox::Clear(); aEntryLst.DeleteAndDestroy( 0, aEntryLst.Count() ); } /*-------------------------------------------------------------------- Beschreibung: Rund um die Entries --------------------------------------------------------------------*/ /*const SwBoxEntry& SwListBox::GetEntry(USHORT nPos) const { if( nPos < aEntryLst.Count() ) return *aEntryLst[ nPos ]; return aDefault; } /*-------------------------------------------------------------------- Beschreibung: aktullen Eintrag zurueckgeben --------------------------------------------------------------------*/ /*const SwBoxEntry& SwListBox::GetSelectEntry() const { USHORT nPos = ListBox::GetSelectEntryPos(); if( nPos < aEntryLst.Count() ) return *aEntryLst[ nPos ]; return aDefault; } void SwListBox::RemoveEntry( USHORT nPos ) { if( nPos < aEntryLst.Count() ) { aEntryLst.DeleteAndDestroy( nPos, 1 ); ListBox::RemoveEntry( nPos ); } } /*-------------------------------------------------------------------- Beschreibung: Eintrag in die ListBox aufnehmen --------------------------------------------------------------------*/ /*void SwListBox::InsertEntry( const SwBoxEntry& rEntry, USHORT nPos ) { if( nPos >= aEntryLst.Count() ) nPos = aEntryLst.Count(); SwBoxEntry* pEntry = new SwBoxEntry( rEntry ); ListBox::InsertEntry( pEntry->aName, nPos ); aEntryLst.C40_INSERT( SwBoxEntry, pEntry, nPos ); } /*-------------------------------------------------------------------- Beschreibung: Sortiert einfuegen --------------------------------------------------------------------*/ /*void SwListBox::InsertEntrySort( const SwBoxEntry& rEntry ) { USHORT nPos; if( !SeekEntry( rEntry, &nPos ) ) { SwBoxEntry* pEntry = new SwBoxEntry( rEntry ); ListBox::InsertEntry( pEntry->aName, nPos ); aEntryLst.C40_INSERT( SwBoxEntry, pEntry, nPos ); } } BOOL SwListBox::SeekEntry( const SwBoxEntry& rEntry, USHORT* pPos ) { register USHORT nO = aEntryLst.Count(), nM, nU = 0; if( nO > 0 ) { nO--; while( nU <= nO ) { nM = nU + ( nO - nU ) / 2; StringCompare eCmp = aEntryLst[ nM ]->aName.ICompare( rEntry.aName ); if( COMPARE_EQUAL == eCmp ) { if( pPos ) *pPos = nM; return TRUE; } else if( COMPARE_GREATER == eCmp ) nU = nM + 1; else if( nM == 0 ) break; else nO = nM - 1; } } if( pPos ) *pPos = nU; return FALSE; } /* */ SwComboBox::SwComboBox(Window* pParent, const ResId& rId, USHORT nStyleBits ): ComboBox(pParent, rId), nStyle(nStyleBits) { // Verwaltung fuer die Stringlist aus der Resource aufbauen USHORT nSize = GetEntryCount(); for( USHORT i=0; i < nSize; ++i ) { const SwBoxEntry* pTmp = new SwBoxEntry(ComboBox::GetEntry(i), i); aEntryLst.Insert(pTmp, aEntryLst.Count() ); } } /*-------------------------------------------------------------------- Beschreibung: Basisklasse Dtor --------------------------------------------------------------------*/ SwComboBox::~SwComboBox() { // das erledigen die Listen doch schon selbst im DTOR! // aEntryLst.DeleteAndDestroy(0, aEntryLst.Count()); // aDelEntryLst.DeleteAndDestroy(0, aDelEntryLst.Count()); } /*-------------------------------------------------------------------- Beschreibung: Eintrag in die ComboBox aufnehmen --------------------------------------------------------------------*/ void SwComboBox::InsertEntry(const SwBoxEntry& rEntry) { InsertSorted(new SwBoxEntry(rEntry)); } /*-------------------------------------------------------------------- Beschreibung: Eintrag aus der Liste loeschen --------------------------------------------------------------------*/ void SwComboBox::RemoveEntry(USHORT nPos) { if(nPos >= aEntryLst.Count()) return; // Altes Element austragen SwBoxEntry* pEntry = aEntryLst[nPos]; aEntryLst.Remove(nPos, 1); ComboBox::RemoveEntry(nPos); // keine neuen Eintraege in die Liste mit aufnehmen if(pEntry->bNew) return; // in DeleteListe eintragen aDelEntryLst.C40_INSERT(SwBoxEntry, pEntry, aDelEntryLst.Count()); } /*-------------------------------------------------------------------- Beschreibung: Position by Name --------------------------------------------------------------------*/ USHORT SwComboBox::GetEntryPos(const SwBoxEntry& rEntry) const { return ComboBox::GetEntryPos(rEntry.aName); } /*-------------------------------------------------------------------- Beschreibung: Rund um die Entries --------------------------------------------------------------------*/ const SwBoxEntry& SwComboBox::GetEntry(USHORT nPos) const { if(nPos < aEntryLst.Count()) return *aEntryLst[nPos]; return aDefault; } /*-------------------------------------------------------------------- Beschreibung: geloeschte Eintraege --------------------------------------------------------------------*/ USHORT SwComboBox::GetRemovedCount() const { return aDelEntryLst.Count(); } const SwBoxEntry& SwComboBox::GetRemovedEntry(USHORT nPos) const { if(nPos < aDelEntryLst.Count()) return *aDelEntryLst[nPos]; return aDefault; } /*-------------------------------------------------------------------- Beschreibung: Sortiert einfuegen --------------------------------------------------------------------*/ void SwComboBox::InsertSorted(SwBoxEntry* pEntry) { ComboBox::InsertEntry(pEntry->aName); USHORT nPos = ComboBox::GetEntryPos(pEntry->aName); aEntryLst.C40_INSERT(SwBoxEntry, pEntry, nPos); } /*-------------------------------------------------------------------- Beschreibung: Je nach Option bestimmte Zeichen ausblenden --------------------------------------------------------------------*/ void SwComboBox::KeyInput( const KeyEvent& rKEvt ) { USHORT nChar = rKEvt.GetCharCode(); if(nStyle & CBS_FILENAME) { #ifdef MAC if(nChar == ':') return; #elif defined UNX if(nChar == '/' || nChar == ' ' ) return; #else if(nChar == ':' || nChar == '\\' || nChar == '.' || nChar == ' ') return; #endif } ComboBox::KeyInput(rKEvt); } /*-------------------------------------------------------------------- Beschreibung: Text nach Option konvertieren --------------------------------------------------------------------*/ String SwComboBox::GetText() const { String aTxt( ComboBox::GetText() ); if(nStyle & CBS_LOWER) GetAppCharClass().toLower( aTxt ); else if( nStyle & CBS_UPPER ) GetAppCharClass().toUpper( aTxt ); return aTxt; } <|endoftext|>
<commit_before>#include <IOKit/hid/IOHIDKeys.h> #include "CommonData.hpp" #include "Config.hpp" #include "EventInputQueue.hpp" #include "FlagStatus.hpp" #include "IOLockWrapper.hpp" #include "ListHookedKeyboard.hpp" #include "RemapClass.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { ListHookedKeyboard listHookedKeyboard; } TimerWrapper ListHookedKeyboard::setcapslock_timer_; void ListHookedKeyboard::static_initialize(IOWorkLoop& workloop) { setcapslock_timer_.initialize(&workloop, NULL, ListHookedKeyboard::setCapsLock_callback); } void ListHookedKeyboard::static_terminate(void) { setcapslock_timer_.terminate(); } ListHookedKeyboard& ListHookedKeyboard::instance(void) { return listHookedKeyboard; } ListHookedKeyboard::Item::Item(IOHIDevice* p) : ListHookedDevice::Item(p), orig_keyboardEventAction_(NULL), orig_keyboardEventTarget_(NULL), orig_updateEventFlagsAction_(NULL), orig_updateEventFlagsTarget_(NULL), replacerestore_lock_(NULL) { replacerestore_lock_ = IOLockWrapper::alloc(); } ListHookedKeyboard::Item::~Item(void) { IOLOG_DEBUG("ListHookedKeyboard::Item::~Item()\n"); restoreEventAction(); IOLockWrapper::free(replacerestore_lock_); } // ====================================================================== bool ListHookedKeyboard::Item::refresh(void) { if (! device_) goto restore; { const char* name = device_->getName(); if (! name) goto restore; if (ListHookedDevice::Item::isConsumer(name)) goto restore; } // ------------------------------------------------------------ if (! Config::get_initialized()) { goto restore; } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_thirdvendor_keyboard) && deviceType_ != DeviceType::APPLE_INTERNAL && deviceType_ != DeviceType::APPLE_EXTERNAL) { goto restore; } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_internal) && deviceType_ == DeviceType::APPLE_INTERNAL) { goto restore; } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_external) && deviceType_ != DeviceType::APPLE_INTERNAL) { goto restore; } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_apple_keyboard) && isEqualVendor(DeviceVendor::APPLE_COMPUTER)) { goto restore; } // Logitech USB Headset if (isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_USB_HEADSET)) { goto restore; } // Logitech Cordless Presenter if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_logitech_cordless_presenter) && isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) { goto restore; } // Kensington Virtual Device (0x0, 0x0) if (isEqualVendorProduct(DeviceVendor::PSEUDO, DeviceProduct::PSEUDO)) { // Note: USB Overdrive also use 0x0,0x0. // We allow to use USB Overdrive. if (deviceType_ != DeviceType::USB_OVERDRIVE) { goto restore; } } #if 0 // Apple Internal Keyboard if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_INTERNAL_KEYBOARD_TRACKPAD_0x021a)) { goto restore; } // Apple External Keyboard if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_ALUMINUM_KEYBOARD_JIS)) { goto restore; } #endif // ------------------------------------------------------------ // NumLock Hacks // // As for some keypads, NumLock is off when it was connected. // We need to call setAlphaLock(true) to activate a device. RemapClassManager::remap_forcenumlockon(this); // ------------------------------------------------------------ return replaceEventAction(); restore: return restoreEventAction(); } bool ListHookedKeyboard::Item::replaceEventAction(void) { IOLockWrapper::ScopedLock lk(replacerestore_lock_); if (! lk) return false; if (! device_) return false; IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_); if (! kbd) return false; bool result = false; // ------------------------------------------------------------ { KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction); if (callback != EventInputQueue::push_KeyboardEventCallback) { IOLOG_DEBUG("HookedKeyboard::replaceEventAction (KeyboardEventCallback) device_:%p\n", device_); orig_keyboardEventAction_ = callback; orig_keyboardEventTarget_ = kbd->_keyboardEventTarget; kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(EventInputQueue::push_KeyboardEventCallback); result = true; } } { UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction); if (callback != EventInputQueue::push_UpdateEventFlagsCallback) { IOLOG_DEBUG("HookedKeyboard::replaceEventAction (UpdateEventFlagsCallback) device_:%p\n", device_); orig_updateEventFlagsAction_ = callback; orig_updateEventFlagsTarget_ = kbd->_updateEventFlagsTarget; kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(EventInputQueue::push_UpdateEventFlagsCallback); result = true; } } return result; } bool ListHookedKeyboard::Item::restoreEventAction(void) { IOLockWrapper::ScopedLock lk(replacerestore_lock_); if (! lk) return false; if (! device_) return false; IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_); if (! kbd) return false; bool result = false; // ---------------------------------------- { KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction); if (callback == EventInputQueue::push_KeyboardEventCallback) { IOLOG_DEBUG("HookedKeyboard::restoreEventAction (KeyboardEventCallback) device_:%p\n", device_); kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(orig_keyboardEventAction_); result = true; } } { UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction); if (callback == EventInputQueue::push_UpdateEventFlagsCallback) { IOLOG_DEBUG("HookedKeyboard::restoreEventAction (UpdateEventFlagsCallback) device_:%p\n", device_); kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(orig_updateEventFlagsAction_); result = true; } } orig_keyboardEventAction_ = NULL; orig_keyboardEventTarget_ = NULL; orig_updateEventFlagsAction_ = NULL; orig_updateEventFlagsTarget_ = NULL; return result; } // ====================================================================== void ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params) { if (params.key >= KeyCode::VK__BEGIN__) { // Invalid keycode IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid key:%d eventType:%d\n", params.key.get(), params.eventType.get()); return; } if (params.eventType == EventType::MODIFY && ! params.key.isModifier()) { // Invalid modifierkeycode IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid modifierkey:%08x\n", params.key.get()); return; } if (params.flags.isVirtualModifiersOn()) { IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get()); return; } // ------------------------------------------------------------ if (RemapClassManager::remap_dropkeyafterremap(params)) return; // ------------------------------------------------------------ KeyboardEventCallback callback = orig_keyboardEventAction_; if (! callback) return; OSObject* target = orig_keyboardEventTarget_; if (! target) return; OSObject* sender = OSDynamicCast(OSObject, device_); if (! sender) return; const AbsoluteTime& ts = CommonData::getcurrent_ts(); OSObject* refcon = NULL; params.log("sending"); callback(target, params.eventType.get(), params.flags.get(), params.key.get(), params.charCode.get(), params.charSet.get(), params.origCharCode.get(), params.origCharSet.get(), params.keyboardType.get(), params.repeat, ts, sender, refcon); CommonData::setcurrent_keyboardType(params.keyboardType); // The CapsLock LED is not designed to turn it on/off frequently. // So, we have to use the timer to call a setAlphaLock function at appropriate frequency. enum { CAPSLOCK_LED_DELAY_MS = 5, }; setcapslock_timer_.setTimeoutMS(CAPSLOCK_LED_DELAY_MS, false); } void ListHookedKeyboard::Item::apply(const Params_UpdateEventFlagsCallback& params) { if (params.flags.isVirtualModifiersOn()) { IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get()); return; } // ------------------------------------------------------------ UpdateEventFlagsCallback callback = orig_updateEventFlagsAction_; if (! callback) return; OSObject* target = orig_updateEventFlagsTarget_; if (! target) return; OSObject* sender = OSDynamicCast(OSObject, device_); if (! sender) return; OSObject* refcon = NULL; params.log("sending"); callback(target, params.flags.get(), sender, refcon); } void ListHookedKeyboard::apply(const Params_KeyboardEventCallBack& params) { IOLockWrapper::ScopedLock lk(list_lock_); if (! lk) return; ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced_nolock()); if (p) { p->apply(params); } } void ListHookedKeyboard::apply(const Params_UpdateEventFlagsCallback& params) { IOLockWrapper::ScopedLock lk(list_lock_); if (! lk) return; ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced_nolock()); if (p) { p->apply(params); } } void ListHookedKeyboard::setCapsLock_callback(OSObject* owner, IOTimerEventSource* sender) { ListHookedKeyboard& self = ListHookedKeyboard::instance(); IOLockWrapper::ScopedLock lk(self.list_lock_); if (! lk) return; if (! self.list_) return; if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_passthrough_capslock_led_status)) return; Flags flags = FlagStatus::makeFlags(); for (Item* p = static_cast<Item*>(self.list_->front()); p; p = static_cast<Item*>(p->getnext())) { if (! p->isReplaced()) continue; IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, p->get()); if (! kbd) continue; // We call setAlphaLock to match a state of CapsLock of the hardware with remapped CapsLock. if (flags.isOn(ModifierFlag::CAPSLOCK)) { if (! kbd->alphaLock()) { kbd->setAlphaLock(true); } } else { if (kbd->alphaLock()) { kbd->setAlphaLock(false); } } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_capslock_led_hack)) { // Set CapsLock LED always. // *** Do not use setAlphaLock for this purpose. It changes the flag status of the hardware CapsLock. *** enum { CAPSLOCK_LED_MASK = 0x2, }; bool isLED = (kbd->getLEDStatus() & CAPSLOCK_LED_MASK); if (! isLED) { kbd->setAlphaLockFeedback(true); } } } } } <commit_msg>remove unnecessary CommonData::setcurrent_keyboardType from ListHookedKeyboard::Item::apply<commit_after>#include <IOKit/hid/IOHIDKeys.h> #include "CommonData.hpp" #include "Config.hpp" #include "EventInputQueue.hpp" #include "FlagStatus.hpp" #include "IOLockWrapper.hpp" #include "ListHookedKeyboard.hpp" #include "RemapClass.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { ListHookedKeyboard listHookedKeyboard; } TimerWrapper ListHookedKeyboard::setcapslock_timer_; void ListHookedKeyboard::static_initialize(IOWorkLoop& workloop) { setcapslock_timer_.initialize(&workloop, NULL, ListHookedKeyboard::setCapsLock_callback); } void ListHookedKeyboard::static_terminate(void) { setcapslock_timer_.terminate(); } ListHookedKeyboard& ListHookedKeyboard::instance(void) { return listHookedKeyboard; } ListHookedKeyboard::Item::Item(IOHIDevice* p) : ListHookedDevice::Item(p), orig_keyboardEventAction_(NULL), orig_keyboardEventTarget_(NULL), orig_updateEventFlagsAction_(NULL), orig_updateEventFlagsTarget_(NULL), replacerestore_lock_(NULL) { replacerestore_lock_ = IOLockWrapper::alloc(); } ListHookedKeyboard::Item::~Item(void) { IOLOG_DEBUG("ListHookedKeyboard::Item::~Item()\n"); restoreEventAction(); IOLockWrapper::free(replacerestore_lock_); } // ====================================================================== bool ListHookedKeyboard::Item::refresh(void) { if (! device_) goto restore; { const char* name = device_->getName(); if (! name) goto restore; if (ListHookedDevice::Item::isConsumer(name)) goto restore; } // ------------------------------------------------------------ if (! Config::get_initialized()) { goto restore; } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_thirdvendor_keyboard) && deviceType_ != DeviceType::APPLE_INTERNAL && deviceType_ != DeviceType::APPLE_EXTERNAL) { goto restore; } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_internal) && deviceType_ == DeviceType::APPLE_INTERNAL) { goto restore; } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_external) && deviceType_ != DeviceType::APPLE_INTERNAL) { goto restore; } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_apple_keyboard) && isEqualVendor(DeviceVendor::APPLE_COMPUTER)) { goto restore; } // Logitech USB Headset if (isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_USB_HEADSET)) { goto restore; } // Logitech Cordless Presenter if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_logitech_cordless_presenter) && isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) { goto restore; } // Kensington Virtual Device (0x0, 0x0) if (isEqualVendorProduct(DeviceVendor::PSEUDO, DeviceProduct::PSEUDO)) { // Note: USB Overdrive also use 0x0,0x0. // We allow to use USB Overdrive. if (deviceType_ != DeviceType::USB_OVERDRIVE) { goto restore; } } #if 0 // Apple Internal Keyboard if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_INTERNAL_KEYBOARD_TRACKPAD_0x021a)) { goto restore; } // Apple External Keyboard if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_ALUMINUM_KEYBOARD_JIS)) { goto restore; } #endif // ------------------------------------------------------------ // NumLock Hacks // // As for some keypads, NumLock is off when it was connected. // We need to call setAlphaLock(true) to activate a device. RemapClassManager::remap_forcenumlockon(this); // ------------------------------------------------------------ return replaceEventAction(); restore: return restoreEventAction(); } bool ListHookedKeyboard::Item::replaceEventAction(void) { IOLockWrapper::ScopedLock lk(replacerestore_lock_); if (! lk) return false; if (! device_) return false; IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_); if (! kbd) return false; bool result = false; // ------------------------------------------------------------ { KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction); if (callback != EventInputQueue::push_KeyboardEventCallback) { IOLOG_DEBUG("HookedKeyboard::replaceEventAction (KeyboardEventCallback) device_:%p\n", device_); orig_keyboardEventAction_ = callback; orig_keyboardEventTarget_ = kbd->_keyboardEventTarget; kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(EventInputQueue::push_KeyboardEventCallback); result = true; } } { UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction); if (callback != EventInputQueue::push_UpdateEventFlagsCallback) { IOLOG_DEBUG("HookedKeyboard::replaceEventAction (UpdateEventFlagsCallback) device_:%p\n", device_); orig_updateEventFlagsAction_ = callback; orig_updateEventFlagsTarget_ = kbd->_updateEventFlagsTarget; kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(EventInputQueue::push_UpdateEventFlagsCallback); result = true; } } return result; } bool ListHookedKeyboard::Item::restoreEventAction(void) { IOLockWrapper::ScopedLock lk(replacerestore_lock_); if (! lk) return false; if (! device_) return false; IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_); if (! kbd) return false; bool result = false; // ---------------------------------------- { KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction); if (callback == EventInputQueue::push_KeyboardEventCallback) { IOLOG_DEBUG("HookedKeyboard::restoreEventAction (KeyboardEventCallback) device_:%p\n", device_); kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(orig_keyboardEventAction_); result = true; } } { UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction); if (callback == EventInputQueue::push_UpdateEventFlagsCallback) { IOLOG_DEBUG("HookedKeyboard::restoreEventAction (UpdateEventFlagsCallback) device_:%p\n", device_); kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(orig_updateEventFlagsAction_); result = true; } } orig_keyboardEventAction_ = NULL; orig_keyboardEventTarget_ = NULL; orig_updateEventFlagsAction_ = NULL; orig_updateEventFlagsTarget_ = NULL; return result; } // ====================================================================== void ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params) { if (params.key >= KeyCode::VK__BEGIN__) { // Invalid keycode IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid key:%d eventType:%d\n", params.key.get(), params.eventType.get()); return; } if (params.eventType == EventType::MODIFY && ! params.key.isModifier()) { // Invalid modifierkeycode IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid modifierkey:%08x\n", params.key.get()); return; } if (params.flags.isVirtualModifiersOn()) { IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get()); return; } // ------------------------------------------------------------ if (RemapClassManager::remap_dropkeyafterremap(params)) return; // ------------------------------------------------------------ KeyboardEventCallback callback = orig_keyboardEventAction_; if (! callback) return; OSObject* target = orig_keyboardEventTarget_; if (! target) return; OSObject* sender = OSDynamicCast(OSObject, device_); if (! sender) return; const AbsoluteTime& ts = CommonData::getcurrent_ts(); OSObject* refcon = NULL; params.log("sending"); callback(target, params.eventType.get(), params.flags.get(), params.key.get(), params.charCode.get(), params.charSet.get(), params.origCharCode.get(), params.origCharSet.get(), params.keyboardType.get(), params.repeat, ts, sender, refcon); // The CapsLock LED is not designed to turn it on/off frequently. // So, we have to use the timer to call a setAlphaLock function at appropriate frequency. enum { CAPSLOCK_LED_DELAY_MS = 5, }; setcapslock_timer_.setTimeoutMS(CAPSLOCK_LED_DELAY_MS, false); } void ListHookedKeyboard::Item::apply(const Params_UpdateEventFlagsCallback& params) { if (params.flags.isVirtualModifiersOn()) { IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get()); return; } // ------------------------------------------------------------ UpdateEventFlagsCallback callback = orig_updateEventFlagsAction_; if (! callback) return; OSObject* target = orig_updateEventFlagsTarget_; if (! target) return; OSObject* sender = OSDynamicCast(OSObject, device_); if (! sender) return; OSObject* refcon = NULL; params.log("sending"); callback(target, params.flags.get(), sender, refcon); } void ListHookedKeyboard::apply(const Params_KeyboardEventCallBack& params) { IOLockWrapper::ScopedLock lk(list_lock_); if (! lk) return; ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced_nolock()); if (p) { p->apply(params); } } void ListHookedKeyboard::apply(const Params_UpdateEventFlagsCallback& params) { IOLockWrapper::ScopedLock lk(list_lock_); if (! lk) return; ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced_nolock()); if (p) { p->apply(params); } } void ListHookedKeyboard::setCapsLock_callback(OSObject* owner, IOTimerEventSource* sender) { ListHookedKeyboard& self = ListHookedKeyboard::instance(); IOLockWrapper::ScopedLock lk(self.list_lock_); if (! lk) return; if (! self.list_) return; if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_passthrough_capslock_led_status)) return; Flags flags = FlagStatus::makeFlags(); for (Item* p = static_cast<Item*>(self.list_->front()); p; p = static_cast<Item*>(p->getnext())) { if (! p->isReplaced()) continue; IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, p->get()); if (! kbd) continue; // We call setAlphaLock to match a state of CapsLock of the hardware with remapped CapsLock. if (flags.isOn(ModifierFlag::CAPSLOCK)) { if (! kbd->alphaLock()) { kbd->setAlphaLock(true); } } else { if (kbd->alphaLock()) { kbd->setAlphaLock(false); } } if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_capslock_led_hack)) { // Set CapsLock LED always. // *** Do not use setAlphaLock for this purpose. It changes the flag status of the hardware CapsLock. *** enum { CAPSLOCK_LED_MASK = 0x2, }; bool isLED = (kbd->getLEDStatus() & CAPSLOCK_LED_MASK); if (! isLED) { kbd->setAlphaLockFeedback(true); } } } } } <|endoftext|>
<commit_before>/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #include "base/Log.h" #include "event/SyncItemListener.h" BEGIN_NAMESPACE void logEvent(const char* msg, SyncItemEvent& event) { LOG.debug("%s: (%s, %s, %s)", msg, event.getItemKey(), event.getSourceName(), event.getSourceURI()); } // listen for the Item added by Server Event void SyncItemListener::itemAddedByServer(SyncItemEvent& event) { logEvent("item added by server", event); } // listen for the Item deleted by Server Event void SyncItemListener::itemDeletedByServer(SyncItemEvent& event) { logEvent("item deleted by server", event); } // listen for the Item updated by Server Event void SyncItemListener::itemUpdatedByServer(SyncItemEvent& event) { logEvent("item updated by server", event); } // listen for the Item added by Client Event void SyncItemListener::itemAddedByClient(SyncItemEvent& event) { logEvent("item added by client", event); } // listen for the Item deleted by Client Event void SyncItemListener::itemDeletedByClient(SyncItemEvent& event) { logEvent("item deleted by client", event); } // listen for the Item updated by Server Event void SyncItemListener::itemUpdatedByClient(SyncItemEvent& event) { logEvent("item updated by server", event); } END_NAMESPACE<commit_msg>added newline at eof<commit_after>/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #include "base/Log.h" #include "event/SyncItemListener.h" BEGIN_NAMESPACE void logEvent(const char* msg, SyncItemEvent& event) { LOG.debug("%s: (%s, %s, %s)", msg, event.getItemKey(), event.getSourceName(), event.getSourceURI()); } // listen for the Item added by Server Event void SyncItemListener::itemAddedByServer(SyncItemEvent& event) { logEvent("item added by server", event); } // listen for the Item deleted by Server Event void SyncItemListener::itemDeletedByServer(SyncItemEvent& event) { logEvent("item deleted by server", event); } // listen for the Item updated by Server Event void SyncItemListener::itemUpdatedByServer(SyncItemEvent& event) { logEvent("item updated by server", event); } // listen for the Item added by Client Event void SyncItemListener::itemAddedByClient(SyncItemEvent& event) { logEvent("item added by client", event); } // listen for the Item deleted by Client Event void SyncItemListener::itemDeletedByClient(SyncItemEvent& event) { logEvent("item deleted by client", event); } // listen for the Item updated by Server Event void SyncItemListener::itemUpdatedByClient(SyncItemEvent& event) { logEvent("item updated by server", event); } END_NAMESPACE <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: shdwcrsr.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 17:14:42 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SHDWCRSR_HXX #define _SHDWCRSR_HXX #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _SV_COLOR_HXX //autogen #include <vcl/color.hxx> #endif #include <limits.h> class Window; class SwShadowCursor { Window* pWin; Color aCol; Point aOldPt; long nOldHeight; USHORT nOldMode; void DrawTri( const Point& rPt, long nHeight, BOOL bLeft ); void DrawCrsr( const Point& rPt, long nHeight, USHORT nMode ); public: SwShadowCursor( Window& rWin, const Color& rCol ) : pWin( &rWin ), nOldMode( USHRT_MAX ), aCol( rCol ) {} ~SwShadowCursor(); void SetPos( const Point& rPt, long nHeight, USHORT nMode ); void Paint(); const Point& GetPoint() const { return aOldPt; } long GetHeight() const { return nOldHeight; } USHORT GetMode() const { return nOldMode; } Rectangle GetRect() const; }; #endif <commit_msg>INTEGRATION: CWS vclcleanup02 (1.1.1.1.512); FILE MERGED 2003/12/11 09:10:18 mt 1.1.1.1.512.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/************************************************************************* * * $RCSfile: shdwcrsr.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2004-01-06 18:25:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SHDWCRSR_HXX #define _SHDWCRSR_HXX #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #include <limits.h> class Window; class SwShadowCursor { Window* pWin; Color aCol; Point aOldPt; long nOldHeight; USHORT nOldMode; void DrawTri( const Point& rPt, long nHeight, BOOL bLeft ); void DrawCrsr( const Point& rPt, long nHeight, USHORT nMode ); public: SwShadowCursor( Window& rWin, const Color& rCol ) : pWin( &rWin ), nOldMode( USHRT_MAX ), aCol( rCol ) {} ~SwShadowCursor(); void SetPos( const Point& rPt, long nHeight, USHORT nMode ); void Paint(); const Point& GetPoint() const { return aOldPt; } long GetHeight() const { return nOldHeight; } USHORT GetMode() const { return nOldMode; } Rectangle GetRect() const; }; #endif <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2018 Advanced Micro Devices, Inc. * Copyright (c) 2018 The Khronos Group 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. * *//*! * \file * \brief VK_KHR_driver_properties tests *//*--------------------------------------------------------------------*/ #include "vktApiDriverPropertiesTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktTestCaseUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" using namespace vk; namespace vkt { namespace api { namespace { static const deUint32 knownDriverIds[] = { // Specified in the Vulkan registry (vk.xml) 1, // author = "Advanced Micro Devices, Inc." comment = "AMD proprietary driver" 2, // author = "Advanced Micro Devices, Inc." comment = "AMD open-source driver" 3, // author = "Mesa open source project" comment = "Mesa RADV driver" 4, // author = "NVIDIA Corporation" comment = "NVIDIA proprietary driver" 5, // author = "Intel Corporation" comment = "Intel proprietary Windows driver" 6, // author = "Intel Corporation" comment = "Intel open-source Mesa driver" 7, // author = "Imagination Technologies" comment = "Imagination proprietary driver" 8, // author = "Qualcomm Technologies, Inc." comment = "Qualcomm proprietary driver" 9, // author = "Arm Limited" comment = "Arm proprietary driver" }; static const VkConformanceVersionKHR knownConformanceVersions[] = { makeConformanceVersionKHR(1, 1, 2, 3), makeConformanceVersionKHR(1, 1, 2, 2), makeConformanceVersionKHR(1, 1, 2, 1), makeConformanceVersionKHR(1, 1, 2, 0), makeConformanceVersionKHR(1, 1, 1, 3), makeConformanceVersionKHR(1, 1, 1, 2), makeConformanceVersionKHR(1, 1, 1, 1), makeConformanceVersionKHR(1, 1, 1, 0), makeConformanceVersionKHR(1, 1, 0, 3), makeConformanceVersionKHR(1, 0, 2, 6), makeConformanceVersionKHR(1, 0, 2, 5), makeConformanceVersionKHR(1, 0, 2, 4), makeConformanceVersionKHR(1, 0, 2, 3), makeConformanceVersionKHR(1, 0, 2, 2), makeConformanceVersionKHR(1, 0, 2, 1), makeConformanceVersionKHR(1, 0, 2, 0), }; DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize) { return deStrnlen(str, maxSize) < maxSize; } DE_INLINE bool operator==(const VkConformanceVersionKHR& a, const VkConformanceVersionKHR& b) { return ((a.major == b.major) && (a.minor == b.minor) && (a.subminor == b.subminor) && (a.patch == b.patch)); } tcu::TestStatus testQueryProperties (Context& context) { // Check extension support if (!isDeviceExtensionSupported(context.getUsedApiVersion(), context.getDeviceExtensions(), "VK_KHR_driver_properties")) TCU_THROW(NotSupportedError, "Unsupported extension: VK_KHR_driver_properties"); // Query the driver properties const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const int memsetPattern = 0xaa; VkPhysicalDeviceProperties2 deviceProperties2; VkPhysicalDeviceDriverPropertiesKHR deviceDriverProperties; deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties)); deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR; deviceDriverProperties.pNext = DE_NULL; deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2)); deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &deviceDriverProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2); // Verify the returned values bool match = false; for (const deUint32* pDriverId = knownDriverIds; (pDriverId != DE_ARRAY_END(knownDriverIds)) && !match; ++pDriverId) { if (deviceDriverProperties.driverID == *pDriverId) { match = true; if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR)) TCU_FAIL("Driver name is not a null-terminated string"); if (deviceDriverProperties.driverName[0] == 0) TCU_FAIL("Driver name is empty"); if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR)) TCU_FAIL("Driver info is not a null-terminated string"); bool conformanceVersionMatch = false; for (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions; pConformanceVersion != DE_ARRAY_END(knownConformanceVersions); ++pConformanceVersion) { if (deviceDriverProperties.conformanceVersion == *pConformanceVersion) { conformanceVersionMatch = true; break; } } if (!conformanceVersionMatch) TCU_FAIL("Wrong driver conformance version"); } } if (!match) TCU_FAIL("Driver ID did not match any known driver"); return tcu::TestStatus::pass("Pass"); } void createTestCases (tcu::TestCaseGroup* group) { addFunctionCase(group, "properties", "Query VkPhysicalDeviceDriverPropertiesKHR and check its values", testQueryProperties); } } // anonymous tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx) { return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases); } } // api } // vkt <commit_msg>Add 1.1.3.0 to known conformance versions<commit_after>/*------------------------------------------------------------------------- * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2018 Advanced Micro Devices, Inc. * Copyright (c) 2018 The Khronos Group 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. * *//*! * \file * \brief VK_KHR_driver_properties tests *//*--------------------------------------------------------------------*/ #include "vktApiDriverPropertiesTests.hpp" #include "vktTestGroupUtil.hpp" #include "vktTestCaseUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" using namespace vk; namespace vkt { namespace api { namespace { static const deUint32 knownDriverIds[] = { // Specified in the Vulkan registry (vk.xml) 1, // author = "Advanced Micro Devices, Inc." comment = "AMD proprietary driver" 2, // author = "Advanced Micro Devices, Inc." comment = "AMD open-source driver" 3, // author = "Mesa open source project" comment = "Mesa RADV driver" 4, // author = "NVIDIA Corporation" comment = "NVIDIA proprietary driver" 5, // author = "Intel Corporation" comment = "Intel proprietary Windows driver" 6, // author = "Intel Corporation" comment = "Intel open-source Mesa driver" 7, // author = "Imagination Technologies" comment = "Imagination proprietary driver" 8, // author = "Qualcomm Technologies, Inc." comment = "Qualcomm proprietary driver" 9, // author = "Arm Limited" comment = "Arm proprietary driver" }; static const VkConformanceVersionKHR knownConformanceVersions[] = { makeConformanceVersionKHR(1, 1, 3, 0), makeConformanceVersionKHR(1, 1, 2, 3), makeConformanceVersionKHR(1, 1, 2, 2), makeConformanceVersionKHR(1, 1, 2, 1), makeConformanceVersionKHR(1, 1, 2, 0), makeConformanceVersionKHR(1, 1, 1, 3), makeConformanceVersionKHR(1, 1, 1, 2), makeConformanceVersionKHR(1, 1, 1, 1), makeConformanceVersionKHR(1, 1, 1, 0), makeConformanceVersionKHR(1, 1, 0, 3), makeConformanceVersionKHR(1, 0, 2, 6), makeConformanceVersionKHR(1, 0, 2, 5), makeConformanceVersionKHR(1, 0, 2, 4), makeConformanceVersionKHR(1, 0, 2, 3), makeConformanceVersionKHR(1, 0, 2, 2), makeConformanceVersionKHR(1, 0, 2, 1), makeConformanceVersionKHR(1, 0, 2, 0), }; DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize) { return deStrnlen(str, maxSize) < maxSize; } DE_INLINE bool operator==(const VkConformanceVersionKHR& a, const VkConformanceVersionKHR& b) { return ((a.major == b.major) && (a.minor == b.minor) && (a.subminor == b.subminor) && (a.patch == b.patch)); } tcu::TestStatus testQueryProperties (Context& context) { // Check extension support if (!isDeviceExtensionSupported(context.getUsedApiVersion(), context.getDeviceExtensions(), "VK_KHR_driver_properties")) TCU_THROW(NotSupportedError, "Unsupported extension: VK_KHR_driver_properties"); // Query the driver properties const VkPhysicalDevice physDevice = context.getPhysicalDevice(); const int memsetPattern = 0xaa; VkPhysicalDeviceProperties2 deviceProperties2; VkPhysicalDeviceDriverPropertiesKHR deviceDriverProperties; deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties)); deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR; deviceDriverProperties.pNext = DE_NULL; deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2)); deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; deviceProperties2.pNext = &deviceDriverProperties; context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2); // Verify the returned values bool match = false; for (const deUint32* pDriverId = knownDriverIds; (pDriverId != DE_ARRAY_END(knownDriverIds)) && !match; ++pDriverId) { if (deviceDriverProperties.driverID == *pDriverId) { match = true; if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR)) TCU_FAIL("Driver name is not a null-terminated string"); if (deviceDriverProperties.driverName[0] == 0) TCU_FAIL("Driver name is empty"); if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR)) TCU_FAIL("Driver info is not a null-terminated string"); bool conformanceVersionMatch = false; for (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions; pConformanceVersion != DE_ARRAY_END(knownConformanceVersions); ++pConformanceVersion) { if (deviceDriverProperties.conformanceVersion == *pConformanceVersion) { conformanceVersionMatch = true; break; } } if (!conformanceVersionMatch) TCU_FAIL("Wrong driver conformance version"); } } if (!match) TCU_FAIL("Driver ID did not match any known driver"); return tcu::TestStatus::pass("Pass"); } void createTestCases (tcu::TestCaseGroup* group) { addFunctionCase(group, "properties", "Query VkPhysicalDeviceDriverPropertiesKHR and check its values", testQueryProperties); } } // anonymous tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx) { return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases); } } // api } // vkt <|endoftext|>
<commit_before>#include "dummy_video.h" #include <halley/core/graphics/painter.h> #include <halley/core/graphics/texture.h> #include <halley/core/graphics/shader.h> #include <halley/core/graphics/render_target/render_target_texture.h> #include "dummy_system.h" using namespace Halley; DummyVideoAPI::DummyVideoAPI(SystemAPI&) {} void DummyVideoAPI::startRender() { } void DummyVideoAPI::finishRender() { } void DummyVideoAPI::setWindow(WindowDefinition&& windowDescriptor) { //window = system.createWindow(windowDescriptor); window = std::make_shared<DummyWindow>(windowDescriptor); } const Window& DummyVideoAPI::getWindow() const { Expects(window); return *window; } bool DummyVideoAPI::hasWindow() const { return static_cast<bool>(window); } std::unique_ptr<Texture> DummyVideoAPI::createTexture(Vector2i size) { return std::make_unique<DummyTexture>(size); } std::unique_ptr<Shader> DummyVideoAPI::createShader(const ShaderDefinition&) { return std::make_unique<DummyShader>(); } std::unique_ptr<TextureRenderTarget> DummyVideoAPI::createTextureRenderTarget() { return std::make_unique<TextureRenderTarget>(); } std::unique_ptr<ScreenRenderTarget> DummyVideoAPI::createScreenRenderTarget() { return std::make_unique<ScreenRenderTarget>(Rect4i({}, getWindow().getWindowRect().getSize())); } std::unique_ptr<MaterialConstantBuffer> DummyVideoAPI::createConstantBuffer() { return std::make_unique<DummyMaterialConstantBuffer>(); } void DummyVideoAPI::init() { } void DummyVideoAPI::deInit() { } std::unique_ptr<Painter> DummyVideoAPI::makePainter(Resources& resources) { return std::make_unique<DummyPainter>(resources); } String DummyVideoAPI::getShaderLanguage() { return "glsl"; } DummyTexture::DummyTexture(Vector2i size) : Texture(size) { } void DummyTexture::load(TextureDescriptor&&) { doneLoading(); } int DummyShader::getUniformLocation(const String&, ShaderType) { return 0; } int DummyShader::getBlockLocation(const String&, ShaderType) { return 0; } void DummyMaterialConstantBuffer::update(const MaterialDataBlock&) {} DummyPainter::DummyPainter(Resources& resources) : Painter(resources) {} void DummyPainter::clear(Colour colour) {} void DummyPainter::setMaterialPass(const Material&, int) {} void DummyPainter::doStartRender() {} void DummyPainter::doEndRender() {} void DummyPainter::setVertices(const MaterialDefinition&, size_t, void*, size_t, unsigned short*, bool) {} void DummyPainter::drawTriangles(size_t) {} void DummyPainter::setViewPort(Rect4i) {} void DummyPainter::setClip(Rect4i, bool) {} void DummyPainter::setMaterialData(const Material&) {} void DummyPainter::onUpdateProjection(Material&) {} <commit_msg>DummyVideoAPI::finishRender now sleeps for 10 milliseconds to avoid headless clients using 100% CPU<commit_after>#include "dummy_video.h" #include <halley/core/graphics/painter.h> #include <halley/core/graphics/texture.h> #include <halley/core/graphics/shader.h> #include <halley/core/graphics/render_target/render_target_texture.h> #include "dummy_system.h" #include <chrono> using namespace Halley; DummyVideoAPI::DummyVideoAPI(SystemAPI&) {} void DummyVideoAPI::startRender() { } void DummyVideoAPI::finishRender() { using namespace std::chrono_literals; std::this_thread::sleep_for(10ms); } void DummyVideoAPI::setWindow(WindowDefinition&& windowDescriptor) { //window = system.createWindow(windowDescriptor); window = std::make_shared<DummyWindow>(windowDescriptor); } const Window& DummyVideoAPI::getWindow() const { Expects(window); return *window; } bool DummyVideoAPI::hasWindow() const { return static_cast<bool>(window); } std::unique_ptr<Texture> DummyVideoAPI::createTexture(Vector2i size) { return std::make_unique<DummyTexture>(size); } std::unique_ptr<Shader> DummyVideoAPI::createShader(const ShaderDefinition&) { return std::make_unique<DummyShader>(); } std::unique_ptr<TextureRenderTarget> DummyVideoAPI::createTextureRenderTarget() { return std::make_unique<TextureRenderTarget>(); } std::unique_ptr<ScreenRenderTarget> DummyVideoAPI::createScreenRenderTarget() { return std::make_unique<ScreenRenderTarget>(Rect4i({}, getWindow().getWindowRect().getSize())); } std::unique_ptr<MaterialConstantBuffer> DummyVideoAPI::createConstantBuffer() { return std::make_unique<DummyMaterialConstantBuffer>(); } void DummyVideoAPI::init() { } void DummyVideoAPI::deInit() { } std::unique_ptr<Painter> DummyVideoAPI::makePainter(Resources& resources) { return std::make_unique<DummyPainter>(resources); } String DummyVideoAPI::getShaderLanguage() { return "glsl"; } DummyTexture::DummyTexture(Vector2i size) : Texture(size) { } void DummyTexture::load(TextureDescriptor&&) { doneLoading(); } int DummyShader::getUniformLocation(const String&, ShaderType) { return 0; } int DummyShader::getBlockLocation(const String&, ShaderType) { return 0; } void DummyMaterialConstantBuffer::update(const MaterialDataBlock&) {} DummyPainter::DummyPainter(Resources& resources) : Painter(resources) {} void DummyPainter::clear(Colour colour) {} void DummyPainter::setMaterialPass(const Material&, int) {} void DummyPainter::doStartRender() {} void DummyPainter::doEndRender() {} void DummyPainter::setVertices(const MaterialDefinition&, size_t, void*, size_t, unsigned short*, bool) {} void DummyPainter::drawTriangles(size_t) {} void DummyPainter::setViewPort(Rect4i) {} void DummyPainter::setClip(Rect4i, bool) {} void DummyPainter::setMaterialData(const Material&) {} void DummyPainter::onUpdateProjection(Material&) {} <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2007 by Lothar May * * * * 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 "clientboard.h" #include "localhand.h" #include <game_defs.h> using namespace std; ClientBoard::ClientBoard() : playerArray(0), actualHand(0), pot(0), sets(0) { } ClientBoard::~ClientBoard() { } void ClientBoard::setPlayer(PlayerInterface** p) { playerArray = p; } void ClientBoard::setHand(HandInterface* br) { actualHand = br; } void ClientBoard::collectSets() { } void ClientBoard::collectPot() { pot += sets; sets = 0; } <commit_msg>Linefeeds.<commit_after>/*************************************************************************** * Copyright (C) 2007 by Lothar May * * * * 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 "clientboard.h" #include "localhand.h" #include <game_defs.h> using namespace std; ClientBoard::ClientBoard() : playerArray(0), actualHand(0), pot(0), sets(0) { } ClientBoard::~ClientBoard() { } void ClientBoard::setPlayer(PlayerInterface** p) { playerArray = p; } void ClientBoard::setHand(HandInterface* br) { actualHand = br; } void ClientBoard::collectSets() { } void ClientBoard::collectPot() { pot += sets; sets = 0; } <|endoftext|>
<commit_before> /* * Copyright (C) 2006-2015 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <iostream> #include <fstream> #include <essentia/algorithmfactory.h> #include <essentia/pool.h> using namespace std; using namespace essentia; using namespace standard; void scaleAudioVector(vector<Real> &buffer, const Real scale) { for (int i=0; i < int(buffer.size()); ++i){ buffer[i] = scale * buffer[i]; } } int main(int argc, char* argv[]) { if (argc < 3) { cout << "ERROR: incorrect number of arguments." << endl; cout << "Usage: " << argv[0] << " audio_input output_file [attenuation_dB]" << endl; cout << "attenuation_dB (optional): value in dB's of the attenuation applied to the predominant pitched component. \n \ A positive value 'mutes' the pitched component. A negative value 'soloes' the pitched component." << endl; exit(1); } string audioFilename = argv[1]; string outputFilename = argv[2]; Real attenuation_dB = -200.f; if (argc ==4){ string attstr = argv[3]; sscanf(attstr.c_str(), "%f",&attenuation_dB); } // register the algorithms in the factory(ies) essentia::init(); Pool pool; /////// PARAMS ////////////// /////// PARAMS ////////////// int framesize = 2048; int hopsize = 128; // 128 for predominant melody Real sr = 44100; bool usePredominant = true; // set to true if PredmonantMelody extraction is used. Set to false if monhonic Pitch-YinFFT is used, AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* audioLoader = factory.create("MonoLoader", "filename", audioFilename, "sampleRate", sr, "downmix", "mix"); Algorithm* frameCutter = factory.create("FrameCutter", "frameSize", framesize, "hopSize", hopsize, // "silentFrames", "noise", "startFromZero", false ); Algorithm* window = factory.create("Windowing", "type", "hann"); Algorithm* equalLoudness = factory.create("EqualLoudness"); Algorithm* fft = factory.create("FFT", "size", framesize); Algorithm* predominantMelody = factory.create("PredominantMelody", "frameSize", framesize, "hopSize", hopsize, "sampleRate", sr); // Algorithm* spectrum = factory.create("Spectrum", "size", framesize); Algorithm* pitchDetect = factory.create("PitchYinFFT", "frameSize", framesize, "sampleRate", sr); // Algorithm* realAccumulator = factory.create("RealAccumulator"); Algorithm* harmonicMask = factory.create("HarmonicMask", "sampleRate", sr, "binWidth", 2, "attenuation", attenuation_dB); Algorithm* ifft = factory.create("IFFT", "size", framesize); Algorithm* overlapAdd = factory.create("OverlapAdd", "frameSize", framesize, "hopSize", hopsize); Algorithm* audioWriter = factory.create("MonoWriter", "filename", outputFilename); vector<Real> pitchIn; vector<Real> pitchConf; vector<Real> audio; vector<Real> eqaudio; vector<Real> frame; vector<Real> wframe; vector<complex<Real> > fftframe; vector<complex<Real> > fftmaskframe; vector<Real> ifftframe; vector<Real> alladuio; // concatenated audio file output // Real confidence; // analysis audioLoader->output("audio").set(audio); equalLoudness->input("signal").set(audio); equalLoudness->output("signal").set(eqaudio); predominantMelody->input("signal").set(eqaudio); predominantMelody->output("pitch").set(pitchIn); predominantMelody->output("pitchConfidence").set(pitchConf); frameCutter->input("signal").set(audio); frameCutter->output("frame").set(frame); window->input("frame").set(frame); window->output("frame").set(wframe); // set spectrum: vector<Real> spec; spectrum->input("frame").set(wframe); spectrum->output("spectrum").set(spec); // set Yin pitch extraction: Real thisPitch = 0., thisConf = 0; pitchDetect->input("spectrum").set(spec); pitchDetect->output("pitch").set(thisPitch); pitchDetect->output("pitchConfidence").set(thisConf); fft->input("frame").set(wframe); fft->output("fft").set(fftframe); // processing harmonic mask (apply mask) harmonicMask->input("fft").set(fftframe); harmonicMask->input("pitch").set(thisPitch); harmonicMask->output("fft").set(fftmaskframe); // Synthesis ifft->input("fft").set(fftmaskframe); ifft->output("frame").set(ifftframe); vector<Real> audioOutput; overlapAdd->input("signal").set(ifftframe); // or frame ? overlapAdd->output("signal").set(audioOutput); //////// /////////// STARTING THE ALGORITHMS ////////////////// cout << "-------- start processing " << audioFilename << " --------" << endl; audioLoader->compute(); equalLoudness->compute(); predominantMelody->compute(); int counter = 0; while (true) { // compute a frame frameCutter->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) { break; } window->compute(); // pitch extraction spectrum->compute(); pitchDetect->compute(); // get predominant pitch if (usePredominant){ thisPitch = pitchIn[counter]; } fft->compute(); harmonicMask-> compute(); ifft->compute(); overlapAdd->compute(); counter++; alladuio.insert(alladuio.end(), audioOutput.begin(), audioOutput.end()); } // write results to file cout << "-------- writing results to file " << outputFilename << " ---------" << endl; // write to output file audioWriter->input("audio").set(alladuio); audioWriter->compute(); delete audioLoader; delete frameCutter; delete fft; delete predominantMelody; delete pitchDetect; //delete realAccumulator; delete harmonicMask; delete ifft; delete overlapAdd; delete audioWriter; essentia::shutdown(); return 0; } <commit_msg>renaming predominantMelody in harmonicMask exampel<commit_after> /* * Copyright (C) 2006-2015 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), 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 Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include <iostream> #include <fstream> #include <essentia/algorithmfactory.h> #include <essentia/pool.h> using namespace std; using namespace essentia; using namespace standard; void scaleAudioVector(vector<Real> &buffer, const Real scale) { for (int i=0; i < int(buffer.size()); ++i){ buffer[i] = scale * buffer[i]; } } int main(int argc, char* argv[]) { if (argc < 3) { cout << "ERROR: incorrect number of arguments." << endl; cout << "Usage: " << argv[0] << " audio_input output_file [attenuation_dB]" << endl; cout << "attenuation_dB (optional): value in dB's of the attenuation applied to the predominant pitched component. \n \ A positive value 'mutes' the pitched component. A negative value 'soloes' the pitched component." << endl; exit(1); } string audioFilename = argv[1]; string outputFilename = argv[2]; Real attenuation_dB = -200.f; if (argc ==4){ string attstr = argv[3]; sscanf(attstr.c_str(), "%f",&attenuation_dB); } // register the algorithms in the factory(ies) essentia::init(); Pool pool; /////// PARAMS ////////////// /////// PARAMS ////////////// int framesize = 2048; int hopsize = 128; // 128 for predominant melody Real sr = 44100; bool usePredominant = true; // set to true if PredmonantMelody extraction is used. Set to false if monhonic Pitch-YinFFT is used, AlgorithmFactory& factory = AlgorithmFactory::instance(); Algorithm* audioLoader = factory.create("MonoLoader", "filename", audioFilename, "sampleRate", sr, "downmix", "mix"); Algorithm* frameCutter = factory.create("FrameCutter", "frameSize", framesize, "hopSize", hopsize, // "silentFrames", "noise", "startFromZero", false ); Algorithm* window = factory.create("Windowing", "type", "hann"); Algorithm* equalLoudness = factory.create("EqualLoudness"); Algorithm* fft = factory.create("FFT", "size", framesize); Algorithm* predominantMelody = factory.create("PredominantPitchMelodia", //PredominantMelody", "frameSize", framesize, "hopSize", hopsize, "sampleRate", sr); // Algorithm* spectrum = factory.create("Spectrum", "size", framesize); Algorithm* pitchDetect = factory.create("PitchYinFFT", "frameSize", framesize, "sampleRate", sr); // Algorithm* realAccumulator = factory.create("RealAccumulator"); Algorithm* harmonicMask = factory.create("HarmonicMask", "sampleRate", sr, "binWidth", 2, "attenuation", attenuation_dB); Algorithm* ifft = factory.create("IFFT", "size", framesize); Algorithm* overlapAdd = factory.create("OverlapAdd", "frameSize", framesize, "hopSize", hopsize); Algorithm* audioWriter = factory.create("MonoWriter", "filename", outputFilename); vector<Real> pitchIn; vector<Real> pitchConf; vector<Real> audio; vector<Real> eqaudio; vector<Real> frame; vector<Real> wframe; vector<complex<Real> > fftframe; vector<complex<Real> > fftmaskframe; vector<Real> ifftframe; vector<Real> alladuio; // concatenated audio file output // Real confidence; // analysis audioLoader->output("audio").set(audio); equalLoudness->input("signal").set(audio); equalLoudness->output("signal").set(eqaudio); predominantMelody->input("signal").set(eqaudio); predominantMelody->output("pitch").set(pitchIn); predominantMelody->output("pitchConfidence").set(pitchConf); frameCutter->input("signal").set(audio); frameCutter->output("frame").set(frame); window->input("frame").set(frame); window->output("frame").set(wframe); // set spectrum: vector<Real> spec; spectrum->input("frame").set(wframe); spectrum->output("spectrum").set(spec); // set Yin pitch extraction: Real thisPitch = 0., thisConf = 0; pitchDetect->input("spectrum").set(spec); pitchDetect->output("pitch").set(thisPitch); pitchDetect->output("pitchConfidence").set(thisConf); fft->input("frame").set(wframe); fft->output("fft").set(fftframe); // processing harmonic mask (apply mask) harmonicMask->input("fft").set(fftframe); harmonicMask->input("pitch").set(thisPitch); harmonicMask->output("fft").set(fftmaskframe); // Synthesis ifft->input("fft").set(fftmaskframe); ifft->output("frame").set(ifftframe); vector<Real> audioOutput; overlapAdd->input("signal").set(ifftframe); // or frame ? overlapAdd->output("signal").set(audioOutput); //////// /////////// STARTING THE ALGORITHMS ////////////////// cout << "-------- start processing " << audioFilename << " --------" << endl; audioLoader->compute(); equalLoudness->compute(); predominantMelody->compute(); int counter = 0; while (true) { // compute a frame frameCutter->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) { break; } window->compute(); // pitch extraction spectrum->compute(); pitchDetect->compute(); // get predominant pitch if (usePredominant){ thisPitch = pitchIn[counter]; } fft->compute(); harmonicMask-> compute(); ifft->compute(); overlapAdd->compute(); counter++; alladuio.insert(alladuio.end(), audioOutput.begin(), audioOutput.end()); } // write results to file cout << "-------- writing results to file " << outputFilename << " ---------" << endl; // write to output file audioWriter->input("audio").set(alladuio); audioWriter->compute(); delete audioLoader; delete frameCutter; delete fft; delete predominantMelody; delete pitchDetect; //delete realAccumulator; delete harmonicMask; delete ifft; delete overlapAdd; delete audioWriter; essentia::shutdown(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c)2015 Oasis LMF Limited * 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 original author of this software 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. */ /* Convert fmprofile output to csv Author: Ben Matharu email: ben.matharu@oasislmf.org */ #include <iostream> #include <stdio.h> #include <stdlib.h> #ifdef __unix #include <unistd.h> #endif #include "../include/oasis.hpp" using namespace std; struct fm_programme { int prog_id; int level_id; int agg_id; int item_id; }; void doit() { printf ("\"prog_id\", \"input_id\", \"level_id\",\"agg_id\"\n"); fm_programme q; int i = fread(&q, sizeof(q), 1, stdin); while (i != 0) { printf("%d, %d, %d, %d\n", q.prog_id, q.item_id, q.level_id, q.agg_id ); i = fread(&q, sizeof(q), 1, stdin); } } void help() { cerr << "-I inputfilename\n" << "-O outputfielname\n" ; } int main(int argc, char* argv[]) { int opt; std::string inFile; std::string outFile; #ifdef __unix while ((opt = getopt(argc, argv, "hI:O:")) != -1) { switch (opt) { case 'I': inFile = optarg; break; case 'O': outFile = optarg; break; case 'h': help(); exit(EXIT_FAILURE); } } #endif initstreams(inFile, outFile); doit(); return 0; } <commit_msg>changed header<commit_after>/* * Copyright (c)2015 Oasis LMF Limited * 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 original author of this software 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. */ /* Convert fmprofile output to csv Author: Ben Matharu email: ben.matharu@oasislmf.org */ #include <iostream> #include <stdio.h> #include <stdlib.h> #ifdef __unix #include <unistd.h> #endif #include "../include/oasis.hpp" using namespace std; struct fm_programme { int prog_id; int level_id; int to_agg_id; int from_agg_id; }; void doit() { printf ("\"prog_id\", \"from_agg_id\", \"level_id\",\"to_agg_id\"\n"); fm_programme q; int i = fread(&q, sizeof(q), 1, stdin); while (i != 0) { printf("%d, %d, %d, %d\n", q.prog_id, q.from_agg_id, q.level_id, q.to_agg_id ); i = fread(&q, sizeof(q), 1, stdin); } } void help() { cerr << "-I inputfilename\n" << "-O outputfielname\n" ; } int main(int argc, char* argv[]) { int opt; std::string inFile; std::string outFile; #ifdef __unix while ((opt = getopt(argc, argv, "hI:O:")) != -1) { switch (opt) { case 'I': inFile = optarg; break; case 'O': outFile = optarg; break; case 'h': help(); exit(EXIT_FAILURE); } } #endif initstreams(inFile, outFile); doit(); return 0; } <|endoftext|>
<commit_before>/* Copyright libCellML Contributors 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 "libcellml/model.h" #include <algorithm> #include <fstream> #include <map> #include <sstream> #include <stack> #include <utility> #include <vector> #include "libcellml/component.h" #include "libcellml/importsource.h" #include "libcellml/parser.h" #include "libcellml/variable.h" #include "libcellml/units.h" namespace libcellml { /** * @brief The Model::ModelImpl struct. * * This struct is the private implementation struct for the Model class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct Model::ModelImpl { std::vector<UnitsPtr>::iterator findUnits(const std::string &name); std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units); std::vector<UnitsPtr> mUnits; }; std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr& u) -> bool { return u->getName() == name; }); } std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr& u) -> bool { return u == units; }); } Model::Model() : mPimpl(new ModelImpl()) { } Model::~Model() { delete mPimpl; } Model::Model(const Model& rhs) : ComponentEntity(rhs) , mPimpl(new ModelImpl()) { mPimpl->mUnits = rhs.mPimpl->mUnits; } Model::Model(Model &&rhs) : ComponentEntity(std::move(rhs)) ,mPimpl(rhs.mPimpl) { rhs.mPimpl = nullptr; } Model& Model::operator=(Model m) { ComponentEntity::operator= (m); m.swap(*this); return *this; } void Model::swap(Model &rhs) { std::swap(this->mPimpl, rhs.mPimpl); } void Model::doAddComponent(const ComponentPtr &c) { // Check for cycles. if (!hasParent(c.get())) { c->setParent(this); ComponentEntity::doAddComponent(c); } } void Model::addUnits(const UnitsPtr & units) { mPimpl->mUnits.push_back(units); } bool Model::removeUnits(size_t index) { bool status = false; if (index < mPimpl->mUnits.size()) { mPimpl->mUnits.erase(mPimpl->mUnits.begin() + index); status = true; } return status; } bool Model::removeUnits(const std::string &name) { bool status = false; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { mPimpl->mUnits.erase(result); status = true; } return status; } bool Model::removeUnits(const UnitsPtr &units) { bool status = false; auto result = mPimpl->findUnits(units); if (result != mPimpl->mUnits.end()) { mPimpl->mUnits.erase(result); status = true; } return status; } void Model::removeAllUnits() { mPimpl->mUnits.clear(); } bool Model::hasUnits(const std::string &name) const { return mPimpl->findUnits(name) != mPimpl->mUnits.end(); } UnitsPtr Model::getUnits(size_t index) const { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); } return units; } UnitsPtr Model::getUnits(const std::string &name) const { UnitsPtr units = nullptr; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { units = *result; } return units; } UnitsPtr Model::takeUnits(size_t index) { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); removeUnits(index); units->clearParent(); } return units; } UnitsPtr Model::takeUnits(const std::string &name) { return takeUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin()); } bool Model::replaceUnits(size_t index, const UnitsPtr &units) { bool status = false; if (removeUnits(index)) { mPimpl->mUnits.insert(mPimpl->mUnits.begin() + index, units); status = true; } return status; } bool Model::replaceUnits(const std::string &name, const UnitsPtr &units) { return replaceUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin(), units); } bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits) { return replaceUnits(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin(), newUnits); } size_t Model::unitsCount() const { return mPimpl->mUnits.size(); } typedef std::shared_ptr<ImportedEntity> ImportedEntityPtr; /** * @brief Resolve the path of the given filename using the given base. * * Resolves the full path to the given @p filename using the @p base. * * This function is only intended to work with local files. It may not * work with bases that use the 'file://' prefix. * * @param filename The @c std::string relative path from the base path. * @param base The @c std::string location on local disk for determining the full path from. * @return The full path from the @p base location to the @p filename */ std::string resolvePath(const std::string& filename, const std::string& base) { // we can be naive here as we know what we are dealing with std::string path = base.substr(0, base.find_last_of('/')+1) + filename; return path; } void resolveImport(ImportedEntityPtr importedEntity, const std::string& baseFile) { if (importedEntity->isImport()) { libcellml::ImportSourcePtr importSource = importedEntity->getImportSource(); if (!importSource->hasModel()) { std::string url = resolvePath(importSource->getUrl(), baseFile); std::ifstream t(url); std::stringstream buffer; buffer << t.rdbuf(); libcellml::Parser p; libcellml::ModelPtr model = p.parseModel(buffer.str()); if (model) { importSource->setModel(model); model->resolveImports(url); } } } } void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile); void resolveComponentImports(ComponentPtr parentComponent, const std::string &baseFile) { for (size_t n = 0; n < parentComponent->componentCount(); ++n) { libcellml::ComponentPtr component = parentComponent->getComponent(n); recurseResolveComponentImports(component, baseFile); } } void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile) { if (component->isImport()) { resolveImport(component, baseFile); } else { resolveComponentImports(component, baseFile); } } void Model::resolveImports(const std::string &baseFile) { for (size_t n = 0; n < unitsCount(); ++n) { libcellml::UnitsPtr units = getUnits(n); resolveImport(units, baseFile); } for (size_t n = 0; n < componentCount(); ++n) { libcellml::ComponentPtr component = getComponent(n); recurseResolveComponentImports(component, baseFile); } } bool isUnresolvedImport(ImportedEntityPtr importedEntity) { bool unresolvedImport = false; if (importedEntity->isImport()) { libcellml::ImportSourcePtr importedSource = importedEntity->getImportSource(); if (!importedSource->hasModel()) { unresolvedImport = true; } } return unresolvedImport; } bool hasUnresolvedComponentImports(libcellml::ComponentPtr component); bool recurseForUnresolvedComponentImports(ComponentPtr parentComponent) { bool unresolvedImports = false; for (size_t n = 0; n < parentComponent->componentCount() && !unresolvedImports; ++n) { libcellml::ComponentPtr component = parentComponent->getComponent(n); unresolvedImports = hasUnresolvedComponentImports(component); } return unresolvedImports; } bool hasUnresolvedComponentImports(libcellml::ComponentPtr component) { bool unresolvedImports = false; if (component->isImport()) { unresolvedImports = isUnresolvedImport(component); } else { unresolvedImports = recurseForUnresolvedComponentImports(component); } return unresolvedImports; } bool Model::hasUnresolvedImports() const { bool unresolvedImports = false; for (size_t n = 0; n < unitsCount() && !unresolvedImports; ++n) { libcellml::UnitsPtr units = getUnits(n); unresolvedImports = isUnresolvedImport(units); } for (size_t n = 0; n < componentCount() && !unresolvedImports; ++n) { libcellml::ComponentPtr component = getComponent(n); unresolvedImports = hasUnresolvedComponentImports(component); } return unresolvedImports; } } <commit_msg>Only parse for a model if the file stream is good.<commit_after>/* Copyright libCellML Contributors 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 "libcellml/model.h" #include <algorithm> #include <fstream> #include <map> #include <sstream> #include <stack> #include <utility> #include <vector> #include "libcellml/component.h" #include "libcellml/importsource.h" #include "libcellml/parser.h" #include "libcellml/variable.h" #include "libcellml/units.h" namespace libcellml { /** * @brief The Model::ModelImpl struct. * * This struct is the private implementation struct for the Model class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct Model::ModelImpl { std::vector<UnitsPtr>::iterator findUnits(const std::string &name); std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units); std::vector<UnitsPtr> mUnits; }; std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr& u) -> bool { return u->getName() == name; }); } std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units) { return std::find_if(mUnits.begin(), mUnits.end(), [=](const UnitsPtr& u) -> bool { return u == units; }); } Model::Model() : mPimpl(new ModelImpl()) { } Model::~Model() { delete mPimpl; } Model::Model(const Model& rhs) : ComponentEntity(rhs) , mPimpl(new ModelImpl()) { mPimpl->mUnits = rhs.mPimpl->mUnits; } Model::Model(Model &&rhs) : ComponentEntity(std::move(rhs)) ,mPimpl(rhs.mPimpl) { rhs.mPimpl = nullptr; } Model& Model::operator=(Model m) { ComponentEntity::operator= (m); m.swap(*this); return *this; } void Model::swap(Model &rhs) { std::swap(this->mPimpl, rhs.mPimpl); } void Model::doAddComponent(const ComponentPtr &c) { // Check for cycles. if (!hasParent(c.get())) { c->setParent(this); ComponentEntity::doAddComponent(c); } } void Model::addUnits(const UnitsPtr & units) { mPimpl->mUnits.push_back(units); } bool Model::removeUnits(size_t index) { bool status = false; if (index < mPimpl->mUnits.size()) { mPimpl->mUnits.erase(mPimpl->mUnits.begin() + index); status = true; } return status; } bool Model::removeUnits(const std::string &name) { bool status = false; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { mPimpl->mUnits.erase(result); status = true; } return status; } bool Model::removeUnits(const UnitsPtr &units) { bool status = false; auto result = mPimpl->findUnits(units); if (result != mPimpl->mUnits.end()) { mPimpl->mUnits.erase(result); status = true; } return status; } void Model::removeAllUnits() { mPimpl->mUnits.clear(); } bool Model::hasUnits(const std::string &name) const { return mPimpl->findUnits(name) != mPimpl->mUnits.end(); } UnitsPtr Model::getUnits(size_t index) const { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); } return units; } UnitsPtr Model::getUnits(const std::string &name) const { UnitsPtr units = nullptr; auto result = mPimpl->findUnits(name); if (result != mPimpl->mUnits.end()) { units = *result; } return units; } UnitsPtr Model::takeUnits(size_t index) { UnitsPtr units = nullptr; if (index < mPimpl->mUnits.size()) { units = mPimpl->mUnits.at(index); removeUnits(index); units->clearParent(); } return units; } UnitsPtr Model::takeUnits(const std::string &name) { return takeUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin()); } bool Model::replaceUnits(size_t index, const UnitsPtr &units) { bool status = false; if (removeUnits(index)) { mPimpl->mUnits.insert(mPimpl->mUnits.begin() + index, units); status = true; } return status; } bool Model::replaceUnits(const std::string &name, const UnitsPtr &units) { return replaceUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin(), units); } bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits) { return replaceUnits(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin(), newUnits); } size_t Model::unitsCount() const { return mPimpl->mUnits.size(); } typedef std::shared_ptr<ImportedEntity> ImportedEntityPtr; /** * @brief Resolve the path of the given filename using the given base. * * Resolves the full path to the given @p filename using the @p base. * * This function is only intended to work with local files. It may not * work with bases that use the 'file://' prefix. * * @param filename The @c std::string relative path from the base path. * @param base The @c std::string location on local disk for determining the full path from. * @return The full path from the @p base location to the @p filename */ std::string resolvePath(const std::string& filename, const std::string& base) { // we can be naive here as we know what we are dealing with std::string path = base.substr(0, base.find_last_of('/')+1) + filename; return path; } void resolveImport(ImportedEntityPtr importedEntity, const std::string& baseFile) { if (importedEntity->isImport()) { libcellml::ImportSourcePtr importSource = importedEntity->getImportSource(); if (!importSource->hasModel()) { std::string url = resolvePath(importSource->getUrl(), baseFile); std::ifstream t(url); if (t.good()) { std::stringstream buffer; buffer << t.rdbuf(); libcellml::Parser p; libcellml::ModelPtr model = p.parseModel(buffer.str()); if (model) { importSource->setModel(model); model->resolveImports(url); } } } } } void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile); void resolveComponentImports(ComponentPtr parentComponent, const std::string &baseFile) { for (size_t n = 0; n < parentComponent->componentCount(); ++n) { libcellml::ComponentPtr component = parentComponent->getComponent(n); recurseResolveComponentImports(component, baseFile); } } void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile) { if (component->isImport()) { resolveImport(component, baseFile); } else { resolveComponentImports(component, baseFile); } } void Model::resolveImports(const std::string &baseFile) { for (size_t n = 0; n < unitsCount(); ++n) { libcellml::UnitsPtr units = getUnits(n); resolveImport(units, baseFile); } for (size_t n = 0; n < componentCount(); ++n) { libcellml::ComponentPtr component = getComponent(n); recurseResolveComponentImports(component, baseFile); } } bool isUnresolvedImport(ImportedEntityPtr importedEntity) { bool unresolvedImport = false; if (importedEntity->isImport()) { libcellml::ImportSourcePtr importedSource = importedEntity->getImportSource(); if (!importedSource->hasModel()) { unresolvedImport = true; } } return unresolvedImport; } bool hasUnresolvedComponentImports(libcellml::ComponentPtr component); bool recurseForUnresolvedComponentImports(ComponentPtr parentComponent) { bool unresolvedImports = false; for (size_t n = 0; n < parentComponent->componentCount() && !unresolvedImports; ++n) { libcellml::ComponentPtr component = parentComponent->getComponent(n); unresolvedImports = hasUnresolvedComponentImports(component); } return unresolvedImports; } bool hasUnresolvedComponentImports(libcellml::ComponentPtr component) { bool unresolvedImports = false; if (component->isImport()) { unresolvedImports = isUnresolvedImport(component); } else { unresolvedImports = recurseForUnresolvedComponentImports(component); } return unresolvedImports; } bool Model::hasUnresolvedImports() const { bool unresolvedImports = false; for (size_t n = 0; n < unitsCount() && !unresolvedImports; ++n) { libcellml::UnitsPtr units = getUnits(n); unresolvedImports = isUnresolvedImport(units); } for (size_t n = 0; n < componentCount() && !unresolvedImports; ++n) { libcellml::ComponentPtr component = getComponent(n); unresolvedImports = hasUnresolvedComponentImports(component); } return unresolvedImports; } } <|endoftext|>
<commit_before>#ifndef ZXTK_UTILITIES_MODULES_REGISTER_SET_INCLUDE_GUARD #define ZXTK_UTILITIES_MODULES_REGISTER_SET_INCLUDE_GUARD #include <zxtk/utilities/exchange.hpp> #include <zxtk/misc/zxtk_types.hpp> #include <zxtk/misc/zxtk_config.hpp> #include <utility> #include <cstddef> namespace zxtk { namespace register_set { namespace impl { #ifdef ZXTK_ENDIANNESS_COMPILE_TIME_CHECK constexpr #endif types::byte little_endian() { return ((std::uint16_t{1}>>8)>0)?0:1; } #ifdef ZXTK_ENDIANNESS_COMPILE_TIME_CHECK constexpr #endif types::byte big_endian() { return ((std::uint16_t{1}>>8)>0)?1:0; } } class Z80_register_set { public: Z80_register_set():st_af{0xffff},st_pc{0x0000} {} // Most Z80 registers are not initialised, but they are initialised // anyway (af and sp are set to ffff on startup and pc, iffs and iv // are 0). We could add in realistic values where compilation flags // (to simulate different z80's), time since last use and other things // but really, I don't know of any use of this. Submit an issue if you // want this feature // WARNING: THIS IS NOT THREAD SAFE. WRITING TO THIS FROM SOMETHING OTHER THAN THE CPU OR I/O IS NOT RECOMMENDED types::byte& a() {return *(reinterpret_cast<types::byte*>(&st_af)+impl::little_endian());} types::byte& f() {return *(reinterpret_cast<types::byte*>(&st_af)+impl::big_endian());} types::byte& b() {return *(reinterpret_cast<types::byte*>(&st_bc)+impl::little_endian());} types::byte& c() {return *(reinterpret_cast<types::byte*>(&st_bc)+impl::big_endian());} types::byte& d() {return *(reinterpret_cast<types::byte*>(&st_de)+impl::little_endian());} types::byte& e() {return *(reinterpret_cast<types::byte*>(&st_de)+impl::big_endian());} types::byte& h() {return *(reinterpret_cast<types::byte*>(&st_hl)+impl::little_endian());} types::byte& l() {return *(reinterpret_cast<types::byte*>(&st_hl)+impl::big_endian());} types::byte& ixh() {return *(reinterpret_cast<types::byte*>(&st_ix)+impl::little_endian());} types::byte& ixl() {return *(reinterpret_cast<types::byte*>(&st_ix)+impl::big_endian());} types::byte& iyh() {return *(reinterpret_cast<types::byte*>(&st_iy)+impl::little_endian());} types::byte& iyl() {return *(reinterpret_cast<types::byte*>(&st_iy)+impl::big_endian());} types::word& af() {return st_af;} types::word& bc() {return st_bc;} types::word& de() {return st_de;} types::word& hl() {return st_hl;} types::word& ix() {return st_ix;} types::word& iy() {return st_iy;} types::word& sp() {return st_sp;} types::word& pc() {return st_pc;} types::byte& i() {return st_i;} types::byte& r() {return st_r;} bool& iff1() {return st_iff1;} bool& iff2() {return st_iff2;} void exx() {std::swap(st_bc,st_bc_a);std::swap(st_de,st_de_a);std::swap(st_hl,st_hl_a);} void ex_af_af() {std::swap(st_af, st_af_a);} // const versions types::byte a() const {return *(reinterpret_cast<const types::byte*>(&st_af)+impl::little_endian());} types::byte f() const {return *(reinterpret_cast<const types::byte*>(&st_af)+impl::big_endian());} types::byte b() const {return *(reinterpret_cast<const types::byte*>(&st_bc)+impl::little_endian());} types::byte c() const {return *(reinterpret_cast<const types::byte*>(&st_bc)+impl::big_endian());} types::byte d() const {return *(reinterpret_cast<const types::byte*>(&st_de)+impl::little_endian());} types::byte e() const {return *(reinterpret_cast<const types::byte*>(&st_de)+impl::big_endian());} types::byte h() const {return *(reinterpret_cast<const types::byte*>(&st_hl)+impl::little_endian());} types::byte l() const {return *(reinterpret_cast<const types::byte*>(&st_hl)+impl::big_endian());} types::byte ixh() const {return *(reinterpret_cast<const types::byte*>(&st_ix)+impl::little_endian());} types::byte ixl() const {return *(reinterpret_cast<const types::byte*>(&st_ix)+impl::big_endian());} types::byte iyh() const {return *(reinterpret_cast<const types::byte*>(&st_iy)+impl::little_endian());} types::byte iyl() const {return *(reinterpret_cast<const types::byte*>(&st_iy)+impl::big_endian());} types::word af() const {return st_af;} types::word bc() const {return st_bc;} types::word de() const {return st_de;} types::word hl() const {return st_hl;} types::word ix() const {return st_ix;} types::word iy() const {return st_iy;} types::word sp() const {return st_sp;} types::word pc() const {return st_pc;} types::byte i() const {return st_i;} types::byte r() const {return st_r;} bool iff1() const {return st_iff1;} bool iff2() const {return st_iff2;} protected: types::word st_af; types::word st_bc; types::word st_de; types::word st_hl; types::word st_af_a; types::word st_bc_a; types::word st_de_a; types::word st_hl_a; types::word st_pc; types::word st_sp; types::word st_ix; types::word st_iy; types::byte st_r; types::byte st_i; bool st_iff1; bool st_iff2; }; } } #endif <commit_msg>Added register set initialisation and corrected interrupts<commit_after>#ifndef ZXTK_UTILITIES_MODULES_REGISTER_SET_INCLUDE_GUARD #define ZXTK_UTILITIES_MODULES_REGISTER_SET_INCLUDE_GUARD #include <zxtk/utilities/exchange.hpp> #include <zxtk/misc/zxtk_types.hpp> #include <zxtk/misc/zxtk_config.hpp> #include <utility> #include <cstddef> namespace zxtk { namespace register_set { namespace impl { #ifdef ZXTK_ENDIANNESS_COMPILE_TIME_CHECK constexpr #endif types::byte little_endian() { return ((std::uint16_t{1}>>8)>0)?0:1; } #ifdef ZXTK_ENDIANNESS_COMPILE_TIME_CHECK constexpr #endif types::byte big_endian() { return ((std::uint16_t{1}>>8)>0)?1:0; } } class Z80_register_set { public: Z80_register_set():st_af{0xffff},st_pc{0x0000} {} // Most Z80 registers are not initialised, but they are initialised // anyway (af and sp are set to ffff on startup and pc, iffs and iv // are 0). We could add in realistic values where compilation flags // (to simulate different z80's), time since last use and other things // but really, I don't know of any use of this. Submit an issue if you // want this feature // WARNING: THIS IS NOT THREAD SAFE. WRITING TO THIS FROM SOMETHING OTHER THAN THE CPU OR I/O IS NOT RECOMMENDED types::byte& a() {return *(reinterpret_cast<types::byte*>(&st_af)+impl::little_endian());} types::byte& f() {return *(reinterpret_cast<types::byte*>(&st_af)+impl::big_endian());} types::byte& b() {return *(reinterpret_cast<types::byte*>(&st_bc)+impl::little_endian());} types::byte& c() {return *(reinterpret_cast<types::byte*>(&st_bc)+impl::big_endian());} types::byte& d() {return *(reinterpret_cast<types::byte*>(&st_de)+impl::little_endian());} types::byte& e() {return *(reinterpret_cast<types::byte*>(&st_de)+impl::big_endian());} types::byte& h() {return *(reinterpret_cast<types::byte*>(&st_hl)+impl::little_endian());} types::byte& l() {return *(reinterpret_cast<types::byte*>(&st_hl)+impl::big_endian());} types::byte& ixh() {return *(reinterpret_cast<types::byte*>(&st_ix)+impl::little_endian());} types::byte& ixl() {return *(reinterpret_cast<types::byte*>(&st_ix)+impl::big_endian());} types::byte& iyh() {return *(reinterpret_cast<types::byte*>(&st_iy)+impl::little_endian());} types::byte& iyl() {return *(reinterpret_cast<types::byte*>(&st_iy)+impl::big_endian());} types::word& af() {return st_af;} types::word& bc() {return st_bc;} types::word& de() {return st_de;} types::word& hl() {return st_hl;} types::word& ix() {return st_ix;} types::word& iy() {return st_iy;} types::word& sp() {return st_sp;} types::word& pc() {return st_pc;} types::byte& i() {return st_i;} types::byte& r() {return st_r;} bool& iff1() {return st_iff1;} bool& iff2() {return st_iff2;} void exx() {std::swap(st_bc,st_bc_a);std::swap(st_de,st_de_a);std::swap(st_hl,st_hl_a);} void ex_af_af() {std::swap(st_af, st_af_a);} // const versions types::byte a() const {return *(reinterpret_cast<const types::byte*>(&st_af)+impl::little_endian());} types::byte f() const {return *(reinterpret_cast<const types::byte*>(&st_af)+impl::big_endian());} types::byte b() const {return *(reinterpret_cast<const types::byte*>(&st_bc)+impl::little_endian());} types::byte c() const {return *(reinterpret_cast<const types::byte*>(&st_bc)+impl::big_endian());} types::byte d() const {return *(reinterpret_cast<const types::byte*>(&st_de)+impl::little_endian());} types::byte e() const {return *(reinterpret_cast<const types::byte*>(&st_de)+impl::big_endian());} types::byte h() const {return *(reinterpret_cast<const types::byte*>(&st_hl)+impl::little_endian());} types::byte l() const {return *(reinterpret_cast<const types::byte*>(&st_hl)+impl::big_endian());} types::byte ixh() const {return *(reinterpret_cast<const types::byte*>(&st_ix)+impl::little_endian());} types::byte ixl() const {return *(reinterpret_cast<const types::byte*>(&st_ix)+impl::big_endian());} types::byte iyh() const {return *(reinterpret_cast<const types::byte*>(&st_iy)+impl::little_endian());} types::byte iyl() const {return *(reinterpret_cast<const types::byte*>(&st_iy)+impl::big_endian());} types::word af() const {return st_af;} types::word bc() const {return st_bc;} types::word de() const {return st_de;} types::word hl() const {return st_hl;} types::word ix() const {return st_ix;} types::word iy() const {return st_iy;} types::word sp() const {return st_sp;} types::word pc() const {return st_pc;} types::byte i() const {return st_i;} types::byte r() const {return st_r;} bool iff() const {return st_iff1;} types::byte get_im() const {return st_im;} void store_im(types::byte b) {switch(b){case 0: case 1: case 2: st_im = b;default:;}} protected: types::word st_af {0xffff}; types::word st_bc {0xffff}; types::word st_de {0xffff}; types::word st_hl {0xffff}; types::word st_af_a {0xffff}; types::word st_bc_a {0xffff}; types::word st_de_a {0xffff}; types::word st_hl_a {0xffff}; types::word st_pc {0x0000}; types::word st_sp {0xffff}; types::word st_ix {0xffff}; types::word st_iy {0xffff}; types::byte st_r {0xff}; types::byte st_i {0xff}; types::byte st_im {0x00}; bool st_iff1 {0}; bool st_iff2 {0}; }; } } #endif <|endoftext|>
<commit_before>// The MIT License(MIT) // // Copyright 2017 bladez-fate // // 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 "data.h" #include "music.h" #include "engine/easy.h" namespace pilecode { namespace { int g_musicIdx = 0; bool g_musicDisabled = false; bool g_musicRandomize = true; } void UpdateMusic() { if (!g_musicDisabled) { // switch background music tracks if (!music::g_background[g_musicIdx].IsPlaying()) { g_musicIdx = (g_musicIdx + 1) % music::g_background.size(); music::g_background[g_musicIdx].Play(0.2f); } } else { if (music::g_background[g_musicIdx].IsPlaying()) { music::g_background[g_musicIdx].Stop(); } if (g_musicRandomize) { g_musicIdx = rand() % music::g_background.size(); g_musicRandomize = false; } else { g_musicIdx = (g_musicIdx + 1) % music::g_background.size(); } } } void ToggleMusic() { g_musicDisabled = !g_musicDisabled; g_musicRandomize = true; } bool IsMusicEnabled() { return !g_musicDisabled; } } <commit_msg>increase music volume<commit_after>// The MIT License(MIT) // // Copyright 2017 bladez-fate // // 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 "data.h" #include "music.h" #include "engine/easy.h" namespace pilecode { namespace { int g_musicIdx = 0; bool g_musicDisabled = false; bool g_musicRandomize = true; } void UpdateMusic() { if (!g_musicDisabled) { // switch background music tracks if (!music::g_background[g_musicIdx].IsPlaying()) { g_musicIdx = (g_musicIdx + 1) % music::g_background.size(); music::g_background[g_musicIdx].Play(0.4f); } } else { if (music::g_background[g_musicIdx].IsPlaying()) { music::g_background[g_musicIdx].Stop(); } if (g_musicRandomize) { g_musicIdx = rand() % music::g_background.size(); g_musicRandomize = false; } else { g_musicIdx = (g_musicIdx + 1) % music::g_background.size(); } } } void ToggleMusic() { g_musicDisabled = !g_musicDisabled; g_musicRandomize = true; } bool IsMusicEnabled() { return !g_musicDisabled; } } <|endoftext|>
<commit_before>#include <node.h> #include <v8.h> #include "LRUCache.h" using namespace v8; void init(Handle<Object> exports) { LRUCache::init(exports); } NODE_MODULE(native, init) <commit_msg>test travis<commit_after>#include <node.h> #include <nan.h> #include "LRUCache.h" using namespace v8; void init(Handle<Object> exports) { LRUCache::init(exports); } NODE_MODULE(native, init) <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <iostream> #include <stdexcept> #include <string> #include <vector> #include <boost/cast.hpp> #include <pkmnsim/enums.hpp> #include <pkmnsim/move.hpp> #include <pkmnsim/team_pokemon.hpp> #include <pkmnsim/database/queries.hpp> #include <pkmnsim/types/prng.hpp> #include "base_pokemon_gen1impl.hpp" #include "base_pokemon_gen2impl.hpp" #include "base_pokemon_modernimpl.hpp" #include "item_impl.hpp" #include "item_berryimpl.hpp" #include "item_machineimpl.hpp" #include "team_pokemon_impl.hpp" #include "team_pokemon_gen1impl.hpp" #include "team_pokemon_gen2impl.hpp" #include "team_pokemon_modernimpl.hpp" using namespace std; namespace pkmnsim { team_pokemon::sptr team_pokemon::make(unsigned int id, unsigned int game, unsigned int level, unsigned int move1, unsigned int move2, unsigned int move3, unsigned int move4) { try { base_pokemon::sptr base = base_pokemon::make(id, game); if(base->get_generation() < 1 or base->get_generation() > 5) throw runtime_error("Gen must be 1-5."); switch(base->get_generation()) { case 1: return sptr(new team_pokemon_gen1impl(base, game, level, move1, move2, move3, move4)); case 2: return sptr(new team_pokemon_gen2impl(base, game, level, move1, move2, move3, move4)); default: return sptr(new team_pokemon_modernimpl(base, game, level, move1, move2, move3, move4)); } } catch(exception &e) { cout << "Caught exception: " << e.what() << endl; exit(EXIT_FAILURE); } } team_pokemon_impl::team_pokemon_impl(base_pokemon::sptr base, unsigned int game, unsigned int lvl, unsigned int move1, unsigned int move2, unsigned int move3, unsigned int move4): team_pokemon() { prng rand_gen; unsigned int gen = database::get_generation(game); personality = rand_gen.lcrng_next(gen); trainer_id = rand_gen.lcrng_next(gen); base_pkmn = base; nickname = base_pkmn->get_species_name(); trainer_name = "Ash"; level = lvl; from_game = game; from_gen = base_pkmn->get_generation(); held_item = item::make(Items::NONE, from_game); ball = PokeBalls::POKE_BALL; attributes = dict<string, int>(); moves = moveset_t(4); move_PPs = vla<unsigned int>(4); icon_path = base_pkmn->get_icon_path(true); moves[0] = move::make(move1, from_game); move_PPs[0] = moves[0]->get_base_pp(); moves[1] = move::make(move2, from_game); move_PPs[1] = moves[1]->get_base_pp(); moves[2] = move::make(move3, from_game); move_PPs[2] = moves[2]->get_base_pp(); moves[3] = move::make(move4, from_game); move_PPs[3] = moves[3]->get_base_pp(); } base_pokemon::sptr team_pokemon_impl::get_base_pokemon(bool copy) const { base_pokemon::sptr to_return = base_pkmn; if(copy) { switch(database::get_generation(from_game)) { case 1: { base_pokemon_gen1impl actual1 = *(boost::polymorphic_downcast<base_pokemon_gen1impl*>(to_return.get())); return base_pokemon::sptr(&actual1); } case 2: { base_pokemon_gen2impl actual2 = *(boost::polymorphic_downcast<base_pokemon_gen2impl*>(to_return.get())); return base_pokemon::sptr(&actual2); } default: { base_pokemon_modernimpl actual345 = *(boost::polymorphic_downcast<base_pokemon_modernimpl*>(to_return.get())); return base_pokemon::sptr(&actual345); } } } else return to_return; } pokemon_text team_pokemon_impl::get_nickname() const {return nickname;} void team_pokemon_impl::set_nickname(pokemon_text name) { if(name.std_string().length() == 0) nickname = base_pkmn->get_species_name(); else if(name.std_string().length() <= 10) nickname = name; } pokemon_text team_pokemon_impl::get_trainer_name() const {return trainer_name;} void team_pokemon_impl::set_trainer_name(pokemon_text name) { if(name.std_string().length() == 0) trainer_name = "Ash"; //Reset to default else if(name.std_string().length() <= 7) trainer_name = name; } unsigned int team_pokemon_impl::get_level() const {return level;} void team_pokemon_impl::set_level(unsigned int lvl) { if(lvl > 0 and lvl <= 100) level = lvl; } unsigned int team_pokemon_impl::get_met_level() const {return met_level;} void team_pokemon_impl::set_met_level(unsigned int lvl) { if(lvl > 0 and lvl <= 100) met_level = lvl; } moveset_t team_pokemon_impl::get_moves() const {return moves;} vla<unsigned int> team_pokemon_impl::get_move_PPs() const {return move_PPs;} void team_pokemon_impl::set_move(unsigned int move_id, unsigned int pos) { //Will fail if move is incompatible with this generation moves[pos] = move::make(move_id, from_game); } void team_pokemon_impl::set_move_PP(unsigned int new_PP, unsigned int pos) { //TODO: implement PP Up stats if(new_PP <= moves[pos]->get_base_pp()) move_PPs[pos] = new_PP; } unsigned int team_pokemon_impl::get_status() const {return nonvolatile_status;} void team_pokemon_impl::set_status(unsigned int status) { if(status >= Statuses::OK and status <= Statuses::SLEEP) nonvolatile_status = status; else status = Statuses::OK; } unsigned int team_pokemon_impl::get_personality() const {return personality;} void team_pokemon_impl::set_personality(unsigned int new_personality) {personality = new_personality;} unsigned int team_pokemon_impl::get_generation() const {return from_gen;} item::sptr team_pokemon_impl::get_held_item(bool copy) const { item::sptr to_return = held_item; unsigned int item_id = to_return->get_item_id(); if(copy) { if(item_id >= Items::TM01 and item_id <= Items::HM08) { item_machineimpl actual_machine = *(boost::polymorphic_downcast<item_machineimpl*>(to_return.get())); return item::sptr(&actual_machine); } else if((item_id >= Items::CHERI_BERRY and item_id <= Items::ROWAP_BERRY) or (item_id >= Items::BERRY and item_id <= Items::MYSTERYBERRY)) { item_berryimpl actual_berry = *(boost::polymorphic_downcast<item_berryimpl*>(to_return.get())); return item::sptr(&actual_berry); } else { item_impl actual = *(boost::polymorphic_downcast<item_impl*>(to_return.get())); return item::sptr(&actual); } } else return to_return; } void team_pokemon_impl::set_held_item(item::sptr new_item) { //Don't set item if it doesn't exist in this game if(database::get_item_index(new_item->get_item_id(), from_game)) held_item = new_item; } void team_pokemon_impl::set_held_item(unsigned int item_id) { set_held_item(item::make(item_id, from_game)); } unsigned int team_pokemon_impl::get_ball() const {return ball;} void team_pokemon_impl::set_ball(unsigned int new_ball) {ball = new_ball;} string team_pokemon_impl::get_icon_path() const {return icon_path;} string team_pokemon_impl::get_sprite_path() const {return sprite_path;} int team_pokemon_impl::get_attribute(string attribute) const {return attributes[attribute];} dict<string, int> team_pokemon_impl::get_attributes() const {return attributes;} bool team_pokemon_impl::has_attribute(string attribute) const {return attributes.has_key(attribute);} void team_pokemon_impl::set_attribute(string attribute, int value) {attributes[attribute] = value;} void team_pokemon_impl::set_hidden_ability(bool val) {has_hidden_ability = val;} unsigned int team_pokemon_impl::get_trainer_gender() const {return otgender;} void team_pokemon_impl::set_trainer_gender(unsigned int new_gender) {otgender = new_gender;} unsigned int team_pokemon_impl::get_trainer_id() const {return trainer_id;} unsigned short team_pokemon_impl::get_public_trainer_id() const {return tid.public_id;} unsigned short team_pokemon_impl::get_secret_trainer_id() const {return tid.secret_id;} void team_pokemon_impl::set_trainer_id(unsigned int id) {trainer_id = id;} void team_pokemon_impl::set_public_trainer_id(unsigned short id) {tid.public_id = id;} void team_pokemon_impl::set_secret_trainer_id(unsigned short id) {tid.secret_id = id;} vector<string> team_pokemon_impl::get_egg_group_names() const {return base_pkmn->get_egg_group_names();} string team_pokemon_impl::get_species_name() const {return base_pkmn->get_species_name();} vector<unsigned int> team_pokemon_impl::get_egg_group_ids() const {return base_pkmn->get_egg_group_ids();} unsigned int team_pokemon_impl::get_game_id() const {return from_game;} unsigned int team_pokemon_impl::get_pokemon_id() const {return base_pkmn->get_pokemon_id();} unsigned int team_pokemon_impl::get_species_id() const {return base_pkmn->get_species_id();} dict<unsigned int, unsigned int> team_pokemon_impl::get_types() const {return base_pkmn->get_types();} dict<unsigned int, unsigned int> team_pokemon_impl::get_base_stats() const {return base_pkmn->get_base_stats();} dict<unsigned , unsigned int> team_pokemon_impl::get_ev_yields() const {return base_pkmn->get_ev_yields();} bool team_pokemon_impl::is_fully_evolved() const {return base_pkmn->is_fully_evolved();} } <commit_msg>team_pokemon: fixed get_item(copy = true)<commit_after>/* * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <iostream> #include <stdexcept> #include <string> #include <vector> #include <boost/cast.hpp> #include <pkmnsim/enums.hpp> #include <pkmnsim/move.hpp> #include <pkmnsim/team_pokemon.hpp> #include <pkmnsim/database/queries.hpp> #include <pkmnsim/types/prng.hpp> #include "base_pokemon_gen1impl.hpp" #include "base_pokemon_gen2impl.hpp" #include "base_pokemon_modernimpl.hpp" #include "item_impl.hpp" #include "item_berryimpl.hpp" #include "item_machineimpl.hpp" #include "team_pokemon_impl.hpp" #include "team_pokemon_gen1impl.hpp" #include "team_pokemon_gen2impl.hpp" #include "team_pokemon_modernimpl.hpp" using namespace std; namespace pkmnsim { team_pokemon::sptr team_pokemon::make(unsigned int id, unsigned int game, unsigned int level, unsigned int move1, unsigned int move2, unsigned int move3, unsigned int move4) { try { base_pokemon::sptr base = base_pokemon::make(id, game); if(base->get_generation() < 1 or base->get_generation() > 5) throw runtime_error("Gen must be 1-5."); switch(base->get_generation()) { case 1: return sptr(new team_pokemon_gen1impl(base, game, level, move1, move2, move3, move4)); case 2: return sptr(new team_pokemon_gen2impl(base, game, level, move1, move2, move3, move4)); default: return sptr(new team_pokemon_modernimpl(base, game, level, move1, move2, move3, move4)); } } catch(exception &e) { cout << "Caught exception: " << e.what() << endl; exit(EXIT_FAILURE); } } team_pokemon_impl::team_pokemon_impl(base_pokemon::sptr base, unsigned int game, unsigned int lvl, unsigned int move1, unsigned int move2, unsigned int move3, unsigned int move4): team_pokemon() { prng rand_gen; unsigned int gen = database::get_generation(game); personality = rand_gen.lcrng_next(gen); trainer_id = rand_gen.lcrng_next(gen); base_pkmn = base; nickname = base_pkmn->get_species_name(); trainer_name = "Ash"; level = lvl; from_game = game; from_gen = base_pkmn->get_generation(); held_item = item::make(Items::NONE, from_game); ball = PokeBalls::POKE_BALL; attributes = dict<string, int>(); moves = moveset_t(4); move_PPs = vla<unsigned int>(4); icon_path = base_pkmn->get_icon_path(true); moves[0] = move::make(move1, from_game); move_PPs[0] = moves[0]->get_base_pp(); moves[1] = move::make(move2, from_game); move_PPs[1] = moves[1]->get_base_pp(); moves[2] = move::make(move3, from_game); move_PPs[2] = moves[2]->get_base_pp(); moves[3] = move::make(move4, from_game); move_PPs[3] = moves[3]->get_base_pp(); } base_pokemon::sptr team_pokemon_impl::get_base_pokemon(bool copy) const { base_pokemon::sptr to_return = base_pkmn; if(copy) { switch(database::get_generation(from_game)) { case 1: { base_pokemon_gen1impl actual1 = *(boost::polymorphic_downcast<base_pokemon_gen1impl*>(to_return.get())); return base_pokemon::sptr(&actual1); } case 2: { base_pokemon_gen2impl actual2 = *(boost::polymorphic_downcast<base_pokemon_gen2impl*>(to_return.get())); return base_pokemon::sptr(&actual2); } default: { base_pokemon_modernimpl actual345 = *(boost::polymorphic_downcast<base_pokemon_modernimpl*>(to_return.get())); return base_pokemon::sptr(&actual345); } } } else return to_return; } pokemon_text team_pokemon_impl::get_nickname() const {return nickname;} void team_pokemon_impl::set_nickname(pokemon_text name) { if(name.std_string().length() == 0) nickname = base_pkmn->get_species_name(); else if(name.std_string().length() <= 10) nickname = name; } pokemon_text team_pokemon_impl::get_trainer_name() const {return trainer_name;} void team_pokemon_impl::set_trainer_name(pokemon_text name) { if(name.std_string().length() == 0) trainer_name = "Ash"; //Reset to default else if(name.std_string().length() <= 7) trainer_name = name; } unsigned int team_pokemon_impl::get_level() const {return level;} void team_pokemon_impl::set_level(unsigned int lvl) { if(lvl > 0 and lvl <= 100) level = lvl; } unsigned int team_pokemon_impl::get_met_level() const {return met_level;} void team_pokemon_impl::set_met_level(unsigned int lvl) { if(lvl > 0 and lvl <= 100) met_level = lvl; } moveset_t team_pokemon_impl::get_moves() const {return moves;} vla<unsigned int> team_pokemon_impl::get_move_PPs() const {return move_PPs;} void team_pokemon_impl::set_move(unsigned int move_id, unsigned int pos) { //Will fail if move is incompatible with this generation moves[pos] = move::make(move_id, from_game); } void team_pokemon_impl::set_move_PP(unsigned int new_PP, unsigned int pos) { //TODO: implement PP Up stats if(new_PP <= moves[pos]->get_base_pp()) move_PPs[pos] = new_PP; } unsigned int team_pokemon_impl::get_status() const {return nonvolatile_status;} void team_pokemon_impl::set_status(unsigned int status) { if(status >= Statuses::OK and status <= Statuses::SLEEP) nonvolatile_status = status; else status = Statuses::OK; } unsigned int team_pokemon_impl::get_personality() const {return personality;} void team_pokemon_impl::set_personality(unsigned int new_personality) {personality = new_personality;} unsigned int team_pokemon_impl::get_generation() const {return from_gen;} item::sptr team_pokemon_impl::get_held_item(bool copy) const { item::sptr to_return = held_item; unsigned int item_id = to_return->get_item_id(); if(copy) return item::make(item_id, from_game); else return to_return; } void team_pokemon_impl::set_held_item(item::sptr new_item) { //Don't set item if it doesn't exist in this game if(database::get_item_index(new_item->get_item_id(), from_game)) held_item = new_item; } void team_pokemon_impl::set_held_item(unsigned int item_id) { set_held_item(item::make(item_id, from_game)); } unsigned int team_pokemon_impl::get_ball() const {return ball;} void team_pokemon_impl::set_ball(unsigned int new_ball) {ball = new_ball;} string team_pokemon_impl::get_icon_path() const {return icon_path;} string team_pokemon_impl::get_sprite_path() const {return sprite_path;} int team_pokemon_impl::get_attribute(string attribute) const {return attributes[attribute];} dict<string, int> team_pokemon_impl::get_attributes() const {return attributes;} bool team_pokemon_impl::has_attribute(string attribute) const {return attributes.has_key(attribute);} void team_pokemon_impl::set_attribute(string attribute, int value) {attributes[attribute] = value;} void team_pokemon_impl::set_hidden_ability(bool val) {has_hidden_ability = val;} unsigned int team_pokemon_impl::get_trainer_gender() const {return otgender;} void team_pokemon_impl::set_trainer_gender(unsigned int new_gender) {otgender = new_gender;} unsigned int team_pokemon_impl::get_trainer_id() const {return trainer_id;} unsigned short team_pokemon_impl::get_public_trainer_id() const {return tid.public_id;} unsigned short team_pokemon_impl::get_secret_trainer_id() const {return tid.secret_id;} void team_pokemon_impl::set_trainer_id(unsigned int id) {trainer_id = id;} void team_pokemon_impl::set_public_trainer_id(unsigned short id) {tid.public_id = id;} void team_pokemon_impl::set_secret_trainer_id(unsigned short id) {tid.secret_id = id;} vector<string> team_pokemon_impl::get_egg_group_names() const {return base_pkmn->get_egg_group_names();} string team_pokemon_impl::get_species_name() const {return base_pkmn->get_species_name();} vector<unsigned int> team_pokemon_impl::get_egg_group_ids() const {return base_pkmn->get_egg_group_ids();} unsigned int team_pokemon_impl::get_game_id() const {return from_game;} unsigned int team_pokemon_impl::get_pokemon_id() const {return base_pkmn->get_pokemon_id();} unsigned int team_pokemon_impl::get_species_id() const {return base_pkmn->get_species_id();} dict<unsigned int, unsigned int> team_pokemon_impl::get_types() const {return base_pkmn->get_types();} dict<unsigned int, unsigned int> team_pokemon_impl::get_base_stats() const {return base_pkmn->get_base_stats();} dict<unsigned , unsigned int> team_pokemon_impl::get_ev_yields() const {return base_pkmn->get_ev_yields();} bool team_pokemon_impl::is_fully_evolved() const {return base_pkmn->is_fully_evolved();} } <|endoftext|>
<commit_before>//===-- tsan_mman.cc --------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "tsan_mman.h" #include "tsan_allocator.h" #include "tsan_rtl.h" #include "tsan_report.h" #include "tsan_flags.h" namespace __tsan { static void SignalUnsafeCall(ThreadState *thr, uptr pc) { if (!thr->in_signal_handler || !flags()->report_signal_unsafe) return; StackTrace stack; stack.ObtainCurrent(thr, pc); ScopedReport rep(ReportTypeSignalUnsafe); rep.AddStack(&stack); OutputReport(rep, rep.GetReport()->stacks[0]); } void *user_alloc(ThreadState *thr, uptr pc, uptr sz) { CHECK_GT(thr->in_rtl, 0); MBlock *b = (MBlock*)Alloc(sz + sizeof(MBlock)); b->size = sz; void *p = b + 1; if (CTX() && CTX()->initialized) { MemoryResetRange(thr, pc, (uptr)p, sz); } DPrintf("#%d: alloc(%lu) = %p\n", thr->tid, sz, p); SignalUnsafeCall(thr, pc); return p; } void user_free(ThreadState *thr, uptr pc, void *p) { CHECK_GT(thr->in_rtl, 0); CHECK_NE(p, (void*)0); DPrintf("#%d: free(%p)\n", thr->tid, p); MBlock *b = user_mblock(thr, p); p = b + 1; if (CTX() && CTX()->initialized && thr->in_rtl == 1) { MemoryRangeFreed(thr, pc, (uptr)p, b->size); } Free(b); SignalUnsafeCall(thr, pc); } void *user_realloc(ThreadState *thr, uptr pc, void *p, uptr sz) { CHECK_GT(thr->in_rtl, 0); void *p2 = 0; // FIXME: Handle "shrinking" more efficiently, // it seems that some software actually does this. if (sz) { p2 = user_alloc(thr, pc, sz); if (p) { MBlock *b = user_mblock(thr, p); internal_memcpy(p2, p, min(b->size, sz)); } } if (p) { user_free(thr, pc, p); } return p2; } void *user_alloc_aligned(ThreadState *thr, uptr pc, uptr sz, uptr align) { CHECK_GT(thr->in_rtl, 0); void *p = user_alloc(thr, pc, sz + align); void *pa = RoundUp(p, align); DCHECK_LE((uptr)pa + sz, (uptr)p + sz + align); return pa; } MBlock *user_mblock(ThreadState *thr, void *p) { CHECK_GT(thr->in_rtl, 0); CHECK_NE(p, (void*)0); MBlock *b = (MBlock*)AllocBlock(p); // FIXME: Output a warning, it's a user error. if (p < (char*)(b + 1) || p > (char*)(b + 1) + b->size) { Printf("user_mblock p=%p b=%p size=%lu beg=%p end=%p\n", p, b, b->size, (char*)(b + 1), (char*)(b + 1) + b->size); CHECK_GE(p, (char*)(b + 1)); CHECK_LE(p, (char*)(b + 1) + b->size); } return b; } void *internal_alloc(MBlockType typ, uptr sz) { ThreadState *thr = cur_thread(); CHECK_GT(thr->in_rtl, 0); return Alloc(sz); } void internal_free(void *p) { ThreadState *thr = cur_thread(); CHECK_GT(thr->in_rtl, 0); Free(p); } } // namespace __tsan <commit_msg>tsan: check for overflow in malloc()<commit_after>//===-- tsan_mman.cc --------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // //===----------------------------------------------------------------------===// #include "tsan_mman.h" #include "tsan_allocator.h" #include "tsan_rtl.h" #include "tsan_report.h" #include "tsan_flags.h" namespace __tsan { static void SignalUnsafeCall(ThreadState *thr, uptr pc) { if (!thr->in_signal_handler || !flags()->report_signal_unsafe) return; StackTrace stack; stack.ObtainCurrent(thr, pc); ScopedReport rep(ReportTypeSignalUnsafe); rep.AddStack(&stack); OutputReport(rep, rep.GetReport()->stacks[0]); } void *user_alloc(ThreadState *thr, uptr pc, uptr sz) { CHECK_GT(thr->in_rtl, 0); if (sz + sizeof(MBlock) < sz) return 0; MBlock *b = (MBlock*)Alloc(sz + sizeof(MBlock)); b->size = sz; void *p = b + 1; if (CTX() && CTX()->initialized) { MemoryResetRange(thr, pc, (uptr)p, sz); } DPrintf("#%d: alloc(%lu) = %p\n", thr->tid, sz, p); SignalUnsafeCall(thr, pc); return p; } void user_free(ThreadState *thr, uptr pc, void *p) { CHECK_GT(thr->in_rtl, 0); CHECK_NE(p, (void*)0); DPrintf("#%d: free(%p)\n", thr->tid, p); MBlock *b = user_mblock(thr, p); p = b + 1; if (CTX() && CTX()->initialized && thr->in_rtl == 1) { MemoryRangeFreed(thr, pc, (uptr)p, b->size); } Free(b); SignalUnsafeCall(thr, pc); } void *user_realloc(ThreadState *thr, uptr pc, void *p, uptr sz) { CHECK_GT(thr->in_rtl, 0); void *p2 = 0; // FIXME: Handle "shrinking" more efficiently, // it seems that some software actually does this. if (sz) { p2 = user_alloc(thr, pc, sz); if (p) { MBlock *b = user_mblock(thr, p); internal_memcpy(p2, p, min(b->size, sz)); } } if (p) { user_free(thr, pc, p); } return p2; } void *user_alloc_aligned(ThreadState *thr, uptr pc, uptr sz, uptr align) { CHECK_GT(thr->in_rtl, 0); void *p = user_alloc(thr, pc, sz + align); void *pa = RoundUp(p, align); DCHECK_LE((uptr)pa + sz, (uptr)p + sz + align); return pa; } MBlock *user_mblock(ThreadState *thr, void *p) { CHECK_GT(thr->in_rtl, 0); CHECK_NE(p, (void*)0); MBlock *b = (MBlock*)AllocBlock(p); // FIXME: Output a warning, it's a user error. if (p < (char*)(b + 1) || p > (char*)(b + 1) + b->size) { Printf("user_mblock p=%p b=%p size=%lu beg=%p end=%p\n", p, b, b->size, (char*)(b + 1), (char*)(b + 1) + b->size); CHECK_GE(p, (char*)(b + 1)); CHECK_LE(p, (char*)(b + 1) + b->size); } return b; } void *internal_alloc(MBlockType typ, uptr sz) { ThreadState *thr = cur_thread(); CHECK_GT(thr->in_rtl, 0); return Alloc(sz); } void internal_free(void *p) { ThreadState *thr = cur_thread(); CHECK_GT(thr->in_rtl, 0); Free(p); } } // namespace __tsan <|endoftext|>
<commit_before>#include "logging.h" #include <boost/log/utility/setup/console.hpp> namespace logging = boost::log; using boost::log::trivial::severity_level; severity_level gLoggingThreshold; int64_t get_curlopt_verbose() { return gLoggingThreshold <= boost::log::trivial::debug ? 1L : 0L; } void logger_init() { gLoggingThreshold = boost::log::trivial::info; logging::add_console_log(std::cout, boost::log::keywords::format = "%Message%", boost::log::keywords::auto_flush = true); boost::log::core::get()->set_filter(boost::log::trivial::severity >= gLoggingThreshold); } void logger_set_threshold(severity_level threshold) { gLoggingThreshold = threshold; boost::log::core::get()->set_filter(boost::log::trivial::severity >= gLoggingThreshold); } int loggerGetSeverity() { return static_cast<int>(gLoggingThreshold); } void LoggerConfig::updateFromPropertyTree(const boost::property_tree::ptree& pt) { CopyFromConfig(loglevel, "loglevel", boost::log::trivial::trace, pt); } void LoggerConfig::writeToStream(std::ostream& out_stream) const { writeOption(out_stream, loglevel, "loglevel"); } // vim: set tabstop=2 shiftwidth=2 expandtab: <commit_msg>Only display curl output in -vv (very verbose) mode<commit_after>#include "logging.h" #include <boost/log/utility/setup/console.hpp> namespace logging = boost::log; using boost::log::trivial::severity_level; severity_level gLoggingThreshold; int64_t get_curlopt_verbose() { return gLoggingThreshold <= boost::log::trivial::trace ? 1L : 0L; } void logger_init() { gLoggingThreshold = boost::log::trivial::info; logging::add_console_log(std::cout, boost::log::keywords::format = "%Message%", boost::log::keywords::auto_flush = true); boost::log::core::get()->set_filter(boost::log::trivial::severity >= gLoggingThreshold); } void logger_set_threshold(severity_level threshold) { gLoggingThreshold = threshold; boost::log::core::get()->set_filter(boost::log::trivial::severity >= gLoggingThreshold); } int loggerGetSeverity() { return static_cast<int>(gLoggingThreshold); } void LoggerConfig::updateFromPropertyTree(const boost::property_tree::ptree& pt) { CopyFromConfig(loglevel, "loglevel", boost::log::trivial::trace, pt); } void LoggerConfig::writeToStream(std::ostream& out_stream) const { writeOption(out_stream, loglevel, "loglevel"); } // vim: set tabstop=2 shiftwidth=2 expandtab: <|endoftext|>
<commit_before>#include "ofApp.h" // ball related properties int ballPosX; // x coordinate of the ball's position int ballPosY; // y coordinate of the ball's position int ballRadius; // radius of the ball bool ballIsMoving; // indicates the moving state of the ball // overall helper values int movementStep; //-------------------------------------------------------------- void ofApp::setup(){ // initialize ball properties ballPosX = 300; ballPosY = 200; ballRadius = 25; ballIsMoving = false; // initialize helper values movementStep = 4; } //-------------------------------------------------------------- void ofApp::update(){ // if ball is supposed to move: update it's position if (ballIsMoving) { // calculate new x coordinate of the ball ballPosX += movementStep; // let the ball bounce between the application window's borders // if ball's x position (considering its radius) is outside right border OR left border if ( (ballPosX > ofGetWindowWidth() - ballRadius) || (ballPosX < 0 + ballRadius) ) { movementStep *= -1; } } } //-------------------------------------------------------------- void ofApp::draw(){ // set color, apply color "fill" flag for shapes, and draw the ball (circle) at the designated position with the designated radius ofSetColor(255, 245, 0); ofFill(); ofCircle(ballPosX, ballPosY, ballRadius); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ // DEBUG: print out pressed key (code) to the console cout << "Pressed key: " << key << endl; // press spacebar (32): toogle between ball's moving state if (key == 32) { ballIsMoving = !ballIsMoving; // toogle moving state back and forth between true and false } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>Draw some application feedback, such as FPS, the mouse's position as well as the currently pressed key, directly to the application's window.<commit_after>#include "ofApp.h" // ball related properties int ballPosX; // x coordinate of the ball's position int ballPosY; // y coordinate of the ball's position int ballRadius; // radius of the ball bool ballIsMoving; // indicates the moving state of the ball // overall helper values int movementStep; // indicates the ball's movement step per update cycle int pressedKey; // store the key (code) of the most recent pressed key of the keyboard bool keyIsPressed; // indicates, if currently a key is pressed //-------------------------------------------------------------- void ofApp::setup(){ // initialize ball properties ballPosX = 300; ballPosY = 200; ballRadius = 25; ballIsMoving = false; // initialize helper values movementStep = 4; } //-------------------------------------------------------------- void ofApp::update(){ // if ball is supposed to move: update it's position if (ballIsMoving) { // calculate new x coordinate of the ball ballPosX += movementStep; // let the ball bounce between the application window's borders // if ball's x position (considering its radius) is outside right border OR left border if ( (ballPosX > ofGetWindowWidth() - ballRadius) || (ballPosX < 0 + ballRadius) ) { movementStep *= -1; } } } //-------------------------------------------------------------- void ofApp::draw(){ // draw some application feedback // // set color: OF pink ofSetColor(236, 50, 135); // draw the framerate (FPS, "frames per second") ofDrawBitmapString(ofToString(ofGetFrameRate()) + "fps", 10, 15); // draw the mouse pointer's position ofDrawBitmapString("Mouse x|y: " + ofToString(mouseX) + "|" + ofToString(mouseY), 110, 15); // draw the pressed key (code), but only if a key is pressed if (keyIsPressed) { ofDrawBitmapString("Key: " + ofToString(pressedKey), 280, 15); } // draw application's (interactive) content // // set color, apply color "fill" flag for shapes, and draw the ball (circle) at the designated position with the designated radius ofSetColor(255, 245, 0); ofFill(); ofCircle(ballPosX, ballPosY, ballRadius); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ // DEBUG: print out pressed key (code) to the console //cout << "Pressed key: " << key << endl; // update key-related helper values pressedKey = key; keyIsPressed = true; // press spacebar (32): toogle between ball's moving state if (key == 32) { ballIsMoving = !ballIsMoving; // toogle moving state back and forth between true and false } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ // update key-related helper value keyIsPressed = false; } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); for (int i = 0; i < 100; i++){ ofLine(0, 500 + ofRandom(-100,100), ofGetWidth(), 500 + ofRandom(-100,100)); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>added a rectangle<commit_after>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofSetColor(ofRandom(0,255), ofRandom (0,255), ofRandom (0,255)); for (int i = 0; i < 100; i++){ ofLine(0, 500 + ofRandom(-100,100), ofGetWidth(), 500 + ofRandom(-100,100)); } for (int i = 0; i < 100; i++){ ofRect(mouseX, i, 100,.5*mouseX); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>#include "ostree.h" #include <json/json.h> #include <stdio.h> #include <unistd.h> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/filesystem.hpp> #include <fstream> #include "logger.h" #include "utils.h" #include <gio/gio.h> boost::shared_ptr<OstreeSysroot> Ostree::LoadSysroot(const std::string &path) { OstreeSysroot *sysroot = NULL; if (path.size()) { GFile *fl = g_file_new_for_path(path.c_str()); sysroot = ostree_sysroot_new(fl); g_object_unref(fl); } else { sysroot = ostree_sysroot_new_default(); } GError *error = NULL; if (!ostree_sysroot_load(sysroot, NULL, &error)) { if (error != NULL) { g_error_free(error); } g_object_unref(sysroot); throw std::runtime_error("could not load sysroot"); } return boost::shared_ptr<OstreeSysroot>(sysroot, g_object_unref); } boost::shared_ptr<OstreeDeployment> Ostree::getStagedDeployment(const std::string &path) { boost::shared_ptr<OstreeSysroot> sysroot = Ostree::LoadSysroot(path); GPtrArray *deployments = NULL; OstreeDeployment *res = NULL; deployments = ostree_sysroot_get_deployments(sysroot.get()); if (deployments->len == 0) { res = NULL; } else { OstreeDeployment *d = static_cast<OstreeDeployment *>(deployments->pdata[0]); res = static_cast<OstreeDeployment *>(g_object_ref(d)); } g_ptr_array_unref(deployments); return boost::shared_ptr<OstreeDeployment>(res, g_object_unref); } bool Ostree::addRemote(OstreeRepo *repo, const std::string &remote, const std::string &url, const data::PackageManagerCredentials &cred) { GCancellable *cancellable = NULL; GError *error = NULL; GVariantBuilder b; GVariant *options; g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}")); g_variant_builder_add(&b, "{s@v}", "gpg-verify", g_variant_new_variant(g_variant_new_boolean(FALSE))); if (cred.cert_file.size() && cred.pkey_file.size() && cred.ca_file.size()) { g_variant_builder_add(&b, "{s@v}", "tls-client-cert-path", g_variant_new_variant(g_variant_new_string(cred.cert_file.c_str()))); g_variant_builder_add(&b, "{s@v}", "tls-client-key-path", g_variant_new_variant(g_variant_new_string(cred.pkey_file.c_str()))); g_variant_builder_add(&b, "{s@v}", "tls-ca-path", g_variant_new_variant(g_variant_new_string(cred.ca_file.c_str()))); } options = g_variant_builder_end(&b); if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS, remote.c_str(), url.c_str(), options, cancellable, &error)) { LOGGER_LOG(LVL_error, "Error of adding remote: " << error->message); g_error_free(error); return false; } if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS, remote.c_str(), url.c_str(), options, cancellable, &error)) { LOGGER_LOG(LVL_error, "Error of adding remote: " << error->message); g_error_free(error); return false; } return true; } #include "ostree-1/ostree.h" OstreePackage::OstreePackage(const std::string &ecu_serial_in, const std::string &ref_name_in, const std::string &desc_in, const std::string &treehub_in) : ecu_serial(ecu_serial_in), ref_name(ref_name_in), description(desc_in), pull_uri(treehub_in) { std::size_t pos = ref_name.find_last_of("-"); branch_name = ref_name.substr(0, pos); refhash = ref_name.substr(pos + 1, std::string::npos); if (branch_name.empty() || refhash.empty()) throw std::runtime_error("malformed OSTree target name: " + ref_name); } data::InstallOutcome OstreePackage::install(const data::PackageManagerCredentials &cred, OstreeConfig config) const { const char remote[] = "aktualizr-remote"; const char *const refs[] = {branch_name.c_str()}; const char *const commit_ids[] = {refhash.c_str()}; const char *opt_osname = NULL; OstreeRepo *repo = NULL; GCancellable *cancellable = NULL; GError *error = NULL; char *revision; GVariantBuilder builder; GVariant *options; if (config.os.size()) { opt_osname = config.os.c_str(); } boost::shared_ptr<OstreeSysroot> sysroot = Ostree::LoadSysroot(config.sysroot); if (!ostree_sysroot_get_repo(sysroot.get(), &repo, cancellable, &error)) { LOGGER_LOG(LVL_error, "could not get repo"); g_error_free(error); return data::InstallOutcome(data::INSTALL_FAILED, "could not get repo"); } if (!Ostree::addRemote(repo, remote, pull_uri, cred)) { return data::InstallOutcome(data::INSTALL_FAILED, "Error of adding remote"); } g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}")); g_variant_builder_add(&builder, "{s@v}", "flags", g_variant_new_variant(g_variant_new_int32(0))); g_variant_builder_add(&builder, "{s@v}", "refs", g_variant_new_variant(g_variant_new_strv(refs, 1))); g_variant_builder_add(&builder, "{s@v}", "override-commit-ids", g_variant_new_variant(g_variant_new_strv(commit_ids, 1))); if (cred.access_token.size()) { GVariantBuilder hdr_builder; std::string av("Bearer "); av += cred.access_token; g_variant_builder_init(&hdr_builder, G_VARIANT_TYPE("a(ss)")); g_variant_builder_add(&hdr_builder, "(ss)", "Authorization", av.c_str()); g_variant_builder_add(&builder, "{s@v}", "http-headers", g_variant_new_variant(g_variant_builder_end(&hdr_builder))); } options = g_variant_ref_sink(g_variant_builder_end(&builder)); if (!ostree_repo_pull_with_options(repo, remote, options, NULL, cancellable, &error)) { LOGGER_LOG(LVL_error, "Error of pulling image: " << error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } GKeyFile *origin = ostree_sysroot_origin_new_from_refspec(sysroot.get(), branch_name.c_str()); if (!ostree_repo_resolve_rev(repo, refhash.c_str(), FALSE, &revision, &error)) { LOGGER_LOG(LVL_error, error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } OstreeDeployment *merge_deployment = ostree_sysroot_get_merge_deployment(sysroot.get(), opt_osname); if (merge_deployment == NULL) { LOGGER_LOG(LVL_error, "No merge deployment"); return data::InstallOutcome(data::INSTALL_FAILED, "No merge deployment"); } if (!ostree_sysroot_prepare_cleanup(sysroot.get(), cancellable, &error)) { LOGGER_LOG(LVL_error, error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } std::ifstream args_stream("/proc/cmdline"); std::string args_content((std::istreambuf_iterator<char>(args_stream)), std::istreambuf_iterator<char>()); std::vector<std::string> args_vector; boost::split(args_vector, args_content, boost::is_any_of(" ")); std::vector<const char *> kargs_strv_vector; kargs_strv_vector.reserve(args_vector.size() + 1); for (std::vector<std::string>::iterator it = args_vector.begin(); it != args_vector.end(); ++it) { kargs_strv_vector.push_back((*it).c_str()); } kargs_strv_vector[args_vector.size()] = 0; GStrv kargs_strv = const_cast<char **>(&kargs_strv_vector[0]); OstreeDeployment *new_deployment = NULL; if (!ostree_sysroot_deploy_tree(sysroot.get(), opt_osname, revision, origin, merge_deployment, kargs_strv, &new_deployment, cancellable, &error)) { LOGGER_LOG(LVL_error, "ostree_sysroot_deploy_tree: " << error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } if (!ostree_sysroot_simple_write_deployment(sysroot.get(), NULL, new_deployment, merge_deployment, OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_NONE, cancellable, &error)) { LOGGER_LOG(LVL_error, "ostree_sysroot_simple_write_deployment:" << error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } LOGGER_LOG(LVL_info, "Performing sync()"); sync(); return data::InstallOutcome(data::OK, "Installation successful"); } OstreeBranch OstreeBranch::getCurrent(const std::string &ecu_serial, const std::string &ostree_sysroot) { boost::shared_ptr<OstreeDeployment> staged_deployment = Ostree::getStagedDeployment(ostree_sysroot); GKeyFile *origin = ostree_deployment_get_origin(staged_deployment.get()); const char *ref = ostree_deployment_get_csum(staged_deployment.get()); char *origin_refspec = g_key_file_get_string(origin, "origin", "refspec", NULL); OstreePackage package(ecu_serial, std::string(origin_refspec) + "-" + ref, origin_refspec, ""); g_free(origin_refspec); return OstreeBranch(true, ostree_deployment_get_osname(staged_deployment.get()), package); } OstreePackage OstreePackage::fromJson(const Json::Value &json) { return OstreePackage(json["ecu_serial"].asString(), json["ref_name"].asString(), json["description"].asString(), json["pull_uri"].asString()); } Json::Value OstreePackage::toEcuVersion(const Json::Value &custom) const { Json::Value installed_image; installed_image["filepath"] = ref_name; installed_image["fileinfo"]["length"] = 0; installed_image["fileinfo"]["hashes"]["sha256"] = refhash; Json::Value value; value["attacks_detected"] = ""; value["installed_image"] = installed_image; value["ecu_serial"] = ecu_serial; value["previous_timeserver_time"] = "1970-01-01T00:00:00Z"; value["timeserver_time"] = "1970-01-01T00:00:00Z"; if (custom != Json::nullValue) { value["custom"] = custom; } return value; } OstreePackage OstreePackage::getEcu(const std::string &ecu_serial, const std::string &ostree_sysroot) { return OstreeBranch::getCurrent(ecu_serial, ostree_sysroot).package; } Json::Value Ostree::getInstalledPackages(const std::string &file_path) { std::string packages_str = Utils::readFile(file_path); std::vector<std::string> package_lines; boost::split(package_lines, packages_str, boost::is_any_of("\n")); Json::Value packages(Json::arrayValue); for (std::vector<std::string>::iterator it = package_lines.begin(); it != package_lines.end(); ++it) { if (it->empty()) { continue; } size_t pos = it->find(" "); if (pos == std::string::npos) { throw std::runtime_error("Wrong packages file format"); } Json::Value package; package["name"] = it->substr(0, pos); package["version"] = it->substr(pos + 1); packages.append(package); } return packages; } <commit_msg>Use kernel arguments from the bootconfig, not the whole /proc/cmdline<commit_after>#include "ostree.h" #include <json/json.h> #include <stdio.h> #include <unistd.h> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/filesystem.hpp> #include <fstream> #include "logger.h" #include "utils.h" #include <gio/gio.h> boost::shared_ptr<OstreeSysroot> Ostree::LoadSysroot(const std::string &path) { OstreeSysroot *sysroot = NULL; if (path.size()) { GFile *fl = g_file_new_for_path(path.c_str()); sysroot = ostree_sysroot_new(fl); g_object_unref(fl); } else { sysroot = ostree_sysroot_new_default(); } GError *error = NULL; if (!ostree_sysroot_load(sysroot, NULL, &error)) { if (error != NULL) { g_error_free(error); } g_object_unref(sysroot); throw std::runtime_error("could not load sysroot"); } return boost::shared_ptr<OstreeSysroot>(sysroot, g_object_unref); } boost::shared_ptr<OstreeDeployment> Ostree::getStagedDeployment(const std::string &path) { boost::shared_ptr<OstreeSysroot> sysroot = Ostree::LoadSysroot(path); GPtrArray *deployments = NULL; OstreeDeployment *res = NULL; deployments = ostree_sysroot_get_deployments(sysroot.get()); if (deployments->len == 0) { res = NULL; } else { OstreeDeployment *d = static_cast<OstreeDeployment *>(deployments->pdata[0]); res = static_cast<OstreeDeployment *>(g_object_ref(d)); } g_ptr_array_unref(deployments); return boost::shared_ptr<OstreeDeployment>(res, g_object_unref); } bool Ostree::addRemote(OstreeRepo *repo, const std::string &remote, const std::string &url, const data::PackageManagerCredentials &cred) { GCancellable *cancellable = NULL; GError *error = NULL; GVariantBuilder b; GVariant *options; g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}")); g_variant_builder_add(&b, "{s@v}", "gpg-verify", g_variant_new_variant(g_variant_new_boolean(FALSE))); if (cred.cert_file.size() && cred.pkey_file.size() && cred.ca_file.size()) { g_variant_builder_add(&b, "{s@v}", "tls-client-cert-path", g_variant_new_variant(g_variant_new_string(cred.cert_file.c_str()))); g_variant_builder_add(&b, "{s@v}", "tls-client-key-path", g_variant_new_variant(g_variant_new_string(cred.pkey_file.c_str()))); g_variant_builder_add(&b, "{s@v}", "tls-ca-path", g_variant_new_variant(g_variant_new_string(cred.ca_file.c_str()))); } options = g_variant_builder_end(&b); if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS, remote.c_str(), url.c_str(), options, cancellable, &error)) { LOGGER_LOG(LVL_error, "Error of adding remote: " << error->message); g_error_free(error); return false; } if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS, remote.c_str(), url.c_str(), options, cancellable, &error)) { LOGGER_LOG(LVL_error, "Error of adding remote: " << error->message); g_error_free(error); return false; } return true; } #include "ostree-1/ostree.h" OstreePackage::OstreePackage(const std::string &ecu_serial_in, const std::string &ref_name_in, const std::string &desc_in, const std::string &treehub_in) : ecu_serial(ecu_serial_in), ref_name(ref_name_in), description(desc_in), pull_uri(treehub_in) { std::size_t pos = ref_name.find_last_of("-"); branch_name = ref_name.substr(0, pos); refhash = ref_name.substr(pos + 1, std::string::npos); if (branch_name.empty() || refhash.empty()) throw std::runtime_error("malformed OSTree target name: " + ref_name); } data::InstallOutcome OstreePackage::install(const data::PackageManagerCredentials &cred, OstreeConfig config) const { const char remote[] = "aktualizr-remote"; const char *const refs[] = {branch_name.c_str()}; const char *const commit_ids[] = {refhash.c_str()}; const char *opt_osname = NULL; OstreeRepo *repo = NULL; GCancellable *cancellable = NULL; GError *error = NULL; char *revision; GVariantBuilder builder; GVariant *options; if (config.os.size()) { opt_osname = config.os.c_str(); } boost::shared_ptr<OstreeSysroot> sysroot = Ostree::LoadSysroot(config.sysroot); if (!ostree_sysroot_get_repo(sysroot.get(), &repo, cancellable, &error)) { LOGGER_LOG(LVL_error, "could not get repo"); g_error_free(error); return data::InstallOutcome(data::INSTALL_FAILED, "could not get repo"); } if (!Ostree::addRemote(repo, remote, pull_uri, cred)) { return data::InstallOutcome(data::INSTALL_FAILED, "Error of adding remote"); } g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}")); g_variant_builder_add(&builder, "{s@v}", "flags", g_variant_new_variant(g_variant_new_int32(0))); g_variant_builder_add(&builder, "{s@v}", "refs", g_variant_new_variant(g_variant_new_strv(refs, 1))); g_variant_builder_add(&builder, "{s@v}", "override-commit-ids", g_variant_new_variant(g_variant_new_strv(commit_ids, 1))); if (cred.access_token.size()) { GVariantBuilder hdr_builder; std::string av("Bearer "); av += cred.access_token; g_variant_builder_init(&hdr_builder, G_VARIANT_TYPE("a(ss)")); g_variant_builder_add(&hdr_builder, "(ss)", "Authorization", av.c_str()); g_variant_builder_add(&builder, "{s@v}", "http-headers", g_variant_new_variant(g_variant_builder_end(&hdr_builder))); } options = g_variant_ref_sink(g_variant_builder_end(&builder)); if (!ostree_repo_pull_with_options(repo, remote, options, NULL, cancellable, &error)) { LOGGER_LOG(LVL_error, "Error of pulling image: " << error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } GKeyFile *origin = ostree_sysroot_origin_new_from_refspec(sysroot.get(), branch_name.c_str()); if (!ostree_repo_resolve_rev(repo, refhash.c_str(), FALSE, &revision, &error)) { LOGGER_LOG(LVL_error, error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } OstreeDeployment *merge_deployment = ostree_sysroot_get_merge_deployment(sysroot.get(), opt_osname); if (merge_deployment == NULL) { LOGGER_LOG(LVL_error, "No merge deployment"); return data::InstallOutcome(data::INSTALL_FAILED, "No merge deployment"); } if (!ostree_sysroot_prepare_cleanup(sysroot.get(), cancellable, &error)) { LOGGER_LOG(LVL_error, error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } std::string args_content = std::string(ostree_bootconfig_parser_get(ostree_deployment_get_bootconfig(merge_deployment), "options")); std::vector<std::string> args_vector; boost::split(args_vector, args_content, boost::is_any_of(" ")); std::vector<const char *> kargs_strv_vector; kargs_strv_vector.reserve(args_vector.size() + 1); for (std::vector<std::string>::iterator it = args_vector.begin(); it != args_vector.end(); ++it) { kargs_strv_vector.push_back((*it).c_str()); } kargs_strv_vector[args_vector.size()] = 0; GStrv kargs_strv = const_cast<char **>(&kargs_strv_vector[0]); OstreeDeployment *new_deployment = NULL; if (!ostree_sysroot_deploy_tree(sysroot.get(), opt_osname, revision, origin, merge_deployment, kargs_strv, &new_deployment, cancellable, &error)) { LOGGER_LOG(LVL_error, "ostree_sysroot_deploy_tree: " << error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } if (!ostree_sysroot_simple_write_deployment(sysroot.get(), NULL, new_deployment, merge_deployment, OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_NONE, cancellable, &error)) { LOGGER_LOG(LVL_error, "ostree_sysroot_simple_write_deployment:" << error->message); data::InstallOutcome install_outcome(data::INSTALL_FAILED, error->message); g_error_free(error); return install_outcome; } LOGGER_LOG(LVL_info, "Performing sync()"); sync(); return data::InstallOutcome(data::OK, "Installation successful"); } OstreeBranch OstreeBranch::getCurrent(const std::string &ecu_serial, const std::string &ostree_sysroot) { boost::shared_ptr<OstreeDeployment> staged_deployment = Ostree::getStagedDeployment(ostree_sysroot); GKeyFile *origin = ostree_deployment_get_origin(staged_deployment.get()); const char *ref = ostree_deployment_get_csum(staged_deployment.get()); char *origin_refspec = g_key_file_get_string(origin, "origin", "refspec", NULL); OstreePackage package(ecu_serial, std::string(origin_refspec) + "-" + ref, origin_refspec, ""); g_free(origin_refspec); return OstreeBranch(true, ostree_deployment_get_osname(staged_deployment.get()), package); } OstreePackage OstreePackage::fromJson(const Json::Value &json) { return OstreePackage(json["ecu_serial"].asString(), json["ref_name"].asString(), json["description"].asString(), json["pull_uri"].asString()); } Json::Value OstreePackage::toEcuVersion(const Json::Value &custom) const { Json::Value installed_image; installed_image["filepath"] = ref_name; installed_image["fileinfo"]["length"] = 0; installed_image["fileinfo"]["hashes"]["sha256"] = refhash; Json::Value value; value["attacks_detected"] = ""; value["installed_image"] = installed_image; value["ecu_serial"] = ecu_serial; value["previous_timeserver_time"] = "1970-01-01T00:00:00Z"; value["timeserver_time"] = "1970-01-01T00:00:00Z"; if (custom != Json::nullValue) { value["custom"] = custom; } return value; } OstreePackage OstreePackage::getEcu(const std::string &ecu_serial, const std::string &ostree_sysroot) { return OstreeBranch::getCurrent(ecu_serial, ostree_sysroot).package; } Json::Value Ostree::getInstalledPackages(const std::string &file_path) { std::string packages_str = Utils::readFile(file_path); std::vector<std::string> package_lines; boost::split(package_lines, packages_str, boost::is_any_of("\n")); Json::Value packages(Json::arrayValue); for (std::vector<std::string>::iterator it = package_lines.begin(); it != package_lines.end(); ++it) { if (it->empty()) { continue; } size_t pos = it->find(" "); if (pos == std::string::npos) { throw std::runtime_error("Wrong packages file format"); } Json::Value package; package["name"] = it->substr(0, pos); package["version"] = it->substr(pos + 1); packages.append(package); } return packages; } <|endoftext|>
<commit_before>//======================================================================= // Copyright 2014-2015 David Simmons-Duffin. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= // Currently, SDPB uses tinyxml2 to parse an input file into an XML // tree, which is stored entirely in memory. This tree is then // transformed into the appropriate data structures using the parse // functions below. In the future, this could be made more memory // efficient by avoiding building the XML tree in memory. // See the manual for a description of the correct XML input format. #include <vector> #include "types.h" #include "parse.h" #include "Polynomial.h" #include "SDP.h" #include "tinyxml2/tinyxml2.h" using std::vector; using tinyxml2::XMLDocument; using tinyxml2::XMLElement; using boost::filesystem::path; // parse a bunch of adjacent elements with tag `name' into a vector<T> // using the function `parse' for each element. template <class T> vector<T> parseMany(const char *name, T(*parse)(XMLElement *), XMLElement *elt) { XMLElement *e; vector<T> v; for (e = elt->FirstChildElement(name); e != NULL; e = e->NextSiblingElement(name)) { v.push_back(parse(e)); } return v; } Real parseReal(XMLElement *xml) { return Real(xml->GetText()); } int parseInt(XMLElement *xml) { return atoi(xml->GetText()); } Vector parseVector(XMLElement *xml) { return parseMany("elt", parseReal, xml); } Matrix parseMatrix(XMLElement *xml) { Matrix m; m.rows = parseInt(xml->FirstChildElement("rows")); m.cols = parseInt(xml->FirstChildElement("cols")); m.elements = parseVector(xml->FirstChildElement("elements")); return m; } Polynomial parsePolynomial(XMLElement *xml) { Polynomial p; p.coefficients = parseMany("coeff", parseReal, xml); return p; } vector<Polynomial> parsePolynomialVector(XMLElement *xml) { return parseMany("polynomial", parsePolynomial, xml); } PolynomialVectorMatrix parsePolynomialVectorMatrix(XMLElement *xml) { PolynomialVectorMatrix m; m.rows = parseInt(xml->FirstChildElement("rows")); m.cols = parseInt(xml->FirstChildElement("cols")); m.elements = parseMany("polynomialVector", parsePolynomialVector, xml->FirstChildElement("elements")); m.samplePoints = parseVector(xml->FirstChildElement("samplePoints")); m.sampleScalings = parseVector(xml->FirstChildElement("sampleScalings")); m.bilinearBasis = parsePolynomialVector(xml->FirstChildElement("bilinearBasis")); return m; } SDP parseBootstrapSDP(XMLElement *xml) { return bootstrapSDP(parseVector(xml->FirstChildElement("objective")), parseMany("polynomialVectorMatrix", parsePolynomialVectorMatrix, xml->FirstChildElement("polynomialVectorMatrices"))); } SDP readBootstrapSDP(const path sdpFile) { XMLDocument doc; #ifndef BOOST_WINDOWS_API doc.LoadFile(sdpFile.c_str()); #else doc.LoadFile(sdpFile.string().c_str()); #endif return parseBootstrapSDP(doc.FirstChildElement("sdp")); } <commit_msg>cosmetic changes<commit_after>//======================================================================= // Copyright 2014-2015 David Simmons-Duffin. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= // Currently, SDPB uses tinyxml2 to parse an input file into an XML // tree, which is stored entirely in memory. This tree is then // transformed into the appropriate data structures using the parse // functions below. In the future, this could be made more memory // efficient by avoiding building the XML tree in memory. // See the manual for a description of the correct XML input format. #include <vector> #include "types.h" #include "parse.h" #include "Polynomial.h" #include "SDP.h" #include "tinyxml2/tinyxml2.h" using std::vector; using tinyxml2::XMLDocument; using tinyxml2::XMLElement; using boost::filesystem::path; // parse a bunch of adjacent elements with tag `name' into a vector<T> // using the function `parse' for each element. template <class T> vector<T> parseMany(const char *name, T(*parse)(XMLElement *), XMLElement *elt) { XMLElement *e; vector<T> v; for (e = elt->FirstChildElement(name); e != NULL; e = e->NextSiblingElement(name)) { v.push_back(parse(e)); } return v; } Real parseReal(XMLElement *xml) { return Real(xml->GetText()); } int parseInt(XMLElement *xml) { return atoi(xml->GetText()); } Vector parseVector(XMLElement *xml) { return parseMany("elt", parseReal, xml); } Matrix parseMatrix(XMLElement *xml) { Matrix m; m.rows = parseInt(xml->FirstChildElement("rows")); m.cols = parseInt(xml->FirstChildElement("cols")); m.elements = parseVector(xml->FirstChildElement("elements")); return m; } Polynomial parsePolynomial(XMLElement *xml) { Polynomial p; p.coefficients = parseMany("coeff", parseReal, xml); return p; } vector<Polynomial> parsePolynomialVector(XMLElement *xml) { return parseMany("polynomial", parsePolynomial, xml); } PolynomialVectorMatrix parsePolynomialVectorMatrix(XMLElement *xml) { PolynomialVectorMatrix m; m.rows = parseInt(xml->FirstChildElement("rows")); m.cols = parseInt(xml->FirstChildElement("cols")); m.elements = parseMany("polynomialVector", parsePolynomialVector, xml->FirstChildElement("elements")); m.samplePoints = parseVector(xml->FirstChildElement("samplePoints")); m.sampleScalings = parseVector(xml->FirstChildElement("sampleScalings")); m.bilinearBasis = parsePolynomialVector(xml->FirstChildElement("bilinearBasis")); return m; } SDP parseBootstrapSDP(XMLElement *xml) { return bootstrapSDP(parseVector(xml->FirstChildElement("objective")), parseMany("polynomialVectorMatrix", parsePolynomialVectorMatrix, xml->FirstChildElement("polynomialVectorMatrices"))); } SDP readBootstrapSDP(const path sdpFile) { XMLDocument doc; #ifndef BOOST_WINDOWS_API doc.LoadFile(sdpFile.c_str()); #else doc.LoadFile(sdpFile.string().c_str()); #endif return parseBootstrapSDP(doc.FirstChildElement("sdp")); } <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem.h" #include <aws/core/config/AWSProfileConfigLoader.h> #include <stdlib.h> #include <string.h> #include "absl/strings/ascii.h" #include "absl/strings/numbers.h" #include "tensorflow/c/experimental/filesystem/filesystem_interface.h" #include "tensorflow/c/experimental/filesystem/plugins/s3/aws_crypto.h" #include "tensorflow/c/tf_status.h" // Implementation of a filesystem for S3 environments. // This filesystem will support `s3://` URI schemes. constexpr char kS3ClientAllocationTag[] = "S3ClientAllocation"; constexpr int64_t kS3TimeoutMsec = 300000; // 5 min constexpr char kExecutorTag[] = "TransferManagerExecutorAllocation"; constexpr int kExecutorPoolSize = 25; constexpr uint64_t kS3MultiPartUploadChunkSize = 50 * 1024 * 1024; // 50 MB constexpr uint64_t kS3MultiPartDownloadChunkSize = 50 * 1024 * 1024; // 50 MB static void* plugin_memory_allocate(size_t size) { return calloc(1, size); } static void plugin_memory_free(void* ptr) { free(ptr); } static void ParseS3Path(const Aws::String& fname, bool object_empty_ok, Aws::String* bucket, Aws::String* object, TF_Status* status) { size_t scheme_end = fname.find("://") + 2; if (fname.substr(0, scheme_end + 1) != "s3://") { TF_SetStatus(status, TF_INVALID_ARGUMENT, "S3 path doesn't start with 's3://'."); return; } size_t bucket_end = fname.find("/", scheme_end + 1); if (bucket_end == std::string::npos) { TF_SetStatus(status, TF_INVALID_ARGUMENT, "S3 path doesn't contain a bucket name."); return; } *bucket = fname.substr(scheme_end + 1, bucket_end - scheme_end - 1); *object = fname.substr(bucket_end + 1); if (object->empty() && !object_empty_ok) { TF_SetStatus(status, TF_INVALID_ARGUMENT, "S3 path doesn't contain an object name."); } } static Aws::Client::ClientConfiguration& GetDefaultClientConfig() { ABSL_CONST_INIT static absl::Mutex cfg_lock(absl::kConstInit); static bool init(false); static Aws::Client::ClientConfiguration cfg; absl::MutexLock l(&cfg_lock); if (!init) { const char* endpoint = getenv("S3_ENDPOINT"); if (endpoint) cfg.endpointOverride = Aws::String(endpoint); const char* region = getenv("AWS_REGION"); // TODO (yongtang): `S3_REGION` should be deprecated after 2.0. if (!region) region = getenv("S3_REGION"); if (region) { cfg.region = Aws::String(region); } else { // Load config file (e.g., ~/.aws/config) only if AWS_SDK_LOAD_CONFIG // is set with a truthy value. const char* load_config_env = getenv("AWS_SDK_LOAD_CONFIG"); std::string load_config = load_config_env ? absl::AsciiStrToLower(load_config_env) : ""; if (load_config == "true" || load_config == "1") { Aws::String config_file; // If AWS_CONFIG_FILE is set then use it, otherwise use ~/.aws/config. const char* config_file_env = getenv("AWS_CONFIG_FILE"); if (config_file_env) { config_file = config_file_env; } else { const char* home_env = getenv("HOME"); if (home_env) { config_file = home_env; config_file += "/.aws/config"; } } Aws::Config::AWSConfigFileProfileConfigLoader loader(config_file); loader.Load(); auto profiles = loader.GetProfiles(); if (!profiles["default"].GetRegion().empty()) cfg.region = profiles["default"].GetRegion(); } } const char* use_https = getenv("S3_USE_HTTPS"); if (use_https) { if (use_https[0] == '0') cfg.scheme = Aws::Http::Scheme::HTTP; else cfg.scheme = Aws::Http::Scheme::HTTPS; } const char* verify_ssl = getenv("S3_VERIFY_SSL"); if (verify_ssl) { if (verify_ssl[0] == '0') cfg.verifySSL = false; else cfg.verifySSL = true; } // if these timeouts are low, you may see an error when // uploading/downloading large files: Unable to connect to endpoint int64_t timeout; cfg.connectTimeoutMs = absl::SimpleAtoi(getenv("S3_CONNECT_TIMEOUT_MSEC"), &timeout) ? timeout : kS3TimeoutMsec; cfg.requestTimeoutMs = absl::SimpleAtoi(getenv("S3_REQUEST_TIMEOUT_MSEC"), &timeout) ? timeout : kS3TimeoutMsec; const char* ca_file = getenv("S3_CA_FILE"); if (ca_file) cfg.caFile = Aws::String(ca_file); const char* ca_path = getenv("S3_CA_PATH"); if (ca_path) cfg.caPath = Aws::String(ca_path); init = true; } return cfg; }; static void GetS3Client(tf_s3_filesystem::S3File* s3_file) { absl::MutexLock l(&s3_file->initialization_lock); if (s3_file->s3_client.get() == nullptr) { Aws::SDKOptions options; options.cryptoOptions.sha256Factory_create_fn = []() { return Aws::MakeShared<tf_s3_filesystem::AWSSHA256Factory>( tf_s3_filesystem::AWSCryptoAllocationTag); }; options.cryptoOptions.sha256HMACFactory_create_fn = []() { return Aws::MakeShared<tf_s3_filesystem::AWSSHA256HmacFactory>( tf_s3_filesystem::AWSCryptoAllocationTag); }; options.cryptoOptions.secureRandomFactory_create_fn = []() { return Aws::MakeShared<tf_s3_filesystem::AWSSecureRandomFactory>( tf_s3_filesystem::AWSCryptoAllocationTag); }; Aws::InitAPI(options); // The creation of S3Client disables virtual addressing: // S3Client(clientConfiguration, signPayloads, useVirtualAddressing = // true) // The purpose is to address the issue encountered when there is an `.` // in the bucket name. Due to TLS hostname validation or DNS rules, // the bucket may not be resolved. Disabling of virtual addressing // should address the issue. See GitHub issue 16397 for details. s3_file->s3_client = Aws::MakeShared<Aws::S3::S3Client>( kS3ClientAllocationTag, GetDefaultClientConfig(), Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, false); } } static void GetExecutor(tf_s3_filesystem::S3File* s3_file) { absl::MutexLock l(&s3_file->initialization_lock); if (s3_file->executor.get() == nullptr) { s3_file->executor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>( kExecutorTag, kExecutorPoolSize); } } static void ShutdownClient(Aws::S3::S3Client* s3_client) { if (s3_client != nullptr) { delete s3_client; Aws::SDKOptions options; Aws::ShutdownAPI(options); } } // SECTION 1. Implementation for `TF_RandomAccessFile` // ---------------------------------------------------------------------------- namespace tf_random_access_file { // TODO(vnvo2409): Implement later } // namespace tf_random_access_file // SECTION 2. Implementation for `TF_WritableFile` // ---------------------------------------------------------------------------- namespace tf_writable_file { // TODO(vnvo2409): Implement later } // namespace tf_writable_file // SECTION 3. Implementation for `TF_ReadOnlyMemoryRegion` // ---------------------------------------------------------------------------- namespace tf_read_only_memory_region { // TODO(vnvo2409): Implement later } // namespace tf_read_only_memory_region // SECTION 4. Implementation for `TF_Filesystem`, the actual filesystem // ---------------------------------------------------------------------------- namespace tf_s3_filesystem { S3File::S3File() : s3_client(nullptr, ShutdownClient), executor(nullptr), transfer_managers(), multi_part_chunk_sizes(), use_multi_part_download(true), initialization_lock() { uint64_t temp_value; multi_part_chunk_sizes[Aws::Transfer::TransferDirection::UPLOAD] = absl::SimpleAtoi(getenv("S3_MULTI_PART_UPLOAD_CHUNK_SIZE"), &temp_value) ? temp_value : kS3MultiPartUploadChunkSize; multi_part_chunk_sizes[Aws::Transfer::TransferDirection::DOWNLOAD] = absl::SimpleAtoi(getenv("S3_MULTI_PART_DOWNLOAD_CHUNK_SIZE"), &temp_value) ? temp_value : kS3MultiPartDownloadChunkSize; use_multi_part_download = absl::SimpleAtoi(getenv("S3_DISABLE_MULTI_PART_DOWNLOAD"), &temp_value) ? (temp_value != 1) : use_multi_part_download; transfer_managers.emplace(Aws::Transfer::TransferDirection::UPLOAD, nullptr); transfer_managers.emplace(Aws::Transfer::TransferDirection::DOWNLOAD, nullptr); } void Init(TF_Filesystem* filesystem, TF_Status* status) { filesystem->plugin_filesystem = new S3File(); TF_SetStatus(status, TF_OK, ""); } void Cleanup(TF_Filesystem* filesystem) { auto s3_file = static_cast<S3File*>(filesystem->plugin_filesystem); delete s3_file; } // TODO(vnvo2409): Implement later } // namespace tf_s3_filesystem static void ProvideFilesystemSupportFor(TF_FilesystemPluginOps* ops, const char* uri) { TF_SetFilesystemVersionMetadata(ops); ops->scheme = strdup(uri); } void TF_InitPlugin(TF_FilesystemPluginInfo* info) { info->plugin_memory_allocate = plugin_memory_allocate; info->plugin_memory_free = plugin_memory_free; info->num_schemes = 1; info->ops = static_cast<TF_FilesystemPluginOps*>( plugin_memory_allocate(info->num_schemes * sizeof(info->ops[0]))); ProvideFilesystemSupportFor(&info->ops[0], "s3"); } <commit_msg>Add get transfer manager<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem.h" #include <aws/core/config/AWSProfileConfigLoader.h> #include <stdlib.h> #include <string.h> #include "absl/strings/ascii.h" #include "absl/strings/numbers.h" #include "tensorflow/c/experimental/filesystem/filesystem_interface.h" #include "tensorflow/c/experimental/filesystem/plugins/s3/aws_crypto.h" #include "tensorflow/c/tf_status.h" // Implementation of a filesystem for S3 environments. // This filesystem will support `s3://` URI schemes. constexpr char kS3ClientAllocationTag[] = "S3ClientAllocation"; constexpr int64_t kS3TimeoutMsec = 300000; // 5 min constexpr char kExecutorTag[] = "TransferManagerExecutorAllocation"; constexpr int kExecutorPoolSize = 25; constexpr uint64_t kS3MultiPartUploadChunkSize = 50 * 1024 * 1024; // 50 MB constexpr uint64_t kS3MultiPartDownloadChunkSize = 50 * 1024 * 1024; // 50 MB static void* plugin_memory_allocate(size_t size) { return calloc(1, size); } static void plugin_memory_free(void* ptr) { free(ptr); } static void ParseS3Path(const Aws::String& fname, bool object_empty_ok, Aws::String* bucket, Aws::String* object, TF_Status* status) { size_t scheme_end = fname.find("://") + 2; if (fname.substr(0, scheme_end + 1) != "s3://") { TF_SetStatus(status, TF_INVALID_ARGUMENT, "S3 path doesn't start with 's3://'."); return; } size_t bucket_end = fname.find("/", scheme_end + 1); if (bucket_end == std::string::npos) { TF_SetStatus(status, TF_INVALID_ARGUMENT, "S3 path doesn't contain a bucket name."); return; } *bucket = fname.substr(scheme_end + 1, bucket_end - scheme_end - 1); *object = fname.substr(bucket_end + 1); if (object->empty() && !object_empty_ok) { TF_SetStatus(status, TF_INVALID_ARGUMENT, "S3 path doesn't contain an object name."); } } static Aws::Client::ClientConfiguration& GetDefaultClientConfig() { ABSL_CONST_INIT static absl::Mutex cfg_lock(absl::kConstInit); static bool init(false); static Aws::Client::ClientConfiguration cfg; absl::MutexLock l(&cfg_lock); if (!init) { const char* endpoint = getenv("S3_ENDPOINT"); if (endpoint) cfg.endpointOverride = Aws::String(endpoint); const char* region = getenv("AWS_REGION"); // TODO (yongtang): `S3_REGION` should be deprecated after 2.0. if (!region) region = getenv("S3_REGION"); if (region) { cfg.region = Aws::String(region); } else { // Load config file (e.g., ~/.aws/config) only if AWS_SDK_LOAD_CONFIG // is set with a truthy value. const char* load_config_env = getenv("AWS_SDK_LOAD_CONFIG"); std::string load_config = load_config_env ? absl::AsciiStrToLower(load_config_env) : ""; if (load_config == "true" || load_config == "1") { Aws::String config_file; // If AWS_CONFIG_FILE is set then use it, otherwise use ~/.aws/config. const char* config_file_env = getenv("AWS_CONFIG_FILE"); if (config_file_env) { config_file = config_file_env; } else { const char* home_env = getenv("HOME"); if (home_env) { config_file = home_env; config_file += "/.aws/config"; } } Aws::Config::AWSConfigFileProfileConfigLoader loader(config_file); loader.Load(); auto profiles = loader.GetProfiles(); if (!profiles["default"].GetRegion().empty()) cfg.region = profiles["default"].GetRegion(); } } const char* use_https = getenv("S3_USE_HTTPS"); if (use_https) { if (use_https[0] == '0') cfg.scheme = Aws::Http::Scheme::HTTP; else cfg.scheme = Aws::Http::Scheme::HTTPS; } const char* verify_ssl = getenv("S3_VERIFY_SSL"); if (verify_ssl) { if (verify_ssl[0] == '0') cfg.verifySSL = false; else cfg.verifySSL = true; } // if these timeouts are low, you may see an error when // uploading/downloading large files: Unable to connect to endpoint int64_t timeout; cfg.connectTimeoutMs = absl::SimpleAtoi(getenv("S3_CONNECT_TIMEOUT_MSEC"), &timeout) ? timeout : kS3TimeoutMsec; cfg.requestTimeoutMs = absl::SimpleAtoi(getenv("S3_REQUEST_TIMEOUT_MSEC"), &timeout) ? timeout : kS3TimeoutMsec; const char* ca_file = getenv("S3_CA_FILE"); if (ca_file) cfg.caFile = Aws::String(ca_file); const char* ca_path = getenv("S3_CA_PATH"); if (ca_path) cfg.caPath = Aws::String(ca_path); init = true; } return cfg; }; static void GetS3Client(tf_s3_filesystem::S3File* s3_file) { absl::MutexLock l(&s3_file->initialization_lock); if (s3_file->s3_client.get() == nullptr) { Aws::SDKOptions options; options.cryptoOptions.sha256Factory_create_fn = []() { return Aws::MakeShared<tf_s3_filesystem::AWSSHA256Factory>( tf_s3_filesystem::AWSCryptoAllocationTag); }; options.cryptoOptions.sha256HMACFactory_create_fn = []() { return Aws::MakeShared<tf_s3_filesystem::AWSSHA256HmacFactory>( tf_s3_filesystem::AWSCryptoAllocationTag); }; options.cryptoOptions.secureRandomFactory_create_fn = []() { return Aws::MakeShared<tf_s3_filesystem::AWSSecureRandomFactory>( tf_s3_filesystem::AWSCryptoAllocationTag); }; Aws::InitAPI(options); // The creation of S3Client disables virtual addressing: // S3Client(clientConfiguration, signPayloads, useVirtualAddressing = // true) // The purpose is to address the issue encountered when there is an `.` // in the bucket name. Due to TLS hostname validation or DNS rules, // the bucket may not be resolved. Disabling of virtual addressing // should address the issue. See GitHub issue 16397 for details. s3_file->s3_client = Aws::MakeShared<Aws::S3::S3Client>( kS3ClientAllocationTag, GetDefaultClientConfig(), Aws::Client::AWSAuthV4Signer::PayloadSigningPolicy::Never, false); } } static void GetExecutor(tf_s3_filesystem::S3File* s3_file) { absl::MutexLock l(&s3_file->initialization_lock); if (s3_file->executor.get() == nullptr) { s3_file->executor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>( kExecutorTag, kExecutorPoolSize); } } static void GetTransferManager( const Aws::Transfer::TransferDirection& direction, tf_s3_filesystem::S3File* s3_file) { absl::MutexLock l(&s3_file->initialization_lock); if (s3_file->transfer_managers[direction].get() == nullptr) { GetS3Client(s3_file); GetExecutor(s3_file); Aws::Transfer::TransferManagerConfiguration config(s3_file->executor.get()); config.s3Client = s3_file->s3_client; config.bufferSize = s3_file->multi_part_chunk_sizes[direction]; // must be larger than pool size * multi part chunk size config.transferBufferMaxHeapSize = (kExecutorPoolSize + 1) * s3_file->multi_part_chunk_sizes[direction]; s3_file->transfer_managers[direction] = Aws::Transfer::TransferManager::Create(config); } } static void ShutdownClient(Aws::S3::S3Client* s3_client) { if (s3_client != nullptr) { delete s3_client; Aws::SDKOptions options; Aws::ShutdownAPI(options); } } // SECTION 1. Implementation for `TF_RandomAccessFile` // ---------------------------------------------------------------------------- namespace tf_random_access_file { // TODO(vnvo2409): Implement later } // namespace tf_random_access_file // SECTION 2. Implementation for `TF_WritableFile` // ---------------------------------------------------------------------------- namespace tf_writable_file { // TODO(vnvo2409): Implement later } // namespace tf_writable_file // SECTION 3. Implementation for `TF_ReadOnlyMemoryRegion` // ---------------------------------------------------------------------------- namespace tf_read_only_memory_region { // TODO(vnvo2409): Implement later } // namespace tf_read_only_memory_region // SECTION 4. Implementation for `TF_Filesystem`, the actual filesystem // ---------------------------------------------------------------------------- namespace tf_s3_filesystem { S3File::S3File() : s3_client(nullptr, ShutdownClient), executor(nullptr), transfer_managers(), multi_part_chunk_sizes(), use_multi_part_download(true), initialization_lock() { uint64_t temp_value; multi_part_chunk_sizes[Aws::Transfer::TransferDirection::UPLOAD] = absl::SimpleAtoi(getenv("S3_MULTI_PART_UPLOAD_CHUNK_SIZE"), &temp_value) ? temp_value : kS3MultiPartUploadChunkSize; multi_part_chunk_sizes[Aws::Transfer::TransferDirection::DOWNLOAD] = absl::SimpleAtoi(getenv("S3_MULTI_PART_DOWNLOAD_CHUNK_SIZE"), &temp_value) ? temp_value : kS3MultiPartDownloadChunkSize; use_multi_part_download = absl::SimpleAtoi(getenv("S3_DISABLE_MULTI_PART_DOWNLOAD"), &temp_value) ? (temp_value != 1) : use_multi_part_download; transfer_managers.emplace(Aws::Transfer::TransferDirection::UPLOAD, nullptr); transfer_managers.emplace(Aws::Transfer::TransferDirection::DOWNLOAD, nullptr); } void Init(TF_Filesystem* filesystem, TF_Status* status) { filesystem->plugin_filesystem = new S3File(); TF_SetStatus(status, TF_OK, ""); } void Cleanup(TF_Filesystem* filesystem) { auto s3_file = static_cast<S3File*>(filesystem->plugin_filesystem); delete s3_file; } // TODO(vnvo2409): Implement later } // namespace tf_s3_filesystem static void ProvideFilesystemSupportFor(TF_FilesystemPluginOps* ops, const char* uri) { TF_SetFilesystemVersionMetadata(ops); ops->scheme = strdup(uri); } void TF_InitPlugin(TF_FilesystemPluginInfo* info) { info->plugin_memory_allocate = plugin_memory_allocate; info->plugin_memory_free = plugin_memory_free; info->num_schemes = 1; info->ops = static_cast<TF_FilesystemPluginOps*>( plugin_memory_allocate(info->num_schemes * sizeof(info->ops[0]))); ProvideFilesystemSupportFor(&info->ops[0], "s3"); } <|endoftext|>
<commit_before>#include <sstream> #include <vector> #include "extensions/filters/network/redis_proxy/command_splitter_impl.h" #include "test/integration/integration.h" using testing::Return; namespace Envoy { namespace { // This is a basic redis_proxy configuration with a single host // in the cluster. The load balancing policy must be set // to random for proper test operation. const std::string CONFIG = R"EOF( admin: access_log_path: /dev/null address: socket_address: address: 127.0.0.1 port_value: 0 static_resources: listeners: name: listener_0 address: socket_address: address: 127.0.0.1 port_value: 0 filter_chains: filters: name: envoy.redis_proxy config: stat_prefix: redis_stats cluster: cluster_0 settings: op_timeout: 5s clusters: - name: cluster_0 lb_policy: CLUSTER_PROVIDED hosts: - socket_address: address: 127.0.0.1 port_value: 0 cluster_type: name: envoy.clusters.redis typed_config: "@type": type.googleapis.com/google.protobuf.Struct value: cluster_refresh_rate: 1s cluster_refresh_timeout: 4s )EOF"; // This is the basic redis_proxy configuration with an upstream // authentication password specified. const std::string CONFIG_WITH_AUTH = CONFIG + R"EOF( extension_protocol_options: envoy.redis_proxy: { auth_password: { inline_string: somepassword }} )EOF"; // This function encodes commands as an array of bulkstrings as transmitted by Redis clients to // Redis servers, according to the Redis protocol. std::string makeBulkStringArray(std::vector<std::string>&& command_strings) { std::stringstream result; result << "*" << command_strings.size() << "\r\n"; for (uint64_t i = 0; i < command_strings.size(); i++) { result << "$" << command_strings[i].size() << "\r\n"; result << command_strings[i] << "\r\n"; } return result.str(); } class RedisClusterIntegrationTest : public testing::TestWithParam<Network::Address::IpVersion>, public BaseIntegrationTest { public: RedisClusterIntegrationTest(const std::string& config = CONFIG, int num_upstreams = 2) : BaseIntegrationTest(GetParam(), config), num_upstreams_(num_upstreams), version_(GetParam()) {} void TearDown() override { test_server_.reset(); fake_upstreams_.clear(); } void initialize() override { setUpstreamCount(num_upstreams_); setDeterministic(); config_helper_.renameListener("redis_proxy"); // Change the port for each of the discovery host in cluster_0. config_helper_.addConfigModifier([this](envoy::config::bootstrap::v2::Bootstrap& bootstrap) { uint32_t upstream_idx = 0; auto* cluster_0 = bootstrap.mutable_static_resources()->mutable_clusters(0); for (int j = 0; j < cluster_0->hosts_size(); ++j) { if (cluster_0->mutable_hosts(j)->has_socket_address()) { auto* host_socket_addr = cluster_0->mutable_hosts(j)->mutable_socket_address(); RELEASE_ASSERT(fake_upstreams_.size() > upstream_idx, ""); host_socket_addr->set_address( fake_upstreams_[upstream_idx]->localAddress()->ip()->addressAsString()); host_socket_addr->set_port_value( fake_upstreams_[upstream_idx++]->localAddress()->ip()->port()); } } }); BaseIntegrationTest::initialize(); mock_rng_ = dynamic_cast<Runtime::MockRandomGenerator*>(&test_server_->server().random()); // Abort now if we cannot downcast the server's random number generator pointer. ASSERT_TRUE(mock_rng_ != nullptr); // Ensure that fake_upstreams_[0] is the load balancer's host of choice by default. ON_CALL(*mock_rng_, random()).WillByDefault(Return(random_index_)); } protected: /** * A single step of a larger test involving a fake Redis client and a specific Redis server. * @param upstream a handle to the server that will respond to the request. * @param request supplies Redis client data to transmit to the Redis server. * @param response supplies Redis server data to transmit to the client. * @param redis_client a handle to the fake redis client that sends the request. * @param fake_upstream_connection supplies a handle to connection from the proxy to the fake * server. * @param auth_password supplies the fake upstream's server password, if not an empty string. */ void roundtripToUpstreamStep(FakeUpstreamPtr& upstream, const std::string& request, const std::string& response, IntegrationTcpClientPtr& redis_client, FakeRawConnectionPtr& fake_upstream_connection, const std::string& auth_password) { std::string proxy_to_server; bool expect_auth_command = false; std::string ok = "+OK\r\n"; redis_client->clearData(); redis_client->write(request); if (fake_upstream_connection.get() == nullptr) { expect_auth_command = (!auth_password.empty()); EXPECT_TRUE(upstream->waitForRawConnection(fake_upstream_connection)); } if (expect_auth_command) { std::string auth_command = makeBulkStringArray({"auth", auth_password}); EXPECT_TRUE(fake_upstream_connection->waitForData(auth_command.size() + request.size(), &proxy_to_server)); // The original request should be the same as the data received by the server. EXPECT_EQ(auth_command + request, proxy_to_server); // Send back an OK for the auth command. EXPECT_TRUE(fake_upstream_connection->write(ok)); } else { EXPECT_TRUE(fake_upstream_connection->waitForData(request.size(), &proxy_to_server)); // The original request should be the same as the data received by the server. EXPECT_EQ(request, proxy_to_server); } EXPECT_TRUE(fake_upstream_connection->write(response)); redis_client->waitForData(response); // The original response should be received by the fake Redis client. EXPECT_EQ(response, redis_client->data()); } /** * Simple bi-directional test between a fake Redis client and Redis server. * @param request supplies Redis client data to transmit to the Redis server. * @param response supplies Redis server data to transmit to the client. */ void simpleRequestAndResponse(const int stream_index, const std::string& request, const std::string& response) { IntegrationTcpClientPtr redis_client = makeTcpConnection(lookupPort("redis_proxy")); FakeRawConnectionPtr fake_upstream_connection; roundtripToUpstreamStep(fake_upstreams_[stream_index], request, response, redis_client, fake_upstream_connection, ""); redis_client->close(); EXPECT_TRUE(fake_upstream_connection->close()); } void expectCallClusterSlot(int stream_index, std::string& response, const std::string& auth_password = "") { std::string cluster_slot_request = makeBulkStringArray({"CLUSTER", "SLOTS"}); fake_upstreams_[stream_index]->set_allow_unexpected_disconnects(true); std::string proxied_cluster_slot_request; FakeRawConnectionPtr fake_upstream_connection_; EXPECT_TRUE(fake_upstreams_[stream_index]->waitForRawConnection(fake_upstream_connection_)); if (auth_password.empty()) { EXPECT_TRUE(fake_upstream_connection_->waitForData(cluster_slot_request.size(), &proxied_cluster_slot_request)); EXPECT_EQ(cluster_slot_request, proxied_cluster_slot_request); } else { std::string auth_request = makeBulkStringArray({"auth", auth_password}); std::string ok = "+OK\r\n"; EXPECT_TRUE(fake_upstream_connection_->waitForData( auth_request.size() + cluster_slot_request.size(), &proxied_cluster_slot_request)); EXPECT_EQ(auth_request + cluster_slot_request, proxied_cluster_slot_request); EXPECT_TRUE(fake_upstream_connection_->write(ok)); } EXPECT_TRUE(fake_upstream_connection_->write(response)); EXPECT_TRUE(fake_upstream_connection_->close()); } /** * Simple response for a single slot redis cluster with a master and slave. * @param master the ip of the master node. * @param slave the ip of the slave node. * @return The cluster slot response. */ std::string singleSlotMasterSlave(const Network::Address::Ip* master, const Network::Address::Ip* slave) { int64_t start_slot = 0; int64_t end_slot = 16383; std::stringstream resp; resp << "*1\r\n" << "*4\r\n" << ":" << start_slot << "\r\n" << ":" << end_slot << "\r\n" << makeIp(master->addressAsString(), master->port()) << makeIp(slave->addressAsString(), slave->port()); return resp.str(); } /** * Simple response for 2 slot redis cluster with 2 nodes. * @param slot1 the ip of the master node of slot1. * @param slot2 the ip of the master node of slot2. * @return The cluster slot response. */ std::string twoSlots(const Network::Address::Ip* slot1, const Network::Address::Ip* slot2, int64_t start_slot1 = 0, int64_t end_slot1 = 10000, int64_t start_slot2 = 10000, int64_t end_slot2 = 16383) { std::stringstream resp; resp << "*2\r\n" << "*3\r\n" << ":" << start_slot1 << "\r\n" << ":" << end_slot1 << "\r\n" << makeIp(slot1->addressAsString(), slot1->port()) << "*3\r\n" << ":" << start_slot2 << "\r\n" << ":" << end_slot2 << "\r\n" << makeIp(slot2->addressAsString(), slot2->port()); return resp.str(); } std::string makeIp(const std::string& address, uint32_t port) { return fmt::format("*2\r\n${0}\r\n{1}\r\n:{2}\r\n", address.size(), address, port); } Runtime::MockRandomGenerator* mock_rng_{}; const int num_upstreams_; const Network::Address::IpVersion version_; int random_index_; }; class RedisClusterWithAuthIntegrationTest : public RedisClusterIntegrationTest { public: RedisClusterWithAuthIntegrationTest(const std::string& config = CONFIG_WITH_AUTH, int num_upstreams = 2) : RedisClusterIntegrationTest(config, num_upstreams) {} }; INSTANTIATE_TEST_SUITE_P(IpVersions, RedisClusterIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); INSTANTIATE_TEST_SUITE_P(IpVersions, RedisClusterWithAuthIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); // This test sends a simple "get foo" command from a fake // downstream client through the proxy to a fake upstream // Redis cluster with a single slot with master and slave. // The fake server sends a valid response back to the client. // The request and response should make it through the envoy // proxy server code unchanged. TEST_P(RedisClusterIntegrationTest, SingleSlotMasterSlave) { random_index_ = 0; on_server_init_function_ = [this]() { std::string cluster_slot_response = singleSlotMasterSlave( fake_upstreams_[0]->localAddress()->ip(), fake_upstreams_[1]->localAddress()->ip()); expectCallClusterSlot(random_index_, cluster_slot_response); }; initialize(); // foo hashes to slot 12182 which is in upstream 0 simpleRequestAndResponse(0, makeBulkStringArray({"get", "foo"}), "$3\r\nbar\r\n"); } // This test sends a simple "get foo" command from a fake // downstream client through the proxy to a fake upstream // Redis cluster with 2 slots. The fake server sends a valid response // back to the client. The request and response should // make it through the envoy proxy server code unchanged. TEST_P(RedisClusterIntegrationTest, TwoSlot) { random_index_ = 0; on_server_init_function_ = [this]() { std::string cluster_slot_response = twoSlots(fake_upstreams_[0]->localAddress()->ip(), fake_upstreams_[1]->localAddress()->ip()); expectCallClusterSlot(random_index_, cluster_slot_response); }; initialize(); // foobar hashes to slot 12325 which is in upstream 1 simpleRequestAndResponse(1, makeBulkStringArray({"get", "foobar"}), "$3\r\nbar\r\n"); // bar hashes to slot 5061 which is in upstream 0 simpleRequestAndResponse(0, makeBulkStringArray({"get", "bar"}), "$3\r\nbar\r\n"); // foo hashes to slot 12182 which is in upstream 1 simpleRequestAndResponse(1, makeBulkStringArray({"get", "foo"}), "$3\r\nbar\r\n"); } // This test sends a simple "get foo" command from a fake // downstream client through the proxy to a fake upstream // Redis cluster with a single slot with master and slave. // The fake server sends a valid response back to the client. // The request and response should make it through the envoy // proxy server code unchanged. // // In this scenario, the fake server will receive 2 auth commands: // one as part of a topology discovery connection (before sending a // "cluster slots" command), and one to authenticate the connection // that carries the "get foo" request. TEST_P(RedisClusterWithAuthIntegrationTest, SingleSlotMasterSlave) { random_index_ = 0; on_server_init_function_ = [this]() { std::string cluster_slot_response = singleSlotMasterSlave( fake_upstreams_[0]->localAddress()->ip(), fake_upstreams_[1]->localAddress()->ip()); expectCallClusterSlot(0, cluster_slot_response, "somepassword"); }; initialize(); IntegrationTcpClientPtr redis_client = makeTcpConnection(lookupPort("redis_proxy")); FakeRawConnectionPtr fake_upstream_connection; roundtripToUpstreamStep(fake_upstreams_[random_index_], makeBulkStringArray({"get", "foo"}), "$3\r\nbar\r\n", redis_client, fake_upstream_connection, "somepassword"); redis_client->close(); EXPECT_TRUE(fake_upstream_connection->close()); } } // namespace } // namespace Envoy <commit_msg>fix static initialization fiasco (#7684)<commit_after>#include <sstream> #include <vector> #include "common/common/macros.h" #include "extensions/filters/network/redis_proxy/command_splitter_impl.h" #include "test/integration/integration.h" using testing::Return; namespace Envoy { namespace { // This is a basic redis_proxy configuration with a single host // in the cluster. The load balancing policy must be set // to random for proper test operation. const std::string& testConfig() { CONSTRUCT_ON_FIRST_USE(std::string, R"EOF( admin: access_log_path: /dev/null address: socket_address: address: 127.0.0.1 port_value: 0 static_resources: listeners: name: listener_0 address: socket_address: address: 127.0.0.1 port_value: 0 filter_chains: filters: name: envoy.redis_proxy config: stat_prefix: redis_stats cluster: cluster_0 settings: op_timeout: 5s clusters: - name: cluster_0 lb_policy: CLUSTER_PROVIDED hosts: - socket_address: address: 127.0.0.1 port_value: 0 cluster_type: name: envoy.clusters.redis typed_config: "@type": type.googleapis.com/google.protobuf.Struct value: cluster_refresh_rate: 1s cluster_refresh_timeout: 4s )EOF"); } // This is the basic redis_proxy configuration with an upstream // authentication password specified. const std::string& testConfigWithAuth() { CONSTRUCT_ON_FIRST_USE(std::string, testConfig() + R"EOF( extension_protocol_options: envoy.redis_proxy: { auth_password: { inline_string: somepassword }} )EOF"); } // This function encodes commands as an array of bulkstrings as transmitted by Redis clients to // Redis servers, according to the Redis protocol. std::string makeBulkStringArray(std::vector<std::string>&& command_strings) { std::stringstream result; result << "*" << command_strings.size() << "\r\n"; for (uint64_t i = 0; i < command_strings.size(); i++) { result << "$" << command_strings[i].size() << "\r\n"; result << command_strings[i] << "\r\n"; } return result.str(); } class RedisClusterIntegrationTest : public testing::TestWithParam<Network::Address::IpVersion>, public BaseIntegrationTest { public: RedisClusterIntegrationTest(const std::string& config = testConfig(), int num_upstreams = 2) : BaseIntegrationTest(GetParam(), config), num_upstreams_(num_upstreams), version_(GetParam()) {} void TearDown() override { test_server_.reset(); fake_upstreams_.clear(); } void initialize() override { setUpstreamCount(num_upstreams_); setDeterministic(); config_helper_.renameListener("redis_proxy"); // Change the port for each of the discovery host in cluster_0. config_helper_.addConfigModifier([this](envoy::config::bootstrap::v2::Bootstrap& bootstrap) { uint32_t upstream_idx = 0; auto* cluster_0 = bootstrap.mutable_static_resources()->mutable_clusters(0); for (int j = 0; j < cluster_0->hosts_size(); ++j) { if (cluster_0->mutable_hosts(j)->has_socket_address()) { auto* host_socket_addr = cluster_0->mutable_hosts(j)->mutable_socket_address(); RELEASE_ASSERT(fake_upstreams_.size() > upstream_idx, ""); host_socket_addr->set_address( fake_upstreams_[upstream_idx]->localAddress()->ip()->addressAsString()); host_socket_addr->set_port_value( fake_upstreams_[upstream_idx++]->localAddress()->ip()->port()); } } }); BaseIntegrationTest::initialize(); mock_rng_ = dynamic_cast<Runtime::MockRandomGenerator*>(&test_server_->server().random()); // Abort now if we cannot downcast the server's random number generator pointer. ASSERT_TRUE(mock_rng_ != nullptr); // Ensure that fake_upstreams_[0] is the load balancer's host of choice by default. ON_CALL(*mock_rng_, random()).WillByDefault(Return(random_index_)); } protected: /** * A single step of a larger test involving a fake Redis client and a specific Redis server. * @param upstream a handle to the server that will respond to the request. * @param request supplies Redis client data to transmit to the Redis server. * @param response supplies Redis server data to transmit to the client. * @param redis_client a handle to the fake redis client that sends the request. * @param fake_upstream_connection supplies a handle to connection from the proxy to the fake * server. * @param auth_password supplies the fake upstream's server password, if not an empty string. */ void roundtripToUpstreamStep(FakeUpstreamPtr& upstream, const std::string& request, const std::string& response, IntegrationTcpClientPtr& redis_client, FakeRawConnectionPtr& fake_upstream_connection, const std::string& auth_password) { std::string proxy_to_server; bool expect_auth_command = false; std::string ok = "+OK\r\n"; redis_client->clearData(); redis_client->write(request); if (fake_upstream_connection.get() == nullptr) { expect_auth_command = (!auth_password.empty()); EXPECT_TRUE(upstream->waitForRawConnection(fake_upstream_connection)); } if (expect_auth_command) { std::string auth_command = makeBulkStringArray({"auth", auth_password}); EXPECT_TRUE(fake_upstream_connection->waitForData(auth_command.size() + request.size(), &proxy_to_server)); // The original request should be the same as the data received by the server. EXPECT_EQ(auth_command + request, proxy_to_server); // Send back an OK for the auth command. EXPECT_TRUE(fake_upstream_connection->write(ok)); } else { EXPECT_TRUE(fake_upstream_connection->waitForData(request.size(), &proxy_to_server)); // The original request should be the same as the data received by the server. EXPECT_EQ(request, proxy_to_server); } EXPECT_TRUE(fake_upstream_connection->write(response)); redis_client->waitForData(response); // The original response should be received by the fake Redis client. EXPECT_EQ(response, redis_client->data()); } /** * Simple bi-directional test between a fake Redis client and Redis server. * @param request supplies Redis client data to transmit to the Redis server. * @param response supplies Redis server data to transmit to the client. */ void simpleRequestAndResponse(const int stream_index, const std::string& request, const std::string& response) { IntegrationTcpClientPtr redis_client = makeTcpConnection(lookupPort("redis_proxy")); FakeRawConnectionPtr fake_upstream_connection; roundtripToUpstreamStep(fake_upstreams_[stream_index], request, response, redis_client, fake_upstream_connection, ""); redis_client->close(); EXPECT_TRUE(fake_upstream_connection->close()); } void expectCallClusterSlot(int stream_index, std::string& response, const std::string& auth_password = "") { std::string cluster_slot_request = makeBulkStringArray({"CLUSTER", "SLOTS"}); fake_upstreams_[stream_index]->set_allow_unexpected_disconnects(true); std::string proxied_cluster_slot_request; FakeRawConnectionPtr fake_upstream_connection_; EXPECT_TRUE(fake_upstreams_[stream_index]->waitForRawConnection(fake_upstream_connection_)); if (auth_password.empty()) { EXPECT_TRUE(fake_upstream_connection_->waitForData(cluster_slot_request.size(), &proxied_cluster_slot_request)); EXPECT_EQ(cluster_slot_request, proxied_cluster_slot_request); } else { std::string auth_request = makeBulkStringArray({"auth", auth_password}); std::string ok = "+OK\r\n"; EXPECT_TRUE(fake_upstream_connection_->waitForData( auth_request.size() + cluster_slot_request.size(), &proxied_cluster_slot_request)); EXPECT_EQ(auth_request + cluster_slot_request, proxied_cluster_slot_request); EXPECT_TRUE(fake_upstream_connection_->write(ok)); } EXPECT_TRUE(fake_upstream_connection_->write(response)); EXPECT_TRUE(fake_upstream_connection_->close()); } /** * Simple response for a single slot redis cluster with a master and slave. * @param master the ip of the master node. * @param slave the ip of the slave node. * @return The cluster slot response. */ std::string singleSlotMasterSlave(const Network::Address::Ip* master, const Network::Address::Ip* slave) { int64_t start_slot = 0; int64_t end_slot = 16383; std::stringstream resp; resp << "*1\r\n" << "*4\r\n" << ":" << start_slot << "\r\n" << ":" << end_slot << "\r\n" << makeIp(master->addressAsString(), master->port()) << makeIp(slave->addressAsString(), slave->port()); return resp.str(); } /** * Simple response for 2 slot redis cluster with 2 nodes. * @param slot1 the ip of the master node of slot1. * @param slot2 the ip of the master node of slot2. * @return The cluster slot response. */ std::string twoSlots(const Network::Address::Ip* slot1, const Network::Address::Ip* slot2, int64_t start_slot1 = 0, int64_t end_slot1 = 10000, int64_t start_slot2 = 10000, int64_t end_slot2 = 16383) { std::stringstream resp; resp << "*2\r\n" << "*3\r\n" << ":" << start_slot1 << "\r\n" << ":" << end_slot1 << "\r\n" << makeIp(slot1->addressAsString(), slot1->port()) << "*3\r\n" << ":" << start_slot2 << "\r\n" << ":" << end_slot2 << "\r\n" << makeIp(slot2->addressAsString(), slot2->port()); return resp.str(); } std::string makeIp(const std::string& address, uint32_t port) { return fmt::format("*2\r\n${0}\r\n{1}\r\n:{2}\r\n", address.size(), address, port); } Runtime::MockRandomGenerator* mock_rng_{}; const int num_upstreams_; const Network::Address::IpVersion version_; int random_index_; }; class RedisClusterWithAuthIntegrationTest : public RedisClusterIntegrationTest { public: RedisClusterWithAuthIntegrationTest(const std::string& config = testConfigWithAuth(), int num_upstreams = 2) : RedisClusterIntegrationTest(config, num_upstreams) {} }; INSTANTIATE_TEST_SUITE_P(IpVersions, RedisClusterIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); INSTANTIATE_TEST_SUITE_P(IpVersions, RedisClusterWithAuthIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); // This test sends a simple "get foo" command from a fake // downstream client through the proxy to a fake upstream // Redis cluster with a single slot with master and slave. // The fake server sends a valid response back to the client. // The request and response should make it through the envoy // proxy server code unchanged. TEST_P(RedisClusterIntegrationTest, SingleSlotMasterSlave) { random_index_ = 0; on_server_init_function_ = [this]() { std::string cluster_slot_response = singleSlotMasterSlave( fake_upstreams_[0]->localAddress()->ip(), fake_upstreams_[1]->localAddress()->ip()); expectCallClusterSlot(random_index_, cluster_slot_response); }; initialize(); // foo hashes to slot 12182 which is in upstream 0 simpleRequestAndResponse(0, makeBulkStringArray({"get", "foo"}), "$3\r\nbar\r\n"); } // This test sends a simple "get foo" command from a fake // downstream client through the proxy to a fake upstream // Redis cluster with 2 slots. The fake server sends a valid response // back to the client. The request and response should // make it through the envoy proxy server code unchanged. TEST_P(RedisClusterIntegrationTest, TwoSlot) { random_index_ = 0; on_server_init_function_ = [this]() { std::string cluster_slot_response = twoSlots(fake_upstreams_[0]->localAddress()->ip(), fake_upstreams_[1]->localAddress()->ip()); expectCallClusterSlot(random_index_, cluster_slot_response); }; initialize(); // foobar hashes to slot 12325 which is in upstream 1 simpleRequestAndResponse(1, makeBulkStringArray({"get", "foobar"}), "$3\r\nbar\r\n"); // bar hashes to slot 5061 which is in upstream 0 simpleRequestAndResponse(0, makeBulkStringArray({"get", "bar"}), "$3\r\nbar\r\n"); // foo hashes to slot 12182 which is in upstream 1 simpleRequestAndResponse(1, makeBulkStringArray({"get", "foo"}), "$3\r\nbar\r\n"); } // This test sends a simple "get foo" command from a fake // downstream client through the proxy to a fake upstream // Redis cluster with a single slot with master and slave. // The fake server sends a valid response back to the client. // The request and response should make it through the envoy // proxy server code unchanged. // // In this scenario, the fake server will receive 2 auth commands: // one as part of a topology discovery connection (before sending a // "cluster slots" command), and one to authenticate the connection // that carries the "get foo" request. TEST_P(RedisClusterWithAuthIntegrationTest, SingleSlotMasterSlave) { random_index_ = 0; on_server_init_function_ = [this]() { std::string cluster_slot_response = singleSlotMasterSlave( fake_upstreams_[0]->localAddress()->ip(), fake_upstreams_[1]->localAddress()->ip()); expectCallClusterSlot(0, cluster_slot_response, "somepassword"); }; initialize(); IntegrationTcpClientPtr redis_client = makeTcpConnection(lookupPort("redis_proxy")); FakeRawConnectionPtr fake_upstream_connection; roundtripToUpstreamStep(fake_upstreams_[random_index_], makeBulkStringArray({"get", "foo"}), "$3\r\nbar\r\n", redis_client, fake_upstream_connection, "somepassword"); redis_client->close(); EXPECT_TRUE(fake_upstream_connection->close()); } } // namespace } // namespace Envoy <|endoftext|>
<commit_before>/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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. =========================================================================*/ // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) #include "itkImageRegionConstIteratorWithIndex.h" #include "itkImageRegionConstIterator.h" // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) #include "mvdVectorImageModel.h" namespace mvd { /* TRANSLATOR mvd::VectorImageModel Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*******************************************************************************/ VectorImageModel ::VectorImageModel( QObject* parent ) : AbstractImageModel( parent ), m_RasterizedBuffer( NULL ), m_PreviousRegion(ImageRegionType()) { } /*******************************************************************************/ VectorImageModel ::~VectorImageModel() { this->ClearBuffer(); } /*******************************************************************************/ void VectorImageModel ::loadFile( const QString& filename ) { DefaultImageFileReaderType::Pointer imageFileReader( DefaultImageFileReaderType::New() ); imageFileReader->SetFileName( filename.toLatin1().data() ); imageFileReader->UpdateOutputInformation(); m_ImageFileReader = imageFileReader; // initialize the channel list for the rendering needs following the // input image // TODO : See if if needs to be moved somewhere else // TODO : use the default display if (m_ImageFileReader->GetOutput()->GetNumberOfComponentsPerPixel() < 3) { m_Channels.resize(1); m_Channels[0] = 0; } else { m_Channels.resize(3); m_Channels[0] = 0; m_Channels[1] = 1; m_Channels[2] = 2; } } void VectorImageModel ::ClearBuffer() { // Delete previous buffer if needed if (m_RasterizedBuffer != NULL) { delete[] m_RasterizedBuffer; m_RasterizedBuffer = NULL; } } unsigned char * VectorImageModel ::RasterizeRegion( const ImageRegionType& region) { m_Region = region; // Don't do anything if the region did not changed // moveMoveEvent (Drag region). if ( m_PreviousRegion != region ) { // check the current and the previous region have some pixels in // common ImageRegionType tempPreviousRegionRegion = m_PreviousRegion; bool res = tempPreviousRegionRegion.Crop(region); // if the first time, image must be read if ( m_PreviousRegion != ImageRegionType() && res) { // Compute loaeded region, and region not loaded yet within the // new requested region this->ComputeRegionsToLoad(m_Region); // Copy the previous buffer into a temporary buf to get the // previously loaded data unsigned char * previousRasterizedBuffer = new unsigned char[3 * m_PreviousRegion.GetNumberOfPixels()]; std::memcpy(previousRasterizedBuffer, m_RasterizedBuffer, 3 * m_PreviousRegion.GetNumberOfPixels()); // Clear the previous buffer this->ClearBuffer(); // Allocate new memory unsigned int nbPixels = 3 * region.GetNumberOfPixels(); m_RasterizedBuffer = new unsigned char[nbPixels]; // Copy the already loaded pixels into the m_RasterizedBuffer unsigned int previousNbPixels = m_PreviousRegion.GetNumberOfPixels(); for (unsigned int idx = 0; idx < previousNbPixels; idx++) { // compose the image index from the buffer index IndexType imageIndex; imageIndex = ComputeImageIndexFromFlippedBuffer(idx, m_PreviousRegion); if (m_AlreadyLoadedRegion.IsInside(imageIndex)) { // Get the buffer index relative to the imageIndex in the // new requested region unsigned int newBufferindex = 0; newBufferindex = ComputeXAxisFlippedBufferIndex(imageIndex, m_Region); // Copy the already loaded values into the new buffer m_RasterizedBuffer[newBufferindex] = previousRasterizedBuffer[3*idx]; m_RasterizedBuffer[newBufferindex + 1] = previousRasterizedBuffer[3*idx + 1]; m_RasterizedBuffer[newBufferindex + 2] = previousRasterizedBuffer[3*idx + 2]; } } // Get the image pixels within not loaded region and add them to // the buffer for (unsigned int idx = 0; idx < m_RegionsToLoadVector.size() ; idx++) { this->DumpImagePixelsWithinRegionIntoBuffer(m_RegionsToLoadVector[idx]); } // free the previous buffer memory (copied one) if (previousRasterizedBuffer != NULL) { delete[] previousRasterizedBuffer; previousRasterizedBuffer = NULL; } } else { // Delete previous buffer if needed this->ClearBuffer(); // Allocate new memory m_RasterizedBuffer = new unsigned char[3 * region.GetNumberOfPixels()]; // rasterize the region this->DumpImagePixelsWithinRegionIntoBuffer(region); } } // Store the region m_PreviousRegion = region; // if ok return the buffer return m_RasterizedBuffer; } void VectorImageModel ::DumpImagePixelsWithinRegionIntoBuffer(const ImageRegionType& region) { // Before doing anything, check if region is inside the buffered // region of image unsigned int currentIndex = 0; // TODO : add some checking const DefaultImageType* image = this->GetOutput(currentIndex); // some checking if (!image->GetBufferedRegion().IsInside(region)) { //itkExceptionMacro(<< "Region to read is oustside of the buffered region."); } // Extract the region of interest in the image m_ExtractFilter = ExtractFilterType::New(); m_ExtractFilter->SetInput(image); m_ExtractFilter->SetExtractionRegion(region); // Use the rendering filter to get m_RenderingFilter = RenderingFilterType::New(); m_RenderingFilter->SetInput(m_ExtractFilter->GetOutput()); m_RenderingFilter->GetRenderingFunction()->SetAutoMinMax(false); m_RenderingFilter->GetRenderingFunction()->SetChannelList(m_Channels); m_RenderingFilter->GetOutput()->SetRequestedRegion(region); m_RenderingFilter->Update(); // Declare the iterator itk::ImageRegionConstIteratorWithIndex< RenderingFilterType::OutputImageType > it(m_RenderingFilter->GetOutput(), region); // Go to begin it.GoToBegin(); while (!it.IsAtEnd()) { // Fill the buffer unsigned int index = 0; index = ComputeXAxisFlippedBufferIndex(it.GetIndex(), m_Region); // Fill the buffer m_RasterizedBuffer[index] = it.Get()[0]; m_RasterizedBuffer[index + 1] = it.Get()[1]; m_RasterizedBuffer[index + 2] = it.Get()[2]; ++it; } } void VectorImageModel ::ComputeRegionsToLoad(const ImageRegionType& region) { // Initialize the region and clear vector m_AlreadyLoadedRegion = m_PreviousRegion; m_RegionsToLoadVector.clear(); // 4 regions to compute ImageRegionType upperRegion; ImageRegionType lowerRegion; ImageRegionType leftRegion; ImageRegionType rightRegion; // local variables IndexType index; ImageRegionType::SizeType size; // Compute the already loaded region as a simple Crop bool res = m_AlreadyLoadedRegion.Crop(region); // ------ upper region upperRegion.SetIndex(region.GetIndex()); size[0] = region.GetSize()[0]; size[1] = vcl_abs( region.GetIndex()[1] - m_AlreadyLoadedRegion.GetIndex()[1]); upperRegion.SetSize(size); // ------ lower region index[0] = region.GetIndex()[0]; index[1] = m_AlreadyLoadedRegion.GetSize()[1] + m_AlreadyLoadedRegion.GetIndex()[1]; lowerRegion.SetIndex(index); size[0] = region.GetSize()[0]; size[1] = vcl_abs( region.GetIndex()[1] + region.GetSize()[1] - m_AlreadyLoadedRegion.GetIndex()[1] - m_AlreadyLoadedRegion.GetSize()[1] ); lowerRegion.SetSize(size); // ------- left region index[0] = region.GetIndex()[0]; index[1] = m_AlreadyLoadedRegion.GetIndex()[1]; leftRegion.SetIndex(index); size[0] = vcl_abs(region.GetIndex(0) - m_AlreadyLoadedRegion.GetIndex()[0]); size[1] = m_AlreadyLoadedRegion.GetSize()[1]; leftRegion.SetSize(size); // -------- right region index[0] = m_AlreadyLoadedRegion.GetIndex()[0] + m_AlreadyLoadedRegion.GetSize()[0]; index[1] = m_AlreadyLoadedRegion.GetIndex()[1]; rightRegion.SetIndex(index); size[0] = vcl_abs(region.GetSize()[0] + region.GetIndex()[0] - m_AlreadyLoadedRegion.GetIndex()[0] - m_AlreadyLoadedRegion.GetSize()[0]); size[1] = m_AlreadyLoadedRegion.GetSize()[1]; rightRegion.SetSize(size); // add the upper region if any pixel if ( upperRegion .GetNumberOfPixels() > 0 ) m_RegionsToLoadVector.push_back(upperRegion); // add the lower region if any pixel if ( lowerRegion.GetNumberOfPixels() > 0 ) m_RegionsToLoadVector.push_back(lowerRegion); // add the left region if any pixel if ( leftRegion.GetNumberOfPixels() > 0 ) m_RegionsToLoadVector.push_back(leftRegion); // add the right region if any pixel if ( rightRegion.GetNumberOfPixels() > 0 ) m_RegionsToLoadVector.push_back(rightRegion); } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ /*******************************************************************************/ } // end namespace 'mvd' <commit_msg>ENH: unnecessary include<commit_after>/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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. =========================================================================*/ // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) #include "itkImageRegionConstIteratorWithIndex.h" // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) #include "mvdVectorImageModel.h" namespace mvd { /* TRANSLATOR mvd::VectorImageModel Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*******************************************************************************/ VectorImageModel ::VectorImageModel( QObject* parent ) : AbstractImageModel( parent ), m_RasterizedBuffer( NULL ), m_PreviousRegion(ImageRegionType()) { } /*******************************************************************************/ VectorImageModel ::~VectorImageModel() { this->ClearBuffer(); } /*******************************************************************************/ void VectorImageModel ::loadFile( const QString& filename ) { DefaultImageFileReaderType::Pointer imageFileReader( DefaultImageFileReaderType::New() ); imageFileReader->SetFileName( filename.toLatin1().data() ); imageFileReader->UpdateOutputInformation(); m_ImageFileReader = imageFileReader; // initialize the channel list for the rendering needs following the // input image // TODO : See if if needs to be moved somewhere else // TODO : use the default display if (m_ImageFileReader->GetOutput()->GetNumberOfComponentsPerPixel() < 3) { m_Channels.resize(1); m_Channels[0] = 0; } else { m_Channels.resize(3); m_Channels[0] = 0; m_Channels[1] = 1; m_Channels[2] = 2; } } void VectorImageModel ::ClearBuffer() { // Delete previous buffer if needed if (m_RasterizedBuffer != NULL) { delete[] m_RasterizedBuffer; m_RasterizedBuffer = NULL; } } unsigned char * VectorImageModel ::RasterizeRegion( const ImageRegionType& region) { m_Region = region; // Don't do anything if the region did not changed // moveMoveEvent (Drag region). if ( m_PreviousRegion != region ) { // check the current and the previous region have some pixels in // common ImageRegionType tempPreviousRegionRegion = m_PreviousRegion; bool res = tempPreviousRegionRegion.Crop(region); // if the first time, image must be read if ( m_PreviousRegion != ImageRegionType() && res) { // Compute loaeded region, and region not loaded yet within the // new requested region this->ComputeRegionsToLoad(m_Region); // Copy the previous buffer into a temporary buf to get the // previously loaded data unsigned char * previousRasterizedBuffer = new unsigned char[3 * m_PreviousRegion.GetNumberOfPixels()]; std::memcpy(previousRasterizedBuffer, m_RasterizedBuffer, 3 * m_PreviousRegion.GetNumberOfPixels()); // Clear the previous buffer this->ClearBuffer(); // Allocate new memory unsigned int nbPixels = 3 * region.GetNumberOfPixels(); m_RasterizedBuffer = new unsigned char[nbPixels]; // Copy the already loaded pixels into the m_RasterizedBuffer unsigned int previousNbPixels = m_PreviousRegion.GetNumberOfPixels(); for (unsigned int idx = 0; idx < previousNbPixels; idx++) { // compose the image index from the buffer index IndexType imageIndex; imageIndex = ComputeImageIndexFromFlippedBuffer(idx, m_PreviousRegion); if (m_AlreadyLoadedRegion.IsInside(imageIndex)) { // Get the buffer index relative to the imageIndex in the // new requested region unsigned int newBufferindex = 0; newBufferindex = ComputeXAxisFlippedBufferIndex(imageIndex, m_Region); // Copy the already loaded values into the new buffer m_RasterizedBuffer[newBufferindex] = previousRasterizedBuffer[3*idx]; m_RasterizedBuffer[newBufferindex + 1] = previousRasterizedBuffer[3*idx + 1]; m_RasterizedBuffer[newBufferindex + 2] = previousRasterizedBuffer[3*idx + 2]; } } // Get the image pixels within not loaded region and add them to // the buffer for (unsigned int idx = 0; idx < m_RegionsToLoadVector.size() ; idx++) { this->DumpImagePixelsWithinRegionIntoBuffer(m_RegionsToLoadVector[idx]); } // free the previous buffer memory (copied one) if (previousRasterizedBuffer != NULL) { delete[] previousRasterizedBuffer; previousRasterizedBuffer = NULL; } } else { // Delete previous buffer if needed this->ClearBuffer(); // Allocate new memory m_RasterizedBuffer = new unsigned char[3 * region.GetNumberOfPixels()]; // rasterize the region this->DumpImagePixelsWithinRegionIntoBuffer(region); } } // Store the region m_PreviousRegion = region; // if ok return the buffer return m_RasterizedBuffer; } void VectorImageModel ::DumpImagePixelsWithinRegionIntoBuffer(const ImageRegionType& region) { // Before doing anything, check if region is inside the buffered // region of image unsigned int currentIndex = 0; // TODO : add some checking const DefaultImageType* image = this->GetOutput(currentIndex); // some checking if (!image->GetBufferedRegion().IsInside(region)) { //itkExceptionMacro(<< "Region to read is oustside of the buffered region."); } // Extract the region of interest in the image m_ExtractFilter = ExtractFilterType::New(); m_ExtractFilter->SetInput(image); m_ExtractFilter->SetExtractionRegion(region); // Use the rendering filter to get m_RenderingFilter = RenderingFilterType::New(); m_RenderingFilter->SetInput(m_ExtractFilter->GetOutput()); m_RenderingFilter->GetRenderingFunction()->SetAutoMinMax(false); m_RenderingFilter->GetRenderingFunction()->SetChannelList(m_Channels); m_RenderingFilter->GetOutput()->SetRequestedRegion(region); m_RenderingFilter->Update(); // Declare the iterator itk::ImageRegionConstIteratorWithIndex< RenderingFilterType::OutputImageType > it(m_RenderingFilter->GetOutput(), region); // Go to begin it.GoToBegin(); while (!it.IsAtEnd()) { // Fill the buffer unsigned int index = 0; index = ComputeXAxisFlippedBufferIndex(it.GetIndex(), m_Region); // Fill the buffer m_RasterizedBuffer[index] = it.Get()[0]; m_RasterizedBuffer[index + 1] = it.Get()[1]; m_RasterizedBuffer[index + 2] = it.Get()[2]; ++it; } } void VectorImageModel ::ComputeRegionsToLoad(const ImageRegionType& region) { // Initialize the region and clear vector m_AlreadyLoadedRegion = m_PreviousRegion; m_RegionsToLoadVector.clear(); // 4 regions to compute ImageRegionType upperRegion; ImageRegionType lowerRegion; ImageRegionType leftRegion; ImageRegionType rightRegion; // local variables IndexType index; ImageRegionType::SizeType size; // Compute the already loaded region as a simple Crop bool res = m_AlreadyLoadedRegion.Crop(region); // ------ upper region upperRegion.SetIndex(region.GetIndex()); size[0] = region.GetSize()[0]; size[1] = vcl_abs( region.GetIndex()[1] - m_AlreadyLoadedRegion.GetIndex()[1]); upperRegion.SetSize(size); // ------ lower region index[0] = region.GetIndex()[0]; index[1] = m_AlreadyLoadedRegion.GetSize()[1] + m_AlreadyLoadedRegion.GetIndex()[1]; lowerRegion.SetIndex(index); size[0] = region.GetSize()[0]; size[1] = vcl_abs( region.GetIndex()[1] + region.GetSize()[1] - m_AlreadyLoadedRegion.GetIndex()[1] - m_AlreadyLoadedRegion.GetSize()[1] ); lowerRegion.SetSize(size); // ------- left region index[0] = region.GetIndex()[0]; index[1] = m_AlreadyLoadedRegion.GetIndex()[1]; leftRegion.SetIndex(index); size[0] = vcl_abs(region.GetIndex(0) - m_AlreadyLoadedRegion.GetIndex()[0]); size[1] = m_AlreadyLoadedRegion.GetSize()[1]; leftRegion.SetSize(size); // -------- right region index[0] = m_AlreadyLoadedRegion.GetIndex()[0] + m_AlreadyLoadedRegion.GetSize()[0]; index[1] = m_AlreadyLoadedRegion.GetIndex()[1]; rightRegion.SetIndex(index); size[0] = vcl_abs(region.GetSize()[0] + region.GetIndex()[0] - m_AlreadyLoadedRegion.GetIndex()[0] - m_AlreadyLoadedRegion.GetSize()[0]); size[1] = m_AlreadyLoadedRegion.GetSize()[1]; rightRegion.SetSize(size); // add the upper region if any pixel if ( upperRegion .GetNumberOfPixels() > 0 ) m_RegionsToLoadVector.push_back(upperRegion); // add the lower region if any pixel if ( lowerRegion.GetNumberOfPixels() > 0 ) m_RegionsToLoadVector.push_back(lowerRegion); // add the left region if any pixel if ( leftRegion.GetNumberOfPixels() > 0 ) m_RegionsToLoadVector.push_back(leftRegion); // add the right region if any pixel if ( rightRegion.GetNumberOfPixels() > 0 ) m_RegionsToLoadVector.push_back(rightRegion); } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ /*******************************************************************************/ } // end namespace 'mvd' <|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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {ROISpot5.png}, {ROISpot5Moving.png} // OUTPUTS: {SIFTResampling.png} // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example demonstrates the use of the // \doxygen{otb}{KeyPointSetsMatchingFilter} for disparity map // estimation. The idea here is to match SIFTs extracted from both the // fixed and the moving images. The use of SIFTs is demonstrated in // section \ref{sec:SIFTDetector}. The // \doxygen{itk}{DeformationFieldSource} will be used // to generate a deformation field by using // interpolation on the deformation values from the point set. More // advanced methods for deformation field interpolation are also // available. // // The first step toward the use of these filters is to include the // appropriate header files. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbKeyPointSetsMatchingFilter.h" //#include "otbSiftFastImageFilter.h" #include "otbImageToSIFTKeyPointSetFilter.h" // Disabling deprecation warning if on visual #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #include "itkDeformationFieldSource.h" // Enabling remaining deprecation warning #ifdef _MSC_VER #pragma warning(pop) #endif #include "itkWarpImageFilter.h" // Software Guide : EndCodeSnippet #include "otbImage.h" #include "otbMacro.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkPointSet.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbLeastSquareAffineTransformEstimator.h" #include "itkResampleImageFilter.h" int main (int argc, char* argv[]) { if (argc!= 9) { std::cerr <<"Usage: "<<argv[0]; std::cerr<<"fixedFileName movingFileName resamplingImageFileName octaves scales threshold ratio secondOrderThreshold" << std::endl; return EXIT_FAILURE; } const char * fixedfname = argv[1]; const char * movingfname = argv[2]; const char * outputImageFilename = argv[3]; const unsigned int octaves = atoi(argv[4]); const unsigned int scales = atoi(argv[5]); float threshold = atof(argv[6]); float ratio = atof(argv[7]); const double secondOrderThreshold = atof(argv[8]); const unsigned int Dimension = 2; // Software Guide : BeginLatex // // Then we must decide what pixel type to use for the image. We choose to do // all the computations in floating point precision and rescale the results // between 0 and 255 in order to export PNG images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef double RealType; typedef unsigned char OutputPixelType; typedef otb::Image<RealType,Dimension> ImageType; typedef otb::Image<OutputPixelType,Dimension> OutputImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The SIFTs obtained for the matching will be stored in vector // form inside a point set. So we need the following types: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::VariableLengthVector<RealType> RealVectorType; typedef itk::PointSet<RealVectorType,Dimension> PointSetType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The filter for computing the SIFTs has a type defined as follows: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet //typedef otb::SiftFastImageFilter<ImageType,PointSetType> //ImageToSIFTKeyPointSetFilterType; typedef otb::ImageToSIFTKeyPointSetFilter<ImageType,PointSetType> ImageToSIFTKeyPointSetFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Although many choices for evaluating the distances during the // matching procedure exist, we choose here to use a simple // Euclidean distance. We can then define the type for the matching filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Statistics::EuclideanDistance<RealVectorType> DistanceType; typedef otb::KeyPointSetsMatchingFilter<PointSetType, DistanceType> EuclideanDistanceMatchingFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The following types are needed for dealing with the matched points. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef PointSetType::PointType PointType; typedef std::pair<PointType,PointType> MatchType; typedef std::vector<MatchType> MatchVectorType; typedef EuclideanDistanceMatchingFilterType::LandmarkListType LandmarkListType; typedef PointSetType::PointsContainer PointsContainerType; typedef PointsContainerType::Iterator PointsIteratorType; typedef PointSetType::PointDataContainer PointDataContainerType; typedef PointDataContainerType::Iterator PointDataIteratorType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We define the type for the image reader. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::ImageFileReader<ImageType> ReaderType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Two readers are instantiated : one for the fixed image, and one // for the moving image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer fixedReader = ReaderType::New(); ReaderType::Pointer movingReader = ReaderType::New(); fixedReader->SetFileName(fixedfname); movingReader->SetFileName(movingfname); fixedReader->UpdateOutputInformation(); movingReader->UpdateOutputInformation(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We will now instantiate the 2 SIFT filters and the filter used // for the matching of the points. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ImageToSIFTKeyPointSetFilterType::Pointer filter1 = ImageToSIFTKeyPointSetFilterType::New(); ImageToSIFTKeyPointSetFilterType::Pointer filter2 = ImageToSIFTKeyPointSetFilterType::New(); EuclideanDistanceMatchingFilterType::Pointer euclideanMatcher = EuclideanDistanceMatchingFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We plug the pipeline and set the parameters. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet bool useBackMatching = 0; filter1->SetInput( fixedReader->GetOutput() ); //filter1->SetScalesNumber(3); filter2->SetInput( movingReader->GetOutput() ); //filter2->SetScalesNumber(3); // Software Guide : BeginCodeSnippet filter1->SetOctavesNumber(octaves); filter1->SetScalesNumber(scales); filter1->SetDoGThreshold(threshold); filter1->SetEdgeThreshold(ratio); filter2->SetOctavesNumber(octaves); filter2->SetScalesNumber(scales); filter2->SetDoGThreshold(threshold); filter2->SetEdgeThreshold(ratio); // Software Guide : EndCodeSnippet std::cout << "SIFT process fixed image" << std::endl; filter1->Update(); std::cout << "SIFT process moving image" << std::endl; filter2->Update(); //filter1->SetNumberOfThreads(1); //filter2->SetNumberOfThreads(1); //Take the minimum point set to compute euclidian diff (vector lengths must be equal) PointSetType::Pointer ptSet1 = filter1->GetOutput(); PointSetType::Pointer ptSet2 = filter2->GetOutput(); typedef PointSetType::PointsContainer PointsContainer; PointsContainer::Pointer ptContainer1,ptContainer2; //Save point container to extract 2 points container with size = min (container1, container2) //TODO simplify subset selection in this itk::PointSet ptContainer1 = ptSet1->GetPoints(); ptContainer2 = ptSet2->GetPoints(); if ( ptSet1->GetNumberOfPoints() > ptSet2->GetNumberOfPoints() ) { ptContainer1 = ptSet2->GetPoints(); ptContainer2 = ptSet1->GetPoints(); } PointsContainer::Pointer ptContainerRes = PointsContainer::New(); typedef PointsContainer::Iterator PointsIterator; PointsIterator pointsIterator = ptContainer2->Begin(); //Construct new point container (subset of input pointset) for (unsigned int id=0;id < ptContainer1->Size();++id) { ptContainerRes->InsertElement(id, pointsIterator->Value()); ++pointsIterator; } if ( ptSet1->GetNumberOfPoints() > ptSet2->GetNumberOfPoints() ) { ptSet1->SetPoints(ptContainerRes); } else { ptSet2->SetPoints(ptContainerRes); } std::cout << "SIFT points size" << std::endl; std::cout << ptSet1->GetNumberOfPoints() << std::endl; std::cout << ptSet2->GetNumberOfPoints() << std::endl; //euclideanMatcher->SetInput1(ptSet1); //euclideanMatcher->SetInput2(ptSet2); euclideanMatcher->SetInput1(filter1->GetOutput()); euclideanMatcher->SetInput2(filter2->GetOutput()); euclideanMatcher->SetDistanceThreshold(secondOrderThreshold); euclideanMatcher->SetUseBackMatching(useBackMatching); std::cout << "Update euclidian distance" << std::endl; euclideanMatcher->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The matched points will be stored into a landmark list. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LandmarkListType::Pointer landmarkList; landmarkList = euclideanMatcher->GetOutput(); std::cout << "Get landmark" << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Apply Mean square algorithm // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Point<double,2> MyPointType; typedef otb::LeastSquareAffineTransformEstimator<MyPointType> EstimatorType; // instantiation EstimatorType::Pointer estimator = EstimatorType::New(); std::cout << "landmark list size " << landmarkList->Size() << std::endl; for (LandmarkListType::Iterator it = landmarkList->Begin(); it != landmarkList->End(); ++it) { //otbMsgDevMacro(<<"landmark1" << it.Get()->GetPoint1() ); //otbMsgDevMacro(<<"landmark2" << it.Get()->GetPoint2() ); std::cout << "landmark1" << it.Get()->GetPoint1() << std::endl; std::cout << "landmark2" << it.Get()->GetPoint2() << std::endl; estimator->AddTiePoints(it.Get()->GetPoint1(),it.Get()->GetPoint2()); } // Trigger computation estimator->Compute(); // meanSquarestimator->SetInput(euclideanMatcher->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Resample the initial image with the transformation evaluated // // Software Guide : EndLatex // Software Guide : BeginLatex // // It is common, as the last step of a registration task, to use // the resulting transform to map the moving image into the fixed // image space. This is easily done with the // \doxygen{itk}{ResampleImageFilter}. First, a ResampleImageFilter // type is instantiated using the image types. It is convenient to // use the fixed image type as the output type since it is likely // that the transformed moving image will be compared with the // fixed image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ResampleImageFilter< ImageType, OutputImageType > ResampleFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // A resampling filter is created and the moving image is connected as // its input. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetInput( movingReader->GetOutput() ); //typedef itk::ImageRegistrationMethod< //ImageType, //ImageType > RegistrationType; //RegistrationType::Pointer registration = RegistrationType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The Transform that is produced as output need to be inversed to // We apply here the resampling algorithm to the "fixed" image // to produce the moving image. Or apply to the moving image // // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // Get the output transform typedef EstimatorType::AffineTransformType AffineTransformType; AffineTransformType::Pointer transform = AffineTransformType::New(); transform->GetInverse( estimator->GetAffineTransform() ); resampler->SetTransform( transform ); resampler->SetSize( fixedReader->GetOutput()->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( fixedReader->GetOutput()->GetOrigin() ); resampler->SetOutputSpacing( fixedReader->GetOutput()->GetSpacing() ); resampler->SetDefaultPixelValue( 100 ); // Software Guide : EndCodeSnippet typedef otb::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( resampler->GetOutput() ); writer->SetFileName( outputImageFilename ); writer->Update(); return EXIT_SUCCESS; } <commit_msg>DOC:sift example<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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {ROISpot5.png}, {ROISpot5Moving.png} // OUTPUTS: {SIFTResampling.png} // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example demonstrates the use of the // \doxygen{otb}{KeyPointSetsMatchingFilter} for transformation // estimation between 2 images. The idea here is to match SIFTs extracted from both the // fixed and the moving images. The use of SIFTs is demonstrated in // section \ref{sec:SIFTDetector}. The // \doxygen{otb}{LeastSquareAffineTransformEstimator} will be used // to generate a transformation field by using // mean square optimisation to estimate // an affine transfrom from the point set. // // The first step toward the use of these filters is to include the // appropriate header files. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbKeyPointSetsMatchingFilter.h" #include "otbImageToSIFTKeyPointSetFilter.h" // Disabling deprecation warning if on visual #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #include "itkDeformationFieldSource.h" // Enabling remaining deprecation warning #ifdef _MSC_VER #pragma warning(pop) #endif // Software Guide : EndCodeSnippet #include "otbImage.h" #include "otbMacro.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "itkPointSet.h" #include "otbLeastSquareAffineTransformEstimator.h" #include "itkResampleImageFilter.h" int main (int argc, char* argv[]) { if (argc!= 9) { std::cerr <<"Usage: "<<argv[0]; std::cerr<<"fixedFileName movingFileName resamplingImageFileName octaves scales threshold ratio secondOrderThreshold" << std::endl; return EXIT_FAILURE; } const char * fixedfname = argv[1]; const char * movingfname = argv[2]; const char * outputImageFilename = argv[3]; const unsigned int octaves = atoi(argv[4]); const unsigned int scales = atoi(argv[5]); float threshold = atof(argv[6]); float ratio = atof(argv[7]); const double secondOrderThreshold = atof(argv[8]); const unsigned int Dimension = 2; // Software Guide : BeginLatex // // Then we must decide what pixel type to use for the image. We choose to do // all the computations in floating point precision and rescale the results // between 0 and 255 in order to export PNG images. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef double RealType; typedef unsigned char OutputPixelType; typedef otb::Image<RealType,Dimension> ImageType; typedef otb::Image<OutputPixelType,Dimension> OutputImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The SIFTs obtained for the matching will be stored in vector // form inside a point set. So we need the following types: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::VariableLengthVector<RealType> RealVectorType; typedef itk::PointSet<RealVectorType,Dimension> PointSetType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The filter for computing the SIFTs has a type defined as follows: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet //typedef otb::SiftFastImageFilter<ImageType,PointSetType> //ImageToSIFTKeyPointSetFilterType; typedef otb::ImageToSIFTKeyPointSetFilter<ImageType,PointSetType> ImageToSIFTKeyPointSetFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Although many choices for evaluating the distances during the // matching procedure exist, we choose here to use a simple // Euclidean distance. We can then define the type for the matching filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Statistics::EuclideanDistance<RealVectorType> DistanceType; typedef otb::KeyPointSetsMatchingFilter<PointSetType, DistanceType> EuclideanDistanceMatchingFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The following types are needed for dealing with the matched points. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef PointSetType::PointType PointType; typedef std::pair<PointType,PointType> MatchType; typedef std::vector<MatchType> MatchVectorType; typedef EuclideanDistanceMatchingFilterType::LandmarkListType LandmarkListType; typedef PointSetType::PointsContainer PointsContainerType; typedef PointsContainerType::Iterator PointsIteratorType; typedef PointSetType::PointDataContainer PointDataContainerType; typedef PointDataContainerType::Iterator PointDataIteratorType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We define the type for the image reader. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::ImageFileReader<ImageType> ReaderType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Two readers are instantiated : one for the fixed image, and one // for the moving image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer fixedReader = ReaderType::New(); ReaderType::Pointer movingReader = ReaderType::New(); fixedReader->SetFileName(fixedfname); movingReader->SetFileName(movingfname); fixedReader->UpdateOutputInformation(); movingReader->UpdateOutputInformation(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We will now instantiate the 2 SIFT filters and the filter used // for the matching of the points. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ImageToSIFTKeyPointSetFilterType::Pointer filter1 = ImageToSIFTKeyPointSetFilterType::New(); ImageToSIFTKeyPointSetFilterType::Pointer filter2 = ImageToSIFTKeyPointSetFilterType::New(); EuclideanDistanceMatchingFilterType::Pointer euclideanMatcher = EuclideanDistanceMatchingFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We plug the pipeline and set the parameters. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter1->SetInput( fixedReader->GetOutput() ); filter2->SetInput( movingReader->GetOutput() ); filter1->SetOctavesNumber(octaves); filter1->SetScalesNumber(scales); filter1->SetDoGThreshold(threshold); filter1->SetEdgeThreshold(ratio); filter2->SetOctavesNumber(octaves); filter2->SetScalesNumber(scales); filter2->SetDoGThreshold(threshold); filter2->SetEdgeThreshold(ratio); // Software Guide : EndCodeSnippet std::cout << "SIFT process fixed image" << std::endl; filter1->Update(); std::cout << "SIFT process moving image" << std::endl; filter2->Update(); //filter1->SetNumberOfThreads(1); //filter2->SetNumberOfThreads(1); //Take the minimum point set to compute euclidian diff (vector lengths must be equal) PointSetType::Pointer ptSet1 = filter1->GetOutput(); PointSetType::Pointer ptSet2 = filter2->GetOutput(); typedef PointSetType::PointsContainer PointsContainer; PointsContainer::Pointer ptContainer1,ptContainer2; //Save point container to extract 2 points container with size = min (container1, container2) //TODO simplify subset selection in this itk::PointSet ptContainer1 = ptSet1->GetPoints(); ptContainer2 = ptSet2->GetPoints(); if ( ptSet1->GetNumberOfPoints() > ptSet2->GetNumberOfPoints() ) { ptContainer1 = ptSet2->GetPoints(); ptContainer2 = ptSet1->GetPoints(); } PointsContainer::Pointer ptContainerRes = PointsContainer::New(); typedef PointsContainer::Iterator PointsIterator; PointsIterator pointsIterator = ptContainer2->Begin(); //Construct new point container (subset of input pointset) for (unsigned int id=0;id < ptContainer1->Size();++id) { ptContainerRes->InsertElement(id, pointsIterator->Value()); ++pointsIterator; } if ( ptSet1->GetNumberOfPoints() > ptSet2->GetNumberOfPoints() ) { ptSet1->SetPoints(ptContainerRes); } else { ptSet2->SetPoints(ptContainerRes); } std::cout << "SIFT points size" << std::endl; std::cout << ptSet1->GetNumberOfPoints() << std::endl; std::cout << ptSet2->GetNumberOfPoints() << std::endl; // Software Guide : BeginLatex // // We use a simple Euclidean distance to select // matched points. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet //TODO use SIFT filters outputs or subset of pointset??? //euclideanMatcher->SetInput1(ptSet1); //euclideanMatcher->SetInput2(ptSet2); euclideanMatcher->SetInput1(filter1->GetOutput()); euclideanMatcher->SetInput2(filter2->GetOutput()); bool useBackMatching = 0; euclideanMatcher->SetDistanceThreshold(secondOrderThreshold); euclideanMatcher->SetUseBackMatching(useBackMatching); std::cout << "Update euclidian distance" << std::endl; euclideanMatcher->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The matched points will be stored into a landmark list. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LandmarkListType::Pointer landmarkList; landmarkList = euclideanMatcher->GetOutput(); std::cout << "Get landmarkList" << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Apply Mean square algorithm // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Point<double,2> MyPointType; typedef otb::LeastSquareAffineTransformEstimator<MyPointType> EstimatorType; // instantiation EstimatorType::Pointer estimator = EstimatorType::New(); std::cout << "landmark list size " << landmarkList->Size() << std::endl; for (LandmarkListType::Iterator it = landmarkList->Begin(); it != landmarkList->End(); ++it) { std::cout << "landmark1" << it.Get()->GetPoint1() << std::endl; std::cout << "landmark2" << it.Get()->GetPoint2() << std::endl; estimator->AddTiePoints(it.Get()->GetPoint1(),it.Get()->GetPoint2()); } // Trigger computation estimator->Compute(); // meanSquarestimator->SetInput(euclideanMatcher->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Resample the initial image with the transformation evaluated // // Software Guide : EndLatex // Software Guide : BeginLatex // // It is common, as the last step of a registration task, to use // the resulting transform to map the moving image into the fixed // image space. This is easily done with the // \doxygen{itk}{ResampleImageFilter}. First, a ResampleImageFilter // type is instantiated using the image types. It is convenient to // use the fixed image type as the output type since it is likely // that the transformed moving image will be compared with the // fixed image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ResampleImageFilter< ImageType, OutputImageType > ResampleFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // A resampling filter is created and the moving image is connected as // its input. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetInput( movingReader->GetOutput() ); //typedef itk::ImageRegistrationMethod< //ImageType, //ImageType > RegistrationType; //RegistrationType::Pointer registration = RegistrationType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The Transform that is produced as output need to be inversed to // We apply here the resampling algorithm to the "fixed" image // to produce the moving image. Or apply to the moving image // // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // Get the output transform typedef EstimatorType::AffineTransformType AffineTransformType; AffineTransformType::Pointer transform = AffineTransformType::New(); transform->GetInverse( estimator->GetAffineTransform() ); resampler->SetTransform( transform ); resampler->SetSize( fixedReader->GetOutput()->GetLargestPossibleRegion().GetSize() ); resampler->SetOutputOrigin( fixedReader->GetOutput()->GetOrigin() ); resampler->SetOutputSpacing( fixedReader->GetOutput()->GetSpacing() ); resampler->SetDefaultPixelValue( 100 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Write resampled image // // Software Guide : EndLatex typedef otb::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( resampler->GetOutput() ); writer->SetFileName( outputImageFilename ); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// $Id: patch_recovery_error_estimator.C,v 1.2 2004-06-02 20:55:17 jwpeterson Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <algorithm> // for std::fill #include <math.h> // for sqrt // Local Includes #include "libmesh_common.h" #include "patch_recovery_error_estimator.h" #include "dof_map.h" #include "fe.h" #include "dense_matrix.h" #include "dense_vector.h" #include "quadrature_gauss.h" #include "libmesh_logging.h" //----------------------------------------------------------------- // ErrorEstimator implementations void PatchRecoveryErrorEstimator::estimate_error (const SteadySystem& system, std::vector<float>& error_per_cell) { START_LOG("estimate_error()", "PatchRecoveryErrorEstimator"); // The current mesh const Mesh& mesh = system.get_mesh(); // The dimensionality of the mesh const unsigned int dim = mesh.mesh_dimension(); // The number of variables in the system const unsigned int n_vars = system.n_vars(); // The DofMap for this system const DofMap& dof_map = system.get_dof_map(); // Resize the error_per_cell vector to be // the number of elements, initialize it to 0. error_per_cell.resize (mesh.n_elem()); std::fill (error_per_cell.begin(), error_per_cell.end(), 0.); // Check for a valid component_mask if (!component_mask.empty()) if (component_mask.size() != n_vars) { std::cerr << "ERROR: component_mask is the wrong size:" << std::endl << " component_mask.size()=" << component_mask.size() << std::endl << ", n_vars=" << n_vars << std::endl; error(); } //------------------------------------------------------------ // Iterate over all the active elements in the mesh // that live on this processor. const_active_local_elem_iterator elem_it (mesh.elements_begin()); const const_active_local_elem_iterator elem_end(mesh.elements_end()); for (; elem_it != elem_end; ++elem_it) { // elem is necessarily an active element on the local processor const Elem* elem = *elem_it; // Build a patch containing the current element // and its neighbors on the local processor std::set<const Elem*> patch; this->build_patch_from_local_neighbors (elem, patch); //------------------------------------------------------------ // Process each variable in the system using the current patch for (unsigned int var=0; var<n_vars; var++) { // Possibly skip this variable if (!component_mask.empty()) if (component_mask[var] == false) continue; // The type of finite element to use for this variable const FEType& fe_type = dof_map.variable_type (var); // Finite element object for use in this patch AutoPtr<FEBase> fe (FEBase::build (dim, fe_type)); // Build an appropriate Gaussian quadrature rule QGauss qrule (dim, fe_type.default_quadrature_order()); // Tell the finite element about the quadrature rule. fe->attach_quadrature_rule (&qrule); // Get Jacobian values, etc.. const std::vector<Real>& JxW = fe->get_JxW(); const std::vector<Point>& q_point = fe->get_xyz(); const std::vector<std::vector<Real> >& phi = fe->get_phi(); const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi(); // global DOF indices std::vector<unsigned int> dof_indices; // Dense matrix and vectors for patch projection. // THE SIZES OF THESE NEED TO GET SMARTER! DenseMatrix<Number> Kp(dim+1,dim+1); DenseVector<Number> Fx(dim+1), Pu_x_h(dim+1), Fy(dim+1), Pu_y_h(dim+1), Fz(dim+1), Pu_z_h(dim+1); //------------------------------------------------------ // Loop over each element in the patch and compute their // contribution to the patch gradient projection. std::set<const Elem*>::const_iterator patch_it = patch.begin(); const std::set<const Elem*>::const_iterator patch_end = patch.end(); for (; patch_it != patch_end; ++patch_it) { // The pth element in the patch const Elem* e_p = *patch_it; // Reinitialize the finite element data for this element fe->reinit (e_p); // Get the global DOF indices for the current variable // in the current element dof_map.dof_indices (e_p, dof_indices, var); // Huh? Something is horribly WRONG! assert (dof_indices.size() == phi.size()); const unsigned int n_dofs = dof_indices.size(); const unsigned int n_qp = qrule.n_points(); // Compute the projection components from this cell. // \int_{Omega_e} \psi_i \psi_j = \int_{Omega_e} du_h/dx_k \psi_i for (unsigned int qp=0; qp<n_qp; qp++) { // The x,y,z location of the current quadrature point const Real x = q_point[qp](0), y = q_point[qp](1), z = q_point[qp](2); // Compute the gradient on the current patch element // at the quadrature point Gradient grad_u_h; for (unsigned int i=0; i<n_dofs; i++) grad_u_h += dphi[i][qp]*system.current_solution(dof_indices[i]); // Construct the shape function values for the patch projection std::vector<Real> psi; { psi.reserve (dim+1); psi.push_back(1); psi.push_back(x); psi.push_back(y); if (dim == 3) psi.push_back(z); } // Patch matrix contribution for (unsigned int i=0; i<Kp.m(); i++) for (unsigned int j=0; j<Kp.n(); j++) Kp(i,j) += JxW[qp]*psi[i]*psi[j]; // Patch RHS contributions for (unsigned int i=0; i<psi.size(); i++) { Fx(i) += JxW[qp]*grad_u_h(0)*psi[i]; Fy(i) += JxW[qp]*grad_u_h(1)*psi[i]; Fz(i) += JxW[qp]*grad_u_h(2)*psi[i]; } } // end quadrature loop } // end patch loop //-------------------------------------------------- // Now we have fully assembled the projection system // for this patch. Project the gradient components. // MAY NEED TO USE PARTIAL PIVOTING! Kp.lu_solve (Fx, Pu_x_h); Kp.lu_solve (Fy, Pu_y_h); Kp.lu_solve (Fz, Pu_z_h); //-------------------------------------------------- // Finally, estimate the error in the current variable // for the current element by computing ||Pgrad_u_h - grad_u_h|| error(); } // end variable loop } // end element loop // Each processor has now computed the error contribuions // for its local elements. We need to sum the vector this->reduce_error(error_per_cell); STOP_LOG("estimate_error()", "PatchRecoveryErrorEstimator"); } void PatchRecoveryErrorEstimator::build_patch_from_local_neighbors (const Elem* e0, std::set<const Elem*> patch, const unsigned int target_patch_size) { START_LOG("build_patch_from_local_neighbors()", "PatchRecoveryErrorEstimator"); // Make sure we are building a patch for an active, local element. // (Are these restrictions necessary?) assert (e0 != NULL); assert (e0->processor_id() == libMesh::processor_id()); assert (e0->active()); // First add the element of interest. patch.insert (e0); // Repeatedly add the neighbors of the elements in the patch until // the target patch size is met while (patch.size() < target_patch_size) { // It is possible that the target patch size is larger than the number // of active elements in the mesh. Since we don't have access to the // Mesh object here the only way we can detect this case is by detecting // a "stagnant patch," i.e. a patch whose size does not increase after adding // face neighbors const unsigned int old_patch_size = patch.size(); // Loop over all the elements in the patch std::set<const Elem*>::const_iterator it = patch.begin(); const std::set<const Elem*>::const_iterator end = patch.end(); for (; (it != end) && (patch.size() < target_patch_size); ++it) { // Convenience. Keep the syntax simple. const Elem* elem = *it; for (unsigned int s=0; s<elem->n_sides(); s++) if (elem->neighbor(s) != NULL) // we have a neighbor on this side { const Elem* neighbor = elem->neighbor(s); if (neighbor->active()) // ... and that neighbor is active if (neighbor->processor_id() == libMesh::processor_id()) // ... and belongs to this processor patch.insert (neighbor); // ... then add it to the patch else // ... the neighbor is *not* active, { // ... so add *all* its active, local children to the patch std::vector<const Elem*> active_children; neighbor->active_family_tree (active_children); for (unsigned int c=0; c<active_children.size(); c++) if (active_children[c]->processor_id() == libMesh::processor_id()) patch.insert (active_children[c]); } } } // Check for a "stagnant" patch if (patch.size() == old_patch_size) { std::cerr << "ERROR: stagnant patch of " << patch.size() << " elements." << std::endl << "Does your target patch size exceed the number of elements?" << std::endl; here(); break; } } // end while loop // make sure all the elements in the patch are active and local // if we are in debug mode #ifdef DEBUG { std::set<const Elem*>::const_iterator it = patch.begin(); const std::set<const Elem*>::const_iterator end = patch.end(); for (; it != end; ++it) { // Convenience. Keep the syntax simple. const Elem* elem = *it; assert (elem->active()); assert (elem->processor_id() == libMesh::processor_id()); } } #endif STOP_LOG("build_patch_from_local_neighbors()", "PatchRecoveryErrorEstimator"); } <commit_msg>changes for complex.<commit_after>// $Id: patch_recovery_error_estimator.C,v 1.3 2004-06-08 14:45:50 spetersen Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <algorithm> // for std::fill #include <math.h> // for sqrt // Local Includes #include "libmesh_common.h" #include "patch_recovery_error_estimator.h" #include "dof_map.h" #include "fe.h" #include "dense_matrix.h" #include "dense_vector.h" #include "quadrature_gauss.h" #include "libmesh_logging.h" //----------------------------------------------------------------- // ErrorEstimator implementations void PatchRecoveryErrorEstimator::estimate_error (const SteadySystem& system, std::vector<float>& error_per_cell) { START_LOG("estimate_error()", "PatchRecoveryErrorEstimator"); // The current mesh const Mesh& mesh = system.get_mesh(); // The dimensionality of the mesh const unsigned int dim = mesh.mesh_dimension(); // The number of variables in the system const unsigned int n_vars = system.n_vars(); // The DofMap for this system const DofMap& dof_map = system.get_dof_map(); // Resize the error_per_cell vector to be // the number of elements, initialize it to 0. error_per_cell.resize (mesh.n_elem()); std::fill (error_per_cell.begin(), error_per_cell.end(), 0.); // Check for a valid component_mask if (!component_mask.empty()) if (component_mask.size() != n_vars) { std::cerr << "ERROR: component_mask is the wrong size:" << std::endl << " component_mask.size()=" << component_mask.size() << std::endl << ", n_vars=" << n_vars << std::endl; error(); } //------------------------------------------------------------ // Iterate over all the active elements in the mesh // that live on this processor. const_active_local_elem_iterator elem_it (mesh.elements_begin()); const const_active_local_elem_iterator elem_end(mesh.elements_end()); for (; elem_it != elem_end; ++elem_it) { // elem is necessarily an active element on the local processor const Elem* elem = *elem_it; // Build a patch containing the current element // and its neighbors on the local processor std::set<const Elem*> patch; this->build_patch_from_local_neighbors (elem, patch); //------------------------------------------------------------ // Process each variable in the system using the current patch for (unsigned int var=0; var<n_vars; var++) { // Possibly skip this variable if (!component_mask.empty()) if (component_mask[var] == false) continue; // The type of finite element to use for this variable const FEType& fe_type = dof_map.variable_type (var); // Finite element object for use in this patch AutoPtr<FEBase> fe (FEBase::build (dim, fe_type)); // Build an appropriate Gaussian quadrature rule QGauss qrule (dim, fe_type.default_quadrature_order()); // Tell the finite element about the quadrature rule. fe->attach_quadrature_rule (&qrule); // Get Jacobian values, etc.. const std::vector<Real>& JxW = fe->get_JxW(); const std::vector<Point>& q_point = fe->get_xyz(); const std::vector<std::vector<Real> >& phi = fe->get_phi(); const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi(); // global DOF indices std::vector<unsigned int> dof_indices; // Dense matrix and vectors for patch projection. // THE SIZES OF THESE NEED TO GET SMARTER! DenseMatrix<Number> Kp(dim+1,dim+1); DenseVector<Number> Fx(dim+1), Pu_x_h(dim+1), Fy(dim+1), Pu_y_h(dim+1), Fz(dim+1), Pu_z_h(dim+1); //------------------------------------------------------ // Loop over each element in the patch and compute their // contribution to the patch gradient projection. std::set<const Elem*>::const_iterator patch_it = patch.begin(); const std::set<const Elem*>::const_iterator patch_end = patch.end(); for (; patch_it != patch_end; ++patch_it) { // The pth element in the patch const Elem* e_p = *patch_it; // Reinitialize the finite element data for this element fe->reinit (e_p); // Get the global DOF indices for the current variable // in the current element dof_map.dof_indices (e_p, dof_indices, var); // Huh? Something is horribly WRONG! assert (dof_indices.size() == phi.size()); const unsigned int n_dofs = dof_indices.size(); const unsigned int n_qp = qrule.n_points(); // Compute the projection components from this cell. // \int_{Omega_e} \psi_i \psi_j = \int_{Omega_e} du_h/dx_k \psi_i for (unsigned int qp=0; qp<n_qp; qp++) { // The x,y,z location of the current quadrature point const Real x = q_point[qp](0), y = q_point[qp](1), z = q_point[qp](2); // Compute the gradient on the current patch element // at the quadrature point Gradient grad_u_h; for (unsigned int i=0; i<n_dofs; i++) // grad_u_h += dphi[i][qp]*system.current_solution(dof_indices[i]); grad_u_h.add_scaled (dphi[i][qp], system.current_solution(dof_indices[i])); // Construct the shape function values for the patch projection std::vector<Real> psi; { psi.reserve (dim+1); psi.push_back(1); psi.push_back(x); psi.push_back(y); if (dim == 3) psi.push_back(z); } // Patch matrix contribution for (unsigned int i=0; i<Kp.m(); i++) for (unsigned int j=0; j<Kp.n(); j++) Kp(i,j) += JxW[qp]*psi[i]*psi[j]; // Patch RHS contributions for (unsigned int i=0; i<psi.size(); i++) { Fx(i) += JxW[qp]*grad_u_h(0)*psi[i]; Fy(i) += JxW[qp]*grad_u_h(1)*psi[i]; Fz(i) += JxW[qp]*grad_u_h(2)*psi[i]; } } // end quadrature loop } // end patch loop //-------------------------------------------------- // Now we have fully assembled the projection system // for this patch. Project the gradient components. // MAY NEED TO USE PARTIAL PIVOTING! Kp.lu_solve (Fx, Pu_x_h); Kp.lu_solve (Fy, Pu_y_h); Kp.lu_solve (Fz, Pu_z_h); //-------------------------------------------------- // Finally, estimate the error in the current variable // for the current element by computing ||Pgrad_u_h - grad_u_h|| error(); } // end variable loop } // end element loop // Each processor has now computed the error contribuions // for its local elements. We need to sum the vector this->reduce_error(error_per_cell); STOP_LOG("estimate_error()", "PatchRecoveryErrorEstimator"); } void PatchRecoveryErrorEstimator::build_patch_from_local_neighbors (const Elem* e0, std::set<const Elem*> patch, const unsigned int target_patch_size) { START_LOG("build_patch_from_local_neighbors()", "PatchRecoveryErrorEstimator"); // Make sure we are building a patch for an active, local element. // (Are these restrictions necessary?) assert (e0 != NULL); assert (e0->processor_id() == libMesh::processor_id()); assert (e0->active()); // First add the element of interest. patch.insert (e0); // Repeatedly add the neighbors of the elements in the patch until // the target patch size is met while (patch.size() < target_patch_size) { // It is possible that the target patch size is larger than the number // of active elements in the mesh. Since we don't have access to the // Mesh object here the only way we can detect this case is by detecting // a "stagnant patch," i.e. a patch whose size does not increase after adding // face neighbors const unsigned int old_patch_size = patch.size(); // Loop over all the elements in the patch std::set<const Elem*>::const_iterator it = patch.begin(); const std::set<const Elem*>::const_iterator end = patch.end(); for (; (it != end) && (patch.size() < target_patch_size); ++it) { // Convenience. Keep the syntax simple. const Elem* elem = *it; for (unsigned int s=0; s<elem->n_sides(); s++) if (elem->neighbor(s) != NULL) // we have a neighbor on this side { const Elem* neighbor = elem->neighbor(s); if (neighbor->active()) // ... and that neighbor is active if (neighbor->processor_id() == libMesh::processor_id()) // ... and belongs to this processor patch.insert (neighbor); // ... then add it to the patch else // ... the neighbor is *not* active, { // ... so add *all* its active, local children to the patch std::vector<const Elem*> active_children; neighbor->active_family_tree (active_children); for (unsigned int c=0; c<active_children.size(); c++) if (active_children[c]->processor_id() == libMesh::processor_id()) patch.insert (active_children[c]); } } } // Check for a "stagnant" patch if (patch.size() == old_patch_size) { std::cerr << "ERROR: stagnant patch of " << patch.size() << " elements." << std::endl << "Does your target patch size exceed the number of elements?" << std::endl; here(); break; } } // end while loop // make sure all the elements in the patch are active and local // if we are in debug mode #ifdef DEBUG { std::set<const Elem*>::const_iterator it = patch.begin(); const std::set<const Elem*>::const_iterator end = patch.end(); for (; it != end; ++it) { // Convenience. Keep the syntax simple. const Elem* elem = *it; assert (elem->active()); assert (elem->processor_id() == libMesh::processor_id()); } } #endif STOP_LOG("build_patch_from_local_neighbors()", "PatchRecoveryErrorEstimator"); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: monst.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:30:10 $ * * 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 <stdlib.h> #include "monst.hxx" #include "invader.hrc" #include "expl.hxx" #include "shapes.hxx" #ifndef _SV_OUTDEV_HXX //autogen #include <vcl/outdev.hxx> #endif #ifndef _TOOLS_TIME_HXX //autogen #include <tools/time.hxx> #endif Gegner::Gegner(Fighter* pFig, Bombe* pBom, ResMgr* pRes) : pFighter(pFig), GegnerListe(0,0), bDown(FALSE), bLeft(TRUE), bAuseMode(FALSE), pBombe(pBom), pBitMonst1(0L), pBitMonst2(0L), pBitMonst3(0L), pBitMonst4(0L), pBitMonst1b(0L), pBitMonst2b(0L), pBitMonst3b(0L), pBitMonst4b(0L), pBitMonst5(0L), pBitMonst5a(0L), pBitMonst5b(0L), nDown(MOVEY) { pBitMonst1 = ImplLoadImage( MONSTER1, pRes ); pBitMonst2 = ImplLoadImage( MONSTER2, pRes ); pBitMonst3 = ImplLoadImage( MONSTER3, pRes ); pBitMonst4 = ImplLoadImage( MONSTER4, pRes ); pBitMonst1b = ImplLoadImage( MONSTER1B, pRes ); pBitMonst2b = ImplLoadImage( MONSTER2B, pRes ); pBitMonst3b = ImplLoadImage( MONSTER3B, pRes ); pBitMonst4b = ImplLoadImage( MONSTER4B, pRes ); pBitMonst5 = ImplLoadImage( MONSTER5, pRes ); pBitMonst5a = ImplLoadImage( MONSTER5A, pRes ); pBitMonst5b = ImplLoadImage( MONSTER5B, pRes ); aOutSize = pBitMonst1->GetSizePixel(); nRandWert = 200; } Gegner::~Gegner() { ClearAll(); delete pBitMonst1; delete pBitMonst2; delete pBitMonst3; delete pBitMonst4; delete pBitMonst1b; delete pBitMonst2b; delete pBitMonst3b; delete pBitMonst4b; delete pBitMonst5; delete pBitMonst5a; delete pBitMonst5b; } void Gegner::InsertGegner(USHORT nType, USHORT x, USHORT y) { Gegner_Impl* pWork = new Gegner_Impl(); pWork->aType = (enum GegnerType)nType; pWork->aMode = MOVE1; pWork->aXY = Point(x,y); pWork->aX = x; pWork->nHits = 0; switch(pWork->aType) { case GEGNER1: pWork->nPoints = 50; pWork->nMaxHits = 1; break; case GEGNER2: pWork->nPoints = 75; pWork->nMaxHits = 2; break; case GEGNER3: pWork->nPoints = 150; pWork->nMaxHits = 3; break; case GEGNER4: pWork->nPoints = 225; pWork->nMaxHits = 5; break; case GEGNER5: pWork->nPoints = 500; pWork->nMaxHits = 3; pWork->aMode = HIDE; break; } Insert(pWork); } void Gegner::Move() { BOOL bNextDown = FALSE; for(long i=0; i<Count(); i++) { if(bDown) { SetGegnerPos(i,Point(GegnerX(i),GegnerY(i)+nDown)); } else if(bLeft) { SetGegnerPos(i,Point(GegnerX(i)+MOVEX,GegnerY(i))); if(GegnerX(i)+MOVEX+aOutSize.Width() > nMaxX) bNextDown = TRUE; } else { SetGegnerPos(i,Point(GegnerX(i)-MOVEX,GegnerY(i))); if(GegnerX(i)-MOVEX <= 0) bNextDown = TRUE; } } if(bDown) { if(bLeft) bLeft = FALSE; else bLeft = TRUE; } bDown = FALSE; if(bNextDown) bDown = TRUE; } void Gegner::DrawGegner(OutputDevice* pDev,Point* pStart) { Time aTime; srand(aTime.GetTime() % 1000); nMaxX = pDev->GetOutputSizePixel().Width()-pStart->X(); for(long i=0; i<Count();i++) { switch(GegType(i)) { case GEGNER1: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst1); SetMode(i,MOVE2); } else if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst1b); SetMode(i,MOVE1); } break; case GEGNER2: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst2); SetMode(i,MOVE2); } else if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst2b); SetMode(i,MOVE1); } break; case GEGNER3: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst3); SetMode(i,MOVE2); } else if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst3b); SetMode(i,MOVE1); } break; case GEGNER4: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst4); SetMode(i,MOVE2); } else if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst4b); SetMode(i,MOVE1); } break; case GEGNER5: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5); DecDelay(i); if(!GetDelay(i)) { SetDelay(i); SetMode(i,MOVE2); } } if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5a); DecDelay(i); if(!GetDelay(i)) { SetDelay(i); SetMode(i,MOVE3); } } if(GegMode(i) == MOVE3) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5b); DecDelay(i); if(!GetDelay(i)) { pBombe->InsertBombe(Point(GegnerX(i)+aOutSize.Width()/2, GegnerY(i)+aOutSize.Height())); SetDelay(i); SetMode(i,MOVE4); } } if(GegMode(i) == MOVE4) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5a); DecDelay(i); if(!GetDelay(i)) { SetDelay(i); SetMode(i,MOVE5); } } if(GegMode(i) == MOVE5) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5); DecDelay(i); if(!GetDelay(i)) SetMode(i,HIDE); } break; } SetKoll(i,Rectangle(Point(GegnerX(i)+KOLLXY,GegnerY(i)+KOLLXY), Point(GegnerX(i)+aOutSize.Width()-KOLLXY, GegnerY(i)+aOutSize.Height()-KOLLXY))); if(bAuseMode && GegMode(i) == MOVE1) { if(GegnerX(i) < pFighter->GetHalf() && GegnerX(i)+aOutSize.Width() > pFighter->GetHalf()) pBombe->InsertBombe(Point(pFighter->GetPoint().X(), GegnerY(i)+aOutSize.Height())); } else { int ran = rand(); if(ran < nRandWert) { if(GegType(i) != GEGNER5) pBombe->InsertBombe(Point(GegnerX(i)+aOutSize.Width()/2, GegnerY(i)+aOutSize.Height())); else if(GegMode(i) == HIDE) { SetMode(i,MOVE1); SetDelay(i); } } } } Move(); } long Gegner::Kollision(Rectangle& rRect, Explosion* pExpl) { long nWert = -1; Rectangle aWork; for(long i=0; i<Count();i++) { aWork = GegnerKoll(i); if((aWork.Left() <= rRect.Left() && aWork.Right() >= rRect.Right()) && (aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) && GegMode(i) != DELETED) { nWert = 0; if(GegnerDest(i)) { SetMode(i,DELETED); if(nWert == -1) nWert = GegnerPoints(i); else nWert += GegnerPoints(i); } pExpl->InsertExpl(GegnerPos(i)); } } return nWert; } BOOL Gegner::GegnerDest(long nWert) { GegnerHit(nWert); if(GetObject(nWert)->nHits >= GetObject(nWert)->nMaxHits) return TRUE; return FALSE; } Rectangle Gegner::GetKoll(long nWert) { return Rectangle(Point(GegnerX(nWert)+aOutSize.Width()/2, GegnerY(nWert)+aOutSize.Height()), Point(GegnerX(nWert)+aOutSize.Width()/2, GegnerY(nWert)+aOutSize.Height())); } BOOL Gegner::RemoveGegner() { for(long i=Count()-1; i>=0; i--) { Gegner_Impl* pWork = GetObject(i); if(pWork->aMode == DELETED) { Remove(pWork); delete pWork; } } if(Count()) return FALSE; else return TRUE; } void Gegner::ClearAll() { for(long i=0; i<Count(); i++) delete GetObject(i); Clear(); } <commit_msg>INTEGRATION: CWS pj17 (1.1.1.1.264); FILE MERGED 2005/02/10 10:45:33 gh 1.1.1.1.264.3: more tuning to make it work nicely under windows too 2005/02/09 09:29:37 gh 1.1.1.1.264.2: finetuning 2005/02/07 17:05:49 gh 1.1.1.1.264.1: some fixes for 32 bit random numbers + enhanced invisible<commit_after>/************************************************************************* * * $RCSfile: monst.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2005-02-11 19:30:58 $ * * 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 <stdlib.h> #include "monst.hxx" #include "invader.hrc" #include "expl.hxx" #include "shapes.hxx" #ifndef _SV_OUTDEV_HXX //autogen #include <vcl/outdev.hxx> #endif #ifndef _TOOLS_TIME_HXX //autogen #include <tools/time.hxx> #endif Gegner::Gegner(Fighter* pFig, Bombe* pBom, ResMgr* pRes) : pFighter(pFig), GegnerListe(0,0), bDown(FALSE), bLeft(TRUE), bAuseMode(FALSE), pBombe(pBom), pBitMonst1(0L), pBitMonst2(0L), pBitMonst3(0L), pBitMonst4(0L), pBitMonst1b(0L), pBitMonst2b(0L), pBitMonst3b(0L), pBitMonst4b(0L), pBitMonst5(0L), pBitMonst5a(0L), pBitMonst5b(0L), nDown(MOVEY) { pBitMonst1 = ImplLoadImage( MONSTER1, pRes ); pBitMonst2 = ImplLoadImage( MONSTER2, pRes ); pBitMonst3 = ImplLoadImage( MONSTER3, pRes ); pBitMonst4 = ImplLoadImage( MONSTER4, pRes ); pBitMonst1b = ImplLoadImage( MONSTER1B, pRes ); pBitMonst2b = ImplLoadImage( MONSTER2B, pRes ); pBitMonst3b = ImplLoadImage( MONSTER3B, pRes ); pBitMonst4b = ImplLoadImage( MONSTER4B, pRes ); pBitMonst5 = ImplLoadImage( MONSTER5, pRes ); pBitMonst5a = ImplLoadImage( MONSTER5A, pRes ); pBitMonst5b = ImplLoadImage( MONSTER5B, pRes ); aOutSize = pBitMonst1->GetSizePixel(); SetRandWert( 100 ); } Gegner::~Gegner() { ClearAll(); delete pBitMonst1; delete pBitMonst2; delete pBitMonst3; delete pBitMonst4; delete pBitMonst1b; delete pBitMonst2b; delete pBitMonst3b; delete pBitMonst4b; delete pBitMonst5; delete pBitMonst5a; delete pBitMonst5b; } void Gegner::InsertGegner(USHORT nType, USHORT x, USHORT y) { Gegner_Impl* pWork = new Gegner_Impl(); pWork->aType = (enum GegnerType)nType; pWork->aMode = MOVE1; pWork->aXY = Point(x,y); pWork->aX = x; pWork->nHits = 0; switch(pWork->aType) { case GEGNER1: pWork->nPoints = 50; pWork->nMaxHits = 1; break; case GEGNER2: pWork->nPoints = 75; pWork->nMaxHits = 2; break; case GEGNER3: pWork->nPoints = 150; pWork->nMaxHits = 3; break; case GEGNER4: pWork->nPoints = 225; pWork->nMaxHits = 5; break; case GEGNER5: pWork->nPoints = 500; pWork->nMaxHits = 3; pWork->aMode = HIDE; break; } Insert(pWork); } void Gegner::Move() { BOOL bNextDown = FALSE; for(long i=0; i<Count(); i++) { if(bDown) { SetGegnerPos(i,Point(GegnerX(i),GegnerY(i)+nDown)); } else if(bLeft) { SetGegnerPos(i,Point(GegnerX(i)+MOVEX,GegnerY(i))); if(GegnerX(i)+MOVEX+aOutSize.Width() > nMaxX) bNextDown = TRUE; } else { SetGegnerPos(i,Point(GegnerX(i)-MOVEX,GegnerY(i))); if(GegnerX(i)-MOVEX <= 0) bNextDown = TRUE; } } if(bDown) { if(bLeft) bLeft = FALSE; else bLeft = TRUE; } bDown = FALSE; if(bNextDown) bDown = TRUE; } void Gegner::DrawGegner(OutputDevice* pDev,Point* pStart) { Time aTime; srand(aTime.GetTime() % 1000); nMaxX = pDev->GetOutputSizePixel().Width()-pStart->X(); for(long i=0; i<Count();i++) { switch(GegType(i)) { case GEGNER1: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst1); SetMode(i,MOVE2); } else if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst1b); SetMode(i,MOVE1); } break; case GEGNER2: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst2); SetMode(i,MOVE2); } else if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst2b); SetMode(i,MOVE1); } break; case GEGNER3: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst3); SetMode(i,MOVE2); } else if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst3b); SetMode(i,MOVE1); } break; case GEGNER4: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst4); SetMode(i,MOVE2); } else if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst4b); SetMode(i,MOVE1); } break; case GEGNER5: if(GegMode(i) == MOVE1) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5); DecDelay(i); if(!GetDelay(i)) { SetDelay(i); SetMode(i,MOVE2); } } if(GegMode(i) == MOVE2) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5a); DecDelay(i); if(!GetDelay(i)) { SetDelay(i); SetMode(i,MOVE3); } } if(GegMode(i) == MOVE3) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5b); DecDelay(i); pBombe->InsertBombe(Point(GegnerX(i), GegnerY(i)+aOutSize.Height()/2)); if(!GetDelay(i)) { SetDelay(i); SetMode(i,MOVE4); } } if(GegMode(i) == MOVE4) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5a); DecDelay(i); if(!GetDelay(i)) { SetDelay(i); if ( rand() % 5 < 2 ) SetMode(i,MOVE3); else SetMode(i,MOVE5); } } if(GegMode(i) == MOVE5) { pDev->DrawImage(Point(pStart->X()+GegnerX(i), pStart->Y()+GegnerY(i)),*pBitMonst5); DecDelay(i); if(!GetDelay(i)) { if ( rand() % 5 < 2 ) { SetMode(i,MOVE1); SetDelay(i); } else SetMode(i,HIDE); } } break; } SetKoll(i,Rectangle(Point(GegnerX(i)+KOLLXY,GegnerY(i)+KOLLXY), Point(GegnerX(i)+aOutSize.Width()-KOLLXY, GegnerY(i)+aOutSize.Height()-KOLLXY))); if(bAuseMode && GegMode(i) == MOVE1) { if(GegnerX(i) < pFighter->GetHalf() && GegnerX(i)+aOutSize.Width() > pFighter->GetHalf()) pBombe->InsertBombe(Point(pFighter->GetPoint().X(), GegnerY(i)+aOutSize.Height()/2)); } else { int ran = rand(); int nScaledLimit; // NOTE: the two expressions are the same in floatingpoint but not in integer if ( RAND_MAX < 32767 ) nScaledLimit = GetRandWert() / (32767 / RAND_MAX); else nScaledLimit = GetRandWert() * (RAND_MAX / 32767); if(GegType(i) != GEGNER5) { if(ran < nScaledLimit ) pBombe->InsertBombe(Point(GegnerX(i), GegnerY(i)+aOutSize.Height()/2)); } else if(GegMode(i) == HIDE) { if(ran < (nScaledLimit *3) /2) { SetMode(i,MOVE1); SetDelay(i); } } } } Move(); } long Gegner::Kollision(Rectangle& rRect, Explosion* pExpl) { long nWert = -1; Rectangle aWork; for(long i=0; i<Count();i++) { aWork = GegnerKoll(i); if((aWork.Left() <= rRect.Left() && aWork.Right() >= rRect.Right()) && (aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) && GegMode(i) != DELETED) { nWert = 0; if(GegnerDest(i)) { SetMode(i,DELETED); if(nWert == -1) nWert = GegnerPoints(i); else nWert += GegnerPoints(i); } pExpl->InsertExpl(GegnerPos(i)); } } return nWert; } BOOL Gegner::GegnerDest(long nWert) { GegnerHit(nWert); if(GetObject(nWert)->nHits >= GetObject(nWert)->nMaxHits) return TRUE; return FALSE; } Rectangle Gegner::GetKoll(long nWert) { return Rectangle(Point(GegnerX(nWert)+aOutSize.Width()/2, GegnerY(nWert)+aOutSize.Height()), Point(GegnerX(nWert)+aOutSize.Width()/2, GegnerY(nWert)+aOutSize.Height())); } BOOL Gegner::RemoveGegner() { for(long i=Count()-1; i>=0; i--) { Gegner_Impl* pWork = GetObject(i); if(pWork->aMode == DELETED) { Remove(pWork); delete pWork; } } if(Count()) return FALSE; else return TRUE; } void Gegner::ClearAll() { for(long i=0; i<Count(); i++) delete GetObject(i); Clear(); } <|endoftext|>
<commit_before>// Tests trace pc guard coverage collection. // // REQUIRES: has_sancovcc // XFAIL: tsan // // RUN: DIR=%t_workdir // RUN: CLANG_ARGS="-O0 -fsanitize-coverage=trace-pc-guard" // RUN: rm -rf $DIR // RUN: mkdir -p $DIR // RUN: cd $DIR // RUN: %clangxx -DSHARED1 $CLANG_ARGS -shared %s -o %t_1.so -fPIC // RUN: %clangxx -DSHARED2 $CLANG_ARGS -shared %s -o %t_2.so -fPIC // RUN: %clangxx -DMAIN $CLANG_ARGS %s -o %t %t_1.so %t_2.so // RUN: %env_tool_opts=coverage=1 %t 2>&1 | FileCheck %s // RUN: %sancovcc -covered-functions -strip_path_prefix=TestCases/ *.sancov \ // RUN: %t %t_1.so %t_2.so 2>&1 | \ // RUN: FileCheck --check-prefix=CHECK-SANCOV %s // RUN: rm -rf $DIR #include <stdio.h> extern "C" { int bar(); int baz(); } #ifdef MAIN int foo() { fprintf(stderr, "foo\n"); return 1; } int main() { fprintf(stderr, "main\n"); foo(); bar(); baz(); } #endif // MAIN extern "C" { #ifdef SHARED1 int bar() { fprintf(stderr, "bar\n"); return 1; } #endif #ifdef SHARED2 int baz() { fprintf(stderr, "baz\n"); return 1; } #endif } // extern "C" // CHECK: main // CHECK-NEXT: foo // CHECK-NEXT: bar // CHECK-NEXT: baz // CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}.sancov 2 PCs written // CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}_2.so.{{.*}}.sancov 1 PCs written // CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}_1.so.{{.*}}.sancov 1 PCs written // // CHECK-SANCOV: Ignoring {{.*}}_1.so and its coverage because __sanitizer_cov* functions were not found. // CHECK-SANCOV: Ignoring {{.*}}_2.so and its coverage because __sanitizer_cov* functions were not found. // CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard-dso.cc:29 foo // CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard-dso.cc:34 main <commit_msg>[sanitizers] disabling dso test as well where appropriate<commit_after>// Tests trace pc guard coverage collection. // // REQUIRES: has_sancovcc // XFAIL: tsan,arm,aarch64,darwin // // RUN: DIR=%t_workdir // RUN: CLANG_ARGS="-O0 -fsanitize-coverage=trace-pc-guard" // RUN: rm -rf $DIR // RUN: mkdir -p $DIR // RUN: cd $DIR // RUN: %clangxx -DSHARED1 $CLANG_ARGS -shared %s -o %t_1.so -fPIC // RUN: %clangxx -DSHARED2 $CLANG_ARGS -shared %s -o %t_2.so -fPIC // RUN: %clangxx -DMAIN $CLANG_ARGS %s -o %t %t_1.so %t_2.so // RUN: %env_tool_opts=coverage=1 %t 2>&1 | FileCheck %s // RUN: %sancovcc -covered-functions -strip_path_prefix=TestCases/ *.sancov \ // RUN: %t %t_1.so %t_2.so 2>&1 | \ // RUN: FileCheck --check-prefix=CHECK-SANCOV %s // RUN: rm -rf $DIR #include <stdio.h> extern "C" { int bar(); int baz(); } #ifdef MAIN int foo() { fprintf(stderr, "foo\n"); return 1; } int main() { fprintf(stderr, "main\n"); foo(); bar(); baz(); } #endif // MAIN extern "C" { #ifdef SHARED1 int bar() { fprintf(stderr, "bar\n"); return 1; } #endif #ifdef SHARED2 int baz() { fprintf(stderr, "baz\n"); return 1; } #endif } // extern "C" // CHECK: main // CHECK-NEXT: foo // CHECK-NEXT: bar // CHECK-NEXT: baz // CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}.sancov 2 PCs written // CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}_2.so.{{.*}}.sancov 1 PCs written // CHECK-NEXT: SanitizerCoverage: ./sanitizer_coverage_trace_pc_guard-dso.{{.*}}_1.so.{{.*}}.sancov 1 PCs written // // CHECK-SANCOV: Ignoring {{.*}}_1.so and its coverage because __sanitizer_cov* functions were not found. // CHECK-SANCOV: Ignoring {{.*}}_2.so and its coverage because __sanitizer_cov* functions were not found. // CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard-dso.cc:29 foo // CHECK-SANCOV-NEXT: sanitizer_coverage_trace_pc_guard-dso.cc:34 main <|endoftext|>
<commit_before> #ifndef __SHUTDOWNICON_HXX__ #define __SHUTDOWNICON_HXX__ #ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_ #include <com/sun/star/frame/XTerminateListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_ #include <com/sun/star/lang/XEventListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _RTL_STRING_HXX #include <rtl/string.hxx> #endif #ifndef _RTL_USTRING_HXX #include <rtl/ustring.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _SFX_SFXUNO_HXX #include <sfx2/sfxuno.hxx> #endif #ifndef _CPPUHELPER_COMPBASE3_HXX_ #include <cppuhelper/compbase3.hxx> #endif class ResMgr; typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::lang::XInitialization, ::com::sun::star::frame::XTerminateListener, ::com::sun::star::lang::XServiceInfo > ShutdownIconServiceBase; class ShutdownIcon : public ShutdownIconServiceBase { ::osl::Mutex m_aMutex; bool m_bVeto; ResMgr *m_pResMgr; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager; static ShutdownIcon *pShutdownIcon; // one instance #ifdef WNT void initSystray(); void deInitSystray(); static void SetAutostartW32( const ::rtl::OUString& aShortcutName, bool bActivate ); static bool GetAutostartW32( const ::rtl::OUString& aShortcutName ); #endif public: ShutdownIcon( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > aSMgr ); virtual ~ShutdownIcon(); SFX_DECL_XSERVICEINFO static ShutdownIcon* getInstance(); static void terminateDesktop(); static void addTerminateListener(); static void FileOpen(); static void OpenURL( ::rtl::OUString& aURL ); static void FromTemplate(); static void SetAutostart( bool bActivate ); static bool GetAutostart(); static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > GetWrapperFactory( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSMgr ); static ::rtl::OUString GetImplementationName_static(); ::rtl::OUString GetResString( int id ); ::rtl::OUString GetUrlDescription( const ::rtl::OUString& aUrl ); void SetVeto( bool bVeto ) { m_bVeto = bVeto;} bool GetVeto() { return m_bVeto; } // Component Helper - force override virtual void SAL_CALL disposing(); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException); // XTerminateListener virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw( ::com::sun::star::uno::Exception ); ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDesktop > m_xDesktop; }; #endif <commit_msg>#87576# include fixed<commit_after> #ifndef __SHUTDOWNICON_HXX__ #define __SHUTDOWNICON_HXX__ #ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_ #include <com/sun/star/frame/XTerminateListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_ #include <com/sun/star/frame/XDesktop.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_ #include <com/sun/star/lang/XEventListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _RTL_STRING_HXX #include <rtl/string.hxx> #endif #ifndef _RTL_USTRING_HXX #include <rtl/ustring.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _SFX_SFXUNO_HXX #include <sfxuno.hxx> #endif #ifndef _CPPUHELPER_COMPBASE3_HXX_ #include <cppuhelper/compbase3.hxx> #endif class ResMgr; typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::lang::XInitialization, ::com::sun::star::frame::XTerminateListener, ::com::sun::star::lang::XServiceInfo > ShutdownIconServiceBase; class ShutdownIcon : public ShutdownIconServiceBase { ::osl::Mutex m_aMutex; bool m_bVeto; ResMgr *m_pResMgr; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager; static ShutdownIcon *pShutdownIcon; // one instance #ifdef WNT void initSystray(); void deInitSystray(); static void SetAutostartW32( const ::rtl::OUString& aShortcutName, bool bActivate ); static bool GetAutostartW32( const ::rtl::OUString& aShortcutName ); #endif public: ShutdownIcon( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > aSMgr ); virtual ~ShutdownIcon(); SFX_DECL_XSERVICEINFO static ShutdownIcon* getInstance(); static void terminateDesktop(); static void addTerminateListener(); static void FileOpen(); static void OpenURL( ::rtl::OUString& aURL ); static void FromTemplate(); static void SetAutostart( bool bActivate ); static bool GetAutostart(); static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > GetWrapperFactory( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSMgr ); static ::rtl::OUString GetImplementationName_static(); ::rtl::OUString GetResString( int id ); ::rtl::OUString GetUrlDescription( const ::rtl::OUString& aUrl ); void SetVeto( bool bVeto ) { m_bVeto = bVeto;} bool GetVeto() { return m_bVeto; } // Component Helper - force override virtual void SAL_CALL disposing(); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException); // XTerminateListener virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException); // XInitialization virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw( ::com::sun::star::uno::Exception ); ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDesktop > m_xDesktop; }; #endif <|endoftext|>
<commit_before>#include "win32_window.h" #include <flutter_windows.h> #include "resource.h" namespace { constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; // The number of Win32Window objects that currently exist. static int g_active_window_count = 0; using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); // Scale helper to convert logical scaler values to physical using passed in // scale factor int Scale(int source, double scale_factor) { return static_cast<int>(source * scale_factor); } // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. // This API is only needed for PerMonitor V1 awareness mode. void EnableFullDpiSupportIfAvailable(HWND hwnd) { HMODULE user32_module = LoadLibraryA("User32.dll"); if (!user32_module) { return; } auto enable_non_client_dpi_scaling = reinterpret_cast<EnableNonClientDpiScaling*>( GetProcAddress(user32_module, "EnableNonClientDpiScaling")); if (enable_non_client_dpi_scaling != nullptr) { enable_non_client_dpi_scaling(hwnd); FreeLibrary(user32_module); } } } // namespace // Manages the Win32Window's window class registration. class WindowClassRegistrar { public: ~WindowClassRegistrar() = default; // Returns the singleton registar instance. static WindowClassRegistrar* GetInstance() { if (!instance_) { instance_ = new WindowClassRegistrar(); } return instance_; } // Returns the name of the window class, registering the class if it hasn't // previously been registered. const wchar_t* GetWindowClass(); // Unregisters the window class. Should only be called if there are no // instances of the window. void UnregisterWindowClass(); private: WindowClassRegistrar() = default; static WindowClassRegistrar* instance_; bool class_registered_ = false; }; WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; const wchar_t* WindowClassRegistrar::GetWindowClass() { if (!class_registered_) { WNDCLASS window_class{}; window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); window_class.lpszClassName = kWindowClassName; window_class.style = CS_HREDRAW | CS_VREDRAW; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = GetModuleHandle(nullptr); window_class.hIcon = LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); window_class.hbrBackground = 0; window_class.lpszMenuName = nullptr; window_class.lpfnWndProc = Win32Window::WndProc; RegisterClass(&window_class); class_registered_ = true; } return kWindowClassName; } void WindowClassRegistrar::UnregisterWindowClass() { UnregisterClass(kWindowClassName, nullptr); class_registered_ = false; } Win32Window::Win32Window() { ++g_active_window_count; } Win32Window::~Win32Window() { --g_active_window_count; Destroy(); } bool Win32Window::CreateAndShow(const std::wstring& title, const Point& origin, const Size& size) { Destroy(); const wchar_t* window_class = WindowClassRegistrar::GetInstance()->GetWindowClass(); const POINT target_point = {static_cast<LONG>(origin.x), static_cast<LONG>(origin.y)}; HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); double scale_factor = dpi / 96.0; HWND window = CreateWindow( window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), Scale(size.width, scale_factor), Scale(size.height, scale_factor), nullptr, nullptr, GetModuleHandle(nullptr), this); if (!window) { return false; } return OnCreate(); } // static LRESULT CALLBACK Win32Window::WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (message == WM_NCCREATE) { auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam); SetWindowLongPtr(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams)); auto that = static_cast<Win32Window*>(window_struct->lpCreateParams); EnableFullDpiSupportIfAvailable(window); that->window_handle_ = window; } else if (Win32Window* that = GetThisFromHandle(window)) { return that->MessageHandler(window, message, wparam, lparam); } return DefWindowProc(window, message, wparam, lparam); } LRESULT Win32Window::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { switch (message) { case WM_DESTROY: window_handle_ = nullptr; Destroy(); if (quit_on_close_) { PostQuitMessage(0); } return 0; case WM_DPICHANGED: { auto newRectSize = reinterpret_cast<RECT*>(lparam); LONG newWidth = newRectSize->right - newRectSize->left; LONG newHeight = newRectSize->bottom - newRectSize->top; SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, newHeight, SWP_NOZORDER | SWP_NOACTIVATE); return 0; } case WM_SIZE: RECT rect = GetClientArea(); if (child_content_ != nullptr) { // Size and position the child window. MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE); } return 0; case WM_ACTIVATE: if (child_content_ != nullptr) { SetFocus(child_content_); } return 0; } return DefWindowProc(window_handle_, message, wparam, lparam); } void Win32Window::Destroy() { OnDestroy(); if (window_handle_) { DestroyWindow(window_handle_); window_handle_ = nullptr; } if (g_active_window_count == 0) { WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); } } Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { return reinterpret_cast<Win32Window*>( GetWindowLongPtr(window, GWLP_USERDATA)); } void Win32Window::SetChildContent(HWND content) { child_content_ = content; SetParent(content, window_handle_); RECT frame = GetClientArea(); MoveWindow(content, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, true); SetFocus(child_content_); } RECT Win32Window::GetClientArea() { RECT frame; GetClientRect(window_handle_, &frame); return frame; } HWND Win32Window::GetHandle() { return window_handle_; } void Win32Window::SetQuitOnClose(bool quit_on_close) { quit_on_close_ = quit_on_close; } bool Win32Window::OnCreate() { // No-op; provided for subclasses. return true; } void Win32Window::OnDestroy() { // No-op; provided for subclasses. } <commit_msg>Avoid skipping variable initialization using case. (#67899)<commit_after>#include "win32_window.h" #include <flutter_windows.h> #include "resource.h" namespace { constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; // The number of Win32Window objects that currently exist. static int g_active_window_count = 0; using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); // Scale helper to convert logical scaler values to physical using passed in // scale factor int Scale(int source, double scale_factor) { return static_cast<int>(source * scale_factor); } // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. // This API is only needed for PerMonitor V1 awareness mode. void EnableFullDpiSupportIfAvailable(HWND hwnd) { HMODULE user32_module = LoadLibraryA("User32.dll"); if (!user32_module) { return; } auto enable_non_client_dpi_scaling = reinterpret_cast<EnableNonClientDpiScaling*>( GetProcAddress(user32_module, "EnableNonClientDpiScaling")); if (enable_non_client_dpi_scaling != nullptr) { enable_non_client_dpi_scaling(hwnd); FreeLibrary(user32_module); } } } // namespace // Manages the Win32Window's window class registration. class WindowClassRegistrar { public: ~WindowClassRegistrar() = default; // Returns the singleton registar instance. static WindowClassRegistrar* GetInstance() { if (!instance_) { instance_ = new WindowClassRegistrar(); } return instance_; } // Returns the name of the window class, registering the class if it hasn't // previously been registered. const wchar_t* GetWindowClass(); // Unregisters the window class. Should only be called if there are no // instances of the window. void UnregisterWindowClass(); private: WindowClassRegistrar() = default; static WindowClassRegistrar* instance_; bool class_registered_ = false; }; WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; const wchar_t* WindowClassRegistrar::GetWindowClass() { if (!class_registered_) { WNDCLASS window_class{}; window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); window_class.lpszClassName = kWindowClassName; window_class.style = CS_HREDRAW | CS_VREDRAW; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = GetModuleHandle(nullptr); window_class.hIcon = LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); window_class.hbrBackground = 0; window_class.lpszMenuName = nullptr; window_class.lpfnWndProc = Win32Window::WndProc; RegisterClass(&window_class); class_registered_ = true; } return kWindowClassName; } void WindowClassRegistrar::UnregisterWindowClass() { UnregisterClass(kWindowClassName, nullptr); class_registered_ = false; } Win32Window::Win32Window() { ++g_active_window_count; } Win32Window::~Win32Window() { --g_active_window_count; Destroy(); } bool Win32Window::CreateAndShow(const std::wstring& title, const Point& origin, const Size& size) { Destroy(); const wchar_t* window_class = WindowClassRegistrar::GetInstance()->GetWindowClass(); const POINT target_point = {static_cast<LONG>(origin.x), static_cast<LONG>(origin.y)}; HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); double scale_factor = dpi / 96.0; HWND window = CreateWindow( window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), Scale(size.width, scale_factor), Scale(size.height, scale_factor), nullptr, nullptr, GetModuleHandle(nullptr), this); if (!window) { return false; } return OnCreate(); } // static LRESULT CALLBACK Win32Window::WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (message == WM_NCCREATE) { auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam); SetWindowLongPtr(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams)); auto that = static_cast<Win32Window*>(window_struct->lpCreateParams); EnableFullDpiSupportIfAvailable(window); that->window_handle_ = window; } else if (Win32Window* that = GetThisFromHandle(window)) { return that->MessageHandler(window, message, wparam, lparam); } return DefWindowProc(window, message, wparam, lparam); } LRESULT Win32Window::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { switch (message) { case WM_DESTROY: window_handle_ = nullptr; Destroy(); if (quit_on_close_) { PostQuitMessage(0); } return 0; case WM_DPICHANGED: { auto newRectSize = reinterpret_cast<RECT*>(lparam); LONG newWidth = newRectSize->right - newRectSize->left; LONG newHeight = newRectSize->bottom - newRectSize->top; SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, newHeight, SWP_NOZORDER | SWP_NOACTIVATE); return 0; } case WM_SIZE: { RECT rect = GetClientArea(); if (child_content_ != nullptr) { // Size and position the child window. MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE); } return 0; } case WM_ACTIVATE: if (child_content_ != nullptr) { SetFocus(child_content_); } return 0; } return DefWindowProc(window_handle_, message, wparam, lparam); } void Win32Window::Destroy() { OnDestroy(); if (window_handle_) { DestroyWindow(window_handle_); window_handle_ = nullptr; } if (g_active_window_count == 0) { WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); } } Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { return reinterpret_cast<Win32Window*>( GetWindowLongPtr(window, GWLP_USERDATA)); } void Win32Window::SetChildContent(HWND content) { child_content_ = content; SetParent(content, window_handle_); RECT frame = GetClientArea(); MoveWindow(content, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, true); SetFocus(child_content_); } RECT Win32Window::GetClientArea() { RECT frame; GetClientRect(window_handle_, &frame); return frame; } HWND Win32Window::GetHandle() { return window_handle_; } void Win32Window::SetQuitOnClose(bool quit_on_close) { quit_on_close_ = quit_on_close; } bool Win32Window::OnCreate() { // No-op; provided for subclasses. return true; } void Win32Window::OnDestroy() { // No-op; provided for subclasses. } <|endoftext|>
<commit_before><commit_msg>no message<commit_after><|endoftext|>
<commit_before><commit_msg>Fixed bug in ProjectGen not merging in code properly for code integrate locations<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stlsheet.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2008-04-04 12:44:44 $ * * 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 _SD_STLSHEET_HXX #define _SD_STLSHEET_HXX #include <rtl/ref.hxx> #include <com/sun/star/style/XStyle.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/beans/XPropertyState.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/util/XModifyBroadcaster.hpp> #include <cppuhelper/interfacecontainer.h> #include <cppuhelper/implbase5.hxx> #include <cppuhelper/basemutex.hxx> #include <svtools/style.hxx> #include <svx/unoipset.hxx> #include <boost/scoped_ptr.hpp> class ModifyListenerForewarder; typedef cppu::ImplInheritanceHelper5< SfxUnoStyleSheet, ::com::sun::star::beans::XPropertySet, ::com::sun::star::lang::XServiceInfo, ::com::sun::star::beans::XPropertyState, ::com::sun::star::util::XModifyBroadcaster, ::com::sun::star::lang::XComponent > SdStyleSheetBase ; class SdStyleSheet : public SdStyleSheetBase, private ::cppu::BaseMutex { public: SdStyleSheet( const rtl::OUString& rDisplayName, SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily, USHORT nMask ); SdStyleSheet( const SdStyleSheet& ); virtual BOOL SetParent (const String& rParentName); virtual SfxItemSet& GetItemSet(); virtual BOOL IsUsed() const; virtual BOOL HasFollowSupport() const; virtual BOOL HasParentSupport() const; virtual BOOL HasClearParentSupport() const; virtual BOOL SetName( const UniString& ); virtual void SetHelpId( const String& r, ULONG nId ); void AdjustToFontHeight(SfxItemSet& rSet, BOOL bOnlyMissingItems = TRUE); SdStyleSheet* GetRealStyleSheet() const; SdStyleSheet* GetPseudoStyleSheet() const; void SetApiName( const ::rtl::OUString& rApiName ); rtl::OUString GetApiName() const; static rtl::OUString GetFamilyString( SfxStyleFamily eFamily ); static SdStyleSheet* CreateEmptyUserStyle( SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily ); // XInterface virtual void SAL_CALL release( ) throw (); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); // XNamed virtual ::rtl::OUString SAL_CALL getName( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException); // XStyle virtual sal_Bool SAL_CALL isUserDefined( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isInUse( ) throw(::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getParentStyle( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setParentStyle( const ::rtl::OUString& aParentStyle ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); // XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XPropertyState virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XModifyBroadcaster virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); void notifyModifyListener(); protected: const SfxItemPropertyMap* getPropertyMapEntry( const ::rtl::OUString& rPropertyName ) const throw(); virtual void Load (SvStream& rIn, USHORT nVersion); virtual void Store(SvStream& rOut); virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType); virtual ~SdStyleSheet(); void throwIfDisposed() throw (::com::sun::star::uno::RuntimeException); virtual void disposing(); rtl::OUString msApiName; rtl::Reference< SfxStyleSheetBasePool > mxPool; /** boradcast helper for events */ ::cppu::OBroadcastHelper mrBHelper; boost::scoped_ptr< ModifyListenerForewarder > mpModifyListenerForewarder; private: SdStyleSheet& operator=( const SdStyleSheet& ); // not implemented }; typedef rtl::Reference< SdStyleSheet > SdStyleSheetRef; typedef std::vector< SdStyleSheetRef > SdStyleSheetVector; #endif // _SD_STLSHEET_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.4.16); FILE MERGED 2008/03/31 13:56:41 rt 1.4.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stlsheet.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SD_STLSHEET_HXX #define _SD_STLSHEET_HXX #include <rtl/ref.hxx> #include <com/sun/star/style/XStyle.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/beans/XPropertyState.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/util/XModifyBroadcaster.hpp> #include <cppuhelper/interfacecontainer.h> #include <cppuhelper/implbase5.hxx> #include <cppuhelper/basemutex.hxx> #include <svtools/style.hxx> #include <svx/unoipset.hxx> #include <boost/scoped_ptr.hpp> class ModifyListenerForewarder; typedef cppu::ImplInheritanceHelper5< SfxUnoStyleSheet, ::com::sun::star::beans::XPropertySet, ::com::sun::star::lang::XServiceInfo, ::com::sun::star::beans::XPropertyState, ::com::sun::star::util::XModifyBroadcaster, ::com::sun::star::lang::XComponent > SdStyleSheetBase ; class SdStyleSheet : public SdStyleSheetBase, private ::cppu::BaseMutex { public: SdStyleSheet( const rtl::OUString& rDisplayName, SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily, USHORT nMask ); SdStyleSheet( const SdStyleSheet& ); virtual BOOL SetParent (const String& rParentName); virtual SfxItemSet& GetItemSet(); virtual BOOL IsUsed() const; virtual BOOL HasFollowSupport() const; virtual BOOL HasParentSupport() const; virtual BOOL HasClearParentSupport() const; virtual BOOL SetName( const UniString& ); virtual void SetHelpId( const String& r, ULONG nId ); void AdjustToFontHeight(SfxItemSet& rSet, BOOL bOnlyMissingItems = TRUE); SdStyleSheet* GetRealStyleSheet() const; SdStyleSheet* GetPseudoStyleSheet() const; void SetApiName( const ::rtl::OUString& rApiName ); rtl::OUString GetApiName() const; static rtl::OUString GetFamilyString( SfxStyleFamily eFamily ); static SdStyleSheet* CreateEmptyUserStyle( SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily ); // XInterface virtual void SAL_CALL release( ) throw (); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); // XNamed virtual ::rtl::OUString SAL_CALL getName( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException); // XStyle virtual sal_Bool SAL_CALL isUserDefined( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isInUse( ) throw(::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getParentStyle( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setParentStyle( const ::rtl::OUString& aParentStyle ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException); // XPropertySet virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XPropertyState virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XModifyBroadcaster virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); void notifyModifyListener(); protected: const SfxItemPropertyMap* getPropertyMapEntry( const ::rtl::OUString& rPropertyName ) const throw(); virtual void Load (SvStream& rIn, USHORT nVersion); virtual void Store(SvStream& rOut); virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType); virtual ~SdStyleSheet(); void throwIfDisposed() throw (::com::sun::star::uno::RuntimeException); virtual void disposing(); rtl::OUString msApiName; rtl::Reference< SfxStyleSheetBasePool > mxPool; /** boradcast helper for events */ ::cppu::OBroadcastHelper mrBHelper; boost::scoped_ptr< ModifyListenerForewarder > mpModifyListenerForewarder; private: SdStyleSheet& operator=( const SdStyleSheet& ); // not implemented }; typedef rtl::Reference< SdStyleSheet > SdStyleSheetRef; typedef std::vector< SdStyleSheetRef > SdStyleSheetVector; #endif // _SD_STLSHEET_HXX <|endoftext|>
<commit_before>/** * The Strawhouse Pattern. * * We allow or deny clients according to their IP address. It may keep * spammers and idiots away, but won't stop a real attacker for more * than a heartbeat. * * \date 25 Nov 2014 * \author Prem Shankar Kumar (\@meprem) */ #include <zmqpp/zmqpp.hpp> #include <string> #include <iostream> using namespace std; int main(int argc, char *argv[]) { // initialize the 0MQ context zmqpp::context context; // Start an authentication engine for this context. This engine // allows or denies incoming connections (talking to the libzmq // core over a protocol called ZAP). zmqpp::auth authenticator{context}; // Get some indication of what the authenticator is deciding authenticator.set_verbose (true); // Configure ZAP domain authenticator.configure_domain ("global"); // Whitelist our address; any other address will be rejected authenticator.allow ("127.0.0.1"); // create and bind a server socket zmqpp::socket server (context, zmqpp::socket_type::push); //server.set(zmqpp::socket_option::zap_domain, "global"); server.bind("tcp://*:9000"); // create and connect a client socket zmqpp::socket client (context, zmqpp::socket_type::pull); client.connect("tcp://127.0.0.1:9000"); // Send a single message from server to client zmqpp::message request; request << "Hello"; server.send(request); zmqpp::message response; client.receive(response); assert("Hello" == response.get(0)); std::cout << "Strawhouse test OK" << std::endl; return 0; } /* prem@prem-Vostro-2420:~/zmqpp-develop/examples$./strawhouse auth: Starting ZAP Authentication Server auth: verbose:true auth: API command=DOMAIN auth: domain=global auth: API command=ALLOW auth: whitelisting ipaddress=127.0.0.1 Strawhouse test OK auth: API command=TERMINATE auth: Shutdown ZAP Authentication Server prem@prem-Vostro-2420:~/zmqpp-develop/examples$ */ <commit_msg>Travis build error fix.<commit_after>/** * The Strawhouse Pattern. * * We allow or deny clients according to their IP address. It may keep * spammers and idiots away, but won't stop a real attacker for more * than a heartbeat. * * \date 25 Nov 2014 * \author Prem Shankar Kumar (\@meprem) */ #include <zmqpp/zmqpp.hpp> #include <string> #include <iostream> using namespace std; int main(int argc, char *argv[]) { // initialize the 0MQ context zmqpp::context context; // Start an authentication engine for this context. This engine // allows or denies incoming connections (talking to the libzmq // core over a protocol called ZAP). zmqpp::auth authenticator(context); // Get some indication of what the authenticator is deciding authenticator.set_verbose (true); // Configure ZAP domain authenticator.configure_domain ("global"); // Whitelist our address; any other address will be rejected authenticator.allow ("127.0.0.1"); // create and bind a server socket zmqpp::socket server (context, zmqpp::socket_type::push); //server.set(zmqpp::socket_option::zap_domain, "global"); server.bind("tcp://*:9000"); // create and connect a client socket zmqpp::socket client (context, zmqpp::socket_type::pull); client.connect("tcp://127.0.0.1:9000"); // Send a single message from server to client zmqpp::message request; request << "Hello"; server.send(request); zmqpp::message response; client.receive(response); assert("Hello" == response.get(0)); std::cout << "Strawhouse test OK" << std::endl; return 0; } /* prem@prem-Vostro-2420:~/zmqpp-develop/examples$./strawhouse auth: Starting ZAP Authentication Server auth: verbose:true auth: API command=DOMAIN auth: domain=global auth: API command=ALLOW auth: whitelisting ipaddress=127.0.0.1 Strawhouse test OK auth: API command=TERMINATE auth: Shutdown ZAP Authentication Server prem@prem-Vostro-2420:~/zmqpp-develop/examples$ */ <|endoftext|>
<commit_before>// netfortune session // Copyright © 2017 Christian Rapp // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "fsession.hpp" #include <thread> namespace bas = boost::asio; FSession::FSession(bas::ip::tcp::socket socket) : socket(std::move(socket)) { std::cout << "FSession created" << std::endl; } FSession::~FSession() { std::cout << "FSession destroyed" << std::endl; } void FSession::start() { std::cout << "Session started" << std::endl; // this will block std::this_thread::sleep_for(std::chrono::seconds(10)); } void FSession::do_read() { this->data_buf.clear(); this->data_buf.resize(2); auto self(shared_from_this()); bas::async_read( this->socket, bas::buffer(this->data_buf, this->data_buf.size()), [this, self](boost::system::error_code ec, size_t bytes) { unsigned short int message_length = 0; if (!ec) { assert(bytes == 2); message_length = ((this->data_buf.at(0) << 8) & this->data_buf.at(1)); std::cout << message_length << std::endl; } }); } void FSession::do_write() {} <commit_msg>Added some hints on how to implement the protocol<commit_after>// netfortune session // Copyright © 2017 Christian Rapp // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "fsession.hpp" #include <thread> namespace bas = boost::asio; FSession::FSession(bas::ip::tcp::socket socket) : socket(std::move(socket)) { std::cout << "FSession created" << std::endl; } FSession::~FSession() { std::cout << "FSession destroyed" << std::endl; } void FSession::start() { std::cout << "Session started" << std::endl; // this will block std::this_thread::sleep_for(std::chrono::seconds(10)); } void FSession::do_read() { // https://stackoverflow.com/a/22291720 // https://stackoverflow.com/a/25687309/1127601 this->data_buf.clear(); this->data_buf.resize(2); auto self(shared_from_this()); bas::async_read( this->socket, bas::buffer(this->data_buf, this->data_buf.size()), [this, self](boost::system::error_code ec, size_t bytes) { unsigned short int message_length = 0; if (!ec) { assert(bytes == 2); message_length = ((this->data_buf.at(0) << 8) & this->data_buf.at(1)); std::cout << message_length << std::endl; } }); } void FSession::do_write() {} <|endoftext|>
<commit_before>#include "IdPasskeyHandler.hpp" #include <errno.h> #include <pwd.h> #include <sys/ioctl.h> #include <sys/types.h> #include <termios.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #if __APPLE__ #include <util.h> #include <sys/ucred.h> #elif __FreeBSD__ #include <sys/types.h> #include <sys/ioctl.h> #include <termios.h> #include <libutil.h> #else #include <pty.h> #endif #include "ServerConnection.hpp" // TODO: This is ugly, fix later. extern map<string, int64_t> idPidMap; extern shared_ptr<et::ServerConnection> globalServer; struct PeerInfo { bool pidKnown; pid_t pid; bool uidKnown; uid_t uid; bool gidKnown; gid_t gid; }; #define FIFO_NAME "/tmp/etserver.idpasskey.fifo" void IdPasskeyHandler::runServer(bool* done) { int num, fd; unsigned int s2; sockaddr_un local, remote; fd = socket(AF_UNIX, SOCK_STREAM, 0); FATAL_FAIL(fd); local.sun_family = AF_UNIX; /* local is declared before socket() ^ */ strcpy(local.sun_path, FIFO_NAME); unlink(local.sun_path); // Also set the accept socket as reusable { int flag = 1; FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int))); } FATAL_FAIL(::bind(fd, (struct sockaddr *)&local, sizeof(sockaddr_un))); listen(fd, 5); LOG(INFO) << "Listening to id/key FIFO"; while(!(*done)) { printf("Waiting for a connection...\n"); socklen_t t = sizeof(remote); if ((s2 = ::accept(fd, (struct sockaddr *)&remote, &t)) == -1) { FATAL_FAIL(-1); } LOG(INFO) << "Connected"; PeerInfo peer = { false, 0, false, 0, false, 0 }; #if defined(SO_PEERCRED) struct ucred ucred; len = sizeof(struct ucred); FATAL_FAIL(getsockopt(s2, SOL_SOCKET, SO_PEERCRED, &ucred, &len)); peer = { true, cred.pid, true, cred.uid, true, cred.gid }; #elif defined(LOCAL_PEERCRED) xucred cred; socklen_t credLen = sizeof(cred); FATAL_FAIL(getsockopt(s2, SOL_LOCAL, LOCAL_PEERCRED, &cred, &credLen)); peer = { false, 0, true, cred.cr_uid, false, 0 }; #endif printf("Credentials from SO_PEERCRED: pid=%ld, euid=%ld, egid=%ld\n", (long) peer.pid, (long) peer.uid, (long) peer.gid); string buf; do { char c; if ((num = read(s2, &c, 1)) == -1) { LOG(FATAL) << "Error while reading from id/key FIFO: " << errno; } else if (num == 1) { if (c == '\0') { VLOG(1) << "Got idPasskey: " << buf << endl; size_t slashIndex = buf.find("/"); if (slashIndex == string::npos) { LOG(ERROR) << "Invalid idPasskey id/key pair: " << buf; } else { string id = buf.substr(0, slashIndex); string key = buf.substr(slashIndex+1); idPidMap[id] = (int64_t)peer.uid; globalServer->addClientKey(id, key); break; } buf = ""; } else { buf += c; } } } while (num > 0); close(s2); } } void IdPasskeyHandler::send(const string& idPasskey) { int fd; sockaddr_un remote; fd = ::socket(AF_UNIX, SOCK_STREAM, 0); FATAL_FAIL(fd); remote.sun_family = AF_UNIX; strcpy(remote.sun_path, FIFO_NAME); if (connect(fd, (struct sockaddr *) &remote, sizeof(sockaddr_un)) < 0) { close(fd); FATAL_FAIL(fd); } FATAL_FAIL(write(fd, &(idPasskey[0]), idPasskey.length())); close(fd); } <commit_msg>chmod<commit_after>#include "IdPasskeyHandler.hpp" #include <errno.h> #include <pwd.h> #include <sys/ioctl.h> #include <sys/types.h> #include <termios.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #if __APPLE__ #include <util.h> #include <sys/ucred.h> #elif __FreeBSD__ #include <sys/types.h> #include <sys/ioctl.h> #include <termios.h> #include <libutil.h> #else #include <pty.h> #endif #include "ServerConnection.hpp" // TODO: This is ugly, fix later. extern map<string, int64_t> idPidMap; extern shared_ptr<et::ServerConnection> globalServer; struct PeerInfo { bool pidKnown; pid_t pid; bool uidKnown; uid_t uid; bool gidKnown; gid_t gid; }; #define FIFO_NAME "/tmp/etserver.idpasskey.fifo" void IdPasskeyHandler::runServer(bool* done) { int num, fd; unsigned int s2; sockaddr_un local, remote; fd = socket(AF_UNIX, SOCK_STREAM, 0); FATAL_FAIL(fd); local.sun_family = AF_UNIX; /* local is declared before socket() ^ */ strcpy(local.sun_path, FIFO_NAME); unlink(local.sun_path); // Also set the accept socket as reusable { int flag = 1; FATAL_FAIL(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(int))); } FATAL_FAIL(::bind(fd, (struct sockaddr *)&local, sizeof(sockaddr_un))); listen(fd, 5); chmod(local.sun_path, 0777); LOG(INFO) << "Listening to id/key FIFO"; while(!(*done)) { printf("Waiting for a connection...\n"); socklen_t t = sizeof(remote); if ((s2 = ::accept(fd, (struct sockaddr *)&remote, &t)) == -1) { FATAL_FAIL(-1); } LOG(INFO) << "Connected"; PeerInfo peer = { false, 0, false, 0, false, 0 }; #if defined(SO_PEERCRED) struct ucred ucred; len = sizeof(struct ucred); FATAL_FAIL(getsockopt(s2, SOL_SOCKET, SO_PEERCRED, &ucred, &len)); peer = { true, cred.pid, true, cred.uid, true, cred.gid }; #elif defined(LOCAL_PEERCRED) xucred cred; socklen_t credLen = sizeof(cred); FATAL_FAIL(getsockopt(s2, SOL_LOCAL, LOCAL_PEERCRED, &cred, &credLen)); peer = { false, 0, true, cred.cr_uid, false, 0 }; #endif printf("Credentials from SO_PEERCRED: pid=%ld, euid=%ld, egid=%ld\n", (long) peer.pid, (long) peer.uid, (long) peer.gid); string buf; do { char c; if ((num = read(s2, &c, 1)) == -1) { LOG(FATAL) << "Error while reading from id/key FIFO: " << errno; } else if (num == 1) { if (c == '\0') { VLOG(1) << "Got idPasskey: " << buf << endl; size_t slashIndex = buf.find("/"); if (slashIndex == string::npos) { LOG(ERROR) << "Invalid idPasskey id/key pair: " << buf; } else { string id = buf.substr(0, slashIndex); string key = buf.substr(slashIndex+1); idPidMap[id] = (int64_t)peer.uid; globalServer->addClientKey(id, key); break; } buf = ""; } else { buf += c; } } } while (num > 0); close(s2); } } void IdPasskeyHandler::send(const string& idPasskey) { int fd; sockaddr_un remote; fd = ::socket(AF_UNIX, SOCK_STREAM, 0); FATAL_FAIL(fd); remote.sun_family = AF_UNIX; strcpy(remote.sun_path, FIFO_NAME); if (connect(fd, (struct sockaddr *) &remote, sizeof(sockaddr_un)) < 0) { close(fd); FATAL_FAIL(-1); } FATAL_FAIL(write(fd, &(idPasskey[0]), idPasskey.length())); close(fd); } <|endoftext|>
<commit_before>// Copyright 2018 The Amber Authors. // // 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 #include "amber/recipe.h" namespace amber { RecipeImpl::RecipeImpl() = default; RecipeImpl::~RecipeImpl() = default; Recipe::Recipe() = default; Recipe::~Recipe() { delete impl_; } std::vector<ShaderInfo> Recipe::GetShaderInfo() const { if (!impl_) return {}; return impl_->GetShaderInfo(); } std::vector<std::string> Recipe::GetRequiredFeatures() const { return impl_ ? impl_->GetRequiredFeatures() : std::vector<std::string>(); } std::vector<std::string> Recipe::GetRequiredExtensions() const { return impl_ ? impl_->GetRequiredExtensions() : std::vector<std::string>(); } } // namespace amber <commit_msg>Initialize the impl_ field of RecipeImpl to null, to avoid problems deleting it if it has not been initialized. (#295)<commit_after>// Copyright 2018 The Amber Authors. // // 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 #include "amber/recipe.h" namespace amber { RecipeImpl::RecipeImpl() = default; RecipeImpl::~RecipeImpl() = default; Recipe::Recipe() : impl_(nullptr) {} Recipe::~Recipe() { delete impl_; } std::vector<ShaderInfo> Recipe::GetShaderInfo() const { if (!impl_) return {}; return impl_->GetShaderInfo(); } std::vector<std::string> Recipe::GetRequiredFeatures() const { return impl_ ? impl_->GetRequiredFeatures() : std::vector<std::string>(); } std::vector<std::string> Recipe::GetRequiredExtensions() const { return impl_ ? impl_->GetRequiredExtensions() : std::vector<std::string>(); } } // namespace amber <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Unit tests for the name and type resolution of the solidity parser. */ #include <string> #include <libdevcore/Log.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Exceptions.h> #include <boost/test/unit_test.hpp> namespace dev { namespace solidity { namespace test { namespace { void parseTextAndResolveNames(std::string const& _source) { Parser parser; ASTPointer<SourceUnit> sourceUnit = parser.parse(std::make_shared<Scanner>(CharStream(_source))); NameAndTypeResolver resolver({}); resolver.registerDeclarations(*sourceUnit); for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) resolver.resolveNamesAndTypes(*contract); } } BOOST_AUTO_TEST_SUITE(SolidityNameAndTypeResolution) BOOST_AUTO_TEST_CASE(smoke_test) { char const* text = "contract test {\n" " uint256 stateVariable1;\n" " function fun(uint256 arg1) { var x; uint256 y; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(double_stateVariable_declaration) { char const* text = "contract test {\n" " uint256 variable;\n" " uint128 variable;\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); } BOOST_AUTO_TEST_CASE(double_function_declaration) { char const* text = "contract test {\n" " function fun() { var x; }\n" " function fun() { var x; }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); } BOOST_AUTO_TEST_CASE(double_variable_declaration) { char const* text = "contract test {\n" " function f() { uint256 x; if (true) { uint256 x; } }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); } BOOST_AUTO_TEST_CASE(name_shadowing) { char const* text = "contract test {\n" " uint256 variable;\n" " function f() { uint32 variable ; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(name_references) { char const* text = "contract test {\n" " uint256 variable;\n" " function f(uint256 arg) returns (uint out) { f(variable); test; out; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(undeclared_name) { char const* text = "contract test {\n" " uint256 variable;\n" " function f(uint256 arg) { f(notfound); }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); } BOOST_AUTO_TEST_CASE(reference_to_later_declaration) { char const* text = "contract test {\n" " function g() { f(); }" " function f() { }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(struct_definition_directly_recursive) { char const* text = "contract test {\n" " struct MyStructName {\n" " address addr;\n" " MyStructName x;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); } BOOST_AUTO_TEST_CASE(struct_definition_indirectly_recursive) { char const* text = "contract test {\n" " struct MyStructName1 {\n" " address addr;\n" " uint256 count;\n" " MyStructName2 x;\n" " }\n" " struct MyStructName2 {\n" " MyStructName1 x;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); } BOOST_AUTO_TEST_CASE(struct_definition_recursion_via_mapping) { char const* text = "contract test {\n" " struct MyStructName1 {\n" " address addr;\n" " uint256 count;\n" " mapping(uint => MyStructName1) x;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_inference_smoke_test) { char const* text = "contract test {\n" " function f(uint256 arg1, uint32 arg2) returns (bool ret) { var x = arg1 + arg2 == 8; ret = x; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_checking_return) { char const* text = "contract test {\n" " function f() returns (bool r) { return 1 >= 2; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_checking_return_wrong_number) { char const* text = "contract test {\n" " function f() returns (bool r1, bool r2) { return 1 >= 2; }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(type_checking_return_wrong_type) { char const* text = "contract test {\n" " function f() returns (uint256 r) { return 1 >= 2; }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(type_checking_function_call) { char const* text = "contract test {\n" " function f() returns (bool r) { return g(12, true) == 3; }\n" " function g(uint256 a, bool b) returns (uint256 r) { }\n" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_conversion_for_comparison) { char const* text = "contract test {\n" " function f() { uint32(2) == int64(2); }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_conversion_for_comparison_invalid) { char const* text = "contract test {\n" " function f() { int32(2) == uint64(2); }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(type_inference_explicit_conversion) { char const* text = "contract test {\n" " function f() returns (int256 r) { var x = int256(uint32(2)); return x; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(large_string_literal) { char const* text = "contract test {\n" " function f() { var x = \"123456789012345678901234567890123\"; }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(balance) { char const* text = "contract test {\n" " function fun() {\n" " uint256 x = address(0).balance;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(balance_invalid) { char const* text = "contract test {\n" " function fun() {\n" " address(0).balance = 7;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(assignment_to_mapping) { char const* text = "contract test {\n" " struct str {\n" " mapping(uint=>uint) map;\n" " }\n" " str data;" " function fun() {\n" " var a = data.map;\n" " data.map = a;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(assignment_to_struct) { char const* text = "contract test {\n" " struct str {\n" " mapping(uint=>uint) map;\n" " }\n" " str data;" " function fun() {\n" " var a = data;\n" " data = a;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <commit_msg>Check that constructor does not have "returns" directive.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Unit tests for the name and type resolution of the solidity parser. */ #include <string> #include <libdevcore/Log.h> #include <libsolidity/Scanner.h> #include <libsolidity/Parser.h> #include <libsolidity/NameAndTypeResolver.h> #include <libsolidity/Exceptions.h> #include <boost/test/unit_test.hpp> namespace dev { namespace solidity { namespace test { namespace { void parseTextAndResolveNames(std::string const& _source) { Parser parser; ASTPointer<SourceUnit> sourceUnit = parser.parse(std::make_shared<Scanner>(CharStream(_source))); NameAndTypeResolver resolver({}); resolver.registerDeclarations(*sourceUnit); for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes()) if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get())) resolver.resolveNamesAndTypes(*contract); } } BOOST_AUTO_TEST_SUITE(SolidityNameAndTypeResolution) BOOST_AUTO_TEST_CASE(smoke_test) { char const* text = "contract test {\n" " uint256 stateVariable1;\n" " function fun(uint256 arg1) { var x; uint256 y; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(double_stateVariable_declaration) { char const* text = "contract test {\n" " uint256 variable;\n" " uint128 variable;\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); } BOOST_AUTO_TEST_CASE(double_function_declaration) { char const* text = "contract test {\n" " function fun() { var x; }\n" " function fun() { var x; }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); } BOOST_AUTO_TEST_CASE(double_variable_declaration) { char const* text = "contract test {\n" " function f() { uint256 x; if (true) { uint256 x; } }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); } BOOST_AUTO_TEST_CASE(name_shadowing) { char const* text = "contract test {\n" " uint256 variable;\n" " function f() { uint32 variable ; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(name_references) { char const* text = "contract test {\n" " uint256 variable;\n" " function f(uint256 arg) returns (uint out) { f(variable); test; out; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(undeclared_name) { char const* text = "contract test {\n" " uint256 variable;\n" " function f(uint256 arg) { f(notfound); }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), DeclarationError); } BOOST_AUTO_TEST_CASE(reference_to_later_declaration) { char const* text = "contract test {\n" " function g() { f(); }" " function f() { }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(struct_definition_directly_recursive) { char const* text = "contract test {\n" " struct MyStructName {\n" " address addr;\n" " MyStructName x;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); } BOOST_AUTO_TEST_CASE(struct_definition_indirectly_recursive) { char const* text = "contract test {\n" " struct MyStructName1 {\n" " address addr;\n" " uint256 count;\n" " MyStructName2 x;\n" " }\n" " struct MyStructName2 {\n" " MyStructName1 x;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), ParserError); } BOOST_AUTO_TEST_CASE(struct_definition_recursion_via_mapping) { char const* text = "contract test {\n" " struct MyStructName1 {\n" " address addr;\n" " uint256 count;\n" " mapping(uint => MyStructName1) x;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_inference_smoke_test) { char const* text = "contract test {\n" " function f(uint256 arg1, uint32 arg2) returns (bool ret) { var x = arg1 + arg2 == 8; ret = x; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_checking_return) { char const* text = "contract test {\n" " function f() returns (bool r) { return 1 >= 2; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_checking_return_wrong_number) { char const* text = "contract test {\n" " function f() returns (bool r1, bool r2) { return 1 >= 2; }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(type_checking_return_wrong_type) { char const* text = "contract test {\n" " function f() returns (uint256 r) { return 1 >= 2; }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(type_checking_function_call) { char const* text = "contract test {\n" " function f() returns (bool r) { return g(12, true) == 3; }\n" " function g(uint256 a, bool b) returns (uint256 r) { }\n" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_conversion_for_comparison) { char const* text = "contract test {\n" " function f() { uint32(2) == int64(2); }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(type_conversion_for_comparison_invalid) { char const* text = "contract test {\n" " function f() { int32(2) == uint64(2); }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(type_inference_explicit_conversion) { char const* text = "contract test {\n" " function f() returns (int256 r) { var x = int256(uint32(2)); return x; }" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(large_string_literal) { char const* text = "contract test {\n" " function f() { var x = \"123456789012345678901234567890123\"; }" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(balance) { char const* text = "contract test {\n" " function fun() {\n" " uint256 x = address(0).balance;\n" " }\n" "}\n"; BOOST_CHECK_NO_THROW(parseTextAndResolveNames(text)); } BOOST_AUTO_TEST_CASE(balance_invalid) { char const* text = "contract test {\n" " function fun() {\n" " address(0).balance = 7;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(assignment_to_mapping) { char const* text = "contract test {\n" " struct str {\n" " mapping(uint=>uint) map;\n" " }\n" " str data;" " function fun() {\n" " var a = data.map;\n" " data.map = a;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(assignment_to_struct) { char const* text = "contract test {\n" " struct str {\n" " mapping(uint=>uint) map;\n" " }\n" " str data;" " function fun() {\n" " var a = data;\n" " data = a;\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_CASE(returns_in_constructor) { char const* text = "contract test {\n" " function test() returns (uint a) {\n" " }\n" "}\n"; BOOST_CHECK_THROW(parseTextAndResolveNames(text), TypeError); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <|endoftext|>
<commit_before>/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 "rtkramp_ggo.h" #include "rtkMacro.h" #include "rtkProjectionsReader.h" #include "rtkFFTRampImageFilter.h" #include "rtkCudaFFTRampImageFilter.h" #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkStreamingImageFilter.h> #include <itkTimeProbe.h> int main(int argc, char * argv[]) { GGO(rtkramp, 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); // Projections reader typedef rtk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( names->GetFileNames() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ) // Ramp filter typedef rtk::FFTRampImageFilter<OutputImageType, OutputImageType, float > rampFilterType; rampFilterType::Pointer rampFilter; if( !strcmp(args_info.hardware_arg, "cuda") ) rampFilter = rtk::CudaFFTRampImageFilter::New(); else rampFilter = rampFilterType::New(); rampFilter->SetInput( reader->GetOutput() ); rampFilter->SetTruncationCorrection(args_info.pad_arg); rampFilter->SetHannCutFrequency(args_info.hann_arg); rampFilter->SetHannCutFrequencyY(args_info.hannY_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) ); itk::TimeProbe probe; probe.Start(); TRY_AND_EXIT_ON_ITK_EXCEPTION( streamer->Update() ) probe.Stop(); std::cout << "The streamed ramp filter update took " << probe.GetMean() << probe.GetUnit() << std::endl; // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( streamer->GetOutput() ); writer->UpdateOutputInformation(); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ) return EXIT_SUCCESS; } <commit_msg>Fix for compilation without cuda<commit_after>/*========================================================================= * * Copyright RTK Consortium * * 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.txt * * 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 "rtkramp_ggo.h" #include "rtkMacro.h" #include "rtkProjectionsReader.h" #include "rtkFFTRampImageFilter.h" #include "rtkConfiguration.h" #if CUDA_FOUND # include "rtkCudaFFTRampImageFilter.h" #endif #include <itkImageFileWriter.h> #include <itkRegularExpressionSeriesFileNames.h> #include <itkStreamingImageFilter.h> #include <itkTimeProbe.h> int main(int argc, char * argv[]) { GGO(rtkramp, 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); // Projections reader typedef rtk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileNames( names->GetFileNames() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() ) // Ramp filter typedef rtk::FFTRampImageFilter<OutputImageType, OutputImageType, float > rampFilterType; rampFilterType::Pointer rampFilter; if( !strcmp(args_info.hardware_arg, "cuda") ) { #if CUDA_FOUND rampFilter = rtk::CudaFFTRampImageFilter::New(); #else std::cerr << "The program has not been compiled with cuda option" << std::endl; return EXIT_FAILURE; #endif } rampFilter = rtk::CudaFFTRampImageFilter::New(); else rampFilter = rampFilterType::New(); rampFilter->SetInput( reader->GetOutput() ); rampFilter->SetTruncationCorrection(args_info.pad_arg); rampFilter->SetHannCutFrequency(args_info.hann_arg); rampFilter->SetHannCutFrequencyY(args_info.hannY_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) ); itk::TimeProbe probe; probe.Start(); TRY_AND_EXIT_ON_ITK_EXCEPTION( streamer->Update() ) probe.Stop(); std::cout << "The streamed ramp filter update took " << probe.GetMean() << probe.GetUnit() << std::endl; // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( streamer->GetOutput() ); writer->UpdateOutputInformation(); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ) return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // // ospray::sg #include "Module.h" #include "../common/RuntimeError.h" // ospray #include "ospcommon/common.h" // std #include <set> /*! \file sg/module/Module.cpp Defines the interface for writing ospray::sg modules */ namespace ospray { namespace sg { /*! allows a user of the scene graph (e.g., a model viewer) to load a scene graph module */ void loadModule(const std::string &moduleName) { static std::set<std::string> alreadyLoaded; if (alreadyLoaded.find(moduleName) != alreadyLoaded.end()) return; alreadyLoaded.insert(moduleName); const std::string libName = "ospray_sg_"+moduleName; const std::string symName = "ospray_sg_"+moduleName+"_init"; ospcommon::loadLibrary(libName); void *sym = ospcommon::getSymbol(symName); if (!sym) throw sg::RuntimeError("could not load module '"+moduleName+"' (symbol '"+symName+"' not found)"); void (*initFct)() = (void (*)())sym; initFct(); } } } <commit_msg>changing sg loadModule to match naming convention of other OSPRay modules<commit_after>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // // ospray::sg #include "Module.h" #include "../common/RuntimeError.h" // ospray #include "ospcommon/common.h" // std #include <set> /*! \file sg/module/Module.cpp Defines the interface for writing ospray::sg modules */ namespace ospray { namespace sg { /*! allows a user of the scene graph (e.g., a model viewer) to load a scene graph module */ void loadModule(const std::string &moduleName) { static std::set<std::string> alreadyLoaded; if (alreadyLoaded.find(moduleName) != alreadyLoaded.end()) return; alreadyLoaded.insert(moduleName); const std::string libName = "ospray_module_sg_"+moduleName; const std::string symName = "ospray_sg_"+moduleName+"_init"; ospcommon::loadLibrary(libName); void *sym = ospcommon::getSymbol(symName); if (!sym) throw sg::RuntimeError("could not load module '"+moduleName+"' (symbol '"+symName+"' not found)"); void (*initFct)() = (void (*)())sym; initFct(); } } } <|endoftext|>
<commit_before>#include "test/mocks/http/mocks.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" #include "library/common/api/external.h" #include "library/common/extensions/filters/http/platform_bridge/filter.h" #include "library/common/extensions/filters/http/platform_bridge/filter.pb.h" using testing::ByMove; using testing::Return; namespace Envoy { namespace Extensions { namespace HttpFilters { namespace PlatformBridge { namespace { std::string to_string(envoy_data data) { return std::string(reinterpret_cast<const char*>(data.bytes), data.length); } class PlatformBridgeFilterTest : public testing::Test { public: void setUpFilter(std::string&& yaml, envoy_http_filter* platform_filter) { envoymobile::extensions::filters::http::platform_bridge::PlatformBridge config; TestUtility::loadFromYaml(yaml, config); Api::External::registerApi(config.platform_filter_name(), platform_filter); config_ = std::make_shared<PlatformBridgeFilterConfig>(config); filter_ = std::make_unique<PlatformBridgeFilter>(config_); filter_->setDecoderFilterCallbacks(decoder_callbacks_); filter_->setEncoderFilterCallbacks(encoder_callbacks_); } typedef struct { unsigned int init_filter_calls; unsigned int on_request_headers_calls; unsigned int on_request_data_calls; unsigned int on_request_trailers_calls; unsigned int on_response_headers_calls; unsigned int on_response_data_calls; unsigned int on_response_trailers_calls; unsigned int release_filter_calls; } filter_invocations; PlatformBridgeFilterConfigSharedPtr config_{}; std::unique_ptr<PlatformBridgeFilter> filter_{}; NiceMock<Http::MockStreamDecoderFilterCallbacks> decoder_callbacks_; NiceMock<Http::MockStreamEncoderFilterCallbacks> encoder_callbacks_; }; TEST_F(PlatformBridgeFilterTest, BasicContinueOnRequestHeaders) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_request_headers = [](envoy_headers c_headers, bool end_stream, const void* context) -> envoy_filter_headers_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(c_headers.length, 1); EXPECT_EQ(to_string(c_headers.headers[0].key), ":authority"); EXPECT_EQ(to_string(c_headers.headers[0].value), "test.code"); EXPECT_TRUE(end_stream); invocations->on_request_headers_calls++; return {kEnvoyFilterHeadersStatusContinue, c_headers}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnRequestHeaders )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestRequestHeaderMapImpl request_headers{{":authority", "test.code"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true)); EXPECT_EQ(invocations.on_request_headers_calls, 1); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnRequestData) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_request_data = [](envoy_data c_data, bool end_stream, const void* context) -> envoy_filter_data_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(to_string(c_data), "request body"); EXPECT_TRUE(end_stream); invocations->on_request_data_calls++; return {kEnvoyFilterDataStatusContinue, c_data}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnRequestData )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Buffer::OwnedImpl request_data = Buffer::OwnedImpl("request body"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(request_data, true)); EXPECT_EQ(invocations.on_request_data_calls, 1); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnRequestTrailers) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_request_trailers = [](envoy_headers c_trailers, const void* context) -> envoy_filter_trailers_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(c_trailers.length, 1); EXPECT_EQ(to_string(c_trailers.headers[0].key), "x-test-trailer"); EXPECT_EQ(to_string(c_trailers.headers[0].value), "test trailer"); invocations->on_request_trailers_calls++; return {kEnvoyFilterTrailersStatusContinue, c_trailers}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnRequestTrailers )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestRequestTrailerMapImpl request_trailers{{"x-test-trailer", "test trailer"}}; EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_trailers)); EXPECT_EQ(invocations.on_request_trailers_calls, 1); } // DIVIDE TEST_F(PlatformBridgeFilterTest, BasicContinueOnResponseHeaders) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_response_headers = [](envoy_headers c_headers, bool end_stream, const void* context) -> envoy_filter_headers_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(c_headers.length, 1); EXPECT_EQ(to_string(c_headers.headers[0].key), ":status"); EXPECT_EQ(to_string(c_headers.headers[0].value), "test.code"); EXPECT_TRUE(end_stream); invocations->on_response_headers_calls++; return {kEnvoyFilterHeadersStatusContinue, c_headers}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnResponseHeaders )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestResponseHeaderMapImpl response_headers{{":status", "test.code"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true)); EXPECT_EQ(invocations.on_response_headers_calls, 1); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnResponseData) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_response_data = [](envoy_data c_data, bool end_stream, const void* context) -> envoy_filter_data_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(to_string(c_data), "response body"); EXPECT_TRUE(end_stream); invocations->on_response_data_calls++; return {kEnvoyFilterDataStatusContinue, c_data}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnResponseData )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Buffer::OwnedImpl response_data = Buffer::OwnedImpl("response body"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(response_data, true)); EXPECT_EQ(invocations.on_response_data_calls, 1); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnResponseTrailers) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_response_trailers = [](envoy_headers c_trailers, const void* context) -> envoy_filter_trailers_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(c_trailers.length, 1); EXPECT_EQ(to_string(c_trailers.headers[0].key), "x-test-trailer"); EXPECT_EQ(to_string(c_trailers.headers[0].value), "test trailer"); invocations->on_response_trailers_calls++; return {kEnvoyFilterTrailersStatusContinue, c_trailers}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnResponseTrailers )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestResponseTrailerMapImpl response_trailers{{"x-test-trailer", "test trailer"}}; EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->encodeTrailers(response_trailers)); EXPECT_EQ(invocations.on_response_trailers_calls, 1); } } // namespace } // namespace PlatformBridge } // namespace HttpFilters } // namespace Extensions } // namespace Envoy <commit_msg>filters: test null and noop filters (#1097)<commit_after>#include "test/mocks/http/mocks.h" #include "test/test_common/utility.h" #include "gtest/gtest.h" #include "library/common/api/external.h" #include "library/common/extensions/filters/http/platform_bridge/filter.h" #include "library/common/extensions/filters/http/platform_bridge/filter.pb.h" using testing::ByMove; using testing::Return; namespace Envoy { namespace Extensions { namespace HttpFilters { namespace PlatformBridge { namespace { std::string to_string(envoy_data data) { return std::string(reinterpret_cast<const char*>(data.bytes), data.length); } class PlatformBridgeFilterTest : public testing::Test { public: void setUpFilter(std::string&& yaml, envoy_http_filter* platform_filter) { envoymobile::extensions::filters::http::platform_bridge::PlatformBridge config; TestUtility::loadFromYaml(yaml, config); Api::External::registerApi(config.platform_filter_name(), platform_filter); config_ = std::make_shared<PlatformBridgeFilterConfig>(config); filter_ = std::make_unique<PlatformBridgeFilter>(config_); filter_->setDecoderFilterCallbacks(decoder_callbacks_); filter_->setEncoderFilterCallbacks(encoder_callbacks_); } typedef struct { unsigned int init_filter_calls; unsigned int on_request_headers_calls; unsigned int on_request_data_calls; unsigned int on_request_trailers_calls; unsigned int on_response_headers_calls; unsigned int on_response_data_calls; unsigned int on_response_trailers_calls; unsigned int release_filter_calls; } filter_invocations; PlatformBridgeFilterConfigSharedPtr config_{}; std::unique_ptr<PlatformBridgeFilter> filter_{}; NiceMock<Http::MockStreamDecoderFilterCallbacks> decoder_callbacks_; NiceMock<Http::MockStreamEncoderFilterCallbacks> encoder_callbacks_; }; TEST_F(PlatformBridgeFilterTest, NullImplementation) { envoy_http_filter* null_filter = static_cast<envoy_http_filter*>(safe_calloc(1, sizeof(envoy_http_filter))); setUpFilter("platform_filter_name: NullImplementation\n", null_filter); Http::TestRequestHeaderMapImpl request_headers{{":authority", "test.code"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); Buffer::OwnedImpl request_data = Buffer::OwnedImpl("request body"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(request_data, false)); Http::TestRequestTrailerMapImpl request_trailers{{"x-test-trailer", "test trailer"}}; EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_trailers)); Http::TestResponseHeaderMapImpl response_headers{{":status", "test.code"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, false)); Buffer::OwnedImpl response_data = Buffer::OwnedImpl("response body"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(response_data, false)); Http::TestResponseTrailerMapImpl response_trailers{{"x-test-trailer", "test trailer"}}; EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->encodeTrailers(response_trailers)); free(null_filter); } TEST_F(PlatformBridgeFilterTest, PartialNullImplementation) { envoy_http_filter* noop_filter = static_cast<envoy_http_filter*>(safe_calloc(1, sizeof(envoy_http_filter))); filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; noop_filter->static_context = &invocations; noop_filter->init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; setUpFilter("platform_filter_name: PartialNullImplementation\n", noop_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestRequestHeaderMapImpl request_headers{{":authority", "test.code"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); Buffer::OwnedImpl request_data = Buffer::OwnedImpl("request body"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(request_data, false)); Http::TestRequestTrailerMapImpl request_trailers{{"x-test-trailer", "test trailer"}}; EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_trailers)); Http::TestResponseHeaderMapImpl response_headers{{":status", "test.code"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, false)); Buffer::OwnedImpl response_data = Buffer::OwnedImpl("response body"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(response_data, false)); Http::TestResponseTrailerMapImpl response_trailers{{"x-test-trailer", "test trailer"}}; EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->encodeTrailers(response_trailers)); free(noop_filter); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnRequestHeaders) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_request_headers = [](envoy_headers c_headers, bool end_stream, const void* context) -> envoy_filter_headers_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(c_headers.length, 1); EXPECT_EQ(to_string(c_headers.headers[0].key), ":authority"); EXPECT_EQ(to_string(c_headers.headers[0].value), "test.code"); EXPECT_TRUE(end_stream); invocations->on_request_headers_calls++; return {kEnvoyFilterHeadersStatusContinue, c_headers}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnRequestHeaders )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestRequestHeaderMapImpl request_headers{{":authority", "test.code"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true)); EXPECT_EQ(invocations.on_request_headers_calls, 1); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnRequestData) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_request_data = [](envoy_data c_data, bool end_stream, const void* context) -> envoy_filter_data_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(to_string(c_data), "request body"); EXPECT_TRUE(end_stream); invocations->on_request_data_calls++; return {kEnvoyFilterDataStatusContinue, c_data}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnRequestData )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Buffer::OwnedImpl request_data = Buffer::OwnedImpl("request body"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(request_data, true)); EXPECT_EQ(invocations.on_request_data_calls, 1); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnRequestTrailers) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_request_trailers = [](envoy_headers c_trailers, const void* context) -> envoy_filter_trailers_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(c_trailers.length, 1); EXPECT_EQ(to_string(c_trailers.headers[0].key), "x-test-trailer"); EXPECT_EQ(to_string(c_trailers.headers[0].value), "test trailer"); invocations->on_request_trailers_calls++; return {kEnvoyFilterTrailersStatusContinue, c_trailers}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnRequestTrailers )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestRequestTrailerMapImpl request_trailers{{"x-test-trailer", "test trailer"}}; EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_trailers)); EXPECT_EQ(invocations.on_request_trailers_calls, 1); } // DIVIDE TEST_F(PlatformBridgeFilterTest, BasicContinueOnResponseHeaders) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_response_headers = [](envoy_headers c_headers, bool end_stream, const void* context) -> envoy_filter_headers_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(c_headers.length, 1); EXPECT_EQ(to_string(c_headers.headers[0].key), ":status"); EXPECT_EQ(to_string(c_headers.headers[0].value), "test.code"); EXPECT_TRUE(end_stream); invocations->on_response_headers_calls++; return {kEnvoyFilterHeadersStatusContinue, c_headers}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnResponseHeaders )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestResponseHeaderMapImpl response_headers{{":status", "test.code"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true)); EXPECT_EQ(invocations.on_response_headers_calls, 1); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnResponseData) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_response_data = [](envoy_data c_data, bool end_stream, const void* context) -> envoy_filter_data_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(to_string(c_data), "response body"); EXPECT_TRUE(end_stream); invocations->on_response_data_calls++; return {kEnvoyFilterDataStatusContinue, c_data}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnResponseData )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Buffer::OwnedImpl response_data = Buffer::OwnedImpl("response body"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(response_data, true)); EXPECT_EQ(invocations.on_response_data_calls, 1); } TEST_F(PlatformBridgeFilterTest, BasicContinueOnResponseTrailers) { envoy_http_filter platform_filter; filter_invocations invocations = {0, 0, 0, 0, 0, 0, 0, 0}; platform_filter.static_context = &invocations; platform_filter.init_filter = [](const void* context) -> const void* { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); invocations->init_filter_calls++; return context; }; platform_filter.on_response_trailers = [](envoy_headers c_trailers, const void* context) -> envoy_filter_trailers_status { filter_invocations* invocations = static_cast<filter_invocations*>(const_cast<void*>(context)); EXPECT_EQ(c_trailers.length, 1); EXPECT_EQ(to_string(c_trailers.headers[0].key), "x-test-trailer"); EXPECT_EQ(to_string(c_trailers.headers[0].value), "test trailer"); invocations->on_response_trailers_calls++; return {kEnvoyFilterTrailersStatusContinue, c_trailers}; }; setUpFilter(R"EOF( platform_filter_name: BasicContinueOnResponseTrailers )EOF", &platform_filter); EXPECT_EQ(invocations.init_filter_calls, 1); Http::TestResponseTrailerMapImpl response_trailers{{"x-test-trailer", "test trailer"}}; EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->encodeTrailers(response_trailers)); EXPECT_EQ(invocations.on_response_trailers_calls, 1); } } // namespace } // namespace PlatformBridge } // namespace HttpFilters } // namespace Extensions } // namespace Envoy <|endoftext|>
<commit_before>#include <utility> #include <cmath> #include "shape.hpp" #include "data_structures.hpp" Shape::Shape(Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef) : index_of_refraction(index_of_refraction), color(color), ambient_coef(ambient_coef), diffuse_coef(diffuse_coef), specular_coef(specular_coef) { } float Shape::getIndexOfRefraction() const { return index_of_refraction; } float Shape::getAmbientCoefficient() const { return ambient_coef; } float Shape::getDiffuseCoefficient() const { return diffuse_coef; } float Shape::getSpecularCoefficient() const { return specular_coef; } Color Shape::getColor() const { return color; } Sphere::Sphere(Point center, float radius, Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef) : Shape(color, index_of_refraction, ambient_coef, diffuse_coef, specular_coef), center(center), radius(radius) { } Ray* Sphere::getIntersection(const Ray& ray) const { Vector c(center.x, center.y, center.z); float det = pow(ray.getDir().dotProduct(c), 2) - ray.getDir().dotProduct(ray.getDir()) * (c.dotProduct(c) - pow(radius, 2)); if (det < 0) { return NULL; } float d = ray.dir.dotProduct(c); if (det == 0) { Point p(ray.dir.i * d, ray.dir.j * d, ray.dir.k * d); Vector v(c.i - p.x, c.j - p.y, c.k - p.z); return new Ray(p,v); } // two collisions else { float sdet = sqrt(det); if (fabsf(d - sdet) > fabsf(d + sdet)) { float d = d + sdet; } else { float d = d - sdet; } Point p(ray.dir.i * d, ray.dir.j * d, ray.dir.k * d); Vector v(c.i - p.x, c.j - p.y, c.k - p.z); return new Ray(p,v); } } Plane::Plane(Point center, Vector normal, Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef) : Shape(color, index_of_refraction, ambient_coef, diffuse_coef, specular_coef), center(center), normal(normal) { } /* Plane::Plane(Point center, Vector normal, Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef) : Shape(color, index_of_refraction, ambient_coef, diffuse_coef, specular_coef), normal(normal) { distance = fabs((float)((normal.i * center.x + normal.j * center.y + normal.k * center.z)/ sqrt(normal.i*normal.i+normal.j*normal.j+normal.k*normal.k))); } */ Ray* Plane::getIntersection(const Ray& ray) const { if(normal.dotProduct(ray.dir)==0){ //ray is parallel to the plane //if(normal.dotProduct(center-ray.origin)==0) //ray is directly on the planex if(normal.dotProduct(Vector(center.x-ray.origin.x, center.y-ray.origin.y, center.z-ray.origin.z))==0) //ray is directly on the plane return new Ray(ray.origin,normal); else //ray never intersects with the plane return NULL; }else{ //must intersect with the at one specific point //solve for parametric equation of a line float t = (normal.i*(center.x-ray.origin.x)+ normal.j*(center.y-ray.origin.y)+ normal.k*(center.z-ray.origin.z))/ (normal.i*ray.dir.i+normal.j*ray.dir.j+normal.k*ray.dir.k); if(t<0) return NULL; else{ Point p = Point(ray.origin.x+ray.dir.i*t, ray.origin.y+ray.dir.j*t, ray.origin.z+ray.dir.k*t); return new Ray(p,normal); } //should not reach this return NULL; } /* tyler's old method Vector v(center.x - ray.origin.x, center.y - ray.origin.y, center.z - ray.origin.z); float d = normal.dotProduct(v) / normal.dotProduct(ray.dir); if (fabsf(d) < 0.0000001) { Point p(ray.dir.i * d + ray.origin.x, ray.dir.j * d + ray.origin.y, ray.dir.k * d + ray.origin.z); return new Ray(p, normal); } else { // we have no collision return NULL; } */ } <commit_msg>Zev you don't need to leave old methods commented out. Also, not my code. Removed old code.<commit_after>#include <utility> #include <cmath> #include "shape.hpp" #include "data_structures.hpp" Shape::Shape(Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef) : index_of_refraction(index_of_refraction), color(color), ambient_coef(ambient_coef), diffuse_coef(diffuse_coef), specular_coef(specular_coef) { } float Shape::getIndexOfRefraction() const { return index_of_refraction; } float Shape::getAmbientCoefficient() const { return ambient_coef; } float Shape::getDiffuseCoefficient() const { return diffuse_coef; } float Shape::getSpecularCoefficient() const { return specular_coef; } Color Shape::getColor() const { return color; } Sphere::Sphere(Point center, float radius, Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef) : Shape(color, index_of_refraction, ambient_coef, diffuse_coef, specular_coef), center(center), radius(radius) { } Ray* Sphere::getIntersection(const Ray& ray) const { Vector c(center.x, center.y, center.z); float det = pow(ray.getDir().dotProduct(c), 2) - ray.getDir().dotProduct(ray.getDir()) * (c.dotProduct(c) - pow(radius, 2)); if (det < 0) { return NULL; } float d = ray.dir.dotProduct(c); if (det == 0) { Point p(ray.dir.i * d, ray.dir.j * d, ray.dir.k * d); Vector v(c.i - p.x, c.j - p.y, c.k - p.z); return new Ray(p,v); } // two collisions else { float sdet = sqrt(det); if (fabsf(d - sdet) > fabsf(d + sdet)) { float d = d + sdet; } else { float d = d - sdet; } Point p(ray.dir.i * d, ray.dir.j * d, ray.dir.k * d); Vector v(c.i - p.x, c.j - p.y, c.k - p.z); return new Ray(p,v); } } Plane::Plane(Point center, Vector normal, Color color, float index_of_refraction, float ambient_coef, float diffuse_coef, float specular_coef) : Shape(color, index_of_refraction, ambient_coef, diffuse_coef, specular_coef), center(center), normal(normal) { } Ray* Plane::getIntersection(const Ray& ray) const { if(normal.dotProduct(ray.dir)==0){ //ray is parallel to the plane //if(normal.dotProduct(center-ray.origin)==0) //ray is directly on the planex if(normal.dotProduct(Vector(center.x-ray.origin.x, center.y-ray.origin.y, center.z-ray.origin.z))==0) //ray is directly on the plane return new Ray(ray.origin,normal); else //ray never intersects with the plane return NULL; }else{ //must intersect with the at one specific point //solve for parametric equation of a line float t = (normal.i*(center.x-ray.origin.x)+ normal.j*(center.y-ray.origin.y)+ normal.k*(center.z-ray.origin.z))/ (normal.i*ray.dir.i+normal.j*ray.dir.j+normal.k*ray.dir.k); if(t<0) return NULL; else{ Point p = Point(ray.origin.x+ray.dir.i*t, ray.origin.y+ray.dir.j*t, ray.origin.z+ray.dir.k*t); return new Ray(p,normal); } //should not reach this return NULL; } } <|endoftext|>
<commit_before>#include "state.h" #include "quadtree.h" #include <glog/logging.h> #include <limits.h> namespace GameState { bool initialized_ = false; sf::Vector2f camera_; sf::FloatRect cameraBounds_; util::Tick ticks_ = 0; std::unique_ptr<entities::Sprite> hero_; float moveSpeed_; // Jumping stuff bool jumping_ = false; int velocityY_ = 0; std::unordered_map<std::string, bool> flags_; std::unordered_map<std::string, std::list<FlagChangeCallback>> flagChangeCallbacks_; std::unordered_map<std::string, int> values_; std::unordered_map<std::string, std::list<ValueChangeCallback>> valueChangeCallbacks_; // Stack is used to mimick maps_ std::stack<std::vector<std::unique_ptr<entities::Sprite>>> sprites_; std::stack<std::unique_ptr<map::Map>> maps_; std::unordered_map<int, TileCallback> tileEvents_; chaiscript::ChaiScript chai_(chaiscript::Std_Lib::library()); #define ADD_METHOD(Class, Name) chai_.add(chaiscript::fun(&Class::Name), #Name) #define ADD_FUNCTION(Name) ADD_METHOD(GameState, Name) #define ADD_TYPE(Type, Name) chai_.add(chaiscript::user_type<Type>(), Name); void initApi() { ADD_FUNCTION(mod); ADD_FUNCTION(initialized); ADD_FUNCTION(ticks); ADD_FUNCTION(loadMap); ADD_FUNCTION(popMap); ADD_FUNCTION(loadCharacter); ADD_FUNCTION(addItem); ADD_FUNCTION(setCharacterMoveSpeed); ADD_FUNCTION(addNpc); ADD_FUNCTION(setNpcCallback); ADD_FUNCTION(showDialog); ADD_FUNCTION(addDialogOption); ADD_FUNCTION(setDialogCallback); ADD_FUNCTION(clearEvents); ADD_FUNCTION(registerTileEvent); ADD_TYPE(entities::Sprite, "Sprite"); ADD_METHOD(entities::Sprite, id); ADD_METHOD(entities::Sprite, hp); ADD_METHOD(entities::Sprite, damage); ADD_METHOD(entities::Sprite, heal); ADD_METHOD(entities::Sprite, startJump); ADD_METHOD(entities::Sprite, move); ADD_METHOD(entities::Sprite, setMaxHp); ADD_METHOD(entities::Sprite, width); ADD_METHOD(entities::Sprite, height); ADD_METHOD(entities::Sprite, jumping); ADD_METHOD(entities::Sprite, setCollisionCallback); ADD_METHOD(entities::Sprite, addItem); ADD_METHOD(entities::Sprite, removeItem); ADD_TYPE(entities::Item, "Item"); ADD_METHOD(entities::Item, held); ADD_METHOD(entities::Item, hold); ADD_METHOD(entities::Item, drop); ADD_FUNCTION(getHero); ADD_FUNCTION(getSprite); ADD_FUNCTION(getNpc); ADD_FUNCTION(getItem); ADD_FUNCTION(getFlag); ADD_FUNCTION(setFlag); ADD_FUNCTION(addFlagChangeCallback); ADD_FUNCTION(getValue); ADD_FUNCTION(setValue); ADD_FUNCTION(addValueChangeCallback); } sf::Vector2f& camera() { return camera_; } entities::Sprite* spriteCollision( const std::unique_ptr<entities::Sprite>& sprite, const sf::FloatRect& collisionRect) { for (const auto& s : sprites()) { if (!s || !s->active() || s->phased() || s->id == sprite->id) { continue; } if (collisionRect.intersects(s->getDimensions())) { return s.get(); } } return nullptr; } float positionOfSpriteAbove(const std::unique_ptr<entities::Sprite>& sprite) { auto dim = sprite->getDimensions(); sf::FloatRect collisionRect(dim.left, 0, dim.width, dim.top); const auto other = spriteCollision(sprite, collisionRect); if (other) { const auto oDim = other->getDimensions(); return oDim.top + oDim.height; } return 0; } float densePositionAbove(const std::unique_ptr<entities::Sprite>& sprite) { float spriteAbove = positionOfSpriteAbove(sprite); float tileAbove = map()->positionOfTileAbove(sprite->getDimensions()); return std::max<float>(spriteAbove, tileAbove); } float positionOfSpriteBelow(const std::unique_ptr<entities::Sprite>& sprite) { auto dim = sprite->getDimensions(); sf::FloatRect collisionRect(dim.left, dim.top + dim.height, dim.width, map()->pixelHeight()); const auto other = spriteCollision(sprite, collisionRect); if (other) { const auto oDim = other->getDimensions(); return oDim.top - dim.height; } return std::numeric_limits<float>::max(); } // TODO(jsvana): make this and Above return the sprite if there is one // for collisions float densePositionBelow(const std::unique_ptr<entities::Sprite>& sprite) { float spriteBelow = positionOfSpriteBelow(sprite); float tileBelow = map()->positionOfTileBelow(sprite->getDimensions()); return std::min<float>(spriteBelow, tileBelow); } int mod(int a, int b) { return a % b; } void setTicks(util::Tick ticks) { ticks_ = ticks; } int ticks() { return (int)(ticks_ % INT_MAX); } void setHero(std::unique_ptr<entities::Sprite> hero) { hero_ = std::move(hero); } const std::unique_ptr<entities::Sprite>& hero() { return hero_; } entities::Sprite* getHero() { return hero_.get(); } void setHeroMoveSpeed(int amount, int total) { moveSpeed_ = (float)amount / (float)total; } int heroMoveSpeed() { return moveSpeed_; } void pushSprites(std::vector<std::unique_ptr<entities::Sprite>> sprites) { sprites_.push(std::move(sprites)); } std::vector<std::unique_ptr<entities::Sprite>>& sprites() { return sprites_.top(); } void popSprites() { sprites_.pop(); } const std::unique_ptr<map::Map>& map() { return maps_.top(); } chaiscript::ChaiScript& chai() { return chai_; } void addTileEvent(int id, TileCallback callback) { tileEvents_[id] = callback; } bool tileHasEvent(int id) { return tileEvents_.find(id) != tileEvents_.end(); } const TileCallback& tileCallback(int id) { return tileEvents_[id]; } void clearTileEvent(int id) { tileEvents_.erase(id); } void clearTileEvents() { tileEvents_.clear(); } void runTileEvent() { int tileNumber = map()->pointToTileNumber(hero_->getPosition()); if (!tileHasEvent(tileNumber)) { return; } TileCallback callback = tileCallback(tileNumber); callback(); clearTileEvent(tileNumber); } bool positionWalkable(const std::unique_ptr<entities::Sprite>& sprite, sf::FloatRect dim) { return positionWalkable(sprite.get(), dim); } bool positionWalkable(entities::Sprite* sprite, sf::FloatRect dim) { if (!map()->positionWalkable(dim)) { return false; } // Check sprite walkability for (const auto& s : sprites()) { if (!s || !s->active() || s->id == sprite->id) { continue; } sf::FloatRect intersection; if (dim.intersects(s->getDimensions(), intersection)) { dispatchCollision(sprite, s.get()); if (!s->phased()) { return false; } } } if (sprite != hero_.get() && dim.intersects(hero_->getDimensions())) { dispatchCollision(sprite, hero_.get()); if (!sprite->phased()) { return false; } } return true; } void dispatchCollision(entities::Sprite* mover, entities::Sprite* other) { if (!mover->collisionFunc) { return; } mover->collisionFunc(other->id); } void markInitialized() { initialized_ = true; } bool initialized() { return initialized_; } bool loadMap(std::string path) { maps_.push(std::make_unique<map::Map>(path)); sprites_.emplace(); sprites().emplace_back(); return true; } bool popMap() { maps_.pop(); sprites_.pop(); return true; } bool loadCharacter(std::string path, int tile, int initX, int initY) { hero_ = std::make_unique<entities::Sprite>(path); hero_->setPosition(initX * map()->tileWidth(), initY * map()->tileHeight()); hero_->setTile(tile); // IDs will start at 1, the hero gets 0 hero_->id = 0; return true; } bool setSpritePosition(entities::Id spriteId, int x, int y) { auto sprite = findSprite<entities::Sprite>(spriteId); if (!sprite) { return false; } sf::Vector2f p = map()->mapToPixel(x, y); sprite->setPosition(p); return true; } bool setCharacterMoveSpeed(int amount, int total) { moveSpeed_ = (float)amount / (float)total; return true; } bool setCharacterMaxHp(int hp) { hero_->setMaxHp(hp); return true; } template <typename T> entities::Id addSprite(const std::string& path, int tile, int x, int y) { sprites().push_back(std::make_unique<T>(path)); auto item = sprites().back().get(); item->setPosition(x * GameState::map()->tileWidth(), y * GameState::map()->tileHeight()); item->setTile(tile); const auto spriteId = sprites().size() - 1; item->id = spriteId; return spriteId; } entities::Id addItem(const std::string& path, int tile, int x, int y) { return addSprite<entities::Item>(path, tile, x, y); } entities::Id addNpc(const std::string& path, int tile, int x, int y) { return addSprite<entities::Npc>(path, tile, x, y); } template <typename T> T* findSprite(const entities::Id spriteId) { if (spriteId >= sprites().size()) { LOG(WARNING) << "Bad sprite ID: " << spriteId; return nullptr; } return static_cast<T*>(sprites()[spriteId].get()); } template <typename T> T* findSprite(const entities::Id spriteId, const entities::SpriteType type) { auto sprite = findSprite<T>(spriteId); if (!sprite) { return nullptr; } if (sprites()[spriteId]->type() != type) { LOG(WARNING) << "ID " << spriteId << " is incorrect type " << static_cast<int>(type) << " (wanted type " << static_cast<int>(sprites()[spriteId]->type()) << ")"; return nullptr; } return sprite; } entities::Sprite* getSprite(const entities::Id spriteId) { return findSprite<entities::Sprite>(spriteId); } entities::Npc* getNpc(const entities::Id npcId) { return findSprite<entities::Npc>(npcId, entities::SpriteType::NPC); } entities::Item* getItem(const entities::Id itemId) { return findSprite<entities::Item>(itemId, entities::SpriteType::ITEM); } bool setNpcCallback(const entities::Id npcId, entities::SpriteCallback callback) { auto npc = findSprite<entities::Npc>(npcId, entities::SpriteType::NPC); if (!npc) { return false; } npc->callbackFunc = callback; return true; } visual::DialogManager::Id showDialog(std::string message) { auto dialog = new visual::Dialog(message); dialog->setPosition(0, SCREEN_HEIGHT - dialog->pixelHeight()); return visual::DialogManager::queueDialog(dialog); } bool addDialogOption(visual::DialogManager::Id uid, std::string option) { return visual::DialogManager::addDialogOption(uid, option); } bool setDialogCallback(visual::DialogManager::Id uid, visual::DialogCallback callback) { return visual::DialogManager::setDialogCallback(uid, callback); } bool registerTileEvent(int x, int y, TileCallback callback) { addTileEvent(map()->mapPointToTileNumber(x, y), callback); return true; } bool clearEvents() { clearTileEvents(); return true; } void setFlag(const std::string& flag, bool value) { flags_[flag] = value; for (auto& callback : flagChangeCallbacks(flag)) { callback(value); } } bool getFlag(const std::string& flag) { const auto iter = flags_.find(flag); if (iter == flags_.end()) { return false; } return iter->second; } const std::list<FlagChangeCallback> flagChangeCallbacks( const std::string& flag) { const auto iter = flagChangeCallbacks_.find(flag); if (iter == flagChangeCallbacks_.end()) { return std::list<FlagChangeCallback>(); } return iter->second; } void addFlagChangeCallback(const std::string& flag, const FlagChangeCallback& func) { flagChangeCallbacks_[flag].push_back(func); } void setValue(const std::string& key, const int value) { values_[key] = value; for (auto& callback : valueChangeCallbacks(key)) { callback(value); } } int getValue(const std::string& key) { const auto iter = values_.find(flag); if (iter == values_.end()) { return 0; } return iter->second; } const std::list<ValueChangeCallback> valueChangeCallbacks( const std::string& key) { const auto iter = valueChangeCallbacks_.find(key); if (iter == valueChangeCallbacks_.end()) { return std::list<ValueChangeCallback>(); } return iter->second; } void addValueChangeCallback(const std::string& key, const ValueChangeCallback& func) { valueChangeCallbacks_[key].push_back(func); } } // namespace GameState <commit_msg>Fix bad commit<commit_after>#include "state.h" #include "quadtree.h" #include <glog/logging.h> #include <limits.h> namespace GameState { bool initialized_ = false; sf::Vector2f camera_; sf::FloatRect cameraBounds_; util::Tick ticks_ = 0; std::unique_ptr<entities::Sprite> hero_; float moveSpeed_; // Jumping stuff bool jumping_ = false; int velocityY_ = 0; std::unordered_map<std::string, bool> flags_; std::unordered_map<std::string, std::list<FlagChangeCallback>> flagChangeCallbacks_; std::unordered_map<std::string, int> values_; std::unordered_map<std::string, std::list<ValueChangeCallback>> valueChangeCallbacks_; // Stack is used to mimick maps_ std::stack<std::vector<std::unique_ptr<entities::Sprite>>> sprites_; std::stack<std::unique_ptr<map::Map>> maps_; std::unordered_map<int, TileCallback> tileEvents_; chaiscript::ChaiScript chai_(chaiscript::Std_Lib::library()); #define ADD_METHOD(Class, Name) chai_.add(chaiscript::fun(&Class::Name), #Name) #define ADD_FUNCTION(Name) ADD_METHOD(GameState, Name) #define ADD_TYPE(Type, Name) chai_.add(chaiscript::user_type<Type>(), Name); void initApi() { ADD_FUNCTION(mod); ADD_FUNCTION(initialized); ADD_FUNCTION(ticks); ADD_FUNCTION(loadMap); ADD_FUNCTION(popMap); ADD_FUNCTION(loadCharacter); ADD_FUNCTION(addItem); ADD_FUNCTION(setCharacterMoveSpeed); ADD_FUNCTION(addNpc); ADD_FUNCTION(setNpcCallback); ADD_FUNCTION(showDialog); ADD_FUNCTION(addDialogOption); ADD_FUNCTION(setDialogCallback); ADD_FUNCTION(clearEvents); ADD_FUNCTION(registerTileEvent); ADD_TYPE(entities::Sprite, "Sprite"); ADD_METHOD(entities::Sprite, id); ADD_METHOD(entities::Sprite, hp); ADD_METHOD(entities::Sprite, damage); ADD_METHOD(entities::Sprite, heal); ADD_METHOD(entities::Sprite, startJump); ADD_METHOD(entities::Sprite, move); ADD_METHOD(entities::Sprite, setMaxHp); ADD_METHOD(entities::Sprite, width); ADD_METHOD(entities::Sprite, height); ADD_METHOD(entities::Sprite, jumping); ADD_METHOD(entities::Sprite, setCollisionCallback); ADD_METHOD(entities::Sprite, addItem); ADD_METHOD(entities::Sprite, removeItem); ADD_TYPE(entities::Item, "Item"); ADD_METHOD(entities::Item, held); ADD_METHOD(entities::Item, hold); ADD_METHOD(entities::Item, drop); ADD_FUNCTION(getHero); ADD_FUNCTION(getSprite); ADD_FUNCTION(getNpc); ADD_FUNCTION(getItem); ADD_FUNCTION(getFlag); ADD_FUNCTION(setFlag); ADD_FUNCTION(addFlagChangeCallback); ADD_FUNCTION(getValue); ADD_FUNCTION(setValue); ADD_FUNCTION(addValueChangeCallback); } sf::Vector2f& camera() { return camera_; } entities::Sprite* spriteCollision( const std::unique_ptr<entities::Sprite>& sprite, const sf::FloatRect& collisionRect) { for (const auto& s : sprites()) { if (!s || !s->active() || s->phased() || s->id == sprite->id) { continue; } if (collisionRect.intersects(s->getDimensions())) { return s.get(); } } return nullptr; } float positionOfSpriteAbove(const std::unique_ptr<entities::Sprite>& sprite) { auto dim = sprite->getDimensions(); sf::FloatRect collisionRect(dim.left, 0, dim.width, dim.top); const auto other = spriteCollision(sprite, collisionRect); if (other) { const auto oDim = other->getDimensions(); return oDim.top + oDim.height; } return 0; } float densePositionAbove(const std::unique_ptr<entities::Sprite>& sprite) { float spriteAbove = positionOfSpriteAbove(sprite); float tileAbove = map()->positionOfTileAbove(sprite->getDimensions()); return std::max<float>(spriteAbove, tileAbove); } float positionOfSpriteBelow(const std::unique_ptr<entities::Sprite>& sprite) { auto dim = sprite->getDimensions(); sf::FloatRect collisionRect(dim.left, dim.top + dim.height, dim.width, map()->pixelHeight()); const auto other = spriteCollision(sprite, collisionRect); if (other) { const auto oDim = other->getDimensions(); return oDim.top - dim.height; } return std::numeric_limits<float>::max(); } // TODO(jsvana): make this and Above return the sprite if there is one // for collisions float densePositionBelow(const std::unique_ptr<entities::Sprite>& sprite) { float spriteBelow = positionOfSpriteBelow(sprite); float tileBelow = map()->positionOfTileBelow(sprite->getDimensions()); return std::min<float>(spriteBelow, tileBelow); } int mod(int a, int b) { return a % b; } void setTicks(util::Tick ticks) { ticks_ = ticks; } int ticks() { return (int)(ticks_ % INT_MAX); } void setHero(std::unique_ptr<entities::Sprite> hero) { hero_ = std::move(hero); } const std::unique_ptr<entities::Sprite>& hero() { return hero_; } entities::Sprite* getHero() { return hero_.get(); } void setHeroMoveSpeed(int amount, int total) { moveSpeed_ = (float)amount / (float)total; } int heroMoveSpeed() { return moveSpeed_; } void pushSprites(std::vector<std::unique_ptr<entities::Sprite>> sprites) { sprites_.push(std::move(sprites)); } std::vector<std::unique_ptr<entities::Sprite>>& sprites() { return sprites_.top(); } void popSprites() { sprites_.pop(); } const std::unique_ptr<map::Map>& map() { return maps_.top(); } chaiscript::ChaiScript& chai() { return chai_; } void addTileEvent(int id, TileCallback callback) { tileEvents_[id] = callback; } bool tileHasEvent(int id) { return tileEvents_.find(id) != tileEvents_.end(); } const TileCallback& tileCallback(int id) { return tileEvents_[id]; } void clearTileEvent(int id) { tileEvents_.erase(id); } void clearTileEvents() { tileEvents_.clear(); } void runTileEvent() { int tileNumber = map()->pointToTileNumber(hero_->getPosition()); if (!tileHasEvent(tileNumber)) { return; } TileCallback callback = tileCallback(tileNumber); callback(); clearTileEvent(tileNumber); } bool positionWalkable(const std::unique_ptr<entities::Sprite>& sprite, sf::FloatRect dim) { return positionWalkable(sprite.get(), dim); } bool positionWalkable(entities::Sprite* sprite, sf::FloatRect dim) { if (!map()->positionWalkable(dim)) { return false; } // Check sprite walkability for (const auto& s : sprites()) { if (!s || !s->active() || s->id == sprite->id) { continue; } sf::FloatRect intersection; if (dim.intersects(s->getDimensions(), intersection)) { dispatchCollision(sprite, s.get()); if (!s->phased()) { return false; } } } if (sprite != hero_.get() && dim.intersects(hero_->getDimensions())) { dispatchCollision(sprite, hero_.get()); if (!sprite->phased()) { return false; } } return true; } void dispatchCollision(entities::Sprite* mover, entities::Sprite* other) { if (!mover->collisionFunc) { return; } mover->collisionFunc(other->id); } void markInitialized() { initialized_ = true; } bool initialized() { return initialized_; } bool loadMap(std::string path) { maps_.push(std::make_unique<map::Map>(path)); sprites_.emplace(); sprites().emplace_back(); return true; } bool popMap() { maps_.pop(); sprites_.pop(); return true; } bool loadCharacter(std::string path, int tile, int initX, int initY) { hero_ = std::make_unique<entities::Sprite>(path); hero_->setPosition(initX * map()->tileWidth(), initY * map()->tileHeight()); hero_->setTile(tile); // IDs will start at 1, the hero gets 0 hero_->id = 0; return true; } bool setSpritePosition(entities::Id spriteId, int x, int y) { auto sprite = findSprite<entities::Sprite>(spriteId); if (!sprite) { return false; } sf::Vector2f p = map()->mapToPixel(x, y); sprite->setPosition(p); return true; } bool setCharacterMoveSpeed(int amount, int total) { moveSpeed_ = (float)amount / (float)total; return true; } bool setCharacterMaxHp(int hp) { hero_->setMaxHp(hp); return true; } template <typename T> entities::Id addSprite(const std::string& path, int tile, int x, int y) { sprites().push_back(std::make_unique<T>(path)); auto item = sprites().back().get(); item->setPosition(x * GameState::map()->tileWidth(), y * GameState::map()->tileHeight()); item->setTile(tile); const auto spriteId = sprites().size() - 1; item->id = spriteId; return spriteId; } entities::Id addItem(const std::string& path, int tile, int x, int y) { return addSprite<entities::Item>(path, tile, x, y); } entities::Id addNpc(const std::string& path, int tile, int x, int y) { return addSprite<entities::Npc>(path, tile, x, y); } template <typename T> T* findSprite(const entities::Id spriteId) { if (spriteId >= sprites().size()) { LOG(WARNING) << "Bad sprite ID: " << spriteId; return nullptr; } return static_cast<T*>(sprites()[spriteId].get()); } template <typename T> T* findSprite(const entities::Id spriteId, const entities::SpriteType type) { auto sprite = findSprite<T>(spriteId); if (!sprite) { return nullptr; } if (sprites()[spriteId]->type() != type) { LOG(WARNING) << "ID " << spriteId << " is incorrect type " << static_cast<int>(type) << " (wanted type " << static_cast<int>(sprites()[spriteId]->type()) << ")"; return nullptr; } return sprite; } entities::Sprite* getSprite(const entities::Id spriteId) { return findSprite<entities::Sprite>(spriteId); } entities::Npc* getNpc(const entities::Id npcId) { return findSprite<entities::Npc>(npcId, entities::SpriteType::NPC); } entities::Item* getItem(const entities::Id itemId) { return findSprite<entities::Item>(itemId, entities::SpriteType::ITEM); } bool setNpcCallback(const entities::Id npcId, entities::SpriteCallback callback) { auto npc = findSprite<entities::Npc>(npcId, entities::SpriteType::NPC); if (!npc) { return false; } npc->callbackFunc = callback; return true; } visual::DialogManager::Id showDialog(std::string message) { auto dialog = new visual::Dialog(message); dialog->setPosition(0, SCREEN_HEIGHT - dialog->pixelHeight()); return visual::DialogManager::queueDialog(dialog); } bool addDialogOption(visual::DialogManager::Id uid, std::string option) { return visual::DialogManager::addDialogOption(uid, option); } bool setDialogCallback(visual::DialogManager::Id uid, visual::DialogCallback callback) { return visual::DialogManager::setDialogCallback(uid, callback); } bool registerTileEvent(int x, int y, TileCallback callback) { addTileEvent(map()->mapPointToTileNumber(x, y), callback); return true; } bool clearEvents() { clearTileEvents(); return true; } void setFlag(const std::string& flag, bool value) { flags_[flag] = value; for (auto& callback : flagChangeCallbacks(flag)) { callback(value); } } bool getFlag(const std::string& flag) { const auto iter = flags_.find(flag); if (iter == flags_.end()) { return false; } return iter->second; } const std::list<FlagChangeCallback> flagChangeCallbacks( const std::string& flag) { const auto iter = flagChangeCallbacks_.find(flag); if (iter == flagChangeCallbacks_.end()) { return std::list<FlagChangeCallback>(); } return iter->second; } void addFlagChangeCallback(const std::string& flag, const FlagChangeCallback& func) { flagChangeCallbacks_[flag].push_back(func); } void setValue(const std::string& key, const int value) { values_[key] = value; for (auto& callback : valueChangeCallbacks(key)) { callback(value); } } int getValue(const std::string& key) { const auto iter = values_.find(key); if (iter == values_.end()) { return 0; } return iter->second; } const std::list<ValueChangeCallback> valueChangeCallbacks( const std::string& key) { const auto iter = valueChangeCallbacks_.find(key); if (iter == valueChangeCallbacks_.end()) { return std::list<ValueChangeCallback>(); } return iter->second; } void addValueChangeCallback(const std::string& key, const ValueChangeCallback& func) { valueChangeCallbacks_[key].push_back(func); } } // namespace GameState <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 2011-2012 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of Arcanet. * * * * Arcanet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * Arcanet is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with Arcanet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "store.h" #include "directory.h" #include "sha512.h" #include "html.h" namespace arc { const String Store::DatabaseDirectory = "db"; const size_t Store::ChunkSize = 256*1024; // 256 Kio Store *Store::Instance = NULL; Store::Store(void) { Interface::Instance->add("/files", this); } Store::~Store(void) { Interface::Instance->remove("/files"); } void Store::addDirectory(const String &name, const String &path) { mDirectories.insert(name, path); } void Store::removeDirectory(const String &name) { mDirectories.erase(name); } void Store::refresh(void) { mFiles.clear(); for(StringMap::iterator it = mDirectories.begin(); it != mDirectories.end(); ++it) { refreshDirectory(it->first, it->second); } } bool Store::get(const Identifier &identifier, Entry &entry, bool content) { entry.content = NULL; try { String entryName = DatabaseDirectory+Directory::Separator+identifier.toString(); String url; if(mFiles.get(identifier,url)) // Hash is on content { Identifier hash; Sha512::Hash(url, hash); entryName = DatabaseDirectory+Directory::Separator+hash.toString(); if(File::Exist(entryName)) // TODO: force reindexation { File file(entryName, File::Read); file.readLine(entry.path); file.read(entry.info); Assert(entry.info.get("type") != "directory"); if(content) entry.content = new File(entry.path, File::Read); // content = file } } else if(File::Exist(entryName)) // Hash is on URL { entry.content = new File(entryName, File::Read); // content = meta entry.content->readLine(entry.path); entry.content->read(entry.info); if(!content) { delete entry.content; entry.content = NULL; } } } catch(Exception &e) { if(entry.content) { delete entry.content; entry.content = NULL; } Log("Store", String("Corrupted entry for ")+identifier.toString()+": "+e.what()); return false; } return true; } bool Store::get(const String &url, Entry &entry, bool content) { Identifier hash; try { if(url.find('/') == String::NotFound) // url is a hash { String s(url); s >> hash; } else { Sha512::Hash(url, hash); } } catch(...) { // TODO: Log return false; } return get(hash, entry, content); } void Store::http(const String &prefix, Http::Request &request) { try { const String &url = request.url; if(request.url == "/") { Http::Response response(request,200); response.send(); Html page(response.sock); page.header(request.url); page.open("h1"); page.text(request.url); page.close("h1"); for(StringMap::iterator it = mDirectories.begin(); it != mDirectories.end(); ++it) { page.link(it->first, it->first); page.br(); } page.footer(); } else { String path = urlToPath(url); if(path[path.size()-1] == Directory::Separator) path.resize(path.size()-1); if(Directory::Exist(path)) { if(url[url.size()-1] != '/') { Http::Response response(request, 301); // Moved Permanently response.headers["Location"] = prefix+url+"/"; response.send(); return; } Http::Response response(request, 200); response.send(); Html page(response.sock); page.header(request.url); page.open("h1"); page.text(request.url); page.close("h1"); Directory dir(path); while(dir.nextFile()) { page.link(dir.fileName(), dir.fileName()); page.br(); } page.footer(); } else if(File::Exist(path)) { Http::Response response(request,200); response.headers["Content-Type"] = "application/octet-stream"; // TODO response.send(); File file(path, File::Read); response.sock->writeBinary(file); } else throw Exception("File not found"); } } catch(const Exception &e) { Log("Store::http",e.what()); throw 404; // Httpd handles integer exceptions } } void Store::refreshDirectory(const String &dirUrl, const String &dirPath) { Log("Store", String("Refreshing directory: ")+dirUrl); Identifier hash; Sha512::Hash(dirUrl, hash); String entryName = DatabaseDirectory+Directory::Separator+hash.toString(); File dirEntry(entryName, File::Write); dirEntry.writeLine(dirPath); StringMap header; header["type"] = "directory"; header["time"] << time(NULL); dirEntry.write(header); Directory dir(dirPath); while(dir.nextFile()) { String url(dirUrl + Directory::Separator + dir.fileName()); ByteString urlHash; Sha512::Hash(url, urlHash); String entryName = DatabaseDirectory+Directory::Separator+urlHash.toString(); if(!dir.fileIsDir() && File::Exist(entryName)) { try { File file(entryName, File::Read); String path; StringMap header; file.readLine(path); file.read(header); StringMap origHeader(header); time_t time; header["time"] >> time; if(!header.contains("type")) throw Exception("Missing type field"); if(header["type"] == "directory") throw Exception("Invalid type for file"); size_t size; String hash; size_t chunkSize; unsigned chunkCount; header["size"] >> size; header["chunk-size"] >> chunkSize; header["chunk-count"] >> chunkCount; header["hash"] >> hash; // If the file has not changed, don't hash it again if(size == dir.fileSize() && time == dir.fileTime()) { mFiles.insert(Identifier(hash), url); dirEntry.write(origHeader); continue; } } catch(Exception &e) { Log("Store", String("Corrupted entry for ")+dir.fileName()+": "+e.what()); } } Log("Store", String("Processing: ")+dir.fileName()); try { if(dir.fileIsDir()) { refreshDirectory(url, dir.filePath()); } else { ByteString dataHash; File data(dir.filePath(), File::Read); Sha512::Hash(data, dataHash); data.close(); size_t chunkSize = ChunkSize; unsigned chunkCount = dir.fileSize()/ChunkSize + 1; StringMap header; dir.getFileInfo(header); header["type"] = "file"; header["chunk-size"] << chunkSize; header["chunk-count"] << chunkCount; header["hash"] << dataHash; mFiles.insert(Identifier(dataHash), url); File file(entryName, File::Write); file.writeLine(dir.filePath()); file.write(header); dirEntry.write(header); data.open(dir.filePath(), File::Read); for(unsigned i=0; i<chunkCount; ++i) { dataHash.clear(); AssertIO(Sha512::Hash(data, ChunkSize, dataHash)); file.writeLine(dataHash); } } } catch(Exception &e) { Log("Store", String("Processing failed for ")+dir.fileName()+": "+e.what()); File::Remove(entryName); } } } String Store::urlToPath(const String &url) const { if(url.empty() || url[0] != '/') throw Exception("Invalid URL"); String dir(url.substr(1)); String path = dir.cut('/'); // Do not accept the parent directory symbol as a security protection if(path.find("..") != String::NotFound) throw Exception("Invalid URL"); String dirPath; if(!mDirectories.get(dir,dirPath)) throw Exception("Directory does not exists"); path.replace('/',Directory::Separator); return dirPath + Directory::Separator + path; } } <commit_msg>Store url handling<commit_after>/************************************************************************* * Copyright (C) 2011-2012 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of Arcanet. * * * * Arcanet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * Arcanet is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with Arcanet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "store.h" #include "directory.h" #include "sha512.h" #include "html.h" namespace arc { const String Store::DatabaseDirectory = "db"; const size_t Store::ChunkSize = 256*1024; // 256 Kio Store *Store::Instance = NULL; Store::Store(void) { Interface::Instance->add("/files", this); } Store::~Store(void) { Interface::Instance->remove("/files"); } void Store::addDirectory(const String &name, const String &path) { mDirectories.insert(name, path); } void Store::removeDirectory(const String &name) { mDirectories.erase(name); } void Store::refresh(void) { mFiles.clear(); for(StringMap::iterator it = mDirectories.begin(); it != mDirectories.end(); ++it) { refreshDirectory("/"+it->first, it->second); } } bool Store::get(const Identifier &identifier, Entry &entry, bool content) { entry.content = NULL; try { String entryName = DatabaseDirectory+Directory::Separator+identifier.toString(); String url; if(mFiles.get(identifier,url)) // Hash is on content { Identifier hash; Sha512::Hash(url, hash); entryName = DatabaseDirectory+Directory::Separator+hash.toString(); if(File::Exist(entryName)) // TODO: force reindexation { File file(entryName, File::Read); file.readLine(entry.path); file.read(entry.info); Assert(entry.info.get("type") != "directory"); if(content) entry.content = new File(entry.path, File::Read); // content = file } } else if(File::Exist(entryName)) // Hash is on URL { entry.content = new File(entryName, File::Read); // content = meta entry.content->readLine(entry.path); entry.content->read(entry.info); if(!content) { delete entry.content; entry.content = NULL; } } } catch(Exception &e) { if(entry.content) { delete entry.content; entry.content = NULL; } Log("Store", String("Corrupted entry for ")+identifier.toString()+": "+e.what()); return false; } return true; } bool Store::get(const String &url, Entry &entry, bool content) { Identifier hash; try { if(url.find('/') == String::NotFound) // url is a hash { String s(url); s >> hash; } else { Sha512::Hash(url, hash); } } catch(...) { // TODO: Log return false; } return get(hash, entry, content); } void Store::http(const String &prefix, Http::Request &request) { try { const String &url = request.url; if(request.url == "/") { Http::Response response(request,200); response.send(); Html page(response.sock); page.header(request.url); page.open("h1"); page.text(request.url); page.close("h1"); for(StringMap::iterator it = mDirectories.begin(); it != mDirectories.end(); ++it) { page.link(it->first, it->first); page.br(); } page.footer(); } else { String path = urlToPath(url); if(path[path.size()-1] == Directory::Separator) path.resize(path.size()-1); if(Directory::Exist(path)) { if(url[url.size()-1] != '/') { Http::Response response(request, 301); // Moved Permanently response.headers["Location"] = prefix+url+"/"; response.send(); return; } Http::Response response(request, 200); response.send(); Html page(response.sock); page.header(request.url); page.open("h1"); page.text(request.url); page.close("h1"); Directory dir(path); while(dir.nextFile()) { page.link(dir.fileName(), dir.fileName()); page.br(); } page.footer(); } else if(File::Exist(path)) { Http::Response response(request,200); response.headers["Content-Type"] = "application/octet-stream"; // TODO response.send(); File file(path, File::Read); response.sock->writeBinary(file); } else throw Exception("File not found"); } } catch(const Exception &e) { Log("Store::http",e.what()); throw 404; // Httpd handles integer exceptions } } void Store::refreshDirectory(const String &dirUrl, const String &dirPath) { Log("Store", String("Refreshing directory: ")+dirUrl); Identifier hash; Sha512::Hash(dirUrl, hash); String entryName = DatabaseDirectory+Directory::Separator+hash.toString(); File dirEntry(entryName, File::Write); dirEntry.writeLine(dirPath); StringMap header; header["type"] = "directory"; header["time"] << time(NULL); dirEntry.write(header); Directory dir(dirPath); while(dir.nextFile()) { String url(dirUrl + '/' + dir.fileName()); ByteString urlHash; Sha512::Hash(url, urlHash); String entryName = DatabaseDirectory+Directory::Separator+urlHash.toString(); if(!dir.fileIsDir() && File::Exist(entryName)) { try { File file(entryName, File::Read); String path; StringMap header; file.readLine(path); file.read(header); StringMap origHeader(header); time_t time; header["time"] >> time; if(!header.contains("type")) throw Exception("Missing type field"); if(header["type"] == "directory") throw Exception("Invalid type for file"); size_t size; String hash; size_t chunkSize; unsigned chunkCount; header["size"] >> size; header["chunk-size"] >> chunkSize; header["chunk-count"] >> chunkCount; header["hash"] >> hash; // If the file has not changed, don't hash it again if(size == dir.fileSize() && time == dir.fileTime()) { mFiles.insert(Identifier(hash), url); dirEntry.write(origHeader); continue; } } catch(Exception &e) { Log("Store", String("Corrupted entry for ")+dir.fileName()+": "+e.what()); } } Log("Store", String("Processing: ")+dir.fileName()); try { if(dir.fileIsDir()) { refreshDirectory(url, dir.filePath()); } else { ByteString dataHash; File data(dir.filePath(), File::Read); Sha512::Hash(data, dataHash); data.close(); size_t chunkSize = ChunkSize; unsigned chunkCount = dir.fileSize()/ChunkSize + 1; StringMap header; dir.getFileInfo(header); header["type"] = "file"; header["chunk-size"] << chunkSize; header["chunk-count"] << chunkCount; header["hash"] << dataHash; mFiles.insert(Identifier(dataHash), url); File file(entryName, File::Write); file.writeLine(dir.filePath()); file.write(header); dirEntry.write(header); data.open(dir.filePath(), File::Read); for(unsigned i=0; i<chunkCount; ++i) { dataHash.clear(); AssertIO(Sha512::Hash(data, ChunkSize, dataHash)); file.writeLine(dataHash); } } } catch(Exception &e) { Log("Store", String("Processing failed for ")+dir.fileName()+": "+e.what()); File::Remove(entryName); } } } String Store::urlToPath(const String &url) const { if(url.empty() || url[0] != '/') throw Exception("Invalid URL"); String dir(url.substr(1)); String path = dir.cut('/'); // Do not accept the parent directory symbol as a security protection if(path.find("..") != String::NotFound) throw Exception("Invalid URL"); String dirPath; if(!mDirectories.get(dir,dirPath)) throw Exception("Directory does not exists"); path.replace('/',Directory::Separator); return dirPath + Directory::Separator + path; } } <|endoftext|>
<commit_before>#pragma once enum TokenType { // Symbols ////// NUL, // Reserved WHITESPACE, // Spaces or tabs INDENT, // Spaces or tabs DEDENT, // Spaces or tabs NEWLINE, // /n LEFT_BRACKET, // { RIGHT_BRACKET, // } LEFT_SQUARE, // [ RIGHT_SQUARE, // ] LEFT_PAREN, // ( RIGHT_PAREN, // ) ARROW, // -> COMMA, // , DOT, // . TRIPLE_DOT // ... COLON, // : DOUBLE_COLON, // :: LEFT_CARROT, // < RIGHT_CARROT, // > SINGLE_QUOTE, // ' DOUBLE_QUOTE, // " TD_QUOTE, // """ // Identifiers // IDENTIFIER, // Custom identifier // Keywords KEY_TYPE, // type KEY_INTRIN, // intrinsic KEY_VOCAB, // vocab KEY_DEFINE, // define KEY_TRAIT, // trait KEY_INSTANCE, // instance KEY_MATCH, // match KEY_CASE, // case KEY_DO, // do KEY_IF, // if KEY_ELSE, // else KEY_DATA // data };<commit_msg>More tokens<commit_after>#pragma once enum TokenType { // Symbols ////// NUL, // Reserved WHITESPACE, // Spaces or tabs INDENT, // Spaces or tabs DEDENT, // Spaces or tabs NEWLINE, // /n LEFT_BRACKET, // { RIGHT_BRACKET, // } LEFT_SQUARE, // [ RIGHT_SQUARE, // ] LEFT_PAREN, // ( RIGHT_PAREN, // ) ARROW, // -> COMMA, // , DOT, // . TRIPLE_DOT // ... COLON, // : DOUBLE_COLON, // :: LEFT_CARROT, // < RIGHT_CARROT, // > SINGLE_QUOTE, // ' DOUBLE_QUOTE, // " TD_QUOTE, // """ // User defined stuff // IDENTIFIER, // foo in foo(->): LIT_INT, // 3 LIT_FLOAT, // 3.14159 LIT_STRING, // "FOO BAR!" // Keywords KEY_TYPE, // type KEY_INTRIN, // intrinsic KEY_VOCAB, // vocab KEY_DEFINE, // define KEY_TRAIT, // trait KEY_INSTANCE, // instance KEY_MATCH, // match KEY_CASE, // case KEY_DO, // do KEY_IF, // if KEY_ELSE, // else KEY_DATA, // data KEY_ABOUT, // about KEY_DOCS, // docs KEY_OP, // operator KEY_LEFT, // left KEY_RIGHT // right }; <|endoftext|>
<commit_before>/* Copyright (c) 2011, The Mineserver Project 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 The Mineserver Project 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 HOLDER 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. */ #ifdef WIN32 #include <winsock2.h> #else #include <netinet/in.h> #include <pwd.h> #endif #ifdef linux #include <unistd.h> #include <libgen.h> #include <wordexp.h> #include <climits> #endif #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> #include <cstdlib> #include <cstring> #include <cstdio> #include <ctime> #include <cmath> #include <cctype> #include "tools.h" #include "logger.h" #include "mineserver.h" #include "config.h" void putSint64(uint8_t* buf, int64_t value) { uint64_t nval = ntohll(value); memcpy(buf, &nval, 8); } void putSint32(uint8_t* buf, int32_t value) { uint32_t nval = htonl(value); memcpy(buf, &nval, 4); } void putSint16(uint8_t* buf, int16_t value) { short value2 = htons(value); memcpy(buf, &value2, 2); } void putFloat(uint8_t* buf, float value) { uint32_t nval; memcpy(&nval, &value, 4); nval = htonl(nval); memcpy(buf, &nval, 4); } void putDouble(uint8_t* buf, double value) { uint64_t nval; memcpy(&nval, &value, 8); nval = ntohll(nval); memcpy(buf, &nval, 8); } double getDouble(uint8_t* buf) { double val; uint64_t ival; memcpy(&ival, buf, 8); ival = ntohll(ival); memcpy(&val, &ival, 8); return val; } float getFloat(uint8_t* buf) { float val; int ival = ntohl(*reinterpret_cast<const int32_t*>(buf)); memcpy(&val, &ival, 4); return val; } int64_t getSint64(uint8_t* buf) { int64_t val; memcpy(&val, buf, 8); val = ntohll(val); return val; } int32_t getSint32(uint8_t* buf) { int val = ntohl(*reinterpret_cast<const int32_t*>(buf)); return val; } int32_t getSint16(uint8_t* buf) { short val = ntohs(*reinterpret_cast<const int16_t*>(buf)); return val; } std::string base36_encode(int value) { std::string output; my_itoa((int)abs(value), output, 36); if (value < 0) { output.insert(output.begin(), '-'); } return output; } void my_itoa(int value, std::string& buf, int base) { std::string hexarray("0123456789abcdefghijklmnopqrstuvwxyz"); int i = 30; buf = ""; if (!value) { buf = "0"; } for (; value && i; --i, value /= base) { buf.insert(buf.begin(), (char)hexarray[value % base]); } } std::string strToLower(std::string temp) { const int len = temp.length(); for (int i = 0; i != len; ++i) { temp[i] = std::tolower(temp[i]); } return temp; } std::string dtos(double n) { std::ostringstream result; result << n; return result.str(); } std::string hash(std::string value) { // Hash the player's name along with a secret to generate a unique hash for this player // Uses the DJB2 algorithm unsigned long hash = 5381; int c; char* cvalue = const_cast<char*>(value.c_str()); while ((c = *cvalue++)) { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } std::ostringstream hashString; hashString << hash; return hashString.str(); } bool fileExists(const std::string& filename) { std::ifstream i(filename.c_str()); return i; } std::string canonicalizePath(const std::string& pathname) { // We assume that pathname is already a path name, with no file component! #if defined(linux) wordexp_t exp_result; wordexp(pathname.c_str(), &exp_result, 0); char * d = strdup(exp_result.we_wordv[0]); wordfree(&exp_result); char * rp = new char[PATH_MAX]; std::memset(rp, 0, PATH_MAX); realpath(d, rp); std::string res(rp); free(d); delete rp; return res; #elif defined(WIN32) return pathname; #else return pathname; #endif } std::string relativeToAbsolute(std::string pathname) { /// This is a very crude way to check if the path is relative. /// We must replace this by a more portable "pathIsRelative()" check. if (!pathname.empty() && pathname[0] != PATH_SEPARATOR) pathname = Mineserver::get()->config()->config_path + PATH_SEPARATOR + pathname; pathname = canonicalizePath(pathname); return pathname; } std::string getHomeDir() { #if defined(linux) return canonicalizePath("~/.mineserver"); #elif defined(WIN32) return "%APPDATA%\Mineserver"; #else return "[ERROR: getHomeDir() not implemented]"; #endif } std::string pathOfExecutable() { const size_t dest_len = 4096; char path[dest_len]; std::memset(path, 0, dest_len); #if defined(linux) if (readlink ("/proc/self/exe", path, dest_len) != -1) { dirname(path); } return std::string(path); #elif defined(WIN32) if (0 == GetModuleFileName(NULL, path, dest_len)) { return ""; } return pathOfFile(path).first; #else return ""; #endif } std::pair<std::string, std::string> pathOfFile(const std::string& filename) { #if defined(linux) char * a = strdup(filename.c_str()); char * b = strdup(filename.c_str()); char * d = dirname(a); std::string res_p(d), res_f(basename(b)); free(a); free(b); return std::make_pair(canonicalizePath(res_p), res_f); #elif defined(WIN32) const size_t dest_len = 4096; char path[dest_len], *pPart; std::memset(path, 0, dest_len); GetFullPathName(filename.c_str(), dest_len, path, &pPart); const size_t diff = pPart - buffer; if (diff > 0 && diff != size_t(-1)) return std::make_pair(std::string(path, diff - 1), std::string(pPart)); else return std::make_pair(std::string(path), ""); #else return std::make_pair("[ERROR IN PATH RECONSTRUCTION: Unknown platform, please implement.]", ""); #endif } <commit_msg>Fixed relative-to-absolute path conversion to allow for unix-style home directories.<commit_after>/* Copyright (c) 2011, The Mineserver Project 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 The Mineserver Project 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 HOLDER 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. */ #ifdef WIN32 #include <winsock2.h> #else #include <netinet/in.h> #include <pwd.h> #endif #ifdef linux #include <unistd.h> #include <libgen.h> #include <wordexp.h> #include <climits> #endif #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> #include <cstdlib> #include <cstring> #include <cstdio> #include <ctime> #include <cmath> #include <cctype> #include "tools.h" #include "logger.h" #include "mineserver.h" #include "config.h" void putSint64(uint8_t* buf, int64_t value) { uint64_t nval = ntohll(value); memcpy(buf, &nval, 8); } void putSint32(uint8_t* buf, int32_t value) { uint32_t nval = htonl(value); memcpy(buf, &nval, 4); } void putSint16(uint8_t* buf, int16_t value) { short value2 = htons(value); memcpy(buf, &value2, 2); } void putFloat(uint8_t* buf, float value) { uint32_t nval; memcpy(&nval, &value, 4); nval = htonl(nval); memcpy(buf, &nval, 4); } void putDouble(uint8_t* buf, double value) { uint64_t nval; memcpy(&nval, &value, 8); nval = ntohll(nval); memcpy(buf, &nval, 8); } double getDouble(uint8_t* buf) { double val; uint64_t ival; memcpy(&ival, buf, 8); ival = ntohll(ival); memcpy(&val, &ival, 8); return val; } float getFloat(uint8_t* buf) { float val; int ival = ntohl(*reinterpret_cast<const int32_t*>(buf)); memcpy(&val, &ival, 4); return val; } int64_t getSint64(uint8_t* buf) { int64_t val; memcpy(&val, buf, 8); val = ntohll(val); return val; } int32_t getSint32(uint8_t* buf) { int val = ntohl(*reinterpret_cast<const int32_t*>(buf)); return val; } int32_t getSint16(uint8_t* buf) { short val = ntohs(*reinterpret_cast<const int16_t*>(buf)); return val; } std::string base36_encode(int value) { std::string output; my_itoa((int)abs(value), output, 36); if (value < 0) { output.insert(output.begin(), '-'); } return output; } void my_itoa(int value, std::string& buf, int base) { std::string hexarray("0123456789abcdefghijklmnopqrstuvwxyz"); int i = 30; buf = ""; if (!value) { buf = "0"; } for (; value && i; --i, value /= base) { buf.insert(buf.begin(), (char)hexarray[value % base]); } } std::string strToLower(std::string temp) { const int len = temp.length(); for (int i = 0; i != len; ++i) { temp[i] = std::tolower(temp[i]); } return temp; } std::string dtos(double n) { std::ostringstream result; result << n; return result.str(); } std::string hash(std::string value) { // Hash the player's name along with a secret to generate a unique hash for this player // Uses the DJB2 algorithm unsigned long hash = 5381; int c; char* cvalue = const_cast<char*>(value.c_str()); while ((c = *cvalue++)) { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } std::ostringstream hashString; hashString << hash; return hashString.str(); } bool fileExists(const std::string& filename) { std::ifstream i(filename.c_str()); return i; } std::string canonicalizePath(const std::string& pathname) { // We assume that pathname is already a path name, with no file component! #if defined(linux) wordexp_t exp_result; wordexp(pathname.c_str(), &exp_result, 0); char * d = strdup(exp_result.we_wordv[0]); wordfree(&exp_result); char * rp = new char[PATH_MAX]; std::memset(rp, 0, PATH_MAX); realpath(d, rp); std::string res(rp); free(d); delete rp; return res; #elif defined(WIN32) return pathname; #else return pathname; #endif } std::string relativeToAbsolute(std::string pathname) { /// This is a very crude way to check if the path is relative. /// We must replace this by a more portable "pathIsRelative()" check. if (!pathname.empty() && pathname[0] != PATH_SEPARATOR && pathname[0] != '~') pathname = Mineserver::get()->config()->config_path + PATH_SEPARATOR + pathname; pathname = canonicalizePath(pathname); return pathname; } std::string getHomeDir() { #if defined(linux) return canonicalizePath("~/.mineserver"); #elif defined(WIN32) return "%APPDATA%\Mineserver"; #else return "[ERROR: getHomeDir() not implemented]"; #endif } std::string pathOfExecutable() { const size_t dest_len = 4096; char path[dest_len]; std::memset(path, 0, dest_len); #if defined(linux) if (readlink ("/proc/self/exe", path, dest_len) != -1) { dirname(path); } return std::string(path); #elif defined(WIN32) if (0 == GetModuleFileName(NULL, path, dest_len)) { return ""; } return pathOfFile(path).first; #else return ""; #endif } std::pair<std::string, std::string> pathOfFile(const std::string& filename) { #if defined(linux) char * a = strdup(filename.c_str()); char * b = strdup(filename.c_str()); char * d = dirname(a); std::string res_p(d), res_f(basename(b)); free(a); free(b); return std::make_pair(canonicalizePath(res_p), res_f); #elif defined(WIN32) const size_t dest_len = 4096; char path[dest_len], *pPart; std::memset(path, 0, dest_len); GetFullPathName(filename.c_str(), dest_len, path, &pPart); const size_t diff = pPart - buffer; if (diff > 0 && diff != size_t(-1)) return std::make_pair(std::string(path, diff - 1), std::string(pPart)); else return std::make_pair(std::string(path), ""); #else return std::make_pair("[ERROR IN PATH RECONSTRUCTION: Unknown platform, please implement.]", ""); #endif } <|endoftext|>
<commit_before>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2017 Victor DENIS (victordenis01@gmail.com) ** ** ** ** 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 "Bookmarks/AddBookmarkDialog.hpp" #include <QTreeView> #include <QHeaderView> #include "Bookmarks/BookmarkManager.hpp" #include "Bookmarks/AddBookmarkProxyModel.hpp" #include "Bookmarks/BookmarksModel.hpp" #include "Bookmarks/BookmarkNode.hpp" #include "Application.hpp" namespace Sn { AddBookmarkDialog::AddBookmarkDialog(const QString& url, const QString& title, QWidget* parent, BookmarksManager* bookmarksManager) : QDialog(parent), m_url(url), m_bookmarksManager(bookmarksManager) { if (!m_bookmarksManager) m_bookmarksManager = Application::instance()->bookmarksManager(); setWindowFlags(Qt::Sheet); setupUI(); QTreeView* view{new QTreeView(this)}; BookmarksModel* model = m_bookmarksManager->bookmarksModel(); m_proxyModel = new AddBookmarkProxyModel(this); m_proxyModel->setSourceModel(model); view->setModel(m_proxyModel); view->expandAll(); view->header()->setStretchLastSection(true); view->header()->hide(); view->setItemsExpandable(false); view->setRootIsDecorated(false); view->setIndentation(10); view->show(); m_location->setModel(m_proxyModel); m_location->setView(view); m_name->setText(title); connect(m_buttonBox, &QDialogButtonBox::accepted, this, &AddBookmarkDialog::accept); } void AddBookmarkDialog::accept() { QModelIndex index{m_location->view()->currentIndex()}; index = m_proxyModel->mapToSource(index); if (!index.isValid()) index = m_bookmarksManager->bookmarksModel()->index(0, 0); BookmarkNode* parent{m_bookmarksManager->bookmarksModel()->node(index)}; BookmarkNode* bookmark{new BookmarkNode(BookmarkNode::Bookmark)}; bookmark->url = m_url; bookmark->title = m_name->text(); m_bookmarksManager->addBookmark(parent, bookmark); QDialog::accept(); } void AddBookmarkDialog::setupUI() { resize(240, 168); m_layout = new QVBoxLayout(this); m_description = new QLabel(tr("Type a name for the bookmark and choose where to keep it"), this); m_description->setTextFormat(Qt::PlainText); m_description->setWordWrap(true); m_name = new QLineEdit(this); m_name->setPlaceholderText(tr("Name of bookmark")); m_location = new QComboBox(this); m_spacer = new QSpacerItem(20, 2, QSizePolicy::Minimum, QSizePolicy::Expanding); m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this); m_buttonBox->setCenterButtons(false); m_layout->addWidget(m_description); m_layout->addWidget(m_name); m_layout->addWidget(m_location); m_layout->addItem(m_spacer); m_layout->addWidget(m_buttonBox); } }<commit_msg>Core/Bookmarks: [Fix] cancel button issue on add bookmark dialog<commit_after>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2017 Victor DENIS (victordenis01@gmail.com) ** ** ** ** 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 "Bookmarks/AddBookmarkDialog.hpp" #include <QTreeView> #include <QHeaderView> #include "Bookmarks/BookmarkManager.hpp" #include "Bookmarks/AddBookmarkProxyModel.hpp" #include "Bookmarks/BookmarksModel.hpp" #include "Bookmarks/BookmarkNode.hpp" #include "Application.hpp" namespace Sn { AddBookmarkDialog::AddBookmarkDialog(const QString& url, const QString& title, QWidget* parent, BookmarksManager* bookmarksManager) : QDialog(parent), m_url(url), m_bookmarksManager(bookmarksManager) { if (!m_bookmarksManager) m_bookmarksManager = Application::instance()->bookmarksManager(); setWindowFlags(Qt::Sheet); setupUI(); QTreeView* view{new QTreeView(this)}; BookmarksModel* model = m_bookmarksManager->bookmarksModel(); m_proxyModel = new AddBookmarkProxyModel(this); m_proxyModel->setSourceModel(model); view->setModel(m_proxyModel); view->expandAll(); view->header()->setStretchLastSection(true); view->header()->hide(); view->setItemsExpandable(false); view->setRootIsDecorated(false); view->setIndentation(10); view->show(); m_location->setModel(m_proxyModel); m_location->setView(view); m_name->setText(title); connect(m_buttonBox, &QDialogButtonBox::accepted, this, &AddBookmarkDialog::accept); connect(m_buttonBox, &QDialogButtonBox::rejected, this, &AddBookmarkDialog::reject); } void AddBookmarkDialog::accept() { QModelIndex index{m_location->view()->currentIndex()}; index = m_proxyModel->mapToSource(index); if (!index.isValid()) index = m_bookmarksManager->bookmarksModel()->index(0, 0); BookmarkNode* parent{m_bookmarksManager->bookmarksModel()->node(index)}; BookmarkNode* bookmark{new BookmarkNode(BookmarkNode::Bookmark)}; bookmark->url = m_url; bookmark->title = m_name->text(); m_bookmarksManager->addBookmark(parent, bookmark); QDialog::accept(); } void AddBookmarkDialog::setupUI() { resize(240, 168); m_layout = new QVBoxLayout(this); m_description = new QLabel(tr("Type a name for the bookmark and choose where to keep it"), this); m_description->setTextFormat(Qt::PlainText); m_description->setWordWrap(true); m_name = new QLineEdit(this); m_name->setPlaceholderText(tr("Name of bookmark")); m_location = new QComboBox(this); m_spacer = new QSpacerItem(20, 2, QSizePolicy::Minimum, QSizePolicy::Expanding); m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok, Qt::Horizontal, this); m_buttonBox->setCenterButtons(false); m_layout->addWidget(m_description); m_layout->addWidget(m_name); m_layout->addWidget(m_location); m_layout->addItem(m_spacer); m_layout->addWidget(m_buttonBox); } }<|endoftext|>
<commit_before>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** 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. ** ***********************************************************************************/ #pragma once #ifndef SIELOBROWSER_ADDBOOKMARKDIALOG_HPP #define SIELOBROWSER_ADDBOOKMARKDIALOG_HPP #include <QDialog> #include <QDialogButtonBox> #include <QLabel> #include <QLineEdit> #include <QComboBox> #include <QSpacerItem> #include <QVBoxLayout> namespace Sn { class BookmarksManager; class AddBookmarkProxyModel; class AddBookmarkDialog: public QDialog { Q_OBJECT public: AddBookmarkDialog(const QString& url, const QString& title, QWidget* parent = nullptr, BookmarksManager* bookmarksManager = nullptr); private slots: void accept(); private: void setupUI(); QString m_url{}; QVBoxLayout* m_layout{nullptr}; QLabel* m_description{nullptr}; QLineEdit* m_name{nullptr}; QComboBox* m_location{nullptr}; QSpacerItem* m_spacer{nullptr}; QDialogButtonBox* m_buttonBox{nullptr}; BookmarksManager* m_bookmarksManager{nullptr}; AddBookmarkProxyModel* m_proxyModel{nullptr}; }; } #endif //SIELOBROWSER_ADDBOOKMARKDIALOG_HPP <commit_msg>Add possibility to edit url<commit_after>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** 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. ** ***********************************************************************************/ #pragma once #ifndef SIELOBROWSER_ADDBOOKMARKDIALOG_HPP #define SIELOBROWSER_ADDBOOKMARKDIALOG_HPP #include <QDialog> #include <QDialogButtonBox> #include <QLabel> #include <QLineEdit> #include <QComboBox> #include <QSpacerItem> #include <QVBoxLayout> namespace Sn { class BookmarksManager; class AddBookmarkProxyModel; class AddBookmarkDialog: public QDialog { Q_OBJECT public: AddBookmarkDialog(const QString& url, const QString& title, QWidget* parent = nullptr, BookmarksManager* bookmarksManager = nullptr); private slots: void accept(); private: void setupUI(); QString m_url{}; QVBoxLayout* m_layout{nullptr}; QLabel* m_description{nullptr}; QLineEdit* m_name{nullptr}; QLineEdit* m_urlEdit{nullptr}; QComboBox* m_location{nullptr}; QSpacerItem* m_spacer{nullptr}; QDialogButtonBox* m_buttonBox{nullptr}; BookmarksManager* m_bookmarksManager{nullptr}; AddBookmarkProxyModel* m_proxyModel{nullptr}; }; } #endif //SIELOBROWSER_ADDBOOKMARKDIALOG_HPP <|endoftext|>
<commit_before>#include "stdafx.h" #include "CppUnitTest.h" #include <RoundRobin.h> #include "ExceptionThrowingRoundRobinTask.h" using namespace CppRoundRobin; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace CppRoundRobinTest { TEST_CLASS(RoundRobinTests) { public: TEST_METHOD(GetPeriod) { RoundRobin robin(1); Assert::AreEqual(robin.GetPeriod(), 1); } TEST_METHOD(SetPeriod) { RoundRobin robin(5); robin.SetPeriod(6); Assert::AreEqual(robin.GetPeriod(), 6); } TEST_METHOD(RunSingleTask) { RoundRobin robin(1); std::shared_ptr<RoundRobinTask> task(new ExceptionThrowingRoundRobinTask(1)); robin.AddTask(task); try { robin.TimerFired(); // force fire the timer robin.Run(); } catch (int e) { Assert::AreEqual(30, e); } } }; }<commit_msg>random changes<commit_after>#include "stdafx.h" #include "CppUnitTest.h" #include <RoundRobin.h> #include "ExceptionThrowingRoundRobinTask.h" using namespace CppRoundRobin; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace CppRoundRobinTest { TEST_CLASS(RoundRobinTests) { public: TEST_METHOD(GetPeriod) { RoundRobin robin(1); Assert::AreEqual(robin.GetPeriod(), 1); } TEST_METHOD(SetPeriod) { RoundRobin robin(5); robin.SetPeriod(6); Assert::AreEqual(robin.GetPeriod(), 6); } TEST_METHOD(RunSingleTask) { RoundRobin robin(1); std::shared_ptr<RoundRobinTask> task(new ExceptionThrowingRoundRobinTask(1)); robin.AddTask(task); try { robin.TimerFired(); // force fire the timer robin.Run(); } catch (int e) { Assert::AreEqual(30, e); } } TEST_METHOD(RunMultipleTasks) { RoundRobin robin(1); std::shared_ptr<RoundRobinTask> task(new ExceptionThrowingRoundRobinTask(1000)); robin.AddTask(task); try { robin.Run(); } catch (int e) { Assert::AreEqual(30, e); } } }; }<|endoftext|>
<commit_before>/* Copyright (c) 2010 Aldo J. Nunez Licensed under the Apache License, Version 2.0. See the LICENSE text file for details. */ #include "Common.h" #include "StackFrame.h" #include "Thread.h" #include "Module.h" #include "SingleDocumentContext.h" #include "CodeContext.h" #include "ExprContext.h" #include "FrameProperty.h" #include "RegisterSet.h" namespace Mago { StackFrame::StackFrame() : mPC( 0 ) { memset( &mFuncSH, 0, sizeof mFuncSH ); memset( &mBlockSH, 0, sizeof mBlockSH ); } StackFrame::~StackFrame() { } HRESULT StackFrame::GetCodeContext( IDebugCodeContext2** ppCodeCxt ) { if ( ppCodeCxt == NULL ) return E_INVALIDARG; HRESULT hr = S_OK; RefPtr<CodeContext> codeContext; hr = MakeCComObject( codeContext ); if ( FAILED( hr ) ) return hr; CComPtr<IDebugDocumentContext2> docContext; hr = GetDocumentContext( &docContext ); if ( FAILED( hr ) ) return hr; hr = codeContext->Init( mPC, mModule, docContext ); if ( FAILED( hr ) ) return hr; return codeContext->QueryInterface( __uuidof( IDebugCodeContext2 ), (void**) ppCodeCxt ); } HRESULT StackFrame::GetDocumentContext( IDebugDocumentContext2** ppCxt ) { if ( ppCxt == NULL ) return E_INVALIDARG; HRESULT hr = S_OK; RefPtr<SingleDocumentContext> docContext; LineInfo line; hr = MakeCComObject( docContext ); if ( FAILED( hr ) ) return hr; hr = GetLineInfo( line ); if ( FAILED( hr ) ) return hr; hr = docContext->Init( line.Filename, line.LineBegin, line.LineEnd, line.LangName, line.LangGuid ); if ( FAILED( hr ) ) return hr; return docContext->QueryInterface( __uuidof( IDebugDocumentContext2 ), (void**) ppCxt ); } HRESULT StackFrame::GetName( BSTR* pbstrName ) { return E_NOTIMPL; } HRESULT StackFrame::GetInfo( FRAMEINFO_FLAGS dwFieldSpec, UINT nRadix, FRAMEINFO* pFrameInfo ) { if ( pFrameInfo == NULL ) return E_INVALIDARG; HRESULT hr = S_OK; pFrameInfo->m_dwValidFields = 0; if ( (dwFieldSpec & FIF_FRAME) != 0 ) { hr = QueryInterface( __uuidof( IDebugStackFrame2 ), (void**) &pFrameInfo->m_pFrame ); _ASSERT( hr == S_OK ); pFrameInfo->m_dwValidFields |= FIF_FRAME; } if ( (dwFieldSpec & FIF_DEBUG_MODULEP) != 0 ) { if ( mModule.Get() != NULL ) { hr = mModule->QueryInterface( __uuidof( IDebugModule2 ), (void**) &pFrameInfo->m_pModule ); _ASSERT( hr == S_OK ); pFrameInfo->m_dwValidFields |= FIF_DEBUG_MODULEP; } } if ( (dwFieldSpec & FIF_STACKRANGE) != 0 ) { #if 0 if ( mDiaStackFrame != NULL ) { // TODO: review all this UINT64 base = 0; DWORD size = 0; mDiaStackFrame->get_base( &base ); mDiaStackFrame->get_size( &size ); pFrameInfo->m_addrMax = base; pFrameInfo->m_addrMin = base - size; pFrameInfo->m_dwValidFields |= FIF_STACKRANGE; } #endif } if ( (dwFieldSpec & FIF_DEBUGINFO) != 0 ) { if ( mModule.Get() != NULL ) { RefPtr<MagoST::ISession> session; pFrameInfo->m_fHasDebugInfo = mModule->GetSymbolSession( session ); } else pFrameInfo->m_fHasDebugInfo = FALSE; pFrameInfo->m_dwValidFields |= FIF_DEBUGINFO; } if ( (dwFieldSpec & FIF_FUNCNAME) != 0 ) { hr = GetFunctionName( &pFrameInfo->m_bstrFuncName ); if ( SUCCEEDED( hr ) ) pFrameInfo->m_dwValidFields |= FIF_FUNCNAME; } if ( (dwFieldSpec & FIF_RETURNTYPE) != 0 ) { //pFrameInfo->m_bstrReturnType; //pFrameInfo->m_dwValidFields |= FIF_RETURNTYPE; } if ( (dwFieldSpec & FIF_ARGS) != 0 ) { //pFrameInfo->m_bstrArgs; //pFrameInfo->m_dwValidFields |= FIF_ARGS; } if ( (dwFieldSpec & FIF_LANGUAGE) != 0 ) { pFrameInfo->m_bstrLanguage = SysAllocString( L"D" ); pFrameInfo->m_dwValidFields |= FIF_LANGUAGE; } if ( (dwFieldSpec & FIF_MODULE) != 0 ) { //pFrameInfo->m_bstrModule; //pFrameInfo->m_dwValidFields |= FIF_MODULE; } //FIF_STALECODE m_fStaleCode //FIF_ANNOTATEDFRAME m_fAnnotatedFrame return S_OK; } HRESULT StackFrame::GetPhysicalStackRange( UINT64* paddrMin, UINT64* paddrMax ) { return E_NOTIMPL; } HRESULT StackFrame::GetExpressionContext( IDebugExpressionContext2** ppExprCxt ) { OutputDebugStringA( "StackFrame::GetExpressionContext\n" ); HRESULT hr = S_OK; if ( mModule == NULL ) return E_NOT_FOUND; hr = MakeExprContext(); if ( FAILED( hr ) ) return hr; *ppExprCxt = mExprContext; (*ppExprCxt)->AddRef(); return S_OK; } HRESULT StackFrame::MakeExprContext() { HRESULT hr = S_OK; // ignore any error, because we don't have to have symbols for expression eval hr = FindFunction(); if ( mExprContext == NULL ) { GuardedArea guard( mExprContextGuard ); if ( mExprContext == NULL ) { RefPtr<ExprContext> exprContext; hr = MakeCComObject( exprContext ); if ( FAILED( hr ) ) return hr; hr = exprContext->Init( mModule, mThread, mFuncSH, mBlockSH, mPC, mRegSet ); if ( FAILED( hr ) ) return hr; mExprContext = exprContext; } } return S_OK; } HRESULT StackFrame::GetLanguageInfo( BSTR* pbstrLanguage, GUID* pguidLanguage ) { return E_NOTIMPL; } HRESULT StackFrame::GetDebugProperty( IDebugProperty2** ppDebugProp ) { OutputDebugStringA( "StackFrame::GetDebugProperty\n" ); if ( ppDebugProp == NULL ) return E_INVALIDARG; HRESULT hr = S_OK; RefPtr<FrameProperty> frameProp; hr = MakeExprContext(); if ( FAILED( hr ) ) return hr; hr = MakeCComObject( frameProp ); if ( FAILED( hr ) ) return hr; hr = frameProp->Init( mRegSet, mExprContext ); if ( FAILED( hr ) ) return hr; *ppDebugProp = frameProp.Detach(); return S_OK; } HRESULT StackFrame::EnumProperties( DEBUGPROP_INFO_FLAGS dwFieldSpec, UINT nRadix, REFIID refiid, DWORD dwTimeout, ULONG* pcelt, IEnumDebugPropertyInfo2** ppEnum ) { OutputDebugStringA( "StackFrame::EnumProperties\n" ); HRESULT hr = S_OK; CComPtr<IDebugProperty2> rootProp; hr = GetDebugProperty( &rootProp ); if ( FAILED( hr ) ) return hr; hr = rootProp->EnumChildren( dwFieldSpec, nRadix, refiid, DBG_ATTRIB_ALL, NULL, dwTimeout, ppEnum ); if ( FAILED( hr ) ) return hr; if ( pcelt != NULL ) { hr = (*ppEnum)->GetCount( pcelt ); if ( FAILED( hr ) ) return hr; } return S_OK; } HRESULT StackFrame::GetThread( IDebugThread2** ppThread ) { if ( ppThread == NULL ) return E_INVALIDARG; return mThread->QueryInterface( __uuidof( IDebugThread2 ), (void**) ppThread ); } //---------------------------------------------------------------------------- void StackFrame::Init( Address pc, IRegisterSet* regSet, Thread* thread, Module* module ) { _ASSERT( regSet != NULL ); _ASSERT( thread != NULL ); _ASSERT( module != NULL ); mPC = pc; mRegSet = regSet; mThread = thread; mModule = module; } HRESULT StackFrame::GetLineInfo( LineInfo& info ) { HRESULT hr = S_OK; RefPtr<MagoST::ISession> session; if ( mModule.Get() == NULL ) return E_NOT_FOUND; if ( !mModule->GetSymbolSession( session ) ) return E_NOT_FOUND; uint16_t sec = 0; uint32_t offset = 0; sec = session->GetSecOffsetFromVA( mPC, offset ); if ( sec == 0 ) return E_FAIL; MagoST::LineNumber line = { 0 }; if ( !session->FindLine( sec, offset, line ) ) return E_FAIL; info.LineBegin.dwLine = line.Number; //info.LineEnd.dwLine = line.NumberEnd; info.LineEnd.dwLine = line.Number; info.LineBegin.dwColumn = 0; info.LineEnd.dwColumn = 0; info.LineBegin.dwLine--; info.LineEnd.dwLine--; // if there's no column info, then these are 0 if ( info.LineBegin.dwColumn > 0 ) info.LineBegin.dwColumn--; if ( info.LineEnd.dwColumn > 0 ) info.LineEnd.dwColumn--; MagoST::FileInfo fileInfo = { 0 }; hr = session->GetFileInfo( line.CompilandIndex, line.FileIndex, fileInfo ); if ( FAILED( hr ) ) return hr; hr = Utf8To16( fileInfo.Name, fileInfo.NameLength, info.Filename.m_str ); if ( FAILED( hr ) ) return hr; // TODO: from the compiland we're supposed to get the language info.LangName = L"D"; info.LangGuid = GetDLanguageId(); return hr; } HRESULT StackFrame::GetFunctionName( BSTR* funcName ) { _ASSERT( funcName != NULL ); HRESULT hr = S_OK; hr = GetFunctionNameWithSymbols( funcName ); if ( FAILED( hr ) ) { hr = GetFunctionNameWithAddress( funcName ); } return hr; } HRESULT StackFrame::GetFunctionNameWithAddress( BSTR* funcName ) { _ASSERT( funcName != NULL ); wchar_t addrStr[ 8 + 1 ] = L""; _ASSERT( sizeof mPC == 4 ); swprintf_s( addrStr, L"%08x", mPC ); *funcName = SysAllocString( addrStr ); if ( *funcName == NULL ) return E_OUTOFMEMORY; return S_OK; } HRESULT StackFrame::GetFunctionNameWithSymbols( BSTR* funcName ) { _ASSERT( funcName != NULL ); HRESULT hr = S_OK; RefPtr<MagoST::ISession> session; MagoST::SymInfoData infoData = { 0 }; MagoST::ISymbolInfo* symInfo = NULL; if ( mModule.Get() == NULL ) return E_NOT_FOUND; if ( !mModule->GetSymbolSession( session ) ) return E_NOT_FOUND; hr = FindFunction(); if ( FAILED( hr ) ) return hr; hr = session->GetSymbolInfo( mFuncSH, infoData, symInfo ); if ( FAILED( hr ) ) return hr; PasString* pstrName = NULL; if ( !symInfo->GetName( pstrName ) ) return E_NOT_FOUND; hr = Utf8To16( pstrName->GetName(), pstrName->GetLength(), *funcName ); if ( FAILED( hr ) ) return hr; // for reference: you get the language by going to a lexical ancestor // that's a compiland, then you get a compiland detail from it return hr; } HRESULT StackFrame::FindFunction() { HRESULT hr = S_OK; RefPtr<MagoST::ISession> session; MagoST::SymHandle symHandle = { 0 }; // already found if ( memcmp( &mFuncSH, &symHandle, sizeof mFuncSH ) != 0 ) return S_OK; if ( mModule.Get() == NULL ) return E_NOT_FOUND; if ( !mModule->GetSymbolSession( session ) ) return E_NOT_FOUND; uint16_t sec = 0; uint32_t offset = 0; sec = session->GetSecOffsetFromVA( mPC, offset ); if ( sec == 0 ) return E_NOT_FOUND; // TODO: verify that it's a function or public symbol (or something else?) hr = session->FindOuterSymbolByAddr( MagoST::SymHeap_GlobalSymbols, sec, offset, symHandle ); if ( FAILED( hr ) ) { hr = session->FindOuterSymbolByAddr( MagoST::SymHeap_StaticSymbols, sec, offset, symHandle ); if ( FAILED( hr ) ) { hr = session->FindOuterSymbolByAddr( MagoST::SymHeap_PublicSymbols, sec, offset, symHandle ); if ( FAILED( hr ) ) return hr; } } mFuncSH = symHandle; hr = session->FindInnermostSymbol( mFuncSH, sec, offset, mBlockSH ); // it might be a public symbol, which doesn't have anything: blocks, args, or locals return S_OK; } } <commit_msg>Removing an assert that was firing, even though it didn't need to. It was firing, because sometimes the module that an address in the callstack is in isn't found. That's expected sometimes.<commit_after>/* Copyright (c) 2010 Aldo J. Nunez Licensed under the Apache License, Version 2.0. See the LICENSE text file for details. */ #include "Common.h" #include "StackFrame.h" #include "Thread.h" #include "Module.h" #include "SingleDocumentContext.h" #include "CodeContext.h" #include "ExprContext.h" #include "FrameProperty.h" #include "RegisterSet.h" namespace Mago { StackFrame::StackFrame() : mPC( 0 ) { memset( &mFuncSH, 0, sizeof mFuncSH ); memset( &mBlockSH, 0, sizeof mBlockSH ); } StackFrame::~StackFrame() { } HRESULT StackFrame::GetCodeContext( IDebugCodeContext2** ppCodeCxt ) { if ( ppCodeCxt == NULL ) return E_INVALIDARG; HRESULT hr = S_OK; RefPtr<CodeContext> codeContext; hr = MakeCComObject( codeContext ); if ( FAILED( hr ) ) return hr; CComPtr<IDebugDocumentContext2> docContext; hr = GetDocumentContext( &docContext ); if ( FAILED( hr ) ) return hr; hr = codeContext->Init( mPC, mModule, docContext ); if ( FAILED( hr ) ) return hr; return codeContext->QueryInterface( __uuidof( IDebugCodeContext2 ), (void**) ppCodeCxt ); } HRESULT StackFrame::GetDocumentContext( IDebugDocumentContext2** ppCxt ) { if ( ppCxt == NULL ) return E_INVALIDARG; HRESULT hr = S_OK; RefPtr<SingleDocumentContext> docContext; LineInfo line; hr = MakeCComObject( docContext ); if ( FAILED( hr ) ) return hr; hr = GetLineInfo( line ); if ( FAILED( hr ) ) return hr; hr = docContext->Init( line.Filename, line.LineBegin, line.LineEnd, line.LangName, line.LangGuid ); if ( FAILED( hr ) ) return hr; return docContext->QueryInterface( __uuidof( IDebugDocumentContext2 ), (void**) ppCxt ); } HRESULT StackFrame::GetName( BSTR* pbstrName ) { return E_NOTIMPL; } HRESULT StackFrame::GetInfo( FRAMEINFO_FLAGS dwFieldSpec, UINT nRadix, FRAMEINFO* pFrameInfo ) { if ( pFrameInfo == NULL ) return E_INVALIDARG; HRESULT hr = S_OK; pFrameInfo->m_dwValidFields = 0; if ( (dwFieldSpec & FIF_FRAME) != 0 ) { hr = QueryInterface( __uuidof( IDebugStackFrame2 ), (void**) &pFrameInfo->m_pFrame ); _ASSERT( hr == S_OK ); pFrameInfo->m_dwValidFields |= FIF_FRAME; } if ( (dwFieldSpec & FIF_DEBUG_MODULEP) != 0 ) { if ( mModule.Get() != NULL ) { hr = mModule->QueryInterface( __uuidof( IDebugModule2 ), (void**) &pFrameInfo->m_pModule ); _ASSERT( hr == S_OK ); pFrameInfo->m_dwValidFields |= FIF_DEBUG_MODULEP; } } if ( (dwFieldSpec & FIF_STACKRANGE) != 0 ) { #if 0 if ( mDiaStackFrame != NULL ) { // TODO: review all this UINT64 base = 0; DWORD size = 0; mDiaStackFrame->get_base( &base ); mDiaStackFrame->get_size( &size ); pFrameInfo->m_addrMax = base; pFrameInfo->m_addrMin = base - size; pFrameInfo->m_dwValidFields |= FIF_STACKRANGE; } #endif } if ( (dwFieldSpec & FIF_DEBUGINFO) != 0 ) { if ( mModule.Get() != NULL ) { RefPtr<MagoST::ISession> session; pFrameInfo->m_fHasDebugInfo = mModule->GetSymbolSession( session ); } else pFrameInfo->m_fHasDebugInfo = FALSE; pFrameInfo->m_dwValidFields |= FIF_DEBUGINFO; } if ( (dwFieldSpec & FIF_FUNCNAME) != 0 ) { hr = GetFunctionName( &pFrameInfo->m_bstrFuncName ); if ( SUCCEEDED( hr ) ) pFrameInfo->m_dwValidFields |= FIF_FUNCNAME; } if ( (dwFieldSpec & FIF_RETURNTYPE) != 0 ) { //pFrameInfo->m_bstrReturnType; //pFrameInfo->m_dwValidFields |= FIF_RETURNTYPE; } if ( (dwFieldSpec & FIF_ARGS) != 0 ) { //pFrameInfo->m_bstrArgs; //pFrameInfo->m_dwValidFields |= FIF_ARGS; } if ( (dwFieldSpec & FIF_LANGUAGE) != 0 ) { pFrameInfo->m_bstrLanguage = SysAllocString( L"D" ); pFrameInfo->m_dwValidFields |= FIF_LANGUAGE; } if ( (dwFieldSpec & FIF_MODULE) != 0 ) { //pFrameInfo->m_bstrModule; //pFrameInfo->m_dwValidFields |= FIF_MODULE; } //FIF_STALECODE m_fStaleCode //FIF_ANNOTATEDFRAME m_fAnnotatedFrame return S_OK; } HRESULT StackFrame::GetPhysicalStackRange( UINT64* paddrMin, UINT64* paddrMax ) { return E_NOTIMPL; } HRESULT StackFrame::GetExpressionContext( IDebugExpressionContext2** ppExprCxt ) { OutputDebugStringA( "StackFrame::GetExpressionContext\n" ); HRESULT hr = S_OK; if ( mModule == NULL ) return E_NOT_FOUND; hr = MakeExprContext(); if ( FAILED( hr ) ) return hr; *ppExprCxt = mExprContext; (*ppExprCxt)->AddRef(); return S_OK; } HRESULT StackFrame::MakeExprContext() { HRESULT hr = S_OK; // ignore any error, because we don't have to have symbols for expression eval hr = FindFunction(); if ( mExprContext == NULL ) { GuardedArea guard( mExprContextGuard ); if ( mExprContext == NULL ) { RefPtr<ExprContext> exprContext; hr = MakeCComObject( exprContext ); if ( FAILED( hr ) ) return hr; hr = exprContext->Init( mModule, mThread, mFuncSH, mBlockSH, mPC, mRegSet ); if ( FAILED( hr ) ) return hr; mExprContext = exprContext; } } return S_OK; } HRESULT StackFrame::GetLanguageInfo( BSTR* pbstrLanguage, GUID* pguidLanguage ) { return E_NOTIMPL; } HRESULT StackFrame::GetDebugProperty( IDebugProperty2** ppDebugProp ) { OutputDebugStringA( "StackFrame::GetDebugProperty\n" ); if ( ppDebugProp == NULL ) return E_INVALIDARG; HRESULT hr = S_OK; RefPtr<FrameProperty> frameProp; hr = MakeExprContext(); if ( FAILED( hr ) ) return hr; hr = MakeCComObject( frameProp ); if ( FAILED( hr ) ) return hr; hr = frameProp->Init( mRegSet, mExprContext ); if ( FAILED( hr ) ) return hr; *ppDebugProp = frameProp.Detach(); return S_OK; } HRESULT StackFrame::EnumProperties( DEBUGPROP_INFO_FLAGS dwFieldSpec, UINT nRadix, REFIID refiid, DWORD dwTimeout, ULONG* pcelt, IEnumDebugPropertyInfo2** ppEnum ) { OutputDebugStringA( "StackFrame::EnumProperties\n" ); HRESULT hr = S_OK; CComPtr<IDebugProperty2> rootProp; hr = GetDebugProperty( &rootProp ); if ( FAILED( hr ) ) return hr; hr = rootProp->EnumChildren( dwFieldSpec, nRadix, refiid, DBG_ATTRIB_ALL, NULL, dwTimeout, ppEnum ); if ( FAILED( hr ) ) return hr; if ( pcelt != NULL ) { hr = (*ppEnum)->GetCount( pcelt ); if ( FAILED( hr ) ) return hr; } return S_OK; } HRESULT StackFrame::GetThread( IDebugThread2** ppThread ) { if ( ppThread == NULL ) return E_INVALIDARG; return mThread->QueryInterface( __uuidof( IDebugThread2 ), (void**) ppThread ); } //---------------------------------------------------------------------------- void StackFrame::Init( Address pc, IRegisterSet* regSet, Thread* thread, Module* module ) { _ASSERT( regSet != NULL ); _ASSERT( thread != NULL ); // there might be no module mPC = pc; mRegSet = regSet; mThread = thread; mModule = module; } HRESULT StackFrame::GetLineInfo( LineInfo& info ) { HRESULT hr = S_OK; RefPtr<MagoST::ISession> session; if ( mModule.Get() == NULL ) return E_NOT_FOUND; if ( !mModule->GetSymbolSession( session ) ) return E_NOT_FOUND; uint16_t sec = 0; uint32_t offset = 0; sec = session->GetSecOffsetFromVA( mPC, offset ); if ( sec == 0 ) return E_FAIL; MagoST::LineNumber line = { 0 }; if ( !session->FindLine( sec, offset, line ) ) return E_FAIL; info.LineBegin.dwLine = line.Number; //info.LineEnd.dwLine = line.NumberEnd; info.LineEnd.dwLine = line.Number; info.LineBegin.dwColumn = 0; info.LineEnd.dwColumn = 0; info.LineBegin.dwLine--; info.LineEnd.dwLine--; // if there's no column info, then these are 0 if ( info.LineBegin.dwColumn > 0 ) info.LineBegin.dwColumn--; if ( info.LineEnd.dwColumn > 0 ) info.LineEnd.dwColumn--; MagoST::FileInfo fileInfo = { 0 }; hr = session->GetFileInfo( line.CompilandIndex, line.FileIndex, fileInfo ); if ( FAILED( hr ) ) return hr; hr = Utf8To16( fileInfo.Name, fileInfo.NameLength, info.Filename.m_str ); if ( FAILED( hr ) ) return hr; // TODO: from the compiland we're supposed to get the language info.LangName = L"D"; info.LangGuid = GetDLanguageId(); return hr; } HRESULT StackFrame::GetFunctionName( BSTR* funcName ) { _ASSERT( funcName != NULL ); HRESULT hr = S_OK; hr = GetFunctionNameWithSymbols( funcName ); if ( FAILED( hr ) ) { hr = GetFunctionNameWithAddress( funcName ); } return hr; } HRESULT StackFrame::GetFunctionNameWithAddress( BSTR* funcName ) { _ASSERT( funcName != NULL ); wchar_t addrStr[ 8 + 1 ] = L""; _ASSERT( sizeof mPC == 4 ); swprintf_s( addrStr, L"%08x", mPC ); *funcName = SysAllocString( addrStr ); if ( *funcName == NULL ) return E_OUTOFMEMORY; return S_OK; } HRESULT StackFrame::GetFunctionNameWithSymbols( BSTR* funcName ) { _ASSERT( funcName != NULL ); HRESULT hr = S_OK; RefPtr<MagoST::ISession> session; MagoST::SymInfoData infoData = { 0 }; MagoST::ISymbolInfo* symInfo = NULL; if ( mModule.Get() == NULL ) return E_NOT_FOUND; if ( !mModule->GetSymbolSession( session ) ) return E_NOT_FOUND; hr = FindFunction(); if ( FAILED( hr ) ) return hr; hr = session->GetSymbolInfo( mFuncSH, infoData, symInfo ); if ( FAILED( hr ) ) return hr; PasString* pstrName = NULL; if ( !symInfo->GetName( pstrName ) ) return E_NOT_FOUND; hr = Utf8To16( pstrName->GetName(), pstrName->GetLength(), *funcName ); if ( FAILED( hr ) ) return hr; // for reference: you get the language by going to a lexical ancestor // that's a compiland, then you get a compiland detail from it return hr; } HRESULT StackFrame::FindFunction() { HRESULT hr = S_OK; RefPtr<MagoST::ISession> session; MagoST::SymHandle symHandle = { 0 }; // already found if ( memcmp( &mFuncSH, &symHandle, sizeof mFuncSH ) != 0 ) return S_OK; if ( mModule.Get() == NULL ) return E_NOT_FOUND; if ( !mModule->GetSymbolSession( session ) ) return E_NOT_FOUND; uint16_t sec = 0; uint32_t offset = 0; sec = session->GetSecOffsetFromVA( mPC, offset ); if ( sec == 0 ) return E_NOT_FOUND; // TODO: verify that it's a function or public symbol (or something else?) hr = session->FindOuterSymbolByAddr( MagoST::SymHeap_GlobalSymbols, sec, offset, symHandle ); if ( FAILED( hr ) ) { hr = session->FindOuterSymbolByAddr( MagoST::SymHeap_StaticSymbols, sec, offset, symHandle ); if ( FAILED( hr ) ) { hr = session->FindOuterSymbolByAddr( MagoST::SymHeap_PublicSymbols, sec, offset, symHandle ); if ( FAILED( hr ) ) return hr; } } mFuncSH = symHandle; hr = session->FindInnermostSymbol( mFuncSH, sec, offset, mBlockSH ); // it might be a public symbol, which doesn't have anything: blocks, args, or locals return S_OK; } } <|endoftext|>
<commit_before>/* * ----------------------------------------------------------------------------- * This source file is part of OGRE * (Object-oriented Graphics Rendering Engine) * For the latest info, see http://www.ogre3d.org/ * * Copyright (c) 2000-2013 Torus Knot Software Ltd * * 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 "OgreMeshLodGenerator.h" #include "OgrePixelCountLodStrategy.h" #include "OgreLodWorkQueueWorker.h" #include "OgreLodWorkQueueInjector.h" #include "OgreLodWorkQueueInjectorListener.h" #include "OgreLodInputProvider.h" #include "OgreLodInputProviderMesh.h" #include "OgreLodInputProviderBuffer.h" #include "OgreLodOutputProvider.h" #include "OgreLodOutputProviderMesh.h" #include "OgreLodOutputProviderCompressedMesh.h" #include "OgreLodOutputProviderBuffer.h" #include "OgreLodOutputProviderCompressedBuffer.h" #include "OgreLodCollapseCost.h" #include "OgreLodCollapseCostCurvature.h" #include "OgreLodCollapseCostProfiler.h" #include "OgreLodCollapseCostOutside.h" #include "OgreLodData.h" #include "OgreLodCollapser.h" namespace Ogre { template<> MeshLodGenerator* Singleton<MeshLodGenerator>::msSingleton = 0; MeshLodGenerator* MeshLodGenerator::getSingletonPtr() { return msSingleton; } MeshLodGenerator& MeshLodGenerator::getSingleton() { assert( msSingleton ); return ( *msSingleton ); } void MeshLodGenerator::getAutoconfig( MeshPtr& inMesh, LodConfig& outLodConfig ) { outLodConfig.mesh = inMesh; outLodConfig.strategy = PixelCountLodStrategy::getSingletonPtr(); LodLevel lodLevel; lodLevel.reductionMethod = LodLevel::VRM_COLLAPSE_COST; Real radius = inMesh->getBoundingSphereRadius(); for (int i = 2; i < 6; i++) { Real i4 = (Real) (i * i * i * i); Real i5 = i4 * (Real) i; // Distance = pixel count // Constant: zoom of the Lod. This could be scaled based on resolution. // Higher constant means first Lod is nearer to camera. Smaller constant means the first Lod is further away from camera. // i4: The stretching. Normally you want to have more Lods in the near, then in far away. // i4 means distance is divided by 16=(2*2*2*2), 81, 256, 625=(5*5*5*5). // if 16 would be smaller, the first Lod would be nearer. if 625 would be bigger, the last Lod would be further awaay. // if you increase 16 and decrease 625, first and Last Lod distance would be smaller. lodLevel.distance = 3388608.f / i4; // reductionValue = collapse cost // Radius: Edges are multiplied by the length, when calculating collapse cost. So as a base value we use radius, which should help in balancing collapse cost to any mesh size. // The constant and i5 are playing together. 1/(1/100k*i5) // You need to determine the quality of nearest Lod and the furthest away first. // I have chosen 1/(1/100k*(2^5)) = 3125 for nearest Lod and 1/(1/100k*(5^5)) = 32 for nearest Lod. // if you divide radius by a bigger number, it means smaller reduction. So radius/3125 is very small reduction for nearest Lod. // if you divide radius by a smaller number, it means bigger reduction. So radius/32 means aggressive reduction for furthest away lod. // current values: 3125, 411, 97, 32 lodLevel.reductionValue = radius / 100000.f * i5; outLodConfig.levels.push_back(lodLevel); } } void MeshLodGenerator::generateAutoconfiguredLodLevels( MeshPtr& mesh ) { LodConfig lodConfig; getAutoconfig(mesh, lodConfig); generateLodLevels(lodConfig); } void MeshLodGenerator::_configureMeshLodUsage( const LodConfig& lodConfig ) { lodConfig.mesh->freeEdgeList(); lodConfig.mesh->setLodStrategy(lodConfig.strategy); MeshLodUsage usage; size_t n = 0; lodConfig.mesh->_setLodInfo(lodConfig.levels.size() + 1); // add Lod levels for (size_t i = 0; i < lodConfig.levels.size(); i++) { // Record usages. First Lod usage is the mesh itself. // Skip lods, which have the same amount of vertices. No buffer generated for them. if (!lodConfig.levels[i].outSkipped) { usage.userValue = lodConfig.levels[i].distance; usage.value = lodConfig.mesh->getLodStrategy()->transformUserValue(usage.userValue); usage.edgeData = NULL; usage.manualMesh.setNull(); usage.manualName = lodConfig.levels[i].manualMeshName; lodConfig.mesh->_setLodUsage(++n, usage); } } // Remove skipped Lod levels lodConfig.mesh->_setLodInfo(n + 1); } MeshLodGenerator::MeshLodGenerator() { if(!LodWorkQueueWorker::getSingletonPtr()){ mWQWorker = new LodWorkQueueWorker(); } else { mWQWorker = NULL; } if(!LodWorkQueueInjector::getSingletonPtr()){ mWQInjector = new LodWorkQueueInjector(); } else { mWQWorker = NULL; } } MeshLodGenerator::~MeshLodGenerator() { delete mWQWorker; delete mWQInjector; } void MeshLodGenerator::_resolveComponents( LodConfig& lodConfig, LodCollapseCostPtr& cost, LodDataPtr& data, LodInputProviderPtr& input, LodOutputProviderPtr& output, LodCollapserPtr& collapser ) { if(cost.isNull()) { cost = LodCollapseCostPtr(new LodCollapseCostCurvature); if(lodConfig.advanced.outsideWeight != 0){ cost = LodCollapseCostPtr(new LodCollapseCostOutside(cost, lodConfig.advanced.outsideWeight, lodConfig.advanced.outsideWalkAngle)); } if(!lodConfig.advanced.profile.empty()){ cost = LodCollapseCostPtr(new LodCollapseCostProfiler(lodConfig.advanced.profile, cost)); } } if(data.isNull()) { data = LodDataPtr(new LodData()); } if(collapser.isNull()) { collapser = LodCollapserPtr(new LodCollapser()); } if(lodConfig.advanced.useBackgroundQueue){ if(input.isNull()) { input = LodInputProviderPtr(new LodInputProviderBuffer(lodConfig.mesh)); } if(output.isNull()) { if(lodConfig.advanced.useCompression){ output = LodOutputProviderPtr(new LodOutputProviderCompressedBuffer(lodConfig.mesh)); } else { output = LodOutputProviderPtr(new LodOutputProviderBuffer(lodConfig.mesh)); } } } else { if(input.isNull()) { input = LodInputProviderPtr(new LodInputProviderMesh(lodConfig.mesh)); } if(output.isNull()) { if(lodConfig.advanced.useCompression){ output = LodOutputProviderPtr(new LodOutputProviderCompressedMesh(lodConfig.mesh)); } else { output = LodOutputProviderPtr(new LodOutputProviderMesh(lodConfig.mesh)); } } } } void MeshLodGenerator::_process( LodConfig& lodConfig, LodCollapseCost* cost, LodData* data, LodInputProvider* input, LodOutputProvider* output, LodCollapser* collapser ) { input->initData(data); data->mUseVertexNormals = data->mUseVertexNormals && lodConfig.advanced.useVertexNormals; cost->initCollapseCosts(data); output->prepare(data); computeLods(lodConfig, data, cost, output, collapser); output->finalize(data); if(!lodConfig.advanced.useBackgroundQueue){ // This will be processed in LodWorkQueueInjector if we use background queue. output->inject(); _configureMeshLodUsage(lodConfig); //lodConfig.mesh->buildEdgeList(); } } void MeshLodGenerator::generateLodLevels( LodConfig& lodConfig, LodCollapseCostPtr cost, LodDataPtr data, LodInputProviderPtr input, LodOutputProviderPtr output, LodCollapserPtr collapser) { _resolveComponents(lodConfig, cost, data, input, output, collapser); if(lodConfig.advanced.useBackgroundQueue){ LodWorkQueueWorker::getSingleton().addRequestToQueue(lodConfig, cost, data, input, output, collapser); } else { _process(lodConfig, cost.get(), data.get(), input.get(), output.get(), collapser.get()); } } void MeshLodGenerator::computeLods(LodConfig& lodConfig, LodData* data, LodCollapseCost* cost, LodOutputProvider* output, LodCollapser* collapser) { int lodID = 0; size_t lastBakeVertexCount = data->mVertexList.size(); for (unsigned short curLod = 0; curLod < lodConfig.levels.size(); curLod++) { if(!lodConfig.levels[curLod].manualMeshName.empty()){ // Manual Lod level lodConfig.levels[curLod].outSkipped = (curLod != 0 && lodConfig.levels[curLod].manualMeshName == lodConfig.levels[curLod - 1].manualMeshName); lodConfig.levels[curLod].outUniqueVertexCount = 0; if (!lodConfig.levels[curLod].outSkipped) { output->bakeManualLodLevel(data, lodConfig.levels[curLod].manualMeshName, lodID++); } } else { size_t vertexCountLimit; Real collapseCostLimit; calcLodVertexCount(lodConfig.levels[curLod], data->mVertexList.size(), vertexCountLimit, collapseCostLimit); collapser->collapse(data, cost, output, vertexCountLimit, collapseCostLimit); size_t vertexCount = data->mCollapseCostHeap.size(); lodConfig.levels[curLod].outUniqueVertexCount = vertexCount; lodConfig.levels[curLod].outSkipped = (vertexCount == data->mVertexList.size()); if (!lodConfig.levels[curLod].outSkipped) { lastBakeVertexCount = data->mVertexList.size(); output->bakeLodLevel(data, lodID++); } } } } void MeshLodGenerator::calcLodVertexCount(const LodLevel& lodLevel, size_t uniqueVertexCount, size_t& outVertexCountLimit,Real& outCollapseCostLimit) { switch (lodLevel.reductionMethod) { case LodLevel::VRM_PROPORTIONAL: outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; outVertexCountLimit = uniqueVertexCount - (size_t)((Real)uniqueVertexCount * lodLevel.reductionValue); break; case LodLevel::VRM_CONSTANT: outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; outVertexCountLimit = (size_t) lodLevel.reductionValue; if (outVertexCountLimit < uniqueVertexCount) { outVertexCountLimit = uniqueVertexCount - outVertexCountLimit; } else { outVertexCountLimit = 0; } break; case LodLevel::VRM_COLLAPSE_COST: outCollapseCostLimit = lodLevel.reductionValue; outVertexCountLimit = 0; break; default: OgreAssert(0, ""); outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; outVertexCountLimit = uniqueVertexCount; break; } } } <commit_msg>Fix constraint for skipping Lod Level<commit_after>/* * ----------------------------------------------------------------------------- * This source file is part of OGRE * (Object-oriented Graphics Rendering Engine) * For the latest info, see http://www.ogre3d.org/ * * Copyright (c) 2000-2013 Torus Knot Software Ltd * * 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 "OgreMeshLodGenerator.h" #include "OgrePixelCountLodStrategy.h" #include "OgreLodWorkQueueWorker.h" #include "OgreLodWorkQueueInjector.h" #include "OgreLodWorkQueueInjectorListener.h" #include "OgreLodInputProvider.h" #include "OgreLodInputProviderMesh.h" #include "OgreLodInputProviderBuffer.h" #include "OgreLodOutputProvider.h" #include "OgreLodOutputProviderMesh.h" #include "OgreLodOutputProviderCompressedMesh.h" #include "OgreLodOutputProviderBuffer.h" #include "OgreLodOutputProviderCompressedBuffer.h" #include "OgreLodCollapseCost.h" #include "OgreLodCollapseCostCurvature.h" #include "OgreLodCollapseCostProfiler.h" #include "OgreLodCollapseCostOutside.h" #include "OgreLodData.h" #include "OgreLodCollapser.h" namespace Ogre { template<> MeshLodGenerator* Singleton<MeshLodGenerator>::msSingleton = 0; MeshLodGenerator* MeshLodGenerator::getSingletonPtr() { return msSingleton; } MeshLodGenerator& MeshLodGenerator::getSingleton() { assert( msSingleton ); return ( *msSingleton ); } void MeshLodGenerator::getAutoconfig( MeshPtr& inMesh, LodConfig& outLodConfig ) { outLodConfig.mesh = inMesh; outLodConfig.strategy = PixelCountLodStrategy::getSingletonPtr(); LodLevel lodLevel; lodLevel.reductionMethod = LodLevel::VRM_COLLAPSE_COST; Real radius = inMesh->getBoundingSphereRadius(); for (int i = 2; i < 6; i++) { Real i4 = (Real) (i * i * i * i); Real i5 = i4 * (Real) i; // Distance = pixel count // Constant: zoom of the Lod. This could be scaled based on resolution. // Higher constant means first Lod is nearer to camera. Smaller constant means the first Lod is further away from camera. // i4: The stretching. Normally you want to have more Lods in the near, then in far away. // i4 means distance is divided by 16=(2*2*2*2), 81, 256, 625=(5*5*5*5). // if 16 would be smaller, the first Lod would be nearer. if 625 would be bigger, the last Lod would be further awaay. // if you increase 16 and decrease 625, first and Last Lod distance would be smaller. lodLevel.distance = 3388608.f / i4; // reductionValue = collapse cost // Radius: Edges are multiplied by the length, when calculating collapse cost. So as a base value we use radius, which should help in balancing collapse cost to any mesh size. // The constant and i5 are playing together. 1/(1/100k*i5) // You need to determine the quality of nearest Lod and the furthest away first. // I have chosen 1/(1/100k*(2^5)) = 3125 for nearest Lod and 1/(1/100k*(5^5)) = 32 for nearest Lod. // if you divide radius by a bigger number, it means smaller reduction. So radius/3125 is very small reduction for nearest Lod. // if you divide radius by a smaller number, it means bigger reduction. So radius/32 means aggressive reduction for furthest away lod. // current values: 3125, 411, 97, 32 lodLevel.reductionValue = radius / 100000.f * i5; outLodConfig.levels.push_back(lodLevel); } } void MeshLodGenerator::generateAutoconfiguredLodLevels( MeshPtr& mesh ) { LodConfig lodConfig; getAutoconfig(mesh, lodConfig); generateLodLevels(lodConfig); } void MeshLodGenerator::_configureMeshLodUsage( const LodConfig& lodConfig ) { lodConfig.mesh->freeEdgeList(); lodConfig.mesh->setLodStrategy(lodConfig.strategy); MeshLodUsage usage; size_t n = 0; lodConfig.mesh->_setLodInfo(lodConfig.levels.size() + 1); // add Lod levels for (size_t i = 0; i < lodConfig.levels.size(); i++) { // Record usages. First Lod usage is the mesh itself. // Skip lods, which have the same amount of vertices. No buffer generated for them. if (!lodConfig.levels[i].outSkipped) { usage.userValue = lodConfig.levels[i].distance; usage.value = lodConfig.mesh->getLodStrategy()->transformUserValue(usage.userValue); usage.edgeData = NULL; usage.manualMesh.setNull(); usage.manualName = lodConfig.levels[i].manualMeshName; lodConfig.mesh->_setLodUsage(++n, usage); } } // Remove skipped Lod levels lodConfig.mesh->_setLodInfo(n + 1); } MeshLodGenerator::MeshLodGenerator() { if(!LodWorkQueueWorker::getSingletonPtr()){ mWQWorker = new LodWorkQueueWorker(); } else { mWQWorker = NULL; } if(!LodWorkQueueInjector::getSingletonPtr()){ mWQInjector = new LodWorkQueueInjector(); } else { mWQWorker = NULL; } } MeshLodGenerator::~MeshLodGenerator() { delete mWQWorker; delete mWQInjector; } void MeshLodGenerator::_resolveComponents( LodConfig& lodConfig, LodCollapseCostPtr& cost, LodDataPtr& data, LodInputProviderPtr& input, LodOutputProviderPtr& output, LodCollapserPtr& collapser ) { if(cost.isNull()) { cost = LodCollapseCostPtr(new LodCollapseCostCurvature); if(lodConfig.advanced.outsideWeight != 0){ cost = LodCollapseCostPtr(new LodCollapseCostOutside(cost, lodConfig.advanced.outsideWeight, lodConfig.advanced.outsideWalkAngle)); } if(!lodConfig.advanced.profile.empty()){ cost = LodCollapseCostPtr(new LodCollapseCostProfiler(lodConfig.advanced.profile, cost)); } } if(data.isNull()) { data = LodDataPtr(new LodData()); } if(collapser.isNull()) { collapser = LodCollapserPtr(new LodCollapser()); } if(lodConfig.advanced.useBackgroundQueue){ if(input.isNull()) { input = LodInputProviderPtr(new LodInputProviderBuffer(lodConfig.mesh)); } if(output.isNull()) { if(lodConfig.advanced.useCompression){ output = LodOutputProviderPtr(new LodOutputProviderCompressedBuffer(lodConfig.mesh)); } else { output = LodOutputProviderPtr(new LodOutputProviderBuffer(lodConfig.mesh)); } } } else { if(input.isNull()) { input = LodInputProviderPtr(new LodInputProviderMesh(lodConfig.mesh)); } if(output.isNull()) { if(lodConfig.advanced.useCompression){ output = LodOutputProviderPtr(new LodOutputProviderCompressedMesh(lodConfig.mesh)); } else { output = LodOutputProviderPtr(new LodOutputProviderMesh(lodConfig.mesh)); } } } } void MeshLodGenerator::_process( LodConfig& lodConfig, LodCollapseCost* cost, LodData* data, LodInputProvider* input, LodOutputProvider* output, LodCollapser* collapser ) { input->initData(data); data->mUseVertexNormals = data->mUseVertexNormals && lodConfig.advanced.useVertexNormals; cost->initCollapseCosts(data); output->prepare(data); computeLods(lodConfig, data, cost, output, collapser); output->finalize(data); if(!lodConfig.advanced.useBackgroundQueue){ // This will be processed in LodWorkQueueInjector if we use background queue. output->inject(); _configureMeshLodUsage(lodConfig); //lodConfig.mesh->buildEdgeList(); } } void MeshLodGenerator::generateLodLevels( LodConfig& lodConfig, LodCollapseCostPtr cost, LodDataPtr data, LodInputProviderPtr input, LodOutputProviderPtr output, LodCollapserPtr collapser) { _resolveComponents(lodConfig, cost, data, input, output, collapser); if(lodConfig.advanced.useBackgroundQueue){ LodWorkQueueWorker::getSingleton().addRequestToQueue(lodConfig, cost, data, input, output, collapser); } else { _process(lodConfig, cost.get(), data.get(), input.get(), output.get(), collapser.get()); } } void MeshLodGenerator::computeLods(LodConfig& lodConfig, LodData* data, LodCollapseCost* cost, LodOutputProvider* output, LodCollapser* collapser) { int lodID = 0; size_t lastBakeVertexCount = data->mVertexList.size(); for (unsigned short curLod = 0; curLod < lodConfig.levels.size(); curLod++) { if(!lodConfig.levels[curLod].manualMeshName.empty()){ // Manual Lod level lodConfig.levels[curLod].outSkipped = (curLod != 0 && lodConfig.levels[curLod].manualMeshName == lodConfig.levels[curLod - 1].manualMeshName); lodConfig.levels[curLod].outUniqueVertexCount = 0; lastBakeVertexCount = -1; if (!lodConfig.levels[curLod].outSkipped) { output->bakeManualLodLevel(data, lodConfig.levels[curLod].manualMeshName, lodID++); } } else { size_t vertexCountLimit; Real collapseCostLimit; calcLodVertexCount(lodConfig.levels[curLod], data->mVertexList.size(), vertexCountLimit, collapseCostLimit); collapser->collapse(data, cost, output, vertexCountLimit, collapseCostLimit); size_t vertexCount = data->mCollapseCostHeap.size(); lodConfig.levels[curLod].outUniqueVertexCount = vertexCount; lodConfig.levels[curLod].outSkipped = (vertexCount == lastBakeVertexCount); if (!lodConfig.levels[curLod].outSkipped) { lastBakeVertexCount = vertexCount; output->bakeLodLevel(data, lodID++); } } } } void MeshLodGenerator::calcLodVertexCount(const LodLevel& lodLevel, size_t uniqueVertexCount, size_t& outVertexCountLimit,Real& outCollapseCostLimit) { switch (lodLevel.reductionMethod) { case LodLevel::VRM_PROPORTIONAL: outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; outVertexCountLimit = uniqueVertexCount - (size_t)((Real)uniqueVertexCount * lodLevel.reductionValue); break; case LodLevel::VRM_CONSTANT: outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; outVertexCountLimit = (size_t) lodLevel.reductionValue; if (outVertexCountLimit < uniqueVertexCount) { outVertexCountLimit = uniqueVertexCount - outVertexCountLimit; } else { outVertexCountLimit = 0; } break; case LodLevel::VRM_COLLAPSE_COST: outCollapseCostLimit = lodLevel.reductionValue; outVertexCountLimit = 0; break; default: OgreAssert(0, ""); outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; outVertexCountLimit = uniqueVertexCount; break; } } } <|endoftext|>
<commit_before><commit_msg>Need to cast to WebCore::Widget explicitly since the method being called takes a void pointer! Argh :(<commit_after><|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 "otbFineRegistration.h" #include <iostream> #include "otbCommandLineArgumentParser.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" #include "otbFineRegistrationImageFilter.h" #include "otbStandardWriterWatcher.h" #include "otbVectorImage.h" #include "otbImageList.h" #include "otbImageListToVectorImageFilter.h" #include "itkTimeProbe.h" #include "itkFixedArray.h" #include "itkNormalizedCorrelationImageToImageMetric.h" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkMattesMutualInformationImageToImageMetric.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkAbsImageFilter.h" #include "itkVectorIndexSelectionCastImageFilter.h" #include "itkBinaryThresholdImageFilter.h" namespace otb { int FineRegistration::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("FineRegistration"); descriptor->SetDescription("Estimate disparity map between two images. Output image contain x offset, y offset and metric value."); descriptor->AddOption("Reference", "The reference image", "ref", 1, true, ApplicationDescriptor::InputImage); descriptor->AddOption("Secondary", "The secondary image", "sec", 1, true, ApplicationDescriptor::FileName); descriptor->AddOption("Output", "The output image", "out", 1, true, ApplicationDescriptor::OutputImage); descriptor->AddOption("ExplorationRadius","Radius (in pixels) of the exploration window", "er",2,true, ApplicationDescriptor::Integer); descriptor->AddOption("MetricRadius","Radius (in pixels) of the metric computation window", "mr",2,true, ApplicationDescriptor::Integer); descriptor->AddOption("CoarseOffset","(optional) Coarse offset (in physical space) between the two images. Default is [0,0].", "co",2,false, ApplicationDescriptor::Real); descriptor->AddOption("SubSamplingRate","(optional) Generate a result at a coarser resolution with a given sub-sampling rate in each direction (in pixels). Default is no sub-sampling", "ssr",2,false, ApplicationDescriptor::Real); descriptor->AddOption("ReferenceGaussianSmoothing","(optional) Perform a gaussian smoothing of the reference image. Parameters are gaussian sigma (in pixels) in each direction. Default is no smoothing.", "rgs",2,false, ApplicationDescriptor::Real); descriptor->AddOption("SecondaryGaussianSmoothing","(optional) Perform a gaussian smoothing of the secondary image. Parameters are gaussian sigma (in pixels) in each direction. Default is no smoothing.", "sgs",2,false, ApplicationDescriptor::Real); descriptor->AddOption("Metric","(optional) Choose the metric used for block matching. Available metrics are cross-correlation (CC), cross-correlation with subtracted mean (CCSM), mean-square difference (MSD), mean reciprocal square difference (MRSD) and mutual information (MI). Default is cross-correlation", "m",1,false, ApplicationDescriptor::String); descriptor->AddOption("SubPixelAccuracy","(optional) Metric extrema location will be refined up to the given accuracy. Default is 0.01", "spa",1,false, ApplicationDescriptor::Real); descriptor->AddOption("ValidityMask","(optional) Threshold to obtain a validity mask. Params are lowerThan or greaterThan and a threshold", "vm",2,false, ApplicationDescriptor::String); return EXIT_SUCCESS; } int FineRegistration::Execute(otb::ApplicationOptionsResult* parseResult) { const unsigned int Dimension = 2; typedef double PixelType; typedef itk::FixedArray<PixelType,Dimension> DeformationValueType; typedef otb::Image< PixelType, Dimension > ImageType; typedef otb::VectorImage<PixelType,Dimension> VectorImageType; typedef otb::ImageList<ImageType> ImageListType; typedef otb::ImageListToVectorImageFilter<ImageListType,VectorImageType> IL2VIFilterType; typedef otb::Image<DeformationValueType,Dimension> FieldImageType; typedef otb::ImageFileReader< ImageType > ReaderType; typedef otb::StreamingImageFileWriter< VectorImageType > WriterType; typedef otb::FineRegistrationImageFilter<ImageType,ImageType,FieldImageType> RegistrationFilterType; typedef itk::DiscreteGaussianImageFilter<ImageType,ImageType> GaussianFilterType; typedef itk::VectorIndexSelectionCastImageFilter<FieldImageType,ImageType> VectorImageToImageFilterType; typedef itk::AbsImageFilter<ImageType,ImageType> AbsFilterType; typedef itk::BinaryThresholdImageFilter<ImageType,ImageType> BinaryThresholdImageFilterType; // Read reference image ReaderType::Pointer freader = ReaderType::New(); freader->SetFileName(parseResult->GetParameterString("Reference")); // Read secondary image ReaderType::Pointer mreader = ReaderType::New(); mreader->SetFileName(parseResult->GetParameterString("Secondary")); // Retrieve main registration parameters RegistrationFilterType::SizeType radius, sradius; ImageType::OffsetType ssrate; sradius[0] = parseResult->GetParameterULong("ExplorationRadius",0); sradius[1] = parseResult->GetParameterULong("ExplorationRadius",1); radius[0] = parseResult->GetParameterULong("MetricRadius",0); radius[1] = parseResult->GetParameterULong("MetricRadius",1); double accuracy = 0.01; if(parseResult->IsOptionPresent("SubPixelAccuracy")) { accuracy = parseResult->GetParameterDouble("SubPixelAccuracy"); } ssrate.Fill(1); if(parseResult->IsOptionPresent("SubSamplingRate")) { ssrate[0] = parseResult->GetParameterDouble("SubSamplingRate",0); ssrate[1] = parseResult->GetParameterDouble("SubSamplingRate",1); } RegistrationFilterType::SpacingType initialOffset; initialOffset.Fill(0); if(parseResult->IsOptionPresent("CoarseOffset")) { initialOffset[0] = parseResult->GetParameterDouble("CoarseOffset",0); initialOffset[1] = parseResult->GetParameterDouble("CoarseOffset",1); } // Display info std::cout<<"Reference image : "<<freader->GetFileName()<<std::endl; std::cout<<"Secondary image : "<<mreader->GetFileName()<<std::endl; std::cout<<"Exploration radius: "<<sradius<<" (pixels)"<<std::endl; std::cout<<"Metric radius : "<<radius<<" (pixels)"<<std::endl; std::cout<<"Sub-sampling rate : "<<ssrate<<" (pixels)"<<std::endl; std::cout<<"Coarse offset : "<<initialOffset<<" (physical unit)"<<std::endl; std::cout<<"Accuracy : "<<accuracy<<" (physical unit)"<<std::endl; RegistrationFilterType::Pointer registration = RegistrationFilterType::New(); registration->SetRadius(radius); registration->SetSearchRadius(sradius); registration->SetSubPixelAccuracy(accuracy); registration->SetGridStep(ssrate); registration->SetInitialOffset(initialOffset); GaussianFilterType::Pointer refGaussianFilter,secGaussianFilter; if(parseResult->IsOptionPresent("ReferenceGaussianSmoothing")) { refGaussianFilter = GaussianFilterType::New(); refGaussianFilter->SetInput(freader->GetOutput()); GaussianFilterType::ArrayType sigma; sigma[0] = parseResult->GetParameterDouble("ReferenceGaussianSmoothing",0); sigma[1] = parseResult->GetParameterDouble("ReferenceGaussianSmoothing",1); refGaussianFilter->SetVariance(sigma); refGaussianFilter->SetUseImageSpacingOff(); std::cout<<"Reference image gaussian smoothing on."<<std::endl; std::cout<<"variance : "<<sigma<<" (pixels)"<<std::endl; registration->SetFixedInput(refGaussianFilter->GetOutput()); } else { std::cout<<"Reference image gaussian smoothing off."<<std::endl; registration->SetFixedInput(freader->GetOutput()); } if(parseResult->IsOptionPresent("SecondaryGaussianSmoothing")) { secGaussianFilter = GaussianFilterType::New(); secGaussianFilter->SetInput(mreader->GetOutput()); GaussianFilterType::ArrayType sigma; sigma[0] = parseResult->GetParameterDouble("SecondaryGaussianSmoothing",0); sigma[1] = parseResult->GetParameterDouble("SecondaryGaussianSmoothing",1); secGaussianFilter->SetVariance(sigma); secGaussianFilter->SetUseImageSpacingOff(); std::cout<<"Secondary image gaussian smoothing on."<<std::endl; std::cout<<"variance : "<<sigma<<" (pixels)"<<std::endl; registration->SetMovingInput(secGaussianFilter->GetOutput()); } else { std::cout<<"Secondary image gaussian smoothing off."<<std::endl; registration->SetMovingInput(mreader->GetOutput()); } // Retrieve metric name std::string metricId = "CC"; if(parseResult->IsOptionPresent("Metric")) { metricId = parseResult->GetParameterString("Metric"); } if(metricId == "CC") { std::cout<<"Metric : Cross-correlation"<<std::endl; typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,ImageType> NCCType; NCCType::Pointer metricPtr = NCCType::New(); metricPtr->SubtractMeanOff(); registration->SetMetric(metricPtr); registration->MinimizeOn(); } else if(metricId == "CCSM") { std::cout<<"Metric : Cross-correlation (mean subtracted)"<<std::endl; typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,ImageType> NCCType; NCCType::Pointer metricPtr = NCCType::New(); metricPtr->SubtractMeanOn(); registration->SetMetric(metricPtr); registration->MinimizeOn(); } else if(metricId == "MSD") { std::cout<<"Metric : Mean square difference"<<std::endl; typedef itk::MeanSquaresImageToImageMetric<ImageType,ImageType> MeanSquareType; MeanSquareType::Pointer metricPtr = MeanSquareType::New(); registration->SetMetric(metricPtr); registration->MinimizeOn(); } else if(metricId == "MRSD") { std::cout<<"Metric : Mean reciprocal square difference"<<std::endl; typedef itk::MeanReciprocalSquareDifferenceImageToImageMetric<ImageType,ImageType> MRSDType; MRSDType::Pointer metricPtr = MRSDType::New(); registration->SetMetric(metricPtr); registration->MinimizeOff(); } else if(metricId == "MI") { std::cout<<"Metric : Mutual information"<<std::endl; typedef itk::MattesMutualInformationImageToImageMetric<ImageType,ImageType> MIType; MIType::Pointer metricPtr = MIType::New(); registration->SetMetric(metricPtr); registration->MinimizeOn(); } else { std::cerr<<"Metric "<<metricId<<" not recognized."<<std::endl; std::cerr<<"Possible choices are: CC, CCMS, MSD, MRSD, MI"<<std::endl; return EXIT_FAILURE; } VectorImageToImageFilterType::Pointer xExtractor = VectorImageToImageFilterType::New(); xExtractor->SetInput(registration->GetOutputDeformationField()); xExtractor->SetIndex(0); VectorImageToImageFilterType::Pointer yExtractor = VectorImageToImageFilterType::New(); yExtractor->SetInput(registration->GetOutputDeformationField()); yExtractor->SetIndex(1); ImageListType::Pointer il = ImageListType::New(); il->PushBack(xExtractor->GetOutput()); il->PushBack(yExtractor->GetOutput()); AbsFilterType::Pointer absFilter; // Invert correlation to get classical rendering if(metricId == "CC" || metricId == "CCSM") { absFilter = AbsFilterType::New(); absFilter->SetInput(registration->GetOutput()); il->PushBack(absFilter->GetOutput()); } else { il->PushBack(registration->GetOutput()); } BinaryThresholdImageFilterType::Pointer threshold; if(parseResult->IsOptionPresent("ValidityMask")) { threshold = BinaryThresholdImageFilterType::New(); if(metricId == "CC" || metricId == "CCSM") { threshold->SetInput(absFilter->GetOutput()); } else { threshold->SetInput(registration->GetOutput()); } if(parseResult->GetParameterString("ValidityMask",0)=="greaterThan") { threshold->SetLowerThreshold(parseResult->GetParameterDouble("ValidityMask",1)); } else if(parseResult->GetParameterString("ValidityMask",0)=="lowerThan") { threshold->SetUpperThreshold(parseResult->GetParameterDouble("ValidityMask",1)); } else { std::cerr<<"Arguments of --ValidityMask option should begin with lowerThan or greaterThan"<<std::endl; return EXIT_FAILURE; } std::cout<<"A validity mask will be produced as the 4th band (valid pixels = 1.0, not valid = 0.0)."<<std::endl; std::cout<<"Pixels are considered valid if metric is "<<parseResult->GetParameterString("ValidityMask",0)<<" "; std::cout<<parseResult->GetParameterDouble("ValidityMask",1)<<std::endl; threshold->SetInsideValue(1.0); threshold->SetOutsideValue(0.); il->PushBack(threshold->GetOutput()); } IL2VIFilterType::Pointer il2vi = IL2VIFilterType::New(); il2vi->SetInput(il); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(parseResult->GetOutputImage()); writer->SetInput(il2vi->GetOutput()); std::cout<<std::endl; otb::StandardWriterWatcher watcher(writer,registration,"Fine Registration"); writer->Update(); return EXIT_SUCCESS; } } <commit_msg>ENH : little change in appli qt<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 "otbFineRegistration.h" #include <iostream> #include "otbCommandLineArgumentParser.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbStreamingImageFileWriter.h" #include "otbFineRegistrationImageFilter.h" #include "otbStandardWriterWatcher.h" #include "otbVectorImage.h" #include "otbImageList.h" #include "otbImageListToVectorImageFilter.h" #include "itkTimeProbe.h" #include "itkFixedArray.h" #include "itkNormalizedCorrelationImageToImageMetric.h" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkMattesMutualInformationImageToImageMetric.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkAbsImageFilter.h" #include "itkVectorIndexSelectionCastImageFilter.h" #include "itkBinaryThresholdImageFilter.h" namespace otb { int FineRegistration::Describe(ApplicationDescriptor* descriptor) { descriptor->SetName("FineRegistration"); descriptor->SetDescription("Estimate disparity map between two images. Output image contain x offset, y offset and metric value."); descriptor->AddOption("Reference", "The reference image", "ref", 1, true, ApplicationDescriptor::InputImage); descriptor->AddOption("Secondary", "The secondary image", "sec", 1, true, ApplicationDescriptor::FileName); descriptor->AddOption("Output", "The output image", "out", 1, true, ApplicationDescriptor::OutputImage); descriptor->AddOption("ExplorationRadius","Radius (in pixels) of the exploration window", "er",2,true, ApplicationDescriptor::Integer); descriptor->AddOption("MetricRadius","Radius (in pixels) of the metric computation window", "mr",2,true, ApplicationDescriptor::Integer); descriptor->AddOption("CoarseOffset","(optional) Coarse offset (in physical space) between the two images. Default is [0,0].", "co",2,false, ApplicationDescriptor::Real); descriptor->AddOption("SubSamplingRate","(optional) Generate a result at a coarser resolution with a given sub-sampling rate in each direction (in pixels). Default is no sub-sampling", "ssr",2,false, ApplicationDescriptor::Real); descriptor->AddOption("ReferenceGaussianSmoothing","(optional) Perform a gaussian smoothing of the reference image. Parameters are gaussian sigma (in pixels) in each direction. Default is no smoothing.", "rgs",2,false, ApplicationDescriptor::Real); descriptor->AddOption("SecondaryGaussianSmoothing","(optional) Perform a gaussian smoothing of the secondary image. Parameters are gaussian sigma (in pixels) in each direction. Default is no smoothing.", "sgs",2,false, ApplicationDescriptor::Real); descriptor->AddOption("Metric","(optional) Choose the metric used for block matching. Available metrics are cross-correlation (CC), cross-correlation with subtracted mean (CCSM), mean-square difference (MSD), mean reciprocal square difference (MRSD) and mutual information (MI). Default is cross-correlation", "m",1,false, ApplicationDescriptor::String); descriptor->AddOption("SubPixelAccuracy","(optional) Metric extrema location will be refined up to the given accuracy. Default is 0.01", "spa",1,false, ApplicationDescriptor::Real); descriptor->AddOption("ValidityMask","(optional) Threshold to obtain a validity mask. Params are lowerThan or greaterThan and a threshold", "vm",2,false, ApplicationDescriptor::Real); return EXIT_SUCCESS; } int FineRegistration::Execute(otb::ApplicationOptionsResult* parseResult) { const unsigned int Dimension = 2; typedef double PixelType; typedef itk::FixedArray<PixelType,Dimension> DeformationValueType; typedef otb::Image< PixelType, Dimension > ImageType; typedef otb::VectorImage<PixelType,Dimension> VectorImageType; typedef otb::ImageList<ImageType> ImageListType; typedef otb::ImageListToVectorImageFilter<ImageListType,VectorImageType> IL2VIFilterType; typedef otb::Image<DeformationValueType,Dimension> FieldImageType; typedef otb::ImageFileReader< ImageType > ReaderType; typedef otb::StreamingImageFileWriter< VectorImageType > WriterType; typedef otb::FineRegistrationImageFilter<ImageType,ImageType,FieldImageType> RegistrationFilterType; typedef itk::DiscreteGaussianImageFilter<ImageType,ImageType> GaussianFilterType; typedef itk::VectorIndexSelectionCastImageFilter<FieldImageType,ImageType> VectorImageToImageFilterType; typedef itk::AbsImageFilter<ImageType,ImageType> AbsFilterType; typedef itk::BinaryThresholdImageFilter<ImageType,ImageType> BinaryThresholdImageFilterType; // Read reference image ReaderType::Pointer freader = ReaderType::New(); freader->SetFileName(parseResult->GetParameterString("Reference")); // Read secondary image ReaderType::Pointer mreader = ReaderType::New(); mreader->SetFileName(parseResult->GetParameterString("Secondary")); // Retrieve main registration parameters RegistrationFilterType::SizeType radius, sradius; ImageType::OffsetType ssrate; sradius[0] = parseResult->GetParameterULong("ExplorationRadius",0); sradius[1] = parseResult->GetParameterULong("ExplorationRadius",1); radius[0] = parseResult->GetParameterULong("MetricRadius",0); radius[1] = parseResult->GetParameterULong("MetricRadius",1); double accuracy = 0.01; if(parseResult->IsOptionPresent("SubPixelAccuracy")) { accuracy = parseResult->GetParameterDouble("SubPixelAccuracy"); } ssrate.Fill(1); if(parseResult->IsOptionPresent("SubSamplingRate")) { ssrate[0] = parseResult->GetParameterDouble("SubSamplingRate",0); ssrate[1] = parseResult->GetParameterDouble("SubSamplingRate",1); } RegistrationFilterType::SpacingType initialOffset; initialOffset.Fill(0); if(parseResult->IsOptionPresent("CoarseOffset")) { initialOffset[0] = parseResult->GetParameterDouble("CoarseOffset",0); initialOffset[1] = parseResult->GetParameterDouble("CoarseOffset",1); } // Display info std::cout<<"Reference image : "<<freader->GetFileName()<<std::endl; std::cout<<"Secondary image : "<<mreader->GetFileName()<<std::endl; std::cout<<"Exploration radius: "<<sradius<<" (pixels)"<<std::endl; std::cout<<"Metric radius : "<<radius<<" (pixels)"<<std::endl; std::cout<<"Sub-sampling rate : "<<ssrate<<" (pixels)"<<std::endl; std::cout<<"Coarse offset : "<<initialOffset<<" (physical unit)"<<std::endl; std::cout<<"Accuracy : "<<accuracy<<" (physical unit)"<<std::endl; RegistrationFilterType::Pointer registration = RegistrationFilterType::New(); registration->SetRadius(radius); registration->SetSearchRadius(sradius); registration->SetSubPixelAccuracy(accuracy); registration->SetGridStep(ssrate); registration->SetInitialOffset(initialOffset); GaussianFilterType::Pointer refGaussianFilter,secGaussianFilter; if(parseResult->IsOptionPresent("ReferenceGaussianSmoothing")) { refGaussianFilter = GaussianFilterType::New(); refGaussianFilter->SetInput(freader->GetOutput()); GaussianFilterType::ArrayType sigma; sigma[0] = parseResult->GetParameterDouble("ReferenceGaussianSmoothing",0); sigma[1] = parseResult->GetParameterDouble("ReferenceGaussianSmoothing",1); refGaussianFilter->SetVariance(sigma); refGaussianFilter->SetUseImageSpacingOff(); std::cout<<"Reference image gaussian smoothing on."<<std::endl; std::cout<<"variance : "<<sigma<<" (pixels)"<<std::endl; registration->SetFixedInput(refGaussianFilter->GetOutput()); } else { std::cout<<"Reference image gaussian smoothing off."<<std::endl; registration->SetFixedInput(freader->GetOutput()); } if(parseResult->IsOptionPresent("SecondaryGaussianSmoothing")) { secGaussianFilter = GaussianFilterType::New(); secGaussianFilter->SetInput(mreader->GetOutput()); GaussianFilterType::ArrayType sigma; sigma[0] = parseResult->GetParameterDouble("SecondaryGaussianSmoothing",0); sigma[1] = parseResult->GetParameterDouble("SecondaryGaussianSmoothing",1); secGaussianFilter->SetVariance(sigma); secGaussianFilter->SetUseImageSpacingOff(); std::cout<<"Secondary image gaussian smoothing on."<<std::endl; std::cout<<"variance : "<<sigma<<" (pixels)"<<std::endl; registration->SetMovingInput(secGaussianFilter->GetOutput()); } else { std::cout<<"Secondary image gaussian smoothing off."<<std::endl; registration->SetMovingInput(mreader->GetOutput()); } // Retrieve metric name std::string metricId = "CC"; if(parseResult->IsOptionPresent("Metric")) { metricId = parseResult->GetParameterString("Metric"); } if(metricId == "CC") { std::cout<<"Metric : Cross-correlation"<<std::endl; typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,ImageType> NCCType; NCCType::Pointer metricPtr = NCCType::New(); metricPtr->SubtractMeanOff(); registration->SetMetric(metricPtr); registration->MinimizeOn(); } else if(metricId == "CCSM") { std::cout<<"Metric : Cross-correlation (mean subtracted)"<<std::endl; typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,ImageType> NCCType; NCCType::Pointer metricPtr = NCCType::New(); metricPtr->SubtractMeanOn(); registration->SetMetric(metricPtr); registration->MinimizeOn(); } else if(metricId == "MSD") { std::cout<<"Metric : Mean square difference"<<std::endl; typedef itk::MeanSquaresImageToImageMetric<ImageType,ImageType> MeanSquareType; MeanSquareType::Pointer metricPtr = MeanSquareType::New(); registration->SetMetric(metricPtr); registration->MinimizeOn(); } else if(metricId == "MRSD") { std::cout<<"Metric : Mean reciprocal square difference"<<std::endl; typedef itk::MeanReciprocalSquareDifferenceImageToImageMetric<ImageType,ImageType> MRSDType; MRSDType::Pointer metricPtr = MRSDType::New(); registration->SetMetric(metricPtr); registration->MinimizeOff(); } else if(metricId == "MI") { std::cout<<"Metric : Mutual information"<<std::endl; typedef itk::MattesMutualInformationImageToImageMetric<ImageType,ImageType> MIType; MIType::Pointer metricPtr = MIType::New(); registration->SetMetric(metricPtr); registration->MinimizeOn(); } else { std::cerr<<"Metric "<<metricId<<" not recognized."<<std::endl; std::cerr<<"Possible choices are: CC, CCMS, MSD, MRSD, MI"<<std::endl; return EXIT_FAILURE; } VectorImageToImageFilterType::Pointer xExtractor = VectorImageToImageFilterType::New(); xExtractor->SetInput(registration->GetOutputDeformationField()); xExtractor->SetIndex(0); VectorImageToImageFilterType::Pointer yExtractor = VectorImageToImageFilterType::New(); yExtractor->SetInput(registration->GetOutputDeformationField()); yExtractor->SetIndex(1); ImageListType::Pointer il = ImageListType::New(); il->PushBack(xExtractor->GetOutput()); il->PushBack(yExtractor->GetOutput()); AbsFilterType::Pointer absFilter; // Invert correlation to get classical rendering if(metricId == "CC" || metricId == "CCSM") { absFilter = AbsFilterType::New(); absFilter->SetInput(registration->GetOutput()); il->PushBack(absFilter->GetOutput()); } else { il->PushBack(registration->GetOutput()); } BinaryThresholdImageFilterType::Pointer threshold; if(parseResult->IsOptionPresent("ValidityMask")) { threshold = BinaryThresholdImageFilterType::New(); if(metricId == "CC" || metricId == "CCSM") { threshold->SetInput(absFilter->GetOutput()); } else { threshold->SetInput(registration->GetOutput()); } if(parseResult->GetParameterString("ValidityMask",0)=="greaterThan") { threshold->SetLowerThreshold(parseResult->GetParameterDouble("ValidityMask",1)); } else if(parseResult->GetParameterString("ValidityMask",0)=="lowerThan") { threshold->SetUpperThreshold(parseResult->GetParameterDouble("ValidityMask",1)); } else { std::cerr<<"Arguments of --ValidityMask option should begin with lowerThan or greaterThan"<<std::endl; return EXIT_FAILURE; } std::cout<<"A validity mask will be produced as the 4th band (valid pixels = 1.0, not valid = 0.0)."<<std::endl; std::cout<<"Pixels are considered valid if metric is "<<parseResult->GetParameterString("ValidityMask",0)<<" "; std::cout<<parseResult->GetParameterDouble("ValidityMask",1)<<std::endl; threshold->SetInsideValue(1.0); threshold->SetOutsideValue(0.); il->PushBack(threshold->GetOutput()); } IL2VIFilterType::Pointer il2vi = IL2VIFilterType::New(); il2vi->SetInput(il); WriterType::Pointer writer = WriterType::New(); writer->SetFileName(parseResult->GetOutputImage()); writer->SetInput(il2vi->GetOutput()); std::cout<<std::endl; otb::StandardWriterWatcher watcher(writer,registration,"Fine Registration"); writer->Update(); return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>#include <new> #include "types.h" #include "kernel.hh" #include "cpputil.hh" #include "spinlock.h" #include "amd64.h" #include "condvar.h" #include "proc.hh" #include "cpu.hh" #include "elf.hh" const std::nothrow_t std::nothrow; void* operator new(std::size_t nbytes) { panic("global operator new"); u64* x = (u64*) kmalloc(nbytes + sizeof(u64), "cpprt new"); *x = nbytes; return x+1; } void operator delete(void* p) noexcept { panic("global operator delete"); u64* x = (u64*) p; kmfree(x-1, x[-1] + sizeof(u64)); } void* operator new[](std::size_t nbytes) { u64* x = (u64*) kmalloc(nbytes + sizeof(u64), "array"); *x = nbytes; return x+1; } void operator delete[](void* p) noexcept { u64* x = (u64*) p; kmfree(x-1, x[-1] + sizeof(u64)); } void * operator new(std::size_t nbytes, void* buf) noexcept { return buf; } void operator delete(void* ptr, void*) noexcept { } void __cxa_pure_virtual(void) { panic("__cxa_pure_virtual"); } int __cxa_guard_acquire(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); pushcli(); while (xchg32(l, 1) != 0) ; /* spin */ if (*x) { xchg32(l, 0); popcli(); return 0; } return 1; } void __cxa_guard_release(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); *x = 1; __sync_synchronize(); xchg32(l, 0); popcli(); } void __cxa_guard_abort(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); xchg32(l, 0); popcli(); } int __cxa_atexit(void (*f)(void*), void *p, void *d) { return 0; } extern "C" void abort(void); void abort(void) { panic("abort"); } static void cxx_terminate(void) { panic("cxx terminate"); } static void cxx_unexpected(void) { panic("cxx unexpected"); } void *__dso_handle; namespace std { std::ostream cout; template<> u128 atomic<u128>::load(memory_order __m) const { __sync_synchronize(); u128 v = _M_i; __sync_synchronize(); return v; } template<> bool atomic<u128>::compare_exchange_weak(u128 &__i1, u128 i2, memory_order __m) { // XXX no __sync_val_compare_and_swap for u128 u128 o = __i1; bool ok = __sync_bool_compare_and_swap(&_M_i, o, i2); if (!ok) __i1 = _M_i; return ok; } }; namespace __cxxabiv1 { void (*__terminate_handler)() = cxx_terminate; void (*__unexpected_handler)() = cxx_unexpected; }; static char malloc_buf[65536]; static std::atomic<size_t> malloc_idx; static bool malloc_proc = false; extern "C" void* malloc(size_t); void* malloc(size_t n) { if (n > PGSIZE) { // libgcc_eh needs to allocate a large chunk of memory once size_t myoff = atomic_fetch_add(&malloc_idx, n); assert(myoff + n <= sizeof(malloc_buf)); return &malloc_buf[myoff]; } if (malloc_proc) { assert(n <= sizeof(myproc()->exception_buf)); assert(cmpxch(&myproc()->exception_inuse, 0, 1)); return myproc()->exception_buf; } u64* p = (u64*) kmalloc(n+8, "cpprt malloc"); *p = n; return p+1; } extern "C" void free(void*); void free(void* vp) { if (vp >= malloc_buf && vp < malloc_buf + sizeof(malloc_buf)) return; if (vp == myproc()->exception_buf) { myproc()->exception_inuse = 0; return; } u64* p = (u64*) vp; kmfree(p-1, p[-1]+8); } extern "C" int dl_iterate_phdr(void); int dl_iterate_phdr(void) { return -1; } extern "C" void __stack_chk_fail(void); void __stack_chk_fail(void) { panic("stack_chk_fail"); } extern "C" int pthread_once(int *oncectl, void (*f)(void)); int pthread_once(int *oncectl, void (*f)(void)) { if (__sync_bool_compare_and_swap(oncectl, 0, 1)) (*f)(); return 0; } extern "C" int pthread_cancel(int tid); int pthread_cancel(int tid) { /* * This function's job is to contain a non-zero opcode that * makes __gthread_active_p in gcc/gthr-posix95.h return 1. */ return 0; } extern "C" int pthread_mutex_lock(int *mu); int pthread_mutex_lock(int *mu) { while (!__sync_bool_compare_and_swap(mu, 0, 1)) ; /* spin */ return 0; } extern "C" int pthread_mutex_unlock(int *mu); int pthread_mutex_unlock(int *mu) { *mu = 0; return 0; } extern "C" void* __cxa_get_globals(void); void* __cxa_get_globals(void) { return myproc()->__cxa_eh_global; } extern "C" void* __cxa_get_globals_fast(void); void* __cxa_get_globals_fast(void) { return myproc()->__cxa_eh_global; } extern "C" void __register_frame(u8*); void initcpprt(void) { #if EXCEPTIONS extern u8 __EH_FRAME_BEGIN__[]; __register_frame(__EH_FRAME_BEGIN__); // Initialize lazy exception handling data structures try { throw 5; } catch (int& x) { assert(x == 5); malloc_proc = true; return; } panic("no catch"); #endif } <commit_msg>Fix comment; I misunderstood __gthread_active_p<commit_after>#include <new> #include "types.h" #include "kernel.hh" #include "cpputil.hh" #include "spinlock.h" #include "amd64.h" #include "condvar.h" #include "proc.hh" #include "cpu.hh" #include "elf.hh" const std::nothrow_t std::nothrow; void* operator new(std::size_t nbytes) { panic("global operator new"); u64* x = (u64*) kmalloc(nbytes + sizeof(u64), "cpprt new"); *x = nbytes; return x+1; } void operator delete(void* p) noexcept { panic("global operator delete"); u64* x = (u64*) p; kmfree(x-1, x[-1] + sizeof(u64)); } void* operator new[](std::size_t nbytes) { u64* x = (u64*) kmalloc(nbytes + sizeof(u64), "array"); *x = nbytes; return x+1; } void operator delete[](void* p) noexcept { u64* x = (u64*) p; kmfree(x-1, x[-1] + sizeof(u64)); } void * operator new(std::size_t nbytes, void* buf) noexcept { return buf; } void operator delete(void* ptr, void*) noexcept { } void __cxa_pure_virtual(void) { panic("__cxa_pure_virtual"); } int __cxa_guard_acquire(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); pushcli(); while (xchg32(l, 1) != 0) ; /* spin */ if (*x) { xchg32(l, 0); popcli(); return 0; } return 1; } void __cxa_guard_release(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); *x = 1; __sync_synchronize(); xchg32(l, 0); popcli(); } void __cxa_guard_abort(s64 *guard) { volatile u8 *x = (u8*) guard; volatile u32 *l = (u32*) (x+4); xchg32(l, 0); popcli(); } int __cxa_atexit(void (*f)(void*), void *p, void *d) { return 0; } extern "C" void abort(void); void abort(void) { panic("abort"); } static void cxx_terminate(void) { panic("cxx terminate"); } static void cxx_unexpected(void) { panic("cxx unexpected"); } void *__dso_handle; namespace std { std::ostream cout; template<> u128 atomic<u128>::load(memory_order __m) const { __sync_synchronize(); u128 v = _M_i; __sync_synchronize(); return v; } template<> bool atomic<u128>::compare_exchange_weak(u128 &__i1, u128 i2, memory_order __m) { // XXX no __sync_val_compare_and_swap for u128 u128 o = __i1; bool ok = __sync_bool_compare_and_swap(&_M_i, o, i2); if (!ok) __i1 = _M_i; return ok; } }; namespace __cxxabiv1 { void (*__terminate_handler)() = cxx_terminate; void (*__unexpected_handler)() = cxx_unexpected; }; static char malloc_buf[65536]; static std::atomic<size_t> malloc_idx; static bool malloc_proc = false; extern "C" void* malloc(size_t); void* malloc(size_t n) { if (n > PGSIZE) { // libgcc_eh needs to allocate a large chunk of memory once size_t myoff = atomic_fetch_add(&malloc_idx, n); assert(myoff + n <= sizeof(malloc_buf)); return &malloc_buf[myoff]; } if (malloc_proc) { assert(n <= sizeof(myproc()->exception_buf)); assert(cmpxch(&myproc()->exception_inuse, 0, 1)); return myproc()->exception_buf; } u64* p = (u64*) kmalloc(n+8, "cpprt malloc"); *p = n; return p+1; } extern "C" void free(void*); void free(void* vp) { if (vp >= malloc_buf && vp < malloc_buf + sizeof(malloc_buf)) return; if (vp == myproc()->exception_buf) { myproc()->exception_inuse = 0; return; } u64* p = (u64*) vp; kmfree(p-1, p[-1]+8); } extern "C" int dl_iterate_phdr(void); int dl_iterate_phdr(void) { return -1; } extern "C" void __stack_chk_fail(void); void __stack_chk_fail(void) { panic("stack_chk_fail"); } extern "C" int pthread_once(int *oncectl, void (*f)(void)); int pthread_once(int *oncectl, void (*f)(void)) { if (__sync_bool_compare_and_swap(oncectl, 0, 1)) (*f)(); return 0; } extern "C" int pthread_cancel(int tid); int pthread_cancel(int tid) { /* * This function's job is to make __gthread_active_p * in gcc/gthr-posix95.h return 1. */ return 0; } extern "C" int pthread_mutex_lock(int *mu); int pthread_mutex_lock(int *mu) { while (!__sync_bool_compare_and_swap(mu, 0, 1)) ; /* spin */ return 0; } extern "C" int pthread_mutex_unlock(int *mu); int pthread_mutex_unlock(int *mu) { *mu = 0; return 0; } extern "C" void* __cxa_get_globals(void); void* __cxa_get_globals(void) { return myproc()->__cxa_eh_global; } extern "C" void* __cxa_get_globals_fast(void); void* __cxa_get_globals_fast(void) { return myproc()->__cxa_eh_global; } extern "C" void __register_frame(u8*); void initcpprt(void) { #if EXCEPTIONS extern u8 __EH_FRAME_BEGIN__[]; __register_frame(__EH_FRAME_BEGIN__); // Initialize lazy exception handling data structures try { throw 5; } catch (int& x) { assert(x == 5); malloc_proc = true; return; } panic("no catch"); #endif } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include "StatsFilter.hpp" #include <unordered_map> #include <pdal/pdal_export.hpp> #include <pdal/Options.hpp> #include <pdal/PDALUtils.hpp> #include <pdal/util/Utils.hpp> namespace pdal { static PluginInfo const s_info = PluginInfo( "filters.stats", "Compute statistics about each dimension (mean, min, max, etc.)", "http://pdal.io/stages/filters.stats.html" ); CREATE_STATIC_PLUGIN(1, 0, StatsFilter, Filter, s_info) std::string StatsFilter::getName() const { return s_info.name; } namespace stats { void Summary::extractMetadata(MetadataNode &m) const { uint32_t cnt = static_cast<uint32_t>(count()); m.add("count", cnt, "count"); m.add("minimum", minimum(), "minimum"); m.add("maximum", maximum(), "maximum"); m.add("average", average(), "average"); m.add("name", m_name, "name"); if (m_enumerate == Enumerate) for (auto& v : m_values) m.addList("values", v.first); else if (m_enumerate == Count) for (auto& v : m_values) { std::string val = std::to_string(v.first) + "/" + std::to_string(v.second); m.addList("counts", val); } } } // namespace stats using namespace stats; bool StatsFilter::processOne(PointRef& point) { for (auto p = m_stats.begin(); p != m_stats.end(); ++p) { Dimension::Id::Enum d = p->first; Summary& c = p->second; c.insert(point.getFieldAs<double>(d)); } return true; } void StatsFilter::filter(PointView& view) { PointRef point(view, 0); for (PointId idx = 0; idx < view.size(); ++idx) { point.setPointId(idx); processOne(point); } } void StatsFilter::done(PointTableRef table) { extractMetadata(); } void StatsFilter::processOptions(const Options& options) { m_dimNames = options.getValueOrDefault<StringList>("dimensions"); m_enums = options.getValueOrDefault<StringList>("enumerate"); m_counts = options.getValueOrDefault<StringList>("count"); } void StatsFilter::prepared(PointTableRef table) { PointLayoutPtr layout(table.layout()); std::unordered_map<std::string, Summary::EnumType> dims; // Add dimensions to the list. if (m_dimNames.empty()) { for (auto id : layout->dims()) dims[layout->dimName(id)] = Summary::NoEnum; } else { for (auto& s : m_dimNames) { if (layout->findDim(s) == Dimension::Id::Unknown) { std::ostringstream out; out << "Dimension '" << s << "' listed in --dimensions option " "does not exist. Ignoring."; Utils::printError(out.str()); } else dims[s] = Summary::NoEnum; } } // Set the enumeration flag for those dimensions specified. for (auto& s : m_enums) { if (dims.find(s) == dims.end()) { std::ostringstream out; out << "Dimension '" << s << "' listed in --enumerate option " "does not exist. Ignoring."; Utils::printError(out.str()); } else dims[s] = Summary::Enumerate; } // Set the enumeration flag for those dimensions specified. for (auto& s : m_counts) { if (dims.find(s) == dims.end()) { std::ostringstream out; out << "Dimension '" << s << "' listed in --count option " "does not exist. Ignoring."; Utils::printError(out.str()); } else dims[s] = Summary::Count; } // Create the summary objects. for (auto& dv : dims) m_stats.insert(std::make_pair(layout->findDim(dv.first), Summary(dv.first, dv.second))); } void StatsFilter::extractMetadata() { uint32_t position(0); for (auto di = m_stats.begin(); di != m_stats.end(); ++di) { const Summary& s = di->second; MetadataNode t = m_metadata.addList("statistic"); t.add("position", position++); s.extractMetadata(t); } } const Summary& StatsFilter::getStats(Dimension::Id::Enum dim) const { for (auto di = m_stats.begin(); di != m_stats.end(); ++di) { Dimension::Id::Enum d = di->first; if (d == dim) return di->second; } throw pdal_error("Dimension not found"); } } // namespace pdal <commit_msg>Replace printError() with log().<commit_after>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include "StatsFilter.hpp" #include <unordered_map> #include <pdal/pdal_export.hpp> #include <pdal/Options.hpp> /** #include <pdal/PDALUtils.hpp> #include <pdal/util/Utils.hpp> **/ namespace pdal { static PluginInfo const s_info = PluginInfo( "filters.stats", "Compute statistics about each dimension (mean, min, max, etc.)", "http://pdal.io/stages/filters.stats.html" ); CREATE_STATIC_PLUGIN(1, 0, StatsFilter, Filter, s_info) std::string StatsFilter::getName() const { return s_info.name; } namespace stats { void Summary::extractMetadata(MetadataNode &m) const { uint32_t cnt = static_cast<uint32_t>(count()); m.add("count", cnt, "count"); m.add("minimum", minimum(), "minimum"); m.add("maximum", maximum(), "maximum"); m.add("average", average(), "average"); m.add("name", m_name, "name"); if (m_enumerate == Enumerate) for (auto& v : m_values) m.addList("values", v.first); else if (m_enumerate == Count) for (auto& v : m_values) { std::string val = std::to_string(v.first) + "/" + std::to_string(v.second); m.addList("counts", val); } } } // namespace stats using namespace stats; bool StatsFilter::processOne(PointRef& point) { for (auto p = m_stats.begin(); p != m_stats.end(); ++p) { Dimension::Id::Enum d = p->first; Summary& c = p->second; c.insert(point.getFieldAs<double>(d)); } return true; } void StatsFilter::filter(PointView& view) { PointRef point(view, 0); for (PointId idx = 0; idx < view.size(); ++idx) { point.setPointId(idx); processOne(point); } } void StatsFilter::done(PointTableRef table) { extractMetadata(); } void StatsFilter::processOptions(const Options& options) { m_dimNames = options.getValueOrDefault<StringList>("dimensions"); m_enums = options.getValueOrDefault<StringList>("enumerate"); m_counts = options.getValueOrDefault<StringList>("count"); } void StatsFilter::prepared(PointTableRef table) { PointLayoutPtr layout(table.layout()); std::unordered_map<std::string, Summary::EnumType> dims; std::ostream& out = log()->get(LogLevel::Warning); // Add dimensions to the list. if (m_dimNames.empty()) { for (auto id : layout->dims()) dims[layout->dimName(id)] = Summary::NoEnum; } else { for (auto& s : m_dimNames) { if (layout->findDim(s) == Dimension::Id::Unknown) out << "Dimension '" << s << "' listed in --dimensions " "option does not exist. Ignoring." << std::endl; else dims[s] = Summary::NoEnum; } } // Set the enumeration flag for those dimensions specified. for (auto& s : m_enums) { if (dims.find(s) == dims.end()) out << "Dimension '" << s << "' listed in --enumerate option " "does not exist. Ignoring." << std::endl; else dims[s] = Summary::Enumerate; } // Set the enumeration flag for those dimensions specified. for (auto& s : m_counts) { if (dims.find(s) == dims.end()) out << "Dimension '" << s << "' listed in --count option " "does not exist. Ignoring." << std::endl; else dims[s] = Summary::Count; } // Create the summary objects. for (auto& dv : dims) m_stats.insert(std::make_pair(layout->findDim(dv.first), Summary(dv.first, dv.second))); } void StatsFilter::extractMetadata() { uint32_t position(0); for (auto di = m_stats.begin(); di != m_stats.end(); ++di) { const Summary& s = di->second; MetadataNode t = m_metadata.addList("statistic"); t.add("position", position++); s.extractMetadata(t); } } const Summary& StatsFilter::getStats(Dimension::Id::Enum dim) const { for (auto di = m_stats.begin(); di != m_stats.end(); ++di) { Dimension::Id::Enum d = di->first; if (d == dim) return di->second; } throw pdal_error("Dimension not found"); } } // namespace pdal <|endoftext|>
<commit_before>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*- // // Copyright (C) 2004 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // // gadurichtextformat.cpp // // 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 <fcntl.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <kdebug.h> #include "gadudccserver.h" #include "libgadu.h" #include "gaduaccount.h" #include <qobject.h> #include <qsocketnotifier.h> #include <qhostaddress.h> GaduDCCServer::GaduDCCServer( QHostAddress* dccIp, unsigned int port ) :QObject() { kdDebug( 14100 ) << "dcc socket NULL, creating new liteining socket " << endl; if ( dccIp == NULL ) { dccIp = new QHostAddress(); dccIp->setAddress( "255.255.255.255" ); } // don't care about UIN at that point dccSock = gg_dcc_socket_create( (unsigned int)-1, port ); if ( dccSock == NULL ){ kdDebug(14100) << "attempt to initialize gadu-dcc listeing socket FAILED" << endl; return; } kdDebug(14100) << "attempt to initialize gadu-dcc listeing socket sucess" << endl; // using global variables sucks, don't have too much choice thou gg_dcc_ip = htonl( dccIp->ip4Addr() ); gg_dcc_port = dccSock->port; createNotifiers( true ); enableNotifiers( dccSock->check ); } GaduDCCServer::~GaduDCCServer() { kdDebug( 14100 ) << "gadu dcc server destructor " << endl; closeDCC(); } void GaduDCCServer::closeDCC() { if ( dccSock ) { disableNotifiers(); destroyNotifiers(); gg_dcc_free( dccSock ); dccSock = NULL; gg_dcc_ip = 0; gg_dcc_port = 0; } } unsigned int GaduDCCServer::listeingPort() { if ( dccSock == NULL ) { return 0; } // else return dccSock->port; } void GaduDCCServer::destroyNotifiers() { disableNotifiers(); if ( read_ ) { delete read_; read_ = NULL; } if ( write_ ) { delete write_; write_ = NULL; } } void GaduDCCServer::createNotifiers( bool connect ) { if ( !dccSock ){ return; } read_ = new QSocketNotifier( dccSock->fd, QSocketNotifier::Read, this ); read_->setEnabled( false ); write_ = new QSocketNotifier( dccSock->fd, QSocketNotifier::Write, this ); write_->setEnabled( false ); if ( connect ) { QObject::connect( read_, SIGNAL( activated( int ) ), SLOT( watcher() ) ); QObject::connect( write_, SIGNAL( activated( int ) ), SLOT( watcher() ) ); } } void GaduDCCServer::enableNotifiers( int checkWhat ) { if( (checkWhat & GG_CHECK_READ) && read_ ) { read_->setEnabled( true ); } if( (checkWhat & GG_CHECK_WRITE) && write_ ) { write_->setEnabled( true ); } } void GaduDCCServer::disableNotifiers() { if ( read_ ) { read_->setEnabled( false ); } if ( write_ ) { write_->setEnabled( false ); } } void GaduDCCServer::watcher() { gg_event* dccEvent; bool handled = false; disableNotifiers(); dccEvent = gg_dcc_watch_fd( dccSock ); if ( ! dccEvent ) { // connection is fucked // we should try to reenable it // closeDCC(); return; } switch ( dccEvent->type ) { case GG_EVENT_NONE: break; case GG_EVENT_DCC_ERROR: kdDebug( 14100 ) << " dcc error occured " << endl; break; case GG_EVENT_DCC_NEW: // I do expect reciver to set this boolean to true if he handled signal // if so, no other reciver should be bothered with it, and I shall not close it // otherwise connection is closed as not handled emit incoming( dccEvent->event.dcc_new, handled ); if ( !handled ) { if ( dccEvent->event.dcc_new->file_fd > 0) { close( dccEvent->event.dcc_new->file_fd ); } gg_dcc_free( dccEvent->event.dcc_new ); } break; default: kdDebug(14100) << "unknown/unhandled DCC EVENT: " << dccEvent->type << endl; break; } if ( dccEvent ) { gg_free_event( dccEvent ); } enableNotifiers( dccSock->check ); } #include "gadudccserver.moc" <commit_msg>don't leak<commit_after>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*- // // Copyright (C) 2004 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // // gadurichtextformat.cpp // // 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 <fcntl.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <kdebug.h> #include "gadudccserver.h" #include "libgadu.h" #include "gaduaccount.h" #include <qobject.h> #include <qsocketnotifier.h> #include <qhostaddress.h> GaduDCCServer::GaduDCCServer( QHostAddress* dccIp, unsigned int port ) :QObject() { kdDebug( 14100 ) << "dcc socket NULL, creating new liteining socket " << endl; // don't care about UIN at that point dccSock = gg_dcc_socket_create( (unsigned int)-1, port ); if ( dccSock == NULL ){ kdDebug(14100) << "attempt to initialize gadu-dcc listeing socket FAILED" << endl; return; } kdDebug(14100) << "attempt to initialize gadu-dcc listeing socket sucess" << endl; // using global variables sucks, don't have too much choice thou if ( dccIp == NULL ) { gg_dcc_ip = 0xffffffff; // 255.255.255.255 } else { gg_dcc_ip = htonl( dccIp->ip4Addr() ); } gg_dcc_port = dccSock->port; createNotifiers( true ); enableNotifiers( dccSock->check ); } GaduDCCServer::~GaduDCCServer() { kdDebug( 14100 ) << "gadu dcc server destructor " << endl; closeDCC(); } void GaduDCCServer::closeDCC() { if ( dccSock ) { disableNotifiers(); destroyNotifiers(); gg_dcc_free( dccSock ); dccSock = NULL; gg_dcc_ip = 0; gg_dcc_port = 0; } } unsigned int GaduDCCServer::listeingPort() { if ( dccSock == NULL ) { return 0; } // else return dccSock->port; } void GaduDCCServer::destroyNotifiers() { disableNotifiers(); if ( read_ ) { delete read_; read_ = NULL; } if ( write_ ) { delete write_; write_ = NULL; } } void GaduDCCServer::createNotifiers( bool connect ) { if ( !dccSock ){ return; } read_ = new QSocketNotifier( dccSock->fd, QSocketNotifier::Read, this ); read_->setEnabled( false ); write_ = new QSocketNotifier( dccSock->fd, QSocketNotifier::Write, this ); write_->setEnabled( false ); if ( connect ) { QObject::connect( read_, SIGNAL( activated( int ) ), SLOT( watcher() ) ); QObject::connect( write_, SIGNAL( activated( int ) ), SLOT( watcher() ) ); } } void GaduDCCServer::enableNotifiers( int checkWhat ) { if( (checkWhat & GG_CHECK_READ) && read_ ) { read_->setEnabled( true ); } if( (checkWhat & GG_CHECK_WRITE) && write_ ) { write_->setEnabled( true ); } } void GaduDCCServer::disableNotifiers() { if ( read_ ) { read_->setEnabled( false ); } if ( write_ ) { write_->setEnabled( false ); } } void GaduDCCServer::watcher() { gg_event* dccEvent; bool handled = false; disableNotifiers(); dccEvent = gg_dcc_watch_fd( dccSock ); if ( ! dccEvent ) { // connection is fucked // we should try to reenable it // closeDCC(); return; } switch ( dccEvent->type ) { case GG_EVENT_NONE: break; case GG_EVENT_DCC_ERROR: kdDebug( 14100 ) << " dcc error occured " << endl; break; case GG_EVENT_DCC_NEW: // I do expect reciver to set this boolean to true if he handled signal // if so, no other reciver should be bothered with it, and I shall not close it // otherwise connection is closed as not handled emit incoming( dccEvent->event.dcc_new, handled ); if ( !handled ) { if ( dccEvent->event.dcc_new->file_fd > 0) { close( dccEvent->event.dcc_new->file_fd ); } gg_dcc_free( dccEvent->event.dcc_new ); } break; default: kdDebug(14100) << "unknown/unhandled DCC EVENT: " << dccEvent->type << endl; break; } if ( dccEvent ) { gg_free_event( dccEvent ); } enableNotifiers( dccSock->check ); } #include "gadudccserver.moc" <|endoftext|>
<commit_before>#include <iostream> #include <talk/base/cryptstring.h> #include <talk/base/logging.h> #include <talk/xmpp/xmppclientsettings.h> #include "xmppthread.h" int main(int argc, char* argv[]) { talk_base::LogMessage::LogToDebug(talk_base::LS_SENSITIVE); talk_base::InsecureCryptStringImpl ipass; ipass.password() = "test"; talk_base::CryptString password = talk_base::CryptString(ipass); // Start xmpp on a different thread XmppThread thread; thread.Start(); // Create client settings buzz::XmppClientSettings xcs; xcs.set_user("test"); xcs.set_pass(password); xcs.set_host("example.org"); xcs.set_use_tls(true); xcs.set_server(talk_base::SocketAddress("example.org", 5222)); thread.Login(xcs); // Use main thread for console input std::string line; while (std::getline(std::cin, line)) { if (line == "quit") break; } return 0; } <commit_msg>Add resource to client settings in hello example<commit_after>#include <iostream> #include <talk/base/cryptstring.h> #include <talk/base/logging.h> #include <talk/xmpp/xmppclientsettings.h> #include "xmppthread.h" int main(int argc, char* argv[]) { talk_base::LogMessage::LogToDebug(talk_base::LS_SENSITIVE); talk_base::InsecureCryptStringImpl ipass; ipass.password() = "test"; talk_base::CryptString password = talk_base::CryptString(ipass); // Start xmpp on a different thread XmppThread thread; thread.Start(); // Create client settings buzz::XmppClientSettings xcs; xcs.set_user("test"); xcs.set_pass(password); xcs.set_host("example.org"); xcs.set_resource("resource"); xcs.set_use_tls(true); xcs.set_server(talk_base::SocketAddress("example.org", 5222)); thread.Login(xcs); // Use main thread for console input std::string line; while (std::getline(std::cin, line)) { if (line == "quit") break; } return 0; } <|endoftext|>
<commit_before>/** * \ file FlushToZero.cpp */ #include <cmath> #include <ATK/Utility/FlushToZero.h> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(FTZ_test) { ATK::FlushToZero ftz; BOOST_CHECK_THROW(throw std::runtime_error("check"), std::runtime_error); // to make unit test happy } <commit_msg>Try again for appveyor<commit_after>/** * \ file FlushToZero.cpp */ #include <cmath> #include <ATK/Utility/FlushToZero.h> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(FTZ_test) { ATK::FlushToZero ftz; BOOST_CHECK_EQUAL(0, 0); // to make unit test happy } <|endoftext|>
<commit_before>#include "types.h" #include "kernel.hh" #include "mmu.h" #include "amd64.h" #include "spinlock.h" #include "condvar.h" #include "queue.h" #include "proc.hh" #include "cpu.hh" #include "bits.hh" #include "kmtrace.hh" #include "sched.hh" #include "vm.hh" enum { sched_debug = 0 }; struct runq { STAILQ_HEAD(queue, proc) q; struct spinlock lock; __padout__; }; static struct runq runq[NCPU] __mpalign__; void post_swtch(void) { if (mycpu()->prev->get_state() == RUNNABLE && mycpu()->prev != idleproc()) addrun(mycpu()->prev); release(&mycpu()->prev->lock); } void sched(void) { extern void threadstub(void); extern void forkret(void); extern void idleheir(void *x); int intena; #if SPINLOCK_DEBUG if(!holding(&myproc()->lock)) panic("sched proc->lock"); #endif if (myproc() == idleproc() && myproc()->get_state() != RUNNABLE) { extern void idlebequeath(void); idlebequeath(); } if(mycpu()->ncli != 1) panic("sched locks"); if(myproc()->get_state() == RUNNING) panic("sched running"); if(readrflags()&FL_IF) panic("sched interruptible"); intena = mycpu()->intena; myproc()->curcycles += rdtsc() - myproc()->tsc; struct proc *next = schednext(); if (next == nullptr) { if (myproc()->get_state() != RUNNABLE || // proc changed its CPU pin? myproc()->cpuid != mycpu()->id) { next = idleproc(); } else { myproc()->set_state(RUNNING); mycpu()->intena = intena; release(&myproc()->lock); return; } } if (next->get_state() != RUNNABLE) panic("non-RUNNABLE next %s %u", next->name, next->get_state()); struct proc *prev = myproc(); mycpu()->proc = next; mycpu()->prev = prev; if (prev->get_state() == ZOMBIE) mtstop(prev); else mtpause(prev); mtign(); switchvm(next); next->set_state(RUNNING); next->tsc = rdtsc(); if (next->context->rip != (uptr)forkret && next->context->rip != (uptr)threadstub && next->context->rip != (uptr)idleheir) { mtresume(next); } mtrec(); swtch(&prev->context, next->context); mycpu()->intena = intena; post_swtch(); } void addrun(struct proc *p) { // Always called with p->lock held struct runq *q; p->set_state(RUNNABLE); q = &runq[p->cpuid]; acquire(&q->lock); STAILQ_INSERT_HEAD(&q->q, p, runqlink); p->runq = q; release(&q->lock); } void delrun(struct proc *p) { // Always called with p->lock held struct runq *q; q = p->runq; acquire(&q->lock); STAILQ_REMOVE(&q->q, p, proc, runqlink); release(&q->lock); } int steal(void) { struct proc *steal; int r = 0; pushcli(); for (int nonexec = 0; nonexec < 2; nonexec++) { for (int i = 1; i < ncpu; i++) { struct runq *q = &runq[(i+mycpu()->id) % ncpu]; struct proc *p; // XXX(sbw) Look for a process to steal. Acquiring q->lock // then p->lock can result in deadlock. So we acquire // q->lock, scan for a process, drop q->lock, acquire p->lock, // and then check that it's still ok to steal p. steal = nullptr; if (tryacquire(&q->lock) == 0) continue; STAILQ_FOREACH(p, &q->q, runqlink) { if (p->get_state() == RUNNABLE && !p->cpu_pin && (p->in_exec_ || nonexec) && p->curcycles != 0 && p->curcycles > VICTIMAGE) { STAILQ_REMOVE(&q->q, p, proc, runqlink); steal = p; break; } } release(&q->lock); if (steal) { acquire(&steal->lock); if (steal->get_state() == RUNNABLE && !steal->cpu_pin && steal->curcycles != 0 && steal->curcycles > VICTIMAGE) { steal->curcycles = 0; steal->cpuid = mycpu()->id; addrun(steal); release(&steal->lock); r = 1; goto found; } if (steal->get_state() == RUNNABLE) addrun(steal); release(&steal->lock); } } } found: popcli(); return r; } struct proc * schednext(void) { // No locks, interrupts enabled struct runq *q; struct proc *p = nullptr; pushcli(); q = &runq[mycpu()->id]; acquire(&q->lock); p = STAILQ_LAST(&q->q, proc, runqlink); if (p) STAILQ_REMOVE(&q->q, p, proc, runqlink); release(&q->lock); popcli(); return p; } void initsched(void) { int i; for (i = 0; i < NCPU; i++) { initlock(&runq[i].lock, "runq", LOCKSTAT_SCHED); STAILQ_INIT(&runq[i].q); } } #if 0 static int migrate(struct proc *p) { // p should not be running, or be on a runqueue, or be myproc() int c; if (p == myproc()) panic("migrate: myproc"); for (c = 0; c < ncpu; c++) { if (c == mycpu()->id) continue; if (idle[c]) { // OK if there is a race acquire(&p->lock); if (p->state == RUNNING) panic("migrate: pid %u name %s is running", p->pid, p->name); if (p->cpu_pin) panic("migrate: pid %u name %s is pinned", p->pid, p->name); p->curcycles = 0; p->cpuid = c; addrun(p); idle[c] = 0; release(&p->lock); return 0; } } return -1; } #endif <commit_msg>flag to only migrate exec's (not on by default)<commit_after>#include "types.h" #include "kernel.hh" #include "mmu.h" #include "amd64.h" #include "spinlock.h" #include "condvar.h" #include "queue.h" #include "proc.hh" #include "cpu.hh" #include "bits.hh" #include "kmtrace.hh" #include "sched.hh" #include "vm.hh" enum { sched_debug = 0 }; enum { steal_nonexec = 1 }; struct runq { STAILQ_HEAD(queue, proc) q; struct spinlock lock; __padout__; }; static struct runq runq[NCPU] __mpalign__; void post_swtch(void) { if (mycpu()->prev->get_state() == RUNNABLE && mycpu()->prev != idleproc()) addrun(mycpu()->prev); release(&mycpu()->prev->lock); } void sched(void) { extern void threadstub(void); extern void forkret(void); extern void idleheir(void *x); int intena; #if SPINLOCK_DEBUG if(!holding(&myproc()->lock)) panic("sched proc->lock"); #endif if (myproc() == idleproc() && myproc()->get_state() != RUNNABLE) { extern void idlebequeath(void); idlebequeath(); } if(mycpu()->ncli != 1) panic("sched locks"); if(myproc()->get_state() == RUNNING) panic("sched running"); if(readrflags()&FL_IF) panic("sched interruptible"); intena = mycpu()->intena; myproc()->curcycles += rdtsc() - myproc()->tsc; struct proc *next = schednext(); if (next == nullptr) { if (myproc()->get_state() != RUNNABLE || // proc changed its CPU pin? myproc()->cpuid != mycpu()->id) { next = idleproc(); } else { myproc()->set_state(RUNNING); mycpu()->intena = intena; release(&myproc()->lock); return; } } if (next->get_state() != RUNNABLE) panic("non-RUNNABLE next %s %u", next->name, next->get_state()); struct proc *prev = myproc(); mycpu()->proc = next; mycpu()->prev = prev; if (prev->get_state() == ZOMBIE) mtstop(prev); else mtpause(prev); mtign(); switchvm(next); next->set_state(RUNNING); next->tsc = rdtsc(); if (next->context->rip != (uptr)forkret && next->context->rip != (uptr)threadstub && next->context->rip != (uptr)idleheir) { mtresume(next); } mtrec(); swtch(&prev->context, next->context); mycpu()->intena = intena; post_swtch(); } void addrun(struct proc *p) { // Always called with p->lock held struct runq *q; p->set_state(RUNNABLE); q = &runq[p->cpuid]; acquire(&q->lock); STAILQ_INSERT_HEAD(&q->q, p, runqlink); p->runq = q; release(&q->lock); } void delrun(struct proc *p) { // Always called with p->lock held struct runq *q; q = p->runq; acquire(&q->lock); STAILQ_REMOVE(&q->q, p, proc, runqlink); release(&q->lock); } int steal(void) { struct proc *steal; int r = 0; pushcli(); for (int nonexec = 0; nonexec < (steal_nonexec ? 2 : 1); nonexec++) { for (int i = 1; i < ncpu; i++) { struct runq *q = &runq[(i+mycpu()->id) % ncpu]; struct proc *p; // XXX(sbw) Look for a process to steal. Acquiring q->lock // then p->lock can result in deadlock. So we acquire // q->lock, scan for a process, drop q->lock, acquire p->lock, // and then check that it's still ok to steal p. steal = nullptr; if (tryacquire(&q->lock) == 0) continue; STAILQ_FOREACH(p, &q->q, runqlink) { if (p->get_state() == RUNNABLE && !p->cpu_pin && (p->in_exec_ || nonexec) && p->curcycles != 0 && p->curcycles > VICTIMAGE) { STAILQ_REMOVE(&q->q, p, proc, runqlink); steal = p; break; } } release(&q->lock); if (steal) { acquire(&steal->lock); if (steal->get_state() == RUNNABLE && !steal->cpu_pin && steal->curcycles != 0 && steal->curcycles > VICTIMAGE) { steal->curcycles = 0; steal->cpuid = mycpu()->id; addrun(steal); release(&steal->lock); r = 1; goto found; } if (steal->get_state() == RUNNABLE) addrun(steal); release(&steal->lock); } } } found: popcli(); return r; } struct proc * schednext(void) { // No locks, interrupts enabled struct runq *q; struct proc *p = nullptr; pushcli(); q = &runq[mycpu()->id]; acquire(&q->lock); p = STAILQ_LAST(&q->q, proc, runqlink); if (p) STAILQ_REMOVE(&q->q, p, proc, runqlink); release(&q->lock); popcli(); return p; } void initsched(void) { int i; for (i = 0; i < NCPU; i++) { initlock(&runq[i].lock, "runq", LOCKSTAT_SCHED); STAILQ_INIT(&runq[i].q); } } #if 0 static int migrate(struct proc *p) { // p should not be running, or be on a runqueue, or be myproc() int c; if (p == myproc()) panic("migrate: myproc"); for (c = 0; c < ncpu; c++) { if (c == mycpu()->id) continue; if (idle[c]) { // OK if there is a race acquire(&p->lock); if (p->state == RUNNING) panic("migrate: pid %u name %s is running", p->pid, p->name); if (p->cpu_pin) panic("migrate: pid %u name %s is pinned", p->pid, p->name); p->curcycles = 0; p->cpuid = c; addrun(p); idle[c] = 0; release(&p->lock); return 0; } } return -1; } #endif <|endoftext|>
<commit_before>// // Copyright (c) 2018, University of Edinburgh // 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 nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <typeinfo> #include <vector> #include <exotica_core/tools.h> #include "exotica_core/property.h" namespace exotica { // * ///////////////////////////// Property ////////////////////////////////////// boost::any Property::Get() const { return value_; } Property::Property(const std::string& prop_name) : name_(prop_name), required_(true) {} Property::Property(const std::string& prop_name, bool is_required) : name_(prop_name), required_(is_required) {} Property::Property(const std::string& prop_name, bool is_required, boost::any val) : name_(prop_name), required_(is_required) { value_ = val; } bool Property::IsRequired() const { return required_; } bool Property::IsSet() const { return !value_.empty(); } bool Property::IsStringType() const { return value_.type() == typeid(std::string); } bool Property::IsInitializerVectorType() const { return value_.type() == typeid(std::vector<exotica::Initializer>); } std::string Property::GetName() const { return name_; } std::string Property::GetType() const { return GetTypeName(value_.type()); } Property::Property(std::initializer_list<boost::any> _val) { std::vector<boost::any> val(_val); if (val.size() != 2 || val[0].type() != typeid(std::string)) ThrowPretty("Invalid property initialization!"); name_ = boost::any_cast<std::string>(val[0]); value_ = val[1]; } // * ///////////////////////// InitializerBase /////////////////////////////////// Initializer::Initializer() { } Initializer::Initializer(const std::string& name) : name_(name) { } Initializer::Initializer(const std::string& name, const std::map<std::string, boost::any>& properties) : name_(name) { for (auto& prop : properties) { properties_.emplace(prop.first, Property(prop.first, true, prop.second)); } } std::string Initializer::GetName() const { return name_; } void Initializer::AddProperty(const Property& prop) { properties_.emplace(prop.GetName(), prop); } bool Initializer::HasProperty(const std::string& name) const { return properties_.find(name) != properties_.end(); } boost::any Initializer::GetProperty(const std::string& name) const { return properties_.at(name).Get(); } void Initializer::SetProperty(const std::string& name, boost::any value) { properties_.at(name).Set(value); } void Initializer::SetName(const std::string& name) { name_ = name; } std::vector<std::string> Initializer::GetPropertyNames() const { return GetKeys(properties_); } } // namespace exotica <commit_msg>[exotica_core] Property: Warn and override if double-adding the same property<commit_after>// // Copyright (c) 2018, University of Edinburgh // 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 nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <typeinfo> #include <vector> #include <exotica_core/tools.h> #include "exotica_core/property.h" namespace exotica { // * ///////////////////////////// Property ////////////////////////////////////// boost::any Property::Get() const { return value_; } Property::Property(const std::string& prop_name) : name_(prop_name), required_(true) {} Property::Property(const std::string& prop_name, bool is_required) : name_(prop_name), required_(is_required) {} Property::Property(const std::string& prop_name, bool is_required, boost::any val) : name_(prop_name), required_(is_required) { value_ = val; } bool Property::IsRequired() const { return required_; } bool Property::IsSet() const { return !value_.empty(); } bool Property::IsStringType() const { return value_.type() == typeid(std::string); } bool Property::IsInitializerVectorType() const { return value_.type() == typeid(std::vector<exotica::Initializer>); } std::string Property::GetName() const { return name_; } std::string Property::GetType() const { return GetTypeName(value_.type()); } Property::Property(std::initializer_list<boost::any> _val) { std::vector<boost::any> val(_val); if (val.size() != 2 || val[0].type() != typeid(std::string)) ThrowPretty("Invalid property initialization!"); name_ = boost::any_cast<std::string>(val[0]); value_ = val[1]; } // * ///////////////////////// InitializerBase /////////////////////////////////// Initializer::Initializer() { } Initializer::Initializer(const std::string& name) : name_(name) { } Initializer::Initializer(const std::string& name, const std::map<std::string, boost::any>& properties) : name_(name) { for (auto& prop : properties) { AddProperty(Property(prop.first, true, prop.second)); } } std::string Initializer::GetName() const { return name_; } void Initializer::AddProperty(const Property& prop) { if (HasProperty(prop.GetName())) { WARNING("Property '" << prop.GetName() << "' already added - overriding."); SetProperty(prop.GetName(), prop.Get()); } else { properties_.emplace(prop.GetName(), prop); } } bool Initializer::HasProperty(const std::string& name) const { return properties_.find(name) != properties_.end(); } boost::any Initializer::GetProperty(const std::string& name) const { return properties_.at(name).Get(); } void Initializer::SetProperty(const std::string& name, boost::any value) { properties_.at(name).Set(value); } void Initializer::SetName(const std::string& name) { name_ = name; } std::vector<std::string> Initializer::GetPropertyNames() const { return GetKeys(properties_); } } // namespace exotica <|endoftext|>
<commit_before>#include "all.h" #include "boost_test.h" class MockBlock : public Block { void work(void) {} }; BOOST_AUTO_TEST_CASE( graphValidityTests ) { BOOST_CHECK(0); #if 0 MockBlock block1; MockBlock block2; MockBlock block3; MockBlock block4; Graph dut; /* No connections yet */ BOOST_CHECK_THROW(dut.checkGraph(), EmptyGraphException); /* Add one valid noodle */ Noodle n1(&block1, &block2); dut.addNoodle(&n1); BOOST_CHECK_EQUAL(dut.checkGraph(), 0); /* Try to add the same noodle again */ BOOST_CHECK_THROW(dut.addNoodle(&n1), DuplicateNoodleException); /* Try to make block1 and block3 be the source for block2 (not ok) */ Noodle n2(&block3, &block2); BOOST_CHECK_THROW(dut.addNoodle(&n2), InputMultipleNoodleException); /* Make block2 be the source for block3 and block4 (allowed) */ Noodle n3(&block2, &block3); Noodle n4(&block2, &block4); dut.addNoodle(&n3); dut.addNoodle(&n4); BOOST_CHECK_EQUAL(dut.checkGraph(), 0); #endif } <commit_msg>update GraphTest and remove tests already covered in PortsTest<commit_after>#include "all.h" #include "boost_test.h" class MockBlock : public Block { public: MockBlock(void) { inputs.add("in"); outputs.add("out"); } void reset(void) {} void work(void) {} }; BOOST_AUTO_TEST_CASE( graphTest ) { MockBlock block1; MockBlock block2; Graph dut; /* No connections yet */ BOOST_CHECK_THROW(dut.checkGraph(), EmptyGraphException); /* Add one valid noodle */ dut.addNoodle({&block1, "out"}, {&block2, "in"}); BOOST_CHECK_EQUAL(dut.checkGraph(), 0); } <|endoftext|>
<commit_before>#pragma once #include "util.cpp" #include <set> #include <cmath> struct Coord { int r, c, h; }; bool operator < (const Coord &a, const Coord &b) { if (a.r != b.r) return a.r < b.r; else if (a.c != b.c) return a.c < b.c; else return a.h < b.h; } double compute_distance(double r1, double c1, double r2, double c2, double r, double c) { if (r1 < 0 || r1 >= r) return 1e9; double dr = abs(r1-r2); double dc = min(abs(c1-c2),c-abs(c1-c2)); return sqrt(dr*dr+dc*dc); } void check_cell(Input &input, Coord cur, vector<Coord>& path, vector<int>& prev, set<Coord>& visited, vector<int>& dist, int idx) { //cerr << "adding balloon: " << cur.r << ' ' << cur.c << ' ' << cur.h << endl; int dr = input.movement_r[cur.r][cur.c][cur.h]; int dc = input.movement_c[cur.r][cur.c][cur.h]; cur.r += dr; cur.c += dc; cur.c = (cur.c + input.c) % input.c; //cerr << "done\n"; if (visited.find(cur) != visited.end()) return; path.push_back(cur); prev.push_back(idx); dist.push_back(dist[idx]+1); visited.insert(cur); } void bfs(Input &input, vector<Coord>& path, vector<int>& prev) { set<Coord> visited; vector<int> dist; int idx = 0; dist.push_back(idx); visited.insert(path[idx]); while (idx < path.size()) { Coord cur = path[idx]; //cerr << "current balloon: " << cur.r << ' ' << cur.c << ' ' << cur.h << endl; if (dist[idx] > 5) break; // out of bounds -> stay there if (cur.r >= input.r || cur.r < 0) { path.push_back(cur); prev.push_back(idx); dist.push_back(dist[idx]+1); } // try changing the altitude else { check_cell(input,cur,path,prev,visited,dist,idx); if (cur.h > 1) { cur.h--; check_cell(input,cur,path,prev,visited,dist,idx); cur.h++; } if (cur.h < input.a) { cur.h++; check_cell(input,cur,path,prev,visited,dist,idx); cur.h--; } } idx++; } } void pathfinding(Input& input, int balloon, double r, double c, double delta) { //TODO fill me //run bfs while (input.balloons[balloon].h.size() <= input.t && compute_distance(input.balloons[balloon].r.back(),input.balloons[balloon].c.back(),r,c,input.r,input.c) > delta) { vector<Coord> path; path.clear(); vector<int> prev; prev.clear(); // add starting cell Coord start; start.r = input.balloons[balloon].r.back(); start.c = input.balloons[balloon].c.back(); start.h = input.balloons[balloon].h.back(); path.push_back(start); prev.push_back(-1); bfs(input,path,prev); // choose the closest end point double mind = 1e9, curd; int idx_min = 1; for (int i = 2; i < path.size(); i++) { curd = compute_distance(path[i].r,path[i].c,r,c,input.r,input.c); if (curd < mind || idx_min == 0) { idx_min = i; mind = curd; } } //cerr << path.size() << endl; vector<Coord> reversed_path; for (int i = idx_min; i != 0; i = prev[i]) reversed_path.push_back(path[i]); /* cerr << "flying from: " << start.r << ' ' << start.c << ' ' << start.h << endl; cerr << "to target: " << r << ' ' << c << endl; cerr << "path\n"; for (int i = reversed_path.size()-1; i >= 0; i--) cerr << reversed_path[i].r << ' ' << reversed_path[i].c << ' ' << reversed_path[i].h << endl; cerr << "end of path\n";//*/ for (int i = reversed_path.size()-1; i >= 0; i--) { input.balloons[balloon].h.push_back(reversed_path[i].h); input.balloons[balloon].r.push_back(reversed_path[i].r); input.balloons[balloon].c.push_back(reversed_path[i].c); if (input.balloons[balloon].h.size() > input.t) break; } //double endr = input.balloons[balloon].r.back(); //double endc = input.balloons[balloon].c.back(); //dist_to_dest = compute_distance(endr,endc,r,c); } // for (int i = 0; i < input.balloons[balloon].r.size()-1; i++) // { // int rc = input.balloons[balloon].r[i]; // int rn = input.balloons[balloon].r[i+1]; // int cc = input.balloons[balloon].c[i]; // int cn = input.balloons[balloon].c[i+1]; // if (abs(cc-cn) > input.c - abs(cc-cn)) // cerr << cc << ' ' << rc << ' ' << 0 << ' ' << 0 << ' ' << input.balloons[balloon].cluster_id / ((double)input.clusters.size()) << endl; // else // cerr << cc << ' ' << rc << ' ' << cn-cc << ' ' << rn-rc << ' ' << input.balloons[balloon].cluster_id / ((double)input.clusters.size()) << endl; // } // cerr << endl; } <commit_msg>minor changes in pathfinding<commit_after>#pragma once #include "util.cpp" #include <set> #include <cmath> struct Coord { int r, c, h; }; bool operator < (const Coord &a, const Coord &b) { if (a.r != b.r) return a.r < b.r; else if (a.c != b.c) return a.c < b.c; else return a.h < b.h; } double compute_distance(double r1, double c1, double r2, double c2, double r, double c) { if (r1 < 0 || r1 >= r) return 1e9; double dr = abs(r1-r2); double dc = min(abs(c1-c2),c-abs(c1-c2)); return sqrt(dr*dr+dc*dc); } void check_cell(Input &input, Coord cur, vector<Coord>& path, vector<int>& prev, set<Coord>& visited, vector<int>& dist, int idx) { //cerr << "adding balloon: " << cur.r << ' ' << cur.c << ' ' << cur.h << endl; int dr = input.movement_r[cur.r][cur.c][cur.h]; int dc = input.movement_c[cur.r][cur.c][cur.h]; cur.r += dr; cur.c += dc; cur.c = (cur.c + input.c) % input.c; //cerr << "done\n"; if (visited.find(cur) != visited.end()) return; path.push_back(cur); prev.push_back(idx); dist.push_back(dist[idx]+1); visited.insert(cur); } void bfs(Input &input, vector<Coord>& path, vector<int>& prev) { set<Coord> visited; vector<int> dist; int idx = 0; dist.push_back(idx); visited.insert(path[idx]); while (idx < path.size()) { Coord cur = path[idx]; //cerr << "current balloon: " << cur.r << ' ' << cur.c << ' ' << cur.h << endl; if (dist[idx] > 5) break; // out of bounds -> stay there if (cur.r >= input.r || cur.r < 0) { path.push_back(cur); prev.push_back(idx); dist.push_back(dist[idx]+1); } // try changing the altitude else { check_cell(input,cur,path,prev,visited,dist,idx); if (cur.h > 1) { cur.h--; check_cell(input,cur,path,prev,visited,dist,idx); cur.h++; } if (cur.h < input.a) { cur.h++; check_cell(input,cur,path,prev,visited,dist,idx); cur.h--; } } idx++; } } void pathfinding(Input& input, int balloon, double r, double c, double delta) { //TODO fill me //run bfs while (input.balloons[balloon].h.size() <= input.t && compute_distance(input.balloons[balloon].r.back(),input.balloons[balloon].c.back(),r,c,input.r,input.c) > delta) { vector<Coord> path; path.clear(); vector<int> prev; prev.clear(); // add starting cell Coord start; start.r = input.balloons[balloon].r.back(); start.c = input.balloons[balloon].c.back(); start.h = input.balloons[balloon].h.back(); path.push_back(start); prev.push_back(-1); bfs(input,path,prev); // choose the closest end point double mind = 1e9, curd; int idx_min = 1; for (int i = 2; i < path.size(); i++) { curd = compute_distance(path[i].r,path[i].c,r,c,input.r,input.c); if (curd < mind || idx_min == 0) { idx_min = i; mind = curd; } } //cerr << path.size() << endl; vector<Coord> reversed_path; for (int i = idx_min; i != 0; i = prev[i]) reversed_path.push_back(path[i]); /* cerr << "flying from: " << start.r << ' ' << start.c << ' ' << start.h << endl; cerr << "to target: " << r << ' ' << c << endl; cerr << "path\n"; for (int i = reversed_path.size()-1; i >= 0; i--) cerr << reversed_path[i].r << ' ' << reversed_path[i].c << ' ' << reversed_path[i].h << endl; cerr << "end of path\n";//*/ for (int i = reversed_path.size()-1; i >= 0; i--) { input.balloons[balloon].h.push_back(reversed_path[i].h); input.balloons[balloon].r.push_back(reversed_path[i].r); input.balloons[balloon].c.push_back(reversed_path[i].c); if (input.balloons[balloon].h.size() > input.t) break; } //double endr = input.balloons[balloon].r.back(); //double endc = input.balloons[balloon].c.back(); //dist_to_dest = compute_distance(endr,endc,r,c); } // cerr << r << ' ' << c << endl; // for (int i = 0; i < input.balloons[balloon].r.size()-1; i++) // { // int rc = input.balloons[balloon].r[i]; // int rn = input.balloons[balloon].r[i+1]; // // int cc = input.balloons[balloon].c[i]; // int cn = input.balloons[balloon].c[i+1]; // // if (abs(cc-cn) > input.c - abs(cc-cn)) // cerr << cc << ' ' << rc << ' ' << 0 << ' ' << 0 << ' ' << input.balloons[balloon].cluster_id / ((double)input.clusters.size()) << endl; // else // cerr << cc << ' ' << rc << ' ' << cn-cc << ' ' << rn-rc << ' ' << input.balloons[balloon].cluster_id / ((double)input.clusters.size()) << endl; // } //cerr << endl; } <|endoftext|>
<commit_before>//===-- DTMMessageParse_Test.cpp --------------------------------*- C++ -*-===// // // This file is distributed uner the MIT license. See LICENSE.txt for details. // //===----------------------------------------------------------------------===// /// /// \file /// Functional tests for parseing DTM Messages /// //===----------------------------------------------------------------------===// #include "NMEAParser.h" #include "gtest/gtest.h" #include <cstring> #include <cmath> #include <iostream> #if 0 | N | Message | |---+-------------| | 1 | W84 Valid | | 2 | W72 Invalid | | 3 | Empty | #endif namespace NMEA { TEST(DTMMessageParse, Valid_W84_Message) { const std::string RawMessage = "$GPDTM,W84,,0.0,N,0.0,E,0.0,W84*6F"; NMEAHeader Header = { .ID = NMEA_TALKER_ID::GPS, .Type = NMEA_MESSAGE_TYPE::DTM, .Valid = 1}; GPDTM Message = {.LLL = "W84", .LSD = "", .lat = 0.0f, .lon = 0.0f, .alt = 0.0f, .RRR = "W84"}; NMEAMessage Expected = {.Header = &Header, .DTM = &Message}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Header EXPECT_EQ(Expected.Header->ID, Result->Header->ID); EXPECT_EQ(Expected.Header->Type, Result->Header->Type); EXPECT_EQ(Expected.Header->Valid, Result->Header->Valid); // Compare Message EXPECT_TRUE(strncmp(Expected.DTM->LLL, Result->DTM->LLL, 3) == 0); EXPECT_EQ(Expected.DTM->LSD[0], Result->DTM->LSD[0]); EXPECT_EQ(Expected.DTM->lat, Result->DTM->lat); EXPECT_EQ(Expected.DTM->lon, Result->DTM->lon); EXPECT_EQ(Expected.DTM->alt, Result->DTM->alt); EXPECT_TRUE(strncmp(Expected.DTM->RRR, Result->DTM->RRR, 3) == 0); }; TEST(DTMMessageParse, Valid_W72_Message) { const std::string RawMessage = "$GPDTM,W72,,0.00,S,0.01,W,-2.8,W84*4F"; NMEAHeader Header = { .ID = NMEA_TALKER_ID::GPS, .Type = NMEA_MESSAGE_TYPE::DTM, .Valid = 1}; GPDTM Message = {.LLL = "W72", .LSD = "", .lat = 0.0f, .lon = -0.01f, .alt = -2.8f, .RRR = "W84"}; NMEAMessage Expected = {.Header = &Header, .DTM = &Message}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Header EXPECT_EQ(Expected.Header->ID, Result->Header->ID); EXPECT_EQ(Expected.Header->Type, Result->Header->Type); EXPECT_EQ(Expected.Header->Valid, Result->Header->Valid); // Compare Message EXPECT_TRUE(strncmp(Expected.DTM->LLL, Result->DTM->LLL, 3) == 0); EXPECT_EQ(Expected.DTM->LSD[0], Result->DTM->LSD[0]); EXPECT_EQ(Expected.DTM->lat, Result->DTM->lat); EXPECT_EQ(Expected.DTM->lon, Result->DTM->lon); EXPECT_EQ(Expected.DTM->alt, Result->DTM->alt); EXPECT_TRUE(strncmp(Expected.DTM->RRR, Result->DTM->RRR, 3) == 0); }; TEST(DTMMessageParse, Valid_999_Message) { const std::string RawMessage = "$GPDTM,999,CH95,0.08,N,0.07,E,-47.7,W84*1C"; NMEAHeader Header = { .ID = NMEA_TALKER_ID::GPS, .Type = NMEA_MESSAGE_TYPE::DTM, .Valid = 1}; GPDTM Message = {.LLL = "999", .LSD = "CH95", .lat = 0.08f, .lon = 0.07f, .alt = -47.7f, .RRR = "W84"}; NMEAMessage Expected = {.Header = &Header, .DTM = &Message}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Header EXPECT_EQ(Expected.Header->ID, Result->Header->ID); EXPECT_EQ(Expected.Header->Type, Result->Header->Type); EXPECT_EQ(Expected.Header->Valid, Result->Header->Valid); // Compare Message EXPECT_TRUE(strncmp(Expected.DTM->LLL, Result->DTM->LLL, 3) == 0); EXPECT_EQ(Expected.DTM->LSD[0], Result->DTM->LSD[0]); EXPECT_EQ(Expected.DTM->lat, Result->DTM->lat); EXPECT_EQ(Expected.DTM->lon, Result->DTM->lon); EXPECT_EQ(Expected.DTM->alt, Result->DTM->alt); EXPECT_TRUE(strncmp(Expected.DTM->RRR, Result->DTM->RRR, 3) == 0); }; TEST(DTMMessageParse, Invalid_Message) { const std::string RawMessage = "asdfliouieniifioewufyshdfj"; NMEAHeader Header = {.ID = NMEA_TALKER_ID::UNKNOWN_TALKER_ID, .Type = NMEA_MESSAGE_TYPE::UNKNOWN_MESSAGE, .Valid = 0}; NMEAMessage Expected = {.Header = &Header, 0}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Headers EXPECT_EQ(Expected.Header->ID, Result->Header->ID) << "Talker ID is incorrect"; EXPECT_EQ(Expected.Header->Type, Result->Header->Type) << "Message type is incorrect"; EXPECT_EQ(Expected.Header->Valid, Result->Header->Valid) << "Message valid status is incorrect"; // Compare Message EXPECT_EQ(Expected.DTM, Result->DTM); } TEST(DTMMessageParse, Empty_Message) { const std::string RawMessage = ""; NMEAHeader Header = {.ID = NMEA_TALKER_ID::UNKNOWN_TALKER_ID, .Type = NMEA_MESSAGE_TYPE::UNKNOWN_MESSAGE, .Valid = 0}; NMEAMessage Expected = {.Header = &Header, 0}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Headers EXPECT_EQ(Expected.Header->ID, Result->Header->ID) << "Talker ID is incorrect"; EXPECT_EQ(Expected.Header->Type, Result->Header->Type) << "Message type is incorrect"; EXPECT_EQ(Expected.Header->Valid, Result->Header->Valid) << "Message valid status is incorrect"; // Compare Message EXPECT_EQ(Expected.DTM, Result->DTM); } } <commit_msg>Update DTMMessageParse<commit_after>//===-- DTMMessageParse_Test.cpp --------------------------------*- C++ -*-===// // // This file is distributed uner the MIT license. See LICENSE.txt for details. // //===----------------------------------------------------------------------===// /// /// \file /// Functional tests for parseing DTM Messages /// //===----------------------------------------------------------------------===// #include "NMEAParser.h" #include "gtest/gtest.h" #include <cstring> #include <cmath> #include <iostream> #if 0 | N | Message | |---+-------------| | 1 | W84 Valid | | 2 | W72 Invalid | | 3 | Empty | #endif namespace NMEA { TEST(DTMMessageParse, Valid_W84_Message) { const std::string RawMessage = "$GPDTM,W84,,0.0,N,0.0,E,0.0,W84*6F"; NMEAMessage Expected = {NMEA_TALKER_ID::GPS, NMEA_MESSAGE_TYPE::DTM, 1, {new GPDTM{"W84", "", 0.0f, 0.0f, 0.0f, "W84"}}}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Header EXPECT_EQ(Expected.ID, Result->ID); EXPECT_EQ(Expected.Type, Result->Type); EXPECT_EQ(Expected.Valid, Result->Valid); // Compare Message EXPECT_TRUE(strncmp(Expected.DTM->LLL, Result->DTM->LLL, 3) == 0); EXPECT_EQ(Expected.DTM->LSD[0], Result->DTM->LSD[0]); EXPECT_EQ(Expected.DTM->lat, Result->DTM->lat); EXPECT_EQ(Expected.DTM->lon, Result->DTM->lon); EXPECT_EQ(Expected.DTM->alt, Result->DTM->alt); EXPECT_TRUE(strncmp(Expected.DTM->RRR, Result->DTM->RRR, 3) == 0); }; TEST(DTMMessageParse, Valid_W72_Message) { const std::string RawMessage = "$GPDTM,W72,,0.00,S,0.01,W,-2.8,W84*4F"; NMEAMessage Expected{NMEA_TALKER_ID::GPS, NMEA_MESSAGE_TYPE::DTM, 1, {new GPDTM{"W72", "", 0.0f, -0.01f, -2.8f, "W84"}}}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Header EXPECT_EQ(Expected.ID, Result->ID); EXPECT_EQ(Expected.Type, Result->Type); EXPECT_EQ(Expected.Valid, Result->Valid); // Compare Message EXPECT_TRUE(strncmp(Expected.DTM->LLL, Result->DTM->LLL, 3) == 0); EXPECT_EQ(Expected.DTM->LSD[0], Result->DTM->LSD[0]); EXPECT_EQ(Expected.DTM->lat, Result->DTM->lat); EXPECT_EQ(Expected.DTM->lon, Result->DTM->lon); EXPECT_EQ(Expected.DTM->alt, Result->DTM->alt); EXPECT_TRUE(strncmp(Expected.DTM->RRR, Result->DTM->RRR, 3) == 0); }; TEST(DTMMessageParse, Valid_999_Message) { const std::string RawMessage = "$GPDTM,999,CH95,0.08,N,0.07,E,-47.7,W84*1C"; NMEAMessage Expected{NMEA_TALKER_ID::GPS, NMEA_MESSAGE_TYPE::DTM, 1, {new GPDTM{"999", "CH95", 0.08f, 0.07f, -47.7f, "W84"}}}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Header EXPECT_EQ(Expected.ID, Result->ID); EXPECT_EQ(Expected.Type, Result->Type); EXPECT_EQ(Expected.Valid, Result->Valid); // Compare Message EXPECT_TRUE(strncmp(Expected.DTM->LLL, Result->DTM->LLL, 3) == 0); EXPECT_EQ(Expected.DTM->LSD[0], Result->DTM->LSD[0]); EXPECT_EQ(Expected.DTM->lat, Result->DTM->lat); EXPECT_EQ(Expected.DTM->lon, Result->DTM->lon); EXPECT_EQ(Expected.DTM->alt, Result->DTM->alt); EXPECT_TRUE(strncmp(Expected.DTM->RRR, Result->DTM->RRR, 3) == 0); }; TEST(DTMMessageParse, Invalid_Message) { const std::string RawMessage = "asdfliouieniifioewufyshdfj"; NMEAMessage Expected{NMEA_TALKER_ID::UNKNOWN_TALKER_ID, NMEA_MESSAGE_TYPE::UNKNOWN_MESSAGE, 0, {}}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Headers EXPECT_EQ(Expected.ID, Result->ID) << "Talker ID is incorrect"; EXPECT_EQ(Expected.Type, Result->Type) << "Message type is incorrect"; EXPECT_EQ(Expected.Valid, Result->Valid) << "Message valid status is incorrect"; // Compare Message EXPECT_EQ(Expected.DTM, Result->DTM); } TEST(DTMMessageParse, Empty_Message) { const std::string RawMessage = ""; NMEAMessage Expected{NMEA_TALKER_ID::UNKNOWN_TALKER_ID, NMEA_MESSAGE_TYPE::UNKNOWN_MESSAGE, 0, {}}; auto Parser = NMEAParser{}; auto Result = Parser.Parse(RawMessage); // Compare Headers EXPECT_EQ(Expected.ID, Result->ID) << "Talker ID is incorrect"; EXPECT_EQ(Expected.Type, Result->Type) << "Message type is incorrect"; EXPECT_EQ(Expected.Valid, Result->Valid) << "Message valid status is incorrect"; // Compare Message EXPECT_EQ(Expected.DTM, Result->DTM); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Teragon Audio. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include "PluginParameters.h" using namespace teragon; #define ADD_TEST(name, func) { \ printf("Test %s: ", name); \ if(func) printf("success\n"); \ else printf("FAIL\n"); \ } #define ASSERT(result) { \ if(!result) return false; \ } #define ASSERT_NOT_NULL(result) { \ if(result == NULL) return false; \ } #define ASSERT_FALSE(result) { \ if(result) return false; \ } #define ASSERT_EQUALS(expected, result) { \ if(abs(abs(result) - abs(expected)) > 0.001) { \ printf("Expected %f, got %f. ", expected, result); \ return false; \ } \ } #define ASSERT_INT_EQUALS(expected, result) { \ if(result != expected) { \ printf("Expected %d, got %d. ", expected, result); \ return false; \ } \ } #define ASSERT_STRING(expected, result) { \ std::string e(expected); \ if(e.compare(result) != 0) { \ printf("Expected '%s', got '%s'. ", expected, result.c_str()); \ return false; \ } \ } static bool testCreateBoolParameter() { BooleanParameter p("test"); ASSERT_FALSE(p.getValue()); ASSERT_EQUALS(0.0, p.getScaledValue()); ASSERT_STRING("test", p.getName()); ASSERT_EQUALS(0.0, p.getDisplayValue()); ASSERT_STRING("false", p.getDisplayText()); ASSERT_STRING("test", p.getSafeName()); return true; } static bool testSetBoolParameter() { BooleanParameter p("test"); ASSERT_FALSE(p.getValue()); p.setValue(1.0); ASSERT(p.getValue()); return true; } static bool testCreateDecibelParameter() { DecibelParameter p("test", -60.0, 3.0, 0.0); ASSERT_EQUALS(0.707739, p.getScaledValue()); ASSERT_EQUALS(1.0, p.getValue()); ASSERT_STRING("0.0 dB", p.getDisplayText()); return true; } static bool testSetDecibelParameter() { DecibelParameter p("test", -60.0, 3.0, -10.0); ASSERT_STRING("-10.0 dB", p.getDisplayText()); p.setValue(1.0); ASSERT_EQUALS(0.707739, p.getScaledValue()); ASSERT_EQUALS(1.0, p.getValue()); ASSERT_STRING("0.0 dB", p.getDisplayText()); p.setScaledValue(0.5); ASSERT_EQUALS(0.5, p.getScaledValue()); ASSERT_EQUALS(0.706769, p.getValue()); ASSERT_STRING("-3.0 dB", p.getDisplayText()); return true; } static bool testCreateFloatParameter() { FloatParameter p("test", 0.0, 50.0, 25.0); ASSERT_EQUALS(25.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); ASSERT_STRING("25.0", p.getDisplayText()); return true; } static bool testSetFloatParameter() { FloatParameter p("test", 0.0, 60.0, 0.0); p.setValue(30.0); ASSERT_EQUALS(30.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.25); ASSERT_EQUALS(15.0, p.getValue()); ASSERT_EQUALS(0.25, p.getScaledValue()); return true; } static bool testCreateFrequencyParameter() { FrequencyParameter p("test", 20.0, 20000.0, 10000.0); ASSERT_EQUALS(10000.0, p.getValue()); ASSERT_EQUALS(0.899657, p.getScaledValue()); ASSERT_STRING("10.0 kHz", p.getDisplayText()); return true; } static bool testSetFrequencyParameter() { FrequencyParameter p("test", 20.0, 20000.0, 10000.0); p.setValue(666.0); ASSERT_EQUALS(666.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.75); ASSERT_EQUALS(3556.559, p.getValue()); ASSERT_EQUALS(0.75, p.getScaledValue()); return true; } static bool testCreateIntegerParameter() { IntegerParameter p("test", 0, 60, 15); ASSERT_EQUALS(15.0, p.getValue()); ASSERT_EQUALS(0.25, p.getScaledValue()); ASSERT_STRING("15", p.getDisplayText()); return true; } static bool testSetIntegerParameter() { IntegerParameter p("test", 0, 60, 15); p.setValue(30); ASSERT_EQUALS(30.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.75); ASSERT_EQUALS(45.0, p.getValue()); ASSERT_EQUALS(0.75, p.getScaledValue()); return true; } static bool testCreateParameterWithBadName() { // NOTE: This test will succeed, I'd rather not throw from the ctor! // So use your head and don't make any weird parameter names. Just know // that the library isn't going to protect you from yourself. :) BooleanParameter p(""); return true; } static bool testCreateParameterWithBadRange() { // NOTE: This test will also succeed, PluginParameters doesn't check for bad ranges // Just be aware of this behavior rather than trying to abuse the library. IntegerParameter p("bad", 100.0, 0.0, 300.0); return true; } static bool testAddParameterToSet() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 1", s.get(0)->getName()); ASSERT_STRING("Parameter 2", s.get(1)->getName()); return true; } static bool testAddNullParameterToSet() { PluginParameterSet s; ASSERT_FALSE(s.add(NULL)); ASSERT_INT_EQUALS(0, s.size()); return true; } static bool testAddDuplicateParameterToSet() { BooleanParameter p("test"); PluginParameterSet s; ASSERT(s.add(&p)); ASSERT_FALSE(s.add(&p)); ASSERT_INT_EQUALS(1, s.size()); return true; } static bool testAddDuplicateSafeNameParameterToSet() { BooleanParameter p1("Parameter1"); BooleanParameter p2("Parameter 1"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT_FALSE(s.add(&p2)); ASSERT_INT_EQUALS(1, s.size()); return true; } static bool testClearParameterSet() { BooleanParameter *p1 = new BooleanParameter("Parameter1"); BooleanParameter *p2 = new BooleanParameter("Parameter2"); PluginParameterSet s; ASSERT(s.add(p1)); ASSERT(s.add(p2)); ASSERT_INT_EQUALS(2, s.size()); s.clear(); ASSERT_INT_EQUALS(0, s.size()); return true; } static bool testGetParameterByName() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); PluginParameter *pe = s.get("Parameter 2"); ASSERT_NOT_NULL(pe); ASSERT_STRING("Parameter 2", pe->getName()); return true; } static bool testGetParameterByIndex() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s.get(1)->getName()); return true; } static bool testGetParameterByNameOperator() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s["Parameter 2"]->getName()); return true; } static bool testGetParameterByIndexOperator() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s[1]->getName()); return true; } static bool testGetSafeName() { BooleanParameter p("hi there"); ASSERT_STRING("hithere", p.getSafeName()); return true; } class TestObserver : public PluginParameterObserver { public: TestObserver(bool &inB) : b(inB) {} void onParameterUpdated(const PluginParameter* parameter) { b = true; } private: bool& b; }; static bool testAddObserver() { bool b = false; BooleanParameter p("test"); TestObserver t(b); p.addObserver(&t); p.setValue(1.0); ASSERT(b); return true; } static bool testRemoveObserver() { bool b = false; BooleanParameter p("test"); TestObserver t(b); p.addObserver(&t); p.removeObserver(&t); p.setValue(1.0); ASSERT_FALSE(b); return true; } static bool testParameterType() { BooleanParameter p("test"); ASSERT_INT_EQUALS(0, p.getType()); p.setType(1234); ASSERT_INT_EQUALS(1234, p.getType()); return true; } static bool testGetMinValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(0.123, p.getMinValue()); return true; } static bool testGetMaxValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(1.23, p.getMaxValue()); return true; } static bool testGetDefaultValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(1.0, p.getDefaultValue()); return true; } static bool testSetParameterUnit() { FloatParameter p("test", 0.0, 1.0, 0.0); ASSERT_STRING("0.0", p.getDisplayText()); p.setUnit("foo"); ASSERT_STRING("0.0 foo", p.getDisplayText()); return true; } int main(int argc, char* argv[]) { ADD_TEST("CreateBoolParameter", testCreateBoolParameter()); ADD_TEST("SetBoolParameter", testSetBoolParameter()); ADD_TEST("CreateDecibelParameter", testCreateDecibelParameter()); ADD_TEST("SetDecibelParameter", testSetDecibelParameter()); ADD_TEST("CreateFloatParameter", testCreateFloatParameter()); ADD_TEST("SetFloatParameter", testSetFloatParameter()); ADD_TEST("CreateFrequencyParameter", testCreateFrequencyParameter()); ADD_TEST("SetFrequencyParameter", testSetFrequencyParameter()); ADD_TEST("CreateIntegerParameter", testCreateIntegerParameter()); ADD_TEST("SetIntegerParameter", testSetIntegerParameter()); ADD_TEST("CreateParameterWithBadName", testCreateParameterWithBadName()); ADD_TEST("CreateParameterWithBadRange", testCreateParameterWithBadRange()); ADD_TEST("AddParameterToSet", testAddParameterToSet()); ADD_TEST("AddNullParameterToSet", testAddNullParameterToSet()); ADD_TEST("AddDuplicateParameterToSet", testAddDuplicateParameterToSet()); ADD_TEST("AddDuplicateSafeNameParameterToSet", testAddDuplicateSafeNameParameterToSet()); ADD_TEST("ClearParameterSet", testClearParameterSet()); ADD_TEST("GetParameterByName", testGetParameterByName()); ADD_TEST("GetParameterByIndex", testGetParameterByIndex()); ADD_TEST("GetParameterByNameOperator", testGetParameterByNameOperator()); ADD_TEST("GetParameterByIndexOperator", testGetParameterByIndexOperator()); ADD_TEST("GetSafeName", testGetSafeName()); ADD_TEST("AddObserver", testAddObserver()); ADD_TEST("RemoveObserver", testRemoveObserver()); ADD_TEST("ParameterType", testParameterType()); ADD_TEST("GetMinValue", testGetMinValue()); ADD_TEST("GetMaxValue", testGetMaxValue()); ADD_TEST("GetDefaultValue", testGetDefaultValue()); ADD_TEST("SetParameterUnit", testSetParameterUnit()); return 0; } <commit_msg>Fix a naggy compiler warning<commit_after>/* * Copyright (c) 2013 Teragon Audio. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include "PluginParameters.h" using namespace teragon; #define ADD_TEST(name, func) { \ printf("Test %s: ", name); \ if(func) printf("success\n"); \ else printf("FAIL\n"); \ } #define ASSERT(result) { \ if(!result) return false; \ } #define ASSERT_NOT_NULL(result) { \ if(result == NULL) return false; \ } #define ASSERT_FALSE(result) { \ if(result) return false; \ } #define ASSERT_EQUALS(expected, result) { \ if(abs(fabs(result) - fabs(expected)) > 0.001) { \ printf("Expected %f, got %f. ", expected, result); \ return false; \ } \ } #define ASSERT_INT_EQUALS(expected, result) { \ if(result != expected) { \ printf("Expected %d, got %d. ", expected, result); \ return false; \ } \ } #define ASSERT_STRING(expected, result) { \ std::string e(expected); \ if(e.compare(result) != 0) { \ printf("Expected '%s', got '%s'. ", expected, result.c_str()); \ return false; \ } \ } static bool testCreateBoolParameter() { BooleanParameter p("test"); ASSERT_FALSE(p.getValue()); ASSERT_EQUALS(0.0, p.getScaledValue()); ASSERT_STRING("test", p.getName()); ASSERT_EQUALS(0.0, p.getDisplayValue()); ASSERT_STRING("false", p.getDisplayText()); ASSERT_STRING("test", p.getSafeName()); return true; } static bool testSetBoolParameter() { BooleanParameter p("test"); ASSERT_FALSE(p.getValue()); p.setValue(1.0); ASSERT(p.getValue()); return true; } static bool testCreateDecibelParameter() { DecibelParameter p("test", -60.0, 3.0, 0.0); ASSERT_EQUALS(0.707739, p.getScaledValue()); ASSERT_EQUALS(1.0, p.getValue()); ASSERT_STRING("0.0 dB", p.getDisplayText()); return true; } static bool testSetDecibelParameter() { DecibelParameter p("test", -60.0, 3.0, -10.0); ASSERT_STRING("-10.0 dB", p.getDisplayText()); p.setValue(1.0); ASSERT_EQUALS(0.707739, p.getScaledValue()); ASSERT_EQUALS(1.0, p.getValue()); ASSERT_STRING("0.0 dB", p.getDisplayText()); p.setScaledValue(0.5); ASSERT_EQUALS(0.5, p.getScaledValue()); ASSERT_EQUALS(0.706769, p.getValue()); ASSERT_STRING("-3.0 dB", p.getDisplayText()); return true; } static bool testCreateFloatParameter() { FloatParameter p("test", 0.0, 50.0, 25.0); ASSERT_EQUALS(25.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); ASSERT_STRING("25.0", p.getDisplayText()); return true; } static bool testSetFloatParameter() { FloatParameter p("test", 0.0, 60.0, 0.0); p.setValue(30.0); ASSERT_EQUALS(30.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.25); ASSERT_EQUALS(15.0, p.getValue()); ASSERT_EQUALS(0.25, p.getScaledValue()); return true; } static bool testCreateFrequencyParameter() { FrequencyParameter p("test", 20.0, 20000.0, 10000.0); ASSERT_EQUALS(10000.0, p.getValue()); ASSERT_EQUALS(0.899657, p.getScaledValue()); ASSERT_STRING("10.0 kHz", p.getDisplayText()); return true; } static bool testSetFrequencyParameter() { FrequencyParameter p("test", 20.0, 20000.0, 10000.0); p.setValue(666.0); ASSERT_EQUALS(666.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.75); ASSERT_EQUALS(3556.559, p.getValue()); ASSERT_EQUALS(0.75, p.getScaledValue()); return true; } static bool testCreateIntegerParameter() { IntegerParameter p("test", 0, 60, 15); ASSERT_EQUALS(15.0, p.getValue()); ASSERT_EQUALS(0.25, p.getScaledValue()); ASSERT_STRING("15", p.getDisplayText()); return true; } static bool testSetIntegerParameter() { IntegerParameter p("test", 0, 60, 15); p.setValue(30); ASSERT_EQUALS(30.0, p.getValue()); ASSERT_EQUALS(0.5, p.getScaledValue()); p.setScaledValue(0.75); ASSERT_EQUALS(45.0, p.getValue()); ASSERT_EQUALS(0.75, p.getScaledValue()); return true; } static bool testCreateParameterWithBadName() { // NOTE: This test will succeed, I'd rather not throw from the ctor! // So use your head and don't make any weird parameter names. Just know // that the library isn't going to protect you from yourself. :) BooleanParameter p(""); return true; } static bool testCreateParameterWithBadRange() { // NOTE: This test will also succeed, PluginParameters doesn't check for bad ranges // Just be aware of this behavior rather than trying to abuse the library. IntegerParameter p("bad", 100.0, 0.0, 300.0); return true; } static bool testAddParameterToSet() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 1", s.get(0)->getName()); ASSERT_STRING("Parameter 2", s.get(1)->getName()); return true; } static bool testAddNullParameterToSet() { PluginParameterSet s; ASSERT_FALSE(s.add(NULL)); ASSERT_INT_EQUALS(0, s.size()); return true; } static bool testAddDuplicateParameterToSet() { BooleanParameter p("test"); PluginParameterSet s; ASSERT(s.add(&p)); ASSERT_FALSE(s.add(&p)); ASSERT_INT_EQUALS(1, s.size()); return true; } static bool testAddDuplicateSafeNameParameterToSet() { BooleanParameter p1("Parameter1"); BooleanParameter p2("Parameter 1"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT_FALSE(s.add(&p2)); ASSERT_INT_EQUALS(1, s.size()); return true; } static bool testClearParameterSet() { BooleanParameter *p1 = new BooleanParameter("Parameter1"); BooleanParameter *p2 = new BooleanParameter("Parameter2"); PluginParameterSet s; ASSERT(s.add(p1)); ASSERT(s.add(p2)); ASSERT_INT_EQUALS(2, s.size()); s.clear(); ASSERT_INT_EQUALS(0, s.size()); return true; } static bool testGetParameterByName() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); PluginParameter *pe = s.get("Parameter 2"); ASSERT_NOT_NULL(pe); ASSERT_STRING("Parameter 2", pe->getName()); return true; } static bool testGetParameterByIndex() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s.get(1)->getName()); return true; } static bool testGetParameterByNameOperator() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s["Parameter 2"]->getName()); return true; } static bool testGetParameterByIndexOperator() { BooleanParameter p1("Parameter 1"); BooleanParameter p2("Parameter 2"); PluginParameterSet s; ASSERT(s.add(&p1)); ASSERT(s.add(&p2)); ASSERT_INT_EQUALS(2, s.size()); ASSERT_STRING("Parameter 2", s[1]->getName()); return true; } static bool testGetSafeName() { BooleanParameter p("hi there"); ASSERT_STRING("hithere", p.getSafeName()); return true; } class TestObserver : public PluginParameterObserver { public: TestObserver(bool &inB) : b(inB) {} void onParameterUpdated(const PluginParameter* parameter) { b = true; } private: bool& b; }; static bool testAddObserver() { bool b = false; BooleanParameter p("test"); TestObserver t(b); p.addObserver(&t); p.setValue(1.0); ASSERT(b); return true; } static bool testRemoveObserver() { bool b = false; BooleanParameter p("test"); TestObserver t(b); p.addObserver(&t); p.removeObserver(&t); p.setValue(1.0); ASSERT_FALSE(b); return true; } static bool testParameterType() { BooleanParameter p("test"); ASSERT_INT_EQUALS(0, p.getType()); p.setType(1234); ASSERT_INT_EQUALS(1234, p.getType()); return true; } static bool testGetMinValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(0.123, p.getMinValue()); return true; } static bool testGetMaxValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(1.23, p.getMaxValue()); return true; } static bool testGetDefaultValue() { FloatParameter p("test", 0.123, 1.23, 1.00); ASSERT_EQUALS(1.0, p.getDefaultValue()); return true; } static bool testSetParameterUnit() { FloatParameter p("test", 0.0, 1.0, 0.0); ASSERT_STRING("0.0", p.getDisplayText()); p.setUnit("foo"); ASSERT_STRING("0.0 foo", p.getDisplayText()); return true; } int main(int argc, char* argv[]) { ADD_TEST("CreateBoolParameter", testCreateBoolParameter()); ADD_TEST("SetBoolParameter", testSetBoolParameter()); ADD_TEST("CreateDecibelParameter", testCreateDecibelParameter()); ADD_TEST("SetDecibelParameter", testSetDecibelParameter()); ADD_TEST("CreateFloatParameter", testCreateFloatParameter()); ADD_TEST("SetFloatParameter", testSetFloatParameter()); ADD_TEST("CreateFrequencyParameter", testCreateFrequencyParameter()); ADD_TEST("SetFrequencyParameter", testSetFrequencyParameter()); ADD_TEST("CreateIntegerParameter", testCreateIntegerParameter()); ADD_TEST("SetIntegerParameter", testSetIntegerParameter()); ADD_TEST("CreateParameterWithBadName", testCreateParameterWithBadName()); ADD_TEST("CreateParameterWithBadRange", testCreateParameterWithBadRange()); ADD_TEST("AddParameterToSet", testAddParameterToSet()); ADD_TEST("AddNullParameterToSet", testAddNullParameterToSet()); ADD_TEST("AddDuplicateParameterToSet", testAddDuplicateParameterToSet()); ADD_TEST("AddDuplicateSafeNameParameterToSet", testAddDuplicateSafeNameParameterToSet()); ADD_TEST("ClearParameterSet", testClearParameterSet()); ADD_TEST("GetParameterByName", testGetParameterByName()); ADD_TEST("GetParameterByIndex", testGetParameterByIndex()); ADD_TEST("GetParameterByNameOperator", testGetParameterByNameOperator()); ADD_TEST("GetParameterByIndexOperator", testGetParameterByIndexOperator()); ADD_TEST("GetSafeName", testGetSafeName()); ADD_TEST("AddObserver", testAddObserver()); ADD_TEST("RemoveObserver", testRemoveObserver()); ADD_TEST("ParameterType", testParameterType()); ADD_TEST("GetMinValue", testGetMinValue()); ADD_TEST("GetMaxValue", testGetMaxValue()); ADD_TEST("GetDefaultValue", testGetDefaultValue()); ADD_TEST("SetParameterUnit", testSetParameterUnit()); return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // This is a test program for Safe-Bit-Fields in the Loki Library. // Copyright (c) 2009 by Fedor Pikus & Rich Sposato // The copyright on this file is protected under the terms of the MIT license. // // Permission to use, copy, modify, distribute and sell this software for any // purpose is hereby granted without fee, provided that the above copyright // notice appear in all copies and that both that copyright notice and this // permission notice appear in supporting documentation. // The author makes no claims about the suitability of this software for any // purpose. It is provided "as is" without express or implied warranty. //////////////////////////////////////////////////////////////////////////////// // $Id$ #include <loki/SafeBits.h> #include <iostream> using namespace std; using namespace Loki; LOKI_BIT_FIELD( unsigned int ) Cat_state; LOKI_BIT_CONST( Cat_state, CAT_NO_STATE, 0 ); // 0x0000 - no bit is set LOKI_BIT_CONST( Cat_state, CAT_SLEEPING, 1 ); // 0x0001 - 1st bit is set LOKI_BIT_CONST( Cat_state, CAT_PURRING, 2 ); // 0x0002 - 2nd bit is set LOKI_BIT_CONST( Cat_state, CAT_PLAYING, 3 ); // 0x0004 - 3rd bit is set LOKI_BIT_FIELD( unsigned int ) Dog_state; LOKI_BIT_CONST( Dog_state, DOG_BARKING, 1 ); LOKI_BIT_CONST( Dog_state, DOG_CHEWING, 2 ); LOKI_BIT_CONST( Dog_state, DOG_DROOLING, 3 ); int main( void ) { cout << "Running tests on Loki safe bit fields." << endl; Cat_state cat_state = CAT_SLEEPING; assert( cat_state ); Dog_state dog_state = DOG_DROOLING; assert( dog_state ); bool happy = cat_state & ( CAT_SLEEPING | CAT_PURRING ); // OK assert( happy ); assert( CAT_SLEEPING < CAT_PURRING ); assert( CAT_SLEEPING <= CAT_SLEEPING ); assert( CAT_SLEEPING <= CAT_PURRING ); assert( CAT_SLEEPING != CAT_PURRING ); assert( CAT_SLEEPING == CAT_SLEEPING ); assert( CAT_PURRING >= CAT_SLEEPING ); assert( CAT_PURRING >= CAT_PURRING ); #ifdef ERROR1 assert( DOG_DROOLING != CAT_SLEEPING ); // Can't compare different types. #endif #ifdef ERROR2 if ( cat_state & DOG_BARKING ) {} // Wrong bit type #endif #ifdef ERROR3 if ( cat_state & CAT_SLEEPING == 0 ) {} // Operator precedence #endif #ifdef ERROR4 if ( dog_state && DOG_BARKING ) {} // Logical && #endif if ( dog_state & DOG_BARKING ) {} // OK #ifdef ERROR5 Cat_state state0 = 0; // Conversion from non-safe bits #endif Cat_state state = CAT_NO_STATE; // OK assert( !state ); state = ~state; assert( state ); assert( state != CAT_NO_STATE ); assert( state & CAT_SLEEPING ); assert( state & CAT_PURRING ); assert( state & CAT_PLAYING ); state = CAT_SLEEPING; assert( state == cat_state ); assert( state.size() == 8 * sizeof( unsigned int ) ); assert( sizeof( Cat_state ) == sizeof( unsigned int ) ); dog_state = DOG_BARKING; #ifdef ERROR6 if ( dog_state == cat_state ) {} // Don't allow comparison of different types. #endif /// @note All These assertions are inside #ifdef sections because they /// compare either Safe_bit_field or Safe_bit_const to literal integers. /// If you compile any of these assertions they should generate errors. /// These #ifdef sections exhaustively demonstrate that all possible /// operations and comparisons with literal values are forbidden. #ifdef ERROR7 assert( dog_state == 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR8 assert( dog_state != 2 ); // Don't allow comparisons to integers. #endif #ifdef ERROR9 assert( dog_state < 2 ); // Don't allow comparisons to integers. #endif #ifdef ERROR10 assert( dog_state > 0 ); // Don't allow comparisons to integers. #endif #ifdef ERROR11 assert( dog_state <= 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR12 assert( dog_state >= 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR13 assert( DOG_BARKING == 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR14 assert( DOG_BARKING != 2 ); // Don't allow comparisons to integers. #endif #ifdef ERROR15 assert( DOG_BARKING < 2 ); // Don't allow comparisons to integers. #endif #ifdef ERROR16 assert( DOG_BARKING > 0 ); // Don't allow comparisons to integers. #endif #ifdef ERROR17 assert( DOG_BARKING <= 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR18 assert( DOG_BARKING >= 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR19 assert( ( dog_state | 1 ) != 0 ); // Don't allow operations with integers. #endif #ifdef ERROR20 assert( ( dog_state & 2 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR21 assert( ( dog_state ^ 1 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR22 assert( ( dog_state |= 2 ) == 3 ); // Don't allow operations with integers. #endif #ifdef ERROR23 assert( ( dog_state &= 3 ) == 2 ); // Don't allow operations with integers. #endif #ifdef ERROR24 assert( ( dog_state ^= 1 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR25 assert( ( DOG_BARKING | 1 ) != 0 ); // Don't allow operations with integers. #endif #ifdef ERROR26 assert( ( DOG_BARKING & 2 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR27 assert( ( DOG_BARKING ^ 1 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR28 assert( ( DOG_BARKING |= 2 ) == 3 ); // Don't allow operations with integers. #endif #ifdef ERROR29 assert( ( DOG_BARKING &= 3 ) == 2 ); // Don't allow operations with integers. #endif #ifdef ERROR30 assert( ( DOG_BARKING ^= 1 ) == 0 ); // Don't allow operations with integers. #endif /// @note All These assertions are inside #ifdef sections because they /// compare either Safe_bit_field or Safe_bit_const to an int variable. /// If you compile any of these assertions they should generate errors. /// These #ifdef sections exhaustively demonstrate that all possible /// operations and comparisons with integers are forbidden. int value = 1; (void)value; #ifdef ERROR31 assert( dog_state == value ); // Don't allow comparisons to integers. #endif #ifdef ERROR32 value = 2; assert( dog_state != value ); // Don't allow comparisons to integers. #endif #ifdef ERROR33 value = 2; assert( dog_state < value ); // Don't allow comparisons to integers. #endif #ifdef ERROR34 value = 0; assert( dog_state > value ); // Don't allow comparisons to integers. #endif #ifdef ERROR35 value = 1; assert( dog_state <= value ); // Don't allow comparisons to integers. #endif #ifdef ERROR36 value = 1; assert( dog_state >= value ); // Don't allow comparisons to integers. #endif #ifdef ERROR37 value = 1; assert( DOG_BARKING == value ); // Don't allow comparisons to integers. #endif #ifdef ERROR38 value = 2; assert( DOG_BARKING != value ); // Don't allow comparisons to integers. #endif #ifdef ERROR39 value = 2; assert( DOG_BARKING < value ); // Don't allow comparisons to integers. #endif #ifdef ERROR40 value = 0; assert( DOG_BARKING > value ); // Don't allow comparisons to integers. #endif #ifdef ERROR41 value = 1; assert( DOG_BARKING <= value ); // Don't allow comparisons to integers. #endif #ifdef ERROR42 value = 1; assert( DOG_BARKING >= value ); // Don't allow comparisons to integers. #endif #ifdef ERROR43 value = 1; assert( ( dog_state | value ) != 0 ); // Don't allow operations with integers. #endif #ifdef ERROR44 value = 2; assert( ( dog_state & value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR45 value = 1; assert( ( dog_state ^ value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR46 value = 2; assert( ( dog_state |= value ) == 3 ); // Don't allow operations with integers. #endif #ifdef ERROR47 value = 3; assert( ( dog_state &= value ) == 2 ); // Don't allow operations with integers. #endif #ifdef ERROR48 value = 1; assert( ( dog_state ^= value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR49 value = 1; assert( ( DOG_BARKING | value ) != 0 ); // Don't allow operations with integers. #endif #ifdef ERROR50 value = 2; assert( ( DOG_BARKING & value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR51 value = 1; assert( ( DOG_BARKING ^ value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR52 value = 2; assert( ( DOG_BARKING |= value ) == 3 ); // Don't allow operations with integers. #endif #ifdef ERROR53 value = 3; assert( ( DOG_BARKING &= value ) == 2 ); // Don't allow operations with integers. #endif #ifdef ERROR54 value = 1; assert( ( DOG_BARKING ^= value ) == 0 ); // Don't allow operations with integers. #endif dog_state |= DOG_CHEWING; assert( dog_state & ( DOG_CHEWING | DOG_BARKING ) ); dog_state &= DOG_CHEWING; assert( dog_state == DOG_CHEWING ); dog_state = ~dog_state; assert( dog_state != DOG_CHEWING ); dog_state = ~dog_state; assert( dog_state == DOG_CHEWING ); cout << "If nothing asserted, then all tests passed!" << endl; return 0; } <commit_msg>Added more code for testing.<commit_after>//////////////////////////////////////////////////////////////////////////////// // // This is a test program for Safe-Bit-Fields in the Loki Library. // Copyright (c) 2009 by Fedor Pikus & Rich Sposato // The copyright on this file is protected under the terms of the MIT license. // // Permission to use, copy, modify, distribute and sell this software for any // purpose is hereby granted without fee, provided that the above copyright // notice appear in all copies and that both that copyright notice and this // permission notice appear in supporting documentation. // The author makes no claims about the suitability of this software for any // purpose. It is provided "as is" without express or implied warranty. //////////////////////////////////////////////////////////////////////////////// // $Id$ #include <loki/SafeBits.h> #include <iostream> using namespace std; using namespace Loki; LOKI_BIT_FIELD( unsigned int ) Cat_state; LOKI_BIT_CONST( Cat_state, CAT_NO_STATE, 0 ); // 0x0000 - no bit is set LOKI_BIT_CONST( Cat_state, CAT_SLEEPING, 1 ); // 0x0001 - 1st bit is set LOKI_BIT_CONST( Cat_state, CAT_PURRING, 2 ); // 0x0002 - 2nd bit is set LOKI_BIT_CONST( Cat_state, CAT_PLAYING, 3 ); // 0x0004 - 3rd bit is set LOKI_BIT_FIELD( unsigned int ) Dog_state; LOKI_BIT_CONST( Dog_state, DOG_BARKING, 1 ); LOKI_BIT_CONST( Dog_state, DOG_CHEWING, 2 ); LOKI_BIT_CONST( Dog_state, DOG_DROOLING, 3 ); LOKI_BIT_CONST( Dog_state, DOG_SLEEPING, 4 ); LOKI_BIT_CONST( Dog_state, DOG_GROWLING, 5 ); LOKI_BIT_CONST( Dog_state, DOG_TIRED, 6 ); LOKI_BIT_CONST( Dog_state, DOG_DEAD, 7 ); LOKI_BIT_CONST( Dog_state, DOG_GROWING, 8 ); LOKI_BIT_CONST( Dog_state, DOG_THINKING, 9 ); LOKI_BIT_CONST( Dog_state, DOG_YELPING, 10 ); LOKI_BIT_CONST( Dog_state, DOG_QUIET, 11 ); LOKI_BIT_CONST( Dog_state, DOG_FETCHING, 12 ); LOKI_BIT_CONST( Dog_state, DOG_HOWLING, 13 ); LOKI_BIT_CONST( Dog_state, DOG_SICK, 14 ); LOKI_BIT_CONST( Dog_state, DOG_JUMPING, 15 ); LOKI_BIT_CONST( Dog_state, DOG_SWIMMING, 16 ); LOKI_BIT_CONST( Dog_state, DOG_BATHING, 17 ); LOKI_BIT_CONST( Dog_state, DOG_EATING, 18 ); LOKI_BIT_CONST( Dog_state, DOG_DRINKING, 19 ); LOKI_BIT_CONST( Dog_state, DOG_PLAYING, 20 ); LOKI_BIT_CONST( Dog_state, DOG_RUNNING, 21 ); LOKI_BIT_CONST( Dog_state, DOG_BITING, 22 ); LOKI_BIT_CONST( Dog_state, DOG_BEGGING, 23 ); LOKI_BIT_CONST( Dog_state, DOG_WHINING, 24 ); LOKI_BIT_CONST( Dog_state, DOG_WALKING, 25 ); LOKI_BIT_CONST( Dog_state, DOG_SINGING, 26 ); LOKI_BIT_CONST( Dog_state, DOG_FIGHTING, 27 ); LOKI_BIT_CONST( Dog_state, DOG_MATING, 28 ); LOKI_BIT_CONST( Dog_state, DOG_FEEDING, 29 ); LOKI_BIT_CONST( Dog_state, DOG_BIRTHING, 30 ); LOKI_BIT_CONST( Dog_state, DOG_SHEDDING, 31 ); LOKI_BIT_CONST( Dog_state, DOG_TALKING, 32 ); #ifdef ERROR0 LOKI_BIT_CONST( Dog_state, DOG_TALKING, 20 ); // Can't have two values with same name. LOKI_BIT_CONST( Dog_state, DOG_BLOGGING, 33 ); // Can't set bit 33 in a 32 bit-sized object. #endif int main( void ) { cout << "Running tests on Loki safe bit fields." << endl; Cat_state cat_state = CAT_SLEEPING; assert( cat_state ); Dog_state dog_state = DOG_DROOLING; assert( dog_state ); bool happy = cat_state & ( CAT_SLEEPING | CAT_PURRING ); // OK assert( happy ); assert( CAT_SLEEPING < CAT_PURRING ); assert( CAT_SLEEPING <= CAT_SLEEPING ); assert( CAT_SLEEPING <= CAT_PURRING ); assert( CAT_SLEEPING != CAT_PURRING ); assert( CAT_SLEEPING == CAT_SLEEPING ); assert( CAT_PURRING >= CAT_SLEEPING ); assert( CAT_PURRING >= CAT_PURRING ); #ifdef ERROR1 assert( DOG_DROOLING != CAT_SLEEPING ); // Can't compare different types. #endif #ifdef ERROR2 if ( cat_state & DOG_BARKING ) {} // Wrong bit type #endif #ifdef ERROR3 if ( cat_state & CAT_SLEEPING == 0 ) {} // Operator precedence #endif #ifdef ERROR4 if ( dog_state && DOG_BARKING ) {} // Logical && #endif if ( dog_state & DOG_BARKING ) {} // OK #ifdef ERROR5 Cat_state state0 = 0; // Conversion from non-safe bits #endif Cat_state state = CAT_NO_STATE; // OK assert( !state ); state = ~state; assert( state ); assert( state != CAT_NO_STATE ); assert( state & CAT_SLEEPING ); assert( state & CAT_PURRING ); assert( state & CAT_PLAYING ); state = CAT_SLEEPING; assert( state == cat_state ); assert( state.size() == ( 8 * sizeof(unsigned int) ) ); assert( sizeof(Cat_state) == sizeof(unsigned int) ); dog_state = DOG_BARKING; #ifdef ERROR6 if ( dog_state == cat_state ) {} // Don't allow comparison of different types. #endif /// @note All These assertions are inside #ifdef sections because they /// compare either SafeBitField or SafeBitConst to literal integers. /// If you compile any of these assertions they should generate errors. /// These #ifdef sections exhaustively demonstrate that all possible /// operations and comparisons with literal values are forbidden. #ifdef ERROR7 assert( dog_state == 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR8 assert( dog_state != 2 ); // Don't allow comparisons to integers. #endif #ifdef ERROR9 assert( dog_state < 2 ); // Don't allow comparisons to integers. #endif #ifdef ERROR10 assert( dog_state > 0 ); // Don't allow comparisons to integers. #endif #ifdef ERROR11 assert( dog_state <= 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR12 assert( dog_state >= 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR13 assert( DOG_BARKING == 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR14 assert( DOG_BARKING != 2 ); // Don't allow comparisons to integers. #endif #ifdef ERROR15 assert( DOG_BARKING < 2 ); // Don't allow comparisons to integers. #endif #ifdef ERROR16 assert( DOG_BARKING > 0 ); // Don't allow comparisons to integers. #endif #ifdef ERROR17 assert( DOG_BARKING <= 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR18 assert( DOG_BARKING >= 1 ); // Don't allow comparisons to integers. #endif #ifdef ERROR19 assert( ( dog_state | 1 ) != 0 ); // Don't allow operations with integers. #endif #ifdef ERROR20 assert( ( dog_state & 2 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR21 assert( ( dog_state ^ 1 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR22 assert( ( dog_state |= 2 ) == 3 ); // Don't allow operations with integers. #endif #ifdef ERROR23 assert( ( dog_state &= 3 ) == 2 ); // Don't allow operations with integers. #endif #ifdef ERROR24 assert( ( dog_state ^= 1 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR25 assert( ( DOG_BARKING | 1 ) != 0 ); // Don't allow operations with integers. #endif #ifdef ERROR26 assert( ( DOG_BARKING & 2 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR27 assert( ( DOG_BARKING ^ 1 ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR28 assert( ( DOG_BARKING |= 2 ) == 3 ); // Don't allow operations with integers. #endif #ifdef ERROR29 assert( ( DOG_BARKING &= 3 ) == 2 ); // Don't allow operations with integers. #endif #ifdef ERROR30 assert( ( DOG_BARKING ^= 1 ) == 0 ); // Don't allow operations with integers. #endif /// @note All These assertions are inside #ifdef sections because they /// compare either SafeBitField or SafeBitConst to an int variable. /// If you compile any of these assertions they should generate errors. /// These #ifdef sections exhaustively demonstrate that all possible /// operations and comparisons with integers are forbidden. int value = 1; (void)value; #ifdef ERROR31 assert( dog_state == value ); // Don't allow comparisons to integers. #endif #ifdef ERROR32 value = 2; assert( dog_state != value ); // Don't allow comparisons to integers. #endif #ifdef ERROR33 value = 2; assert( dog_state < value ); // Don't allow comparisons to integers. #endif #ifdef ERROR34 value = 0; assert( dog_state > value ); // Don't allow comparisons to integers. #endif #ifdef ERROR35 value = 1; assert( dog_state <= value ); // Don't allow comparisons to integers. #endif #ifdef ERROR36 value = 1; assert( dog_state >= value ); // Don't allow comparisons to integers. #endif #ifdef ERROR37 value = 1; assert( DOG_BARKING == value ); // Don't allow comparisons to integers. #endif #ifdef ERROR38 value = 2; assert( DOG_BARKING != value ); // Don't allow comparisons to integers. #endif #ifdef ERROR39 value = 2; assert( DOG_BARKING < value ); // Don't allow comparisons to integers. #endif #ifdef ERROR40 value = 0; assert( DOG_BARKING > value ); // Don't allow comparisons to integers. #endif #ifdef ERROR41 value = 1; assert( DOG_BARKING <= value ); // Don't allow comparisons to integers. #endif #ifdef ERROR42 value = 1; assert( DOG_BARKING >= value ); // Don't allow comparisons to integers. #endif #ifdef ERROR43 value = 1; assert( ( dog_state | value ) != 0 ); // Don't allow operations with integers. #endif #ifdef ERROR44 value = 2; assert( ( dog_state & value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR45 value = 1; assert( ( dog_state ^ value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR46 value = 2; assert( ( dog_state |= value ) == 3 ); // Don't allow operations with integers. #endif #ifdef ERROR47 value = 3; assert( ( dog_state &= value ) == 2 ); // Don't allow operations with integers. #endif #ifdef ERROR48 value = 1; assert( ( dog_state ^= value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR49 value = 1; assert( ( DOG_BARKING | value ) != 0 ); // Don't allow operations with integers. #endif #ifdef ERROR50 value = 2; assert( ( DOG_BARKING & value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR51 value = 1; assert( ( DOG_BARKING ^ value ) == 0 ); // Don't allow operations with integers. #endif #ifdef ERROR52 value = 2; assert( ( DOG_BARKING |= value ) == 3 ); // Don't allow operations with integers. #endif #ifdef ERROR53 value = 3; assert( ( DOG_BARKING &= value ) == 2 ); // Don't allow operations with integers. #endif #ifdef ERROR54 value = 1; assert( ( DOG_BARKING ^= value ) == 0 ); // Don't allow operations with integers. #endif dog_state |= DOG_CHEWING; assert( dog_state & ( DOG_CHEWING | DOG_BARKING ) ); dog_state &= DOG_CHEWING; assert( dog_state == DOG_CHEWING ); dog_state = ~dog_state; assert( dog_state != DOG_CHEWING ); dog_state = ~dog_state; assert( dog_state == DOG_CHEWING ); cout << "If nothing asserted, then all tests passed!" << endl; return 0; } <|endoftext|>
<commit_before>#include "fountain.h" #include "TestApplication.h" using namespace fei; Texture tex; Camera cam; TestApplication testApp; Clock mainClock; ShaderProgram shader; Image image, image2; void test() { //auto eg = testApp.getEngine(); //if (eg->window->getKey(GLFW_KEY_W)) speed += fei::Vec2(0.0f, 2.0f); //if (eg->window->getKey(GLFW_KEY_S)) speed += fei::Vec2(0.0f, -2.0f); //if (eg->window->getKey(GLFW_KEY_A)) speed += fei::Vec2(-2.0f, 0.0f); //if (eg->window->getKey(GLFW_KEY_D)) speed += fei::Vec2(2.0f, 0.0f); Vec2 speed(0); auto *joystick = fei::Control::getInstance()->getJoystick(); if (joystick) { speed = joystick->getAxes() * 500.0f * (float)mainClock.getDeltaTime(); image.setAngle(speed.getAngle()); speed = joystick->getDirection() * 50.0f * (float)mainClock.getDeltaTime(); tex.rotate(-speed.x); } //cam.setPosition(pos); cam.update(); tex.draw(); image.draw(); image2.draw(); //char *buffer = fei::readFileBuffer("1.txt"); //if (buffer) { //std::printf("%s", buffer); //delete [] buffer; //} //std::printf("Time: %f Frame: %lld\n", fei::Time::getInstance()->getTime(), fei::Time::getInstance()->getFrame()); mainClock.tick(); } void TestApplication::engineSetting(fei::Engine *eg) { if (!eg) return; eg->window->setSize(800, 600); eg->window->setTitle("fountain-tests"); eg->window->setResizable(false); eg->setFrameFunc(test); Render::getInstance()->setViewport(fei::Rect(0, 0, 800, 600)); cam.setCameraSize(fei::Vec2(4000, 3000)); tex.loadFile("test.png"); image = tex.getImage(fei::Vec2(100.0f), fei::Vec2(200.0f)); image2 = image.getImage(fei::Vec2(0.0f), fei::Vec2(100.0f)); image.setPosition(fei::Vec2(0.0f, 256.0f)); shader.loadFile("vs.vert", "fs.frag"); tex.setScale(2.0f); tex.setAnchor(Vec2(0.0f, -256.0f)); //tex.setShader(&shader); //Math::getInstance()->setRandomSeed(9312); //Render::getInstance()->setClearColor(FEI_Blue); //Scene::getInstance()->gotoScene(new TestScene()); } int main() { testApp.run(); return 0; } <commit_msg>edit fountain-test<commit_after>#include "fountain.h" #include "TestApplication.h" using namespace fei; Texture tex; Camera cam; TestApplication testApp; Clock mainClock; ShaderProgram shader; Image image, image2; void test() { auto *joystick = fei::Control::getInstance()->getJoystick(); if (joystick) { Vec2 speed = joystick->getAxes() * 500.0f * (float)mainClock.getDeltaTime(); image.setAngle(speed.getAngle()); speed = joystick->getDirection() * 50.0f * (float)mainClock.getDeltaTime(); tex.rotate(-speed.x); } cam.update(); tex.draw(); image.draw(); image2.draw(); mainClock.tick(); } void TestApplication::engineSetting(fei::Engine *eg) { if (!eg) return; eg->window->setSize(800, 600); eg->window->setTitle("fountain-tests"); eg->window->setResizable(false); eg->setFrameFunc(test); Render::getInstance()->setViewport(fei::Rect(0, 0, 800, 600)); cam.setCameraSize(fei::Vec2(800, 600)); tex.loadFile("test.png"); image = tex.getImage(fei::Vec2(100.0f), fei::Vec2(200.0f)); image2 = image.getImage(fei::Vec2(0.0f), fei::Vec2(100.0f)); image.setPosition(fei::Vec2(0.0f, 256.0f)); shader.loadFile("vs.vert", "fs.frag"); tex.setScale(0.4f); tex.setAnchor(Vec2(0.0f, -256.0f)); tex.setShader(&shader); //Math::getInstance()->setRandomSeed(9312); //Render::getInstance()->setClearColor(FEI_Blue); //Scene::getInstance()->gotoScene(new TestScene()); } int main() { testApp.run(); return 0; } <|endoftext|>
<commit_before>/* ============================================================================ Name : DmdSignal.cpp Author : weizhenwei, <weizhenwei1988@gmail.com> Date :2016.02.13 Copyright : * Copyright (c) 2016, weizhenwei * 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 {organization} 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 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. * * Description : signal processing implementation file. ============================================================================ */ #include <assert.h> #include <signal.h> #include <string> #include "DmdLog.h" #include "DmdSignal.h" namespace opendmd { void DmdRegisterDefaultSignal() { signal(SIGPIPE, SIG_IGN); signal(SIGTERM, SIG_DFL); signal(SIGHUP, SIG_DFL); } void DmdRegisterSignalHandler(int sig, DmdSignalHandler pSigHandler) { signal(sig, pSigHandler); } /* * No Name Default Action Description * 2 SIGINT terminate process interrupt program * 3 SIGQUIT create core image quit program * 4 SIGILL create core image illegal instruction * 5 SIGTRAP create core image trace trap * 6 SIGABRT create core image abort program (formerly SIGIOT) * 7 SIGEMT create core image emulate instruction executed * 8 SIGFPE create core image floating-point exception * 9 SIGKILL terminate process kill program * 10 SIGBUS create core image bus error * 11 SIGSEGV create core image segmentation violation * 12 SIGSYS create core image non-existent system call invoked * 13 SIGPIPE terminate process write on a pipe with no reader * 14 SIGALRM terminate process real-time timer expired * 15 SIGTERM terminate process software termination signal * 16 SIGURG discard signal urgent condition present on socket * 17 SIGSTOP stop process stop (cannot be caught or ignored) * 18 SIGTSTP stop process stop signal generated from keyboard * 19 SIGCONT discard signal continue after stop * 20 SIGCHLD discard signal child status has changed * 21 SIGTTIN stop process background read attempted from control terminal * 22 SIGTTOU stop process background write attempted to control terminal * 23 SIGIO discard signal I/O is possible on a descriptor (see fcntl(2)) * 24 SIGXCPU terminate process cpu time limit exceeded (see setrlimit(2)) * 25 SIGXFSZ terminate process file size limit exceeded (see setrlimit(2)) * 26 SIGVTALRM terminate process virtual time alarm (see setitimer(2)) * 27 SIGPROF terminate process profiling timer alarm (see setitimer(2)) * 28 SIGWINCH discard signal Window size change * 29 SIGINFO discard signal status request from keyboard * 30 SIGUSR1 terminate process User defined signal 1 * 31 SIGUSR2 terminate process User defined signal 2 */ string DmdSignalToString(int sig) { if (sig == SIGHUP) { return "SIGHUP"; } else if (sig == SIGINT) { return "SIGINT"; } else if (sig == SIGQUIT) { return "SIGQUIT"; } else if (sig == SIGILL) { return "SIGILL"; } else if (sig == SIGTRAP) { return "SIGTRAP"; } else if (sig == SIGABRT) { return "SIGABRT"; } else if (sig == SIGEMT) { return "SIGEMT"; } else if (sig == SIGFPE) { return "SIGFPE"; } else if (sig == SIGKILL) { return "SIGKILL"; } else if (sig == SIGBUS) { return "SIGBUS"; } else if (sig == SIGSEGV) { return "SIGSEGV"; } else if (sig == SIGSYS) { return "SIGSYS"; } else if (sig == SIGPIPE) { return "SIGPIPE"; } else if (sig == SIGALRM) { return "SIGALRM"; } else if (sig == SIGTERM) { return "SIGTERM"; } else if (sig == SIGURG) { return "SIGURG"; } else if (sig == SIGSTOP) { return "SIGSTOP"; } else if (sig == SIGTSTP) { return "SIGTSTP"; } else if (sig == SIGCONT) { return "SIGCONT"; } else if (sig == SIGCHLD) { return "SIGCHLD"; } else if (sig == SIGTTIN) { return "SIGTTIN"; } else if (sig == SIGTTOU) { return "SIGTTOU"; } else if (sig == SIGIO) { return "SIGIO"; } else if (sig == SIGXCPU) { return "SIGXCPU"; } else if (sig == SIGXFSZ) { return "SIGXFSZ"; } else if (sig == SIGVTALRM) { return "SIGVTALRM"; } else if (sig == SIGPROF) { return "SIGPROF"; } else if (sig == SIGWINCH) { return "SIGWINCH"; } else if (sig == SIGINFO) { return "SIGINFO"; } else if (sig == SIGUSR1) { return "SIGUSR1"; } else if (sig == SIGUSR2) { return "SIGUSR2"; } else { return "Unknown signal"; } } } // namespace opendmd <commit_msg>fix compile error on linux<commit_after>/* ============================================================================ Name : DmdSignal.cpp Author : weizhenwei, <weizhenwei1988@gmail.com> Date :2016.02.13 Copyright : * Copyright (c) 2016, weizhenwei * 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 {organization} 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 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. * * Description : signal processing implementation file. ============================================================================ */ #include <assert.h> #include <signal.h> #include <string> #include "DmdLog.h" #include "DmdSignal.h" namespace opendmd { void DmdRegisterDefaultSignal() { signal(SIGPIPE, SIG_IGN); signal(SIGTERM, SIG_DFL); signal(SIGHUP, SIG_DFL); } void DmdRegisterSignalHandler(int sig, DmdSignalHandler pSigHandler) { signal(sig, pSigHandler); } /* * No Name Default Action Description * 2 SIGINT terminate process interrupt program * 3 SIGQUIT create core image quit program * 4 SIGILL create core image illegal instruction * 5 SIGTRAP create core image trace trap * 6 SIGABRT create core image abort program (formerly SIGIOT) * 7 SIGEMT create core image emulate instruction executed * 8 SIGFPE create core image floating-point exception * 9 SIGKILL terminate process kill program * 10 SIGBUS create core image bus error * 11 SIGSEGV create core image segmentation violation * 12 SIGSYS create core image non-existent system call invoked * 13 SIGPIPE terminate process write on a pipe with no reader * 14 SIGALRM terminate process real-time timer expired * 15 SIGTERM terminate process software termination signal * 16 SIGURG discard signal urgent condition present on socket * 17 SIGSTOP stop process stop (cannot be caught or ignored) * 18 SIGTSTP stop process stop signal generated from keyboard * 19 SIGCONT discard signal continue after stop * 20 SIGCHLD discard signal child status has changed * 21 SIGTTIN stop process background read attempted from control terminal * 22 SIGTTOU stop process background write attempted to control terminal * 23 SIGIO discard signal I/O is possible on a descriptor (see fcntl(2)) * 24 SIGXCPU terminate process cpu time limit exceeded (see setrlimit(2)) * 25 SIGXFSZ terminate process file size limit exceeded (see setrlimit(2)) * 26 SIGVTALRM terminate process virtual time alarm (see setitimer(2)) * 27 SIGPROF terminate process profiling timer alarm (see setitimer(2)) * 28 SIGWINCH discard signal Window size change * 29 SIGINFO discard signal status request from keyboard * 30 SIGUSR1 terminate process User defined signal 1 * 31 SIGUSR2 terminate process User defined signal 2 */ string DmdSignalToString(int sig) { if (sig == SIGHUP) { return "SIGHUP"; } else if (sig == SIGINT) { return "SIGINT"; } else if (sig == SIGQUIT) { return "SIGQUIT"; } else if (sig == SIGILL) { return "SIGILL"; } else if (sig == SIGTRAP) { return "SIGTRAP"; } else if (sig == SIGABRT) { return "SIGABRT"; /* } else if (sig == SIGEMT) { // didn't define on linux; return "SIGEMT"; */ } else if (sig == SIGFPE) { return "SIGFPE"; } else if (sig == SIGKILL) { return "SIGKILL"; } else if (sig == SIGBUS) { return "SIGBUS"; } else if (sig == SIGSEGV) { return "SIGSEGV"; } else if (sig == SIGSYS) { return "SIGSYS"; } else if (sig == SIGPIPE) { return "SIGPIPE"; } else if (sig == SIGALRM) { return "SIGALRM"; } else if (sig == SIGTERM) { return "SIGTERM"; } else if (sig == SIGURG) { return "SIGURG"; } else if (sig == SIGSTOP) { return "SIGSTOP"; } else if (sig == SIGTSTP) { return "SIGTSTP"; } else if (sig == SIGCONT) { return "SIGCONT"; } else if (sig == SIGCHLD) { return "SIGCHLD"; } else if (sig == SIGTTIN) { return "SIGTTIN"; } else if (sig == SIGTTOU) { return "SIGTTOU"; } else if (sig == SIGIO) { return "SIGIO"; } else if (sig == SIGXCPU) { return "SIGXCPU"; } else if (sig == SIGXFSZ) { return "SIGXFSZ"; } else if (sig == SIGVTALRM) { return "SIGVTALRM"; } else if (sig == SIGPROF) { return "SIGPROF"; } else if (sig == SIGWINCH) { return "SIGWINCH"; /* } else if (sig == SIGINFO) { // didn't define on linux; return "SIGINFO"; */ } else if (sig == SIGUSR1) { return "SIGUSR1"; } else if (sig == SIGUSR2) { return "SIGUSR2"; } else { return "Unknown signal"; } } } // namespace opendmd <|endoftext|>
<commit_before>/*! \class TrackFitPCAProducer * * \author S Viret / L Storchi * \date 2016, Mar 4 * */ #ifndef TRACK_FITTER_PCA_H #define TRACK_FITTER_PCA_H #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/L1TrackTrigger/interface/TTTypes.h" #include "DataFormats/L1TrackTrigger/interface/TTCluster.h" #include "DataFormats/L1TrackTrigger/interface/TTStub.h" #include "DataFormats/L1TrackTrigger/interface/TTTrack.h" #include "DataFormats/Common/interface/DetSetVectorNew.h" #include "DataFormats/GeometryCommonDetAlgo/interface/MeasurementPoint.h" #include "DataFormats/BeamSpot/interface/BeamSpot.h" #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/CommonDetUnit/interface/GeomDetUnit.h" #include "Geometry/Records/interface/StackedTrackerGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/StackedTrackerGeometry.h" #include "L1Trigger/TrackFindingAM/interface/CMSPatternLayer.h" #include "L1Trigger/TrackFindingAM/interface/PatternFinder.h" #include "L1Trigger/TrackFindingAM/interface/SectorTree.h" #include "L1Trigger/TrackFindingAM/interface/Hit.h" #include "L1Trigger/TrackFindingAM/interface/PCATrackFitter.h" #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/shared_ptr.hpp> #include <memory> #include <string> #include <map> #include <vector> #include <iostream> #include <fstream> #include <math.h> //#ifndef __APPLE__ //BOOST_CLASS_EXPORT_IMPLEMENT(CMSPatternLayer) //#endif class TrackFitPCAProducer : public edm::EDProducer { public: /// Constructor explicit TrackFitPCAProducer( const edm::ParameterSet& iConfig ); /// Destructor; ~TrackFitPCAProducer(); private: /// Data members double mMagneticField; unsigned int nSectors; unsigned int nWedges; std::string nBKName; int nThresh; const StackedTrackerGeometry *theStackedTracker; edm::InputTag TTStubsInputTag; edm::InputTag TTPatternsInputTag; std::string TTTrackOutputTag; std::string TTTrackBinaryOutputTag; /// Mandatory methods virtual void beginRun( const edm::Run& run, const edm::EventSetup& iSetup ); virtual void endRun( const edm::Run& run, const edm::EventSetup& iSetup ); virtual void produce( edm::Event& iEvent, const edm::EventSetup& iSetup ); }; /// Close class /*! \brief Implementation of methods */ /// Constructors TrackFitPCAProducer::TrackFitPCAProducer( const edm::ParameterSet& iConfig ) { TTStubsInputTag = iConfig.getParameter< edm::InputTag >( "TTInputStubs" ); TTPatternsInputTag = iConfig.getParameter< edm::InputTag >( "TTInputPatterns" ); TTTrackOutputTag = iConfig.getParameter< std::string >( "TTTrackName" ); produces< std::vector< TTTrack< Ref_PixelDigi_ > > >( TTTrackOutputTag ); } /// Destructor TrackFitPCAProducer::~TrackFitPCAProducer() {} /// Begin run void TrackFitPCAProducer::beginRun( const edm::Run& run, const edm::EventSetup& iSetup ) { /// Get the geometry references edm::ESHandle< StackedTrackerGeometry > StackedTrackerGeomHandle; iSetup.get< StackedTrackerGeometryRecord >().get( StackedTrackerGeomHandle ); theStackedTracker = StackedTrackerGeomHandle.product(); /// Get magnetic field edm::ESHandle<MagneticField> magneticFieldHandle; iSetup.get<IdealMagneticFieldRecord>().get(magneticFieldHandle); const MagneticField* theMagneticField = magneticFieldHandle.product(); double mMagneticFieldStrength = theMagneticField->inTesla(GlobalPoint(0,0,0)).z(); mMagneticField = (floor(mMagneticFieldStrength*10.0 + 0.5))/10.0; } /// End run void TrackFitPCAProducer::endRun( const edm::Run& run, const edm::EventSetup& iSetup ) {} /// Implement the producer void TrackFitPCAProducer::produce( edm::Event& iEvent, const edm::EventSetup& iSetup ) { /// Prepare output /// The temporary collection is used to store tracks /// before removal of duplicates std::auto_ptr< std::vector< TTTrack< Ref_PixelDigi_ > > > TTTracksForOutput( new std::vector< TTTrack< Ref_PixelDigi_ > > ); /// Get the Stubs already stored away edm::Handle< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > > > TTStubHandle; edm::Handle< std::vector< TTTrack< Ref_PixelDigi_ > > > TTPatternHandle; iEvent.getByLabel( TTStubsInputTag, TTStubHandle ); iEvent.getByLabel( TTPatternsInputTag, TTPatternHandle ); /// STEP 0 /// Prepare output TTTracksForOutput->clear(); int layer = 0; int ladder = 0; int module = 0; int nbLayers = 0; /// Loop over TCs unsigned int tkCnt = 0; unsigned int j = 0; std::map< unsigned int , edm::Ref< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >, TTStub< Ref_PixelDigi_ > > > stubMap; PCATrackFitter* PCA = new PCATrackFitter(nbLayers); // Floating point /// STEP 0 /// Read PCAConst file PCA->read_float_const_filename ("../data/barrel_tow16_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow17_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow18_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow19_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow20_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow21_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow22_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow23_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow24_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow25_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow26_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow27_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow28_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow29_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow30_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow31_pca_const.txt"); /// STEP 1 /// Loop over track candidates // std::cout << "Start the loop over " << TTPatternHandle->size() << " pattern(s) in order to recover the stubs" << std::endl; std::vector<Hit*> m_hits; for(unsigned int i=0;i<m_hits.size();i++) delete m_hits[i]; m_hits.clear(); std::vector<Track*> tracks; for(unsigned int i=0;i<tracks.size();i++) delete tracks[i]; tracks.clear(); edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >::const_iterator inputIter; edmNew::DetSet< TTStub< Ref_PixelDigi_ > >::const_iterator stubIter; std::vector< TTTrack< Ref_PixelDigi_ > >::const_iterator iterTTTrack; /// Go on only if there are TCs from PixelDigis if ( TTPatternHandle->size() > 0 ) { for ( iterTTTrack = TTPatternHandle->begin(); iterTTTrack != TTPatternHandle->end(); ++iterTTTrack ) { edm::Ptr< TTTrack< Ref_PixelDigi_ > > tempTrackPtr( TTPatternHandle, tkCnt++ ); j = 0; m_hits.clear(); tracks.clear(); stubMap.clear(); /// Get everything relevant unsigned int seedSector = tempTrackPtr->getSector(); Track* TC = new Track(); TC->setCharge(tempTrackPtr->getWedge()); TC->setCurve(tempTrackPtr->getMomentum(5).perp()); TC->setEta0(tempTrackPtr->getMomentum(5).eta()); TC->setPhi0(tempTrackPtr->getMomentum(5).phi()); TC->setZ0(tempTrackPtr->getPOCA(5).z()); // Get the stubs in the TC std::vector< edm::Ref< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >, TTStub< Ref_PixelDigi_ > > > trackStubs = tempTrackPtr->getStubRefs(); // Loop over stubs contained in the pattern to recover the info for(unsigned int i=0;i<trackStubs.size();i++) { ++j; edm::Ref< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >, TTStub< Ref_PixelDigi_ > > tempStubRef = trackStubs.at(i); stubMap.insert( std::make_pair( j, tempStubRef ) ); /// Calculate average coordinates col/row for inner/outer Cluster /// These are already corrected for being at the center of each pixel MeasurementPoint mp0 = tempStubRef->getClusterRef(0)->findAverageLocalCoordinates(); GlobalPoint posStub = theStackedTracker->findGlobalPosition( &(*tempStubRef) ); StackedTrackerDetId detIdStub( tempStubRef->getDetId() ); //bool isPS = theStackedTracker->isPSModule( detIdStub ); const GeomDetUnit* det0 = theStackedTracker->idToDetUnit( detIdStub, 0 ); const GeomDetUnit* det1 = theStackedTracker->idToDetUnit( detIdStub, 1 ); /// Find pixel pitch and topology related information const PixelGeomDetUnit* pix0 = dynamic_cast< const PixelGeomDetUnit* >( det0 ); const PixelGeomDetUnit* pix1 = dynamic_cast< const PixelGeomDetUnit* >( det1 ); const PixelTopology* top0 = dynamic_cast< const PixelTopology* >( &(pix0->specificTopology()) ); const PixelTopology* top1 = dynamic_cast< const PixelTopology* >( &(pix1->specificTopology()) ); /// Find the z-segment int cols0 = top0->ncolumns(); int cols1 = top1->ncolumns(); int ratio = cols0/cols1; /// This assumes the ratio is integer! int segment = floor( mp0.y() / ratio ); // Here we rearrange the number in order to be compatible with the AM emulator if ( detIdStub.isBarrel() ) { layer = detIdStub.iLayer()+4; ladder = detIdStub.iPhi()-1; module = detIdStub.iZ()-1; } else if ( detIdStub.isEndcap() ) { layer = 10+detIdStub.iZ()+abs((int)(detIdStub.iSide())-2)*7; ladder = detIdStub.iRing()-1; module = detIdStub.iPhi()-1; } int strip = mp0.x(); int tp = -1; float eta = 0; float phi0 = 0; float spt = 0; float x = posStub.x(); float y = posStub.y(); float z = posStub.z(); float x0 = 0.; float y0 = 0.; float z0 = 0.; float ip = sqrt(x0*x0+y0*y0); Hit* h = new Hit(layer,ladder, module, segment, strip, j, tp, spt, ip, eta, phi0, x, y, z, x0, y0, z0, tempStubRef->getTriggerDisplacement()-tempStubRef->getTriggerOffset()); m_hits.push_back(h); } /// End of loop over track stubs if (tempTrackPtr->getSector()!=18) continue; // For the moment don't need to bother with the rest PCA->setSectorID(tempTrackPtr->getSector()); PCA->setTrack(TC); PCA->fit(m_hits); tracks = PCA->getTracks(); PCA->clean(); delete TC; std::vector<double> chi2v = PCA->get_chi2f(); if (chi2v.size() == tracks.size()) { // Store the tracks (no duplicate cleaning yet) // cout<<"Found "<<tracks.size()<<" track"<<endl; std::vector< edm::Ref< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >, TTStub< Ref_PixelDigi_ > > > tempVec; for(unsigned int tt=0;tt<tracks.size();tt++) { tempVec.clear(); vector<int> stubs = tracks[tt]->getStubs(); for(unsigned int sti=0;sti<stubs.size();sti++) tempVec.push_back( stubMap[ stubs[sti] ]); double pz = tracks[tt]->getCurve()/(tan(2*atan(exp(-tracks[tt]->getEta0())))); TTTrack< Ref_PixelDigi_ > tempTrack( tempVec ); GlobalPoint POCA(0.,0.,tracks[tt]->getZ0()); GlobalVector mom(tracks[tt]->getCurve()*cos(tracks[tt]->getPhi0()), tracks[tt]->getCurve()*sin(tracks[tt]->getPhi0()), pz); tempTrack.setSector( seedSector ); tempTrack.setWedge( tracks[tt]->getCharge() ); tempTrack.setMomentum( mom , 5); tempTrack.setPOCA( POCA , 5); tempTrack.setChi2(chi2v[tt]); TTTracksForOutput->push_back( tempTrack ); delete tracks[tt]; } } } // End of loop over patterns delete(PCA); } /// Put in the event content iEvent.put( TTTracksForOutput, TTTrackOutputTag); } // DEFINE THIS AS A PLUG-IN DEFINE_FWK_MODULE(TrackFitPCAProducer); #endif <commit_msg>bug fix to have all barrel sectors in fit<commit_after>/*! \class TrackFitPCAProducer * * \author S Viret / L Storchi * \date 2016, Mar 4 * */ #ifndef TRACK_FITTER_PCA_H #define TRACK_FITTER_PCA_H #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/L1TrackTrigger/interface/TTTypes.h" #include "DataFormats/L1TrackTrigger/interface/TTCluster.h" #include "DataFormats/L1TrackTrigger/interface/TTStub.h" #include "DataFormats/L1TrackTrigger/interface/TTTrack.h" #include "DataFormats/Common/interface/DetSetVectorNew.h" #include "DataFormats/GeometryCommonDetAlgo/interface/MeasurementPoint.h" #include "DataFormats/BeamSpot/interface/BeamSpot.h" #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/CommonDetUnit/interface/GeomDetUnit.h" #include "Geometry/Records/interface/StackedTrackerGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/StackedTrackerGeometry.h" #include "L1Trigger/TrackFindingAM/interface/CMSPatternLayer.h" #include "L1Trigger/TrackFindingAM/interface/PatternFinder.h" #include "L1Trigger/TrackFindingAM/interface/SectorTree.h" #include "L1Trigger/TrackFindingAM/interface/Hit.h" #include "L1Trigger/TrackFindingAM/interface/PCATrackFitter.h" #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/shared_ptr.hpp> #include <memory> #include <string> #include <map> #include <vector> #include <iostream> #include <fstream> #include <math.h> //#ifndef __APPLE__ //BOOST_CLASS_EXPORT_IMPLEMENT(CMSPatternLayer) //#endif class TrackFitPCAProducer : public edm::EDProducer { public: /// Constructor explicit TrackFitPCAProducer( const edm::ParameterSet& iConfig ); /// Destructor; ~TrackFitPCAProducer(); private: /// Data members double mMagneticField; unsigned int nSectors; unsigned int nWedges; std::string nBKName; int nThresh; const StackedTrackerGeometry *theStackedTracker; edm::InputTag TTStubsInputTag; edm::InputTag TTPatternsInputTag; std::string TTTrackOutputTag; std::string TTTrackBinaryOutputTag; /// Mandatory methods virtual void beginRun( const edm::Run& run, const edm::EventSetup& iSetup ); virtual void endRun( const edm::Run& run, const edm::EventSetup& iSetup ); virtual void produce( edm::Event& iEvent, const edm::EventSetup& iSetup ); }; /// Close class /*! \brief Implementation of methods */ /// Constructors TrackFitPCAProducer::TrackFitPCAProducer( const edm::ParameterSet& iConfig ) { TTStubsInputTag = iConfig.getParameter< edm::InputTag >( "TTInputStubs" ); TTPatternsInputTag = iConfig.getParameter< edm::InputTag >( "TTInputPatterns" ); TTTrackOutputTag = iConfig.getParameter< std::string >( "TTTrackName" ); produces< std::vector< TTTrack< Ref_PixelDigi_ > > >( TTTrackOutputTag ); } /// Destructor TrackFitPCAProducer::~TrackFitPCAProducer() {} /// Begin run void TrackFitPCAProducer::beginRun( const edm::Run& run, const edm::EventSetup& iSetup ) { /// Get the geometry references edm::ESHandle< StackedTrackerGeometry > StackedTrackerGeomHandle; iSetup.get< StackedTrackerGeometryRecord >().get( StackedTrackerGeomHandle ); theStackedTracker = StackedTrackerGeomHandle.product(); /// Get magnetic field edm::ESHandle<MagneticField> magneticFieldHandle; iSetup.get<IdealMagneticFieldRecord>().get(magneticFieldHandle); const MagneticField* theMagneticField = magneticFieldHandle.product(); double mMagneticFieldStrength = theMagneticField->inTesla(GlobalPoint(0,0,0)).z(); mMagneticField = (floor(mMagneticFieldStrength*10.0 + 0.5))/10.0; } /// End run void TrackFitPCAProducer::endRun( const edm::Run& run, const edm::EventSetup& iSetup ) {} /// Implement the producer void TrackFitPCAProducer::produce( edm::Event& iEvent, const edm::EventSetup& iSetup ) { /// Prepare output /// The temporary collection is used to store tracks /// before removal of duplicates std::auto_ptr< std::vector< TTTrack< Ref_PixelDigi_ > > > TTTracksForOutput( new std::vector< TTTrack< Ref_PixelDigi_ > > ); /// Get the Stubs already stored away edm::Handle< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > > > TTStubHandle; edm::Handle< std::vector< TTTrack< Ref_PixelDigi_ > > > TTPatternHandle; iEvent.getByLabel( TTStubsInputTag, TTStubHandle ); iEvent.getByLabel( TTPatternsInputTag, TTPatternHandle ); /// STEP 0 /// Prepare output TTTracksForOutput->clear(); int layer = 0; int ladder = 0; int module = 0; int nbLayers = 0; /// Loop over TCs unsigned int tkCnt = 0; unsigned int j = 0; std::map< unsigned int , edm::Ref< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >, TTStub< Ref_PixelDigi_ > > > stubMap; PCATrackFitter* PCA = new PCATrackFitter(nbLayers); // Floating point /// STEP 0 /// Read PCAConst file PCA->read_float_const_filename ("../data/barrel_tow16_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow17_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow18_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow19_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow20_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow21_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow22_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow23_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow24_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow25_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow26_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow27_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow28_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow29_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow30_pca_const.txt"); PCA->read_float_const_filename ("../data/barrel_tow31_pca_const.txt"); /// STEP 1 /// Loop over track candidates // std::cout << "Start the loop over " << TTPatternHandle->size() << " pattern(s) in order to recover the stubs" << std::endl; std::vector<Hit*> m_hits; for(unsigned int i=0;i<m_hits.size();i++) delete m_hits[i]; m_hits.clear(); std::vector<Track*> tracks; for(unsigned int i=0;i<tracks.size();i++) delete tracks[i]; tracks.clear(); edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >::const_iterator inputIter; edmNew::DetSet< TTStub< Ref_PixelDigi_ > >::const_iterator stubIter; std::vector< TTTrack< Ref_PixelDigi_ > >::const_iterator iterTTTrack; /// Go on only if there are TCs from PixelDigis if ( TTPatternHandle->size() > 0 ) { for ( iterTTTrack = TTPatternHandle->begin(); iterTTTrack != TTPatternHandle->end(); ++iterTTTrack ) { edm::Ptr< TTTrack< Ref_PixelDigi_ > > tempTrackPtr( TTPatternHandle, tkCnt++ ); j = 0; m_hits.clear(); tracks.clear(); stubMap.clear(); /// Get everything relevant unsigned int seedSector = tempTrackPtr->getSector(); Track* TC = new Track(); TC->setCharge(tempTrackPtr->getWedge()); TC->setCurve(tempTrackPtr->getMomentum(5).perp()); TC->setEta0(tempTrackPtr->getMomentum(5).eta()); TC->setPhi0(tempTrackPtr->getMomentum(5).phi()); TC->setZ0(tempTrackPtr->getPOCA(5).z()); // Get the stubs in the TC std::vector< edm::Ref< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >, TTStub< Ref_PixelDigi_ > > > trackStubs = tempTrackPtr->getStubRefs(); // Loop over stubs contained in the pattern to recover the info for(unsigned int i=0;i<trackStubs.size();i++) { ++j; edm::Ref< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >, TTStub< Ref_PixelDigi_ > > tempStubRef = trackStubs.at(i); stubMap.insert( std::make_pair( j, tempStubRef ) ); /// Calculate average coordinates col/row for inner/outer Cluster /// These are already corrected for being at the center of each pixel MeasurementPoint mp0 = tempStubRef->getClusterRef(0)->findAverageLocalCoordinates(); GlobalPoint posStub = theStackedTracker->findGlobalPosition( &(*tempStubRef) ); StackedTrackerDetId detIdStub( tempStubRef->getDetId() ); //bool isPS = theStackedTracker->isPSModule( detIdStub ); const GeomDetUnit* det0 = theStackedTracker->idToDetUnit( detIdStub, 0 ); const GeomDetUnit* det1 = theStackedTracker->idToDetUnit( detIdStub, 1 ); /// Find pixel pitch and topology related information const PixelGeomDetUnit* pix0 = dynamic_cast< const PixelGeomDetUnit* >( det0 ); const PixelGeomDetUnit* pix1 = dynamic_cast< const PixelGeomDetUnit* >( det1 ); const PixelTopology* top0 = dynamic_cast< const PixelTopology* >( &(pix0->specificTopology()) ); const PixelTopology* top1 = dynamic_cast< const PixelTopology* >( &(pix1->specificTopology()) ); /// Find the z-segment int cols0 = top0->ncolumns(); int cols1 = top1->ncolumns(); int ratio = cols0/cols1; /// This assumes the ratio is integer! int segment = floor( mp0.y() / ratio ); // Here we rearrange the number in order to be compatible with the AM emulator if ( detIdStub.isBarrel() ) { layer = detIdStub.iLayer()+4; ladder = detIdStub.iPhi()-1; module = detIdStub.iZ()-1; } else if ( detIdStub.isEndcap() ) { layer = 10+detIdStub.iZ()+abs((int)(detIdStub.iSide())-2)*7; ladder = detIdStub.iRing()-1; module = detIdStub.iPhi()-1; } int strip = mp0.x(); int tp = -1; float eta = 0; float phi0 = 0; float spt = 0; float x = posStub.x(); float y = posStub.y(); float z = posStub.z(); float x0 = 0.; float y0 = 0.; float z0 = 0.; float ip = sqrt(x0*x0+y0*y0); Hit* h = new Hit(layer,ladder, module, segment, strip, j, tp, spt, ip, eta, phi0, x, y, z, x0, y0, z0, tempStubRef->getTriggerDisplacement()-tempStubRef->getTriggerOffset()); m_hits.push_back(h); } /// End of loop over track stubs //if (tempTrackPtr->getSector()!=18) continue; // For the moment don't need to bother with the rest if (tempTrackPtr->getSector() < 16 || tempTrackPtr->getSector() > 31) continue; // For the moment don't need to bother with the rest PCA->setSectorID(tempTrackPtr->getSector()); PCA->setTrack(TC); PCA->fit(m_hits); tracks = PCA->getTracks(); PCA->clean(); delete TC; std::vector<double> chi2v = PCA->get_chi2f(); if (chi2v.size() == tracks.size()) { // Store the tracks (no duplicate cleaning yet) // cout<<"Found "<<tracks.size()<<" track"<<endl; std::vector< edm::Ref< edmNew::DetSetVector< TTStub< Ref_PixelDigi_ > >, TTStub< Ref_PixelDigi_ > > > tempVec; for(unsigned int tt=0;tt<tracks.size();tt++) { tempVec.clear(); vector<int> stubs = tracks[tt]->getStubs(); for(unsigned int sti=0;sti<stubs.size();sti++) tempVec.push_back( stubMap[ stubs[sti] ]); double pz = tracks[tt]->getCurve()/(tan(2*atan(exp(-tracks[tt]->getEta0())))); TTTrack< Ref_PixelDigi_ > tempTrack( tempVec ); GlobalPoint POCA(0.,0.,tracks[tt]->getZ0()); GlobalVector mom(tracks[tt]->getCurve()*cos(tracks[tt]->getPhi0()), tracks[tt]->getCurve()*sin(tracks[tt]->getPhi0()), pz); tempTrack.setSector( seedSector ); tempTrack.setWedge( tracks[tt]->getCharge() ); tempTrack.setMomentum( mom , 5); tempTrack.setPOCA( POCA , 5); tempTrack.setChi2(chi2v[tt]); TTTracksForOutput->push_back( tempTrack ); delete tracks[tt]; } } } // End of loop over patterns delete(PCA); } /// Put in the event content iEvent.put( TTTracksForOutput, TTTrackOutputTag); } // DEFINE THIS AS A PLUG-IN DEFINE_FWK_MODULE(TrackFitPCAProducer); #endif <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.1 1999/11/09 01:05:35 twl * Initial revision * * Revision 1.3 1999/11/08 20:45:19 rahul * Swat for adding in Product name and CVS comment log variable. * */ #if !defined(XML4CDEFS_HPP) #define XML4CDEFS_HPP // --------------------------------------------------------------------------- // These are the various representations of the current version of XML4C. // These are updated for every build. They must be at the top because they // can be used by various per-compiler headers below. // --------------------------------------------------------------------------- #define XML4C_DLLVersionStr "3_0" static const char* const gXML4CVersionStr = "3_0"; static const char* const gXML4CFullVersionStr = "3_0_0"; static const unsigned int gXML4CMajVersion = 3; static const unsigned int gXML4CMinVersion = 0; static const unsigned int gXML4CRevision = 0; // --------------------------------------------------------------------------- // Include the header that does automatic sensing of the current platform // and compiler. // --------------------------------------------------------------------------- #include <util/AutoSense.hpp> // --------------------------------------------------------------------------- // According to the platform we include a platform specific file. This guy // will set up any platform specific stuff, such as character mode. // --------------------------------------------------------------------------- #if defined(XML_WIN32) #include <util/Platforms/Win32/Win32Defs.hpp> #endif #if defined(XML_AIX) #include <util/Platforms/AIX/AIXDefs.hpp> #endif #if defined(XML_SOLARIS) #include <util/Platforms/Solaris/SolarisDefs.hpp> #endif #if defined(XML_HPUX) #include <util/Platforms/HPUX/HPUXDefs.hpp> #endif #if defined(XML_TANDEM) #include <util/Platforms/Tandem/TandemDefs.hpp> #endif #if defined(XML_LINUX) #include <util/Platforms/Linux/LinuxDefs.hpp> #endif #if defined(XML_OE390) #include <util/Platforms/OS390/OE390Defs.hpp> #endif #if defined(XML_OS2) #include <util/Platforms/OS2/OS2Defs.hpp> #endif #if defined(XML_MACOS) #include <util/Platforms/MaxOS/MacOSDefs.hpp> #endif // --------------------------------------------------------------------------- // And now we subinclude a header according to the development environment // we are on. This guy defines for each platform some basic stuff that is // specific to the development environment. // --------------------------------------------------------------------------- #if defined(XML_VISUALCPP) #include <util/Compilers/VCPPDefs.hpp> #endif #if defined(XML_CSET) #include <util/Compilers/CSetDefs.hpp> #endif #if defined(XML_BORLAND) #include <util/Compilers/BorlandCDefs.hpp> #endif #if defined(XML_SUNCC) #include <util/Compilers/SunCCDefs.hpp> #endif #if defined(XML_SOLARIS_KAICC) #include <util/Compilers/SunKaiDefs.hpp> #endif #if defined(XML_GNUG) #include <util/Compilers/GNUGDefs.hpp> #endif #if defined(XML_HPUX_CC) || defined(XML_HPUX_aCC) || defined(XML_HPUX_KAICC) #include <util/Compilers/HPCCDefs.hpp> #endif #if defined(XML_TANDEMCC) #include <util/Compilers/TandemCCDefs.hpp> #endif #if defined(XML_GCC) #include <util/Compilers/GCCDefs.hpp> #endif #if defined(XML_MVSCPP) #include <util/Compilers/MVSCPPDefs.hpp> #endif #if defined(XML_IBMVAW32) #include <util/Compilers/IBMVAW32Defs.hpp> #endif #if defined(XML_IBMVAOS2) #include <util/Compilers/IBMVAOS2Defs.hpp> #endif #if defined(XML_METROWERKS) #include <util/Compilers/CodeWarriorDefs.hpp> #endif // --------------------------------------------------------------------------- // Some general typedefs that are defined for internal flexibility. // // Note that UTF16Ch is fixed at 16 bits, whereas XMLCh floats in size per // platform, to whatever is the native wide char format there. UCS4Ch is // fixed at 32 bits. The types we defined them in terms of are defined per // compiler, using whatever types are the right ones for them to get these // 16/32 bit sizes. // --------------------------------------------------------------------------- typedef unsigned char XMLByte; typedef XMLUInt16 UTF16Ch; typedef XMLUInt32 UCS4Ch; // --------------------------------------------------------------------------- // Handle boolean. If the platform can handle booleans itself, then we // map our boolean type to the native type. Otherwise we create a default // one as an int and define const values for true and false. // // This flag will be set in the per-development environment stuff above. // --------------------------------------------------------------------------- #if defined(NO_NATIVE_BOOL) typedef int bool; const bool true = 1; const bool false = 0; #endif // --------------------------------------------------------------------------- // Set up the import/export keyword for our core projects. The // PLATFORM_XXXX keywords are set in the per-development environment // include above. // --------------------------------------------------------------------------- #if defined(PROJ_XMLUTIL) #define XMLUTIL_EXPORT PLATFORM_EXPORT #else #define XMLUTIL_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_XMLPARSER) #define XMLPARSER_EXPORT PLATFORM_EXPORT #else #define XMLPARSER_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_SAX4C) #define SAX_EXPORT PLATFORM_EXPORT #else #define SAX_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_DOM) #define CDOM_EXPORT PLATFORM_EXPORT #else #define CDOM_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_PARSERS) #define PARSERS_EXPORT PLATFORM_EXPORT #else #define PARSERS_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_VALIDATORS) #define VALIDATORS_EXPORT PLATFORM_EXPORT #else #define VALIDATORS_EXPORT PLATFORM_IMPORT #endif #endif <commit_msg>Changed version numbers<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.2 1999/11/10 02:02:51 abagchi * Changed version numbers * * Revision 1.1.1.1 1999/11/09 01:05:35 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:19 rahul * Swat for adding in Product name and CVS comment log variable. * */ #if !defined(XML4CDEFS_HPP) #define XML4CDEFS_HPP // --------------------------------------------------------------------------- // These are the various representations of the current version of XML4C. // These are updated for every build. They must be at the top because they // can be used by various per-compiler headers below. // --------------------------------------------------------------------------- #define XML4C_DLLVersionStr "1_0" static const char* const gXML4CVersionStr = "1_0"; static const char* const gXML4CFullVersionStr = "1_0_0"; static const unsigned int gXML4CMajVersion = 1; static const unsigned int gXML4CMinVersion = 0; static const unsigned int gXML4CRevision = 0; // --------------------------------------------------------------------------- // Include the header that does automatic sensing of the current platform // and compiler. // --------------------------------------------------------------------------- #include <util/AutoSense.hpp> // --------------------------------------------------------------------------- // According to the platform we include a platform specific file. This guy // will set up any platform specific stuff, such as character mode. // --------------------------------------------------------------------------- #if defined(XML_WIN32) #include <util/Platforms/Win32/Win32Defs.hpp> #endif #if defined(XML_AIX) #include <util/Platforms/AIX/AIXDefs.hpp> #endif #if defined(XML_SOLARIS) #include <util/Platforms/Solaris/SolarisDefs.hpp> #endif #if defined(XML_HPUX) #include <util/Platforms/HPUX/HPUXDefs.hpp> #endif #if defined(XML_TANDEM) #include <util/Platforms/Tandem/TandemDefs.hpp> #endif #if defined(XML_LINUX) #include <util/Platforms/Linux/LinuxDefs.hpp> #endif #if defined(XML_OE390) #include <util/Platforms/OS390/OE390Defs.hpp> #endif #if defined(XML_OS2) #include <util/Platforms/OS2/OS2Defs.hpp> #endif #if defined(XML_MACOS) #include <util/Platforms/MaxOS/MacOSDefs.hpp> #endif // --------------------------------------------------------------------------- // And now we subinclude a header according to the development environment // we are on. This guy defines for each platform some basic stuff that is // specific to the development environment. // --------------------------------------------------------------------------- #if defined(XML_VISUALCPP) #include <util/Compilers/VCPPDefs.hpp> #endif #if defined(XML_CSET) #include <util/Compilers/CSetDefs.hpp> #endif #if defined(XML_BORLAND) #include <util/Compilers/BorlandCDefs.hpp> #endif #if defined(XML_SUNCC) #include <util/Compilers/SunCCDefs.hpp> #endif #if defined(XML_SOLARIS_KAICC) #include <util/Compilers/SunKaiDefs.hpp> #endif #if defined(XML_GNUG) #include <util/Compilers/GNUGDefs.hpp> #endif #if defined(XML_HPUX_CC) || defined(XML_HPUX_aCC) || defined(XML_HPUX_KAICC) #include <util/Compilers/HPCCDefs.hpp> #endif #if defined(XML_TANDEMCC) #include <util/Compilers/TandemCCDefs.hpp> #endif #if defined(XML_GCC) #include <util/Compilers/GCCDefs.hpp> #endif #if defined(XML_MVSCPP) #include <util/Compilers/MVSCPPDefs.hpp> #endif #if defined(XML_IBMVAW32) #include <util/Compilers/IBMVAW32Defs.hpp> #endif #if defined(XML_IBMVAOS2) #include <util/Compilers/IBMVAOS2Defs.hpp> #endif #if defined(XML_METROWERKS) #include <util/Compilers/CodeWarriorDefs.hpp> #endif // --------------------------------------------------------------------------- // Some general typedefs that are defined for internal flexibility. // // Note that UTF16Ch is fixed at 16 bits, whereas XMLCh floats in size per // platform, to whatever is the native wide char format there. UCS4Ch is // fixed at 32 bits. The types we defined them in terms of are defined per // compiler, using whatever types are the right ones for them to get these // 16/32 bit sizes. // --------------------------------------------------------------------------- typedef unsigned char XMLByte; typedef XMLUInt16 UTF16Ch; typedef XMLUInt32 UCS4Ch; // --------------------------------------------------------------------------- // Handle boolean. If the platform can handle booleans itself, then we // map our boolean type to the native type. Otherwise we create a default // one as an int and define const values for true and false. // // This flag will be set in the per-development environment stuff above. // --------------------------------------------------------------------------- #if defined(NO_NATIVE_BOOL) typedef int bool; const bool true = 1; const bool false = 0; #endif // --------------------------------------------------------------------------- // Set up the import/export keyword for our core projects. The // PLATFORM_XXXX keywords are set in the per-development environment // include above. // --------------------------------------------------------------------------- #if defined(PROJ_XMLUTIL) #define XMLUTIL_EXPORT PLATFORM_EXPORT #else #define XMLUTIL_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_XMLPARSER) #define XMLPARSER_EXPORT PLATFORM_EXPORT #else #define XMLPARSER_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_SAX4C) #define SAX_EXPORT PLATFORM_EXPORT #else #define SAX_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_DOM) #define CDOM_EXPORT PLATFORM_EXPORT #else #define CDOM_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_PARSERS) #define PARSERS_EXPORT PLATFORM_EXPORT #else #define PARSERS_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_VALIDATORS) #define VALIDATORS_EXPORT PLATFORM_EXPORT #else #define VALIDATORS_EXPORT PLATFORM_IMPORT #endif #endif <|endoftext|>
<commit_before>#include "HuboMotor.h" #include <string> #include <iostream> HuboMotor::HuboMotor(){ this->ticks_position = 0; this->desired_position = 0; this->omega = MAX_ANGULAR_VELOCITY; //NEW_DATA currGoal = 0; interStep = 0; interVel = 0; currVel = 0; currPos = 0; currCurrent = 0; currTemp = 0; enabled = false; homed = false; zeroed = false; } HuboMotor::HuboMotor(long mpos1, long mpos2, long kp, long kd, long ki, long dz, long off, long hlim, long hld, long hv1, long hv2, long hma, long sm, long ers, long as, long md, long v_max, long a_max, long jam_lim, long jamd, long pwm_lim, long i_err, long b_err){ this->mpos1 = mpos1; this->mpos2 = mpos2; this->Kp = kp; this->Kd = kd; this->Ki = ki; this->dz = dz; this->off = off; this->hlim = hlim; this->hld = hld; this->hv1 = hv1; this->hv2 = hv2; this->hma = hma; this->sm = sm; this->ers = ers; this->as = as; this->md = md; this->v_max = v_max; this->a_max = a_max; this->jam_lim = jam_lim; this->jamd = jamd; this->pwm_lim = pwm_lim; this->i_err = i_err; this->b_err = b_err; this->ticks_position = 0; this->desired_position = 0; this->omega = MAX_ANGULAR_VELOCITY; currGoal = 0; interStep = 0; interVel = 0; currVel = 0; currPos = 0; currCurrent = 0; currTemp = 0; enabled = false; homed = false; zeroed = false; } HuboMotor::HuboMotor(const HuboMotor& rhs){ this->mpos1 = rhs.mpos1; this->mpos2 = rhs.mpos2; this->Kp = rhs.Kp; this->Kd = rhs.Kd; this->Ki = rhs.Ki; this->dz = rhs.dz; this->off = rhs.off; this->hlim = rhs.hlim; this->hld = rhs.hld; this->hv1 = rhs.hv1; this->hv2 = rhs.hv2; this->hma = rhs.hma; this->sm = rhs.sm; this->ers = rhs.ers; this->as = rhs.as; this->md = rhs.md; this->v_max = rhs.v_max; this->a_max = rhs.a_max; this->jam_lim = rhs.jam_lim; this->jamd = rhs.jamd; this->pwm_lim = rhs.pwm_lim; this->i_err = rhs.i_err; this->b_err = rhs.b_err; this->ticks_position = rhs.ticks_position; this->desired_position = rhs.desired_position; this->omega = rhs.omega; //NEW_DATA this->name = rhs.name; this->currGoal = rhs.currGoal; this->interStep = rhs.interStep; this->interVel = rhs.interVel; this->currVel = rhs.currVel; this->currPos = rhs.currPos; this->currCurrent = rhs.currCurrent; this->currTemp = rhs.currTemp; this->enabled = rhs.enabled; this->homed = rhs.homed; this->zeroed = rhs.zeroed; } void HuboMotor::setUpperLimit(long limit){ this->mpos2 = limit; } void HuboMotor::setLowerLimit(long limit){ this->mpos1 = limit; } void HuboMotor::setPositionGain(long kp, long kd, long ki){ this->Kp = kp; this->Kd = kd; this->Ki = ki; } void HuboMotor::setCurrentGain(long kpt, long kdt, long kf){ this->Kpt = kpt; this->Kdt = kdt; this->Kf = kf; } void HuboMotor::setDeadZone(int dz){ this->dz = dz; } void HuboMotor::setHomeset1(long off, long hlim, long hld){ this->off = off; this->hlim = hlim; this->hld = hld; } void HuboMotor::setHomeset2(long hv1, long hv2, long hma, long sm){ this->hv1 = hv1; this->hv2 = hv2; this->hma = hma; this->sm = sm; } void HuboMotor::setEncoderResolution(long ers, long as, long md){ this->ers = ers; this->as = as; this->md = md; } void HuboMotor::setSpeedLimit(long vel, long acc){ this->v_max = vel; this->a_max = acc; } void HuboMotor::setJamPowerLimit(long jam_lim, long jamd, long pwm_lim){ this->jam_lim = jam_lim; this->jamd = jamd; this->pwm_lim = pwm_lim; } void HuboMotor::setErrorLimit(long i_err, long b_err){ this->i_err = i_err; this->b_err = b_err; } void HuboMotor::setGearRatios(long drive, long driven, long harm, long enc){ this->drive = drive; this->driven = driven; this->harm = harm; this->enc = enc; } void HuboMotor::setTicksPosition(long ticks){ this->ticks_position = ticks; } void HuboMotor::setDesiredPosition(long ticks){ this->desired_position = ticks; } void HuboMotor::setAngularVelocity(double omega){ this->omega = omega; } long HuboMotor::getUpperLimit(){ return this->mpos2; } long HuboMotor::getLowerLimit(){ return this->mpos1; } long HuboMotor::getKp(){ return this->Kp; } long HuboMotor::getKi(){ return this->Ki; } long HuboMotor::getKd(){ return this->Kd; } long HuboMotor::getKpt(){ return this->Kpt; } long HuboMotor::getKdt(){ return this->Kdt; } long HuboMotor::getKf(){ return this->Kf; } long HuboMotor::getDz(){ return this->dz; } long HuboMotor::getOff(){ return this->off; } long HuboMotor::getHlim(){ return this->hlim; } long HuboMotor::getHld(){ return this->hld; } long HuboMotor::getHv1(){ return this->hv1; } long HuboMotor::getHv2(){ return this->hv2; } long HuboMotor::getHma(){ return this->hma; } long HuboMotor::getSm(){ return this->sm; } long HuboMotor::getErs(){ return this->ers; } long HuboMotor::getAs(){ return this->as; } long HuboMotor::getMd(){ return this->md; } long HuboMotor::getVmax(){ return this->v_max; } long HuboMotor::getAmax(){ return this->a_max; } long HuboMotor::getJamLim(){ return this->jam_lim; } long HuboMotor::getJamd(){ return this->jamd; } long HuboMotor::getPwmLim(){ return this->pwm_lim; } long HuboMotor::getIerr(){ return i_err; } long HuboMotor::getBerr(){ return b_err; } long HuboMotor::getTicksPosition(){ return this->ticks_position; } long HuboMotor::getDesiredPosition(){ return this->desired_position; } bool HuboMotor::requiresMotion(){ return desired_position - ticks_position != 0; } double HuboMotor::ticksToRadians(long ticks){ return (ticks * (double)(this->drive * 2 * M_PI))/(this->driven * this->harm * this->enc); } long HuboMotor::radiansToTicks(double rad){ return (long)(rad * ((double)(this->driven * this->harm * this->enc))/(this->drive * 2 * M_PI)); } long HuboMotor::interpolate(int MAX_STEP, int MIN_STEP){ const float LEAP_PERCENTAGE = .5; const int FREQUENCY = 100; //Hertz if (MAX_STEP == 0) MAX_STEP = radiansToTicks(omega) / 100; int error = desired_position - ticks_position; int output = desired_position; if((abs(error) > MIN_STEP)){ output = (int)(LEAP_PERCENTAGE * error); if(abs(output) > MAX_STEP) output = output < 0 ? -MAX_STEP : MAX_STEP; } else output = error; output += ticks_position; ticks_position = output; return output; } double HuboMotor::interpolate(){ const float LEAP_PERCENTAGE = .5; const double MIN_STEP = .00000001; const double MAX_STEP = interVel/100; //Radians per second, divided by our operating frequency. double error = currGoal - interStep; if (error == 0) return currGoal; std::cout << error; double output = currGoal; if((abs(error) > MIN_STEP)){ output = (LEAP_PERCENTAGE * error); if(abs(output) > MAX_STEP) output = output < 0 ? -MAX_STEP : MAX_STEP; } else output = error; output += interStep; interStep = output; return interStep; } void HuboMotor::setName(string name){ this->name = name; } void HuboMotor::setGoalPosition(double rads){ currGoal = rads; } void HuboMotor::setInterVelocity(double omega){ interVel = omega; } void HuboMotor::update(double position, double velocity, double temperature, double current){ currPos = position; currVel = velocity; currTemp = temperature; currCurrent = current; } void HuboMotor::setEnabled(bool enabled){ this->enabled = enabled; interStep = currPos; //If we have recently changed from non-interpolation to interpolation, the step MUST be updated. } void HuboMotor::setHomed(bool homed){ this->homed = homed; } void HuboMotor::setZeroed(bool zeroed){ this->zeroed = zeroed; } string HuboMotor::getName(){ return name; } double HuboMotor::getGoalPosition(){ return currGoal; } double HuboMotor::getPosition(){ return currPos; } double HuboMotor::getVelocity(){ return currVel; } double HuboMotor::getTemperature(){ return currTemp; } double HuboMotor::getCurrent(){ return currCurrent; } bool HuboMotor::isEnabled(){ return enabled; } bool HuboMotor::isHomed(){ return homed; } bool HuboMotor::isZeroed(){ return zeroed; } <commit_msg>more debug.<commit_after>#include "HuboMotor.h" #include <string> #include <iostream> HuboMotor::HuboMotor(){ this->ticks_position = 0; this->desired_position = 0; this->omega = MAX_ANGULAR_VELOCITY; //NEW_DATA currGoal = 0; interStep = 0; interVel = 0; currVel = 0; currPos = 0; currCurrent = 0; currTemp = 0; enabled = false; homed = false; zeroed = false; } HuboMotor::HuboMotor(long mpos1, long mpos2, long kp, long kd, long ki, long dz, long off, long hlim, long hld, long hv1, long hv2, long hma, long sm, long ers, long as, long md, long v_max, long a_max, long jam_lim, long jamd, long pwm_lim, long i_err, long b_err){ this->mpos1 = mpos1; this->mpos2 = mpos2; this->Kp = kp; this->Kd = kd; this->Ki = ki; this->dz = dz; this->off = off; this->hlim = hlim; this->hld = hld; this->hv1 = hv1; this->hv2 = hv2; this->hma = hma; this->sm = sm; this->ers = ers; this->as = as; this->md = md; this->v_max = v_max; this->a_max = a_max; this->jam_lim = jam_lim; this->jamd = jamd; this->pwm_lim = pwm_lim; this->i_err = i_err; this->b_err = b_err; this->ticks_position = 0; this->desired_position = 0; this->omega = MAX_ANGULAR_VELOCITY; currGoal = 0; interStep = 0; interVel = 0; currVel = 0; currPos = 0; currCurrent = 0; currTemp = 0; enabled = false; homed = false; zeroed = false; } HuboMotor::HuboMotor(const HuboMotor& rhs){ this->mpos1 = rhs.mpos1; this->mpos2 = rhs.mpos2; this->Kp = rhs.Kp; this->Kd = rhs.Kd; this->Ki = rhs.Ki; this->dz = rhs.dz; this->off = rhs.off; this->hlim = rhs.hlim; this->hld = rhs.hld; this->hv1 = rhs.hv1; this->hv2 = rhs.hv2; this->hma = rhs.hma; this->sm = rhs.sm; this->ers = rhs.ers; this->as = rhs.as; this->md = rhs.md; this->v_max = rhs.v_max; this->a_max = rhs.a_max; this->jam_lim = rhs.jam_lim; this->jamd = rhs.jamd; this->pwm_lim = rhs.pwm_lim; this->i_err = rhs.i_err; this->b_err = rhs.b_err; this->ticks_position = rhs.ticks_position; this->desired_position = rhs.desired_position; this->omega = rhs.omega; //NEW_DATA this->name = rhs.name; this->currGoal = rhs.currGoal; this->interStep = rhs.interStep; this->interVel = rhs.interVel; this->currVel = rhs.currVel; this->currPos = rhs.currPos; this->currCurrent = rhs.currCurrent; this->currTemp = rhs.currTemp; this->enabled = rhs.enabled; this->homed = rhs.homed; this->zeroed = rhs.zeroed; } void HuboMotor::setUpperLimit(long limit){ this->mpos2 = limit; } void HuboMotor::setLowerLimit(long limit){ this->mpos1 = limit; } void HuboMotor::setPositionGain(long kp, long kd, long ki){ this->Kp = kp; this->Kd = kd; this->Ki = ki; } void HuboMotor::setCurrentGain(long kpt, long kdt, long kf){ this->Kpt = kpt; this->Kdt = kdt; this->Kf = kf; } void HuboMotor::setDeadZone(int dz){ this->dz = dz; } void HuboMotor::setHomeset1(long off, long hlim, long hld){ this->off = off; this->hlim = hlim; this->hld = hld; } void HuboMotor::setHomeset2(long hv1, long hv2, long hma, long sm){ this->hv1 = hv1; this->hv2 = hv2; this->hma = hma; this->sm = sm; } void HuboMotor::setEncoderResolution(long ers, long as, long md){ this->ers = ers; this->as = as; this->md = md; } void HuboMotor::setSpeedLimit(long vel, long acc){ this->v_max = vel; this->a_max = acc; } void HuboMotor::setJamPowerLimit(long jam_lim, long jamd, long pwm_lim){ this->jam_lim = jam_lim; this->jamd = jamd; this->pwm_lim = pwm_lim; } void HuboMotor::setErrorLimit(long i_err, long b_err){ this->i_err = i_err; this->b_err = b_err; } void HuboMotor::setGearRatios(long drive, long driven, long harm, long enc){ this->drive = drive; this->driven = driven; this->harm = harm; this->enc = enc; } void HuboMotor::setTicksPosition(long ticks){ this->ticks_position = ticks; } void HuboMotor::setDesiredPosition(long ticks){ this->desired_position = ticks; } void HuboMotor::setAngularVelocity(double omega){ this->omega = omega; } long HuboMotor::getUpperLimit(){ return this->mpos2; } long HuboMotor::getLowerLimit(){ return this->mpos1; } long HuboMotor::getKp(){ return this->Kp; } long HuboMotor::getKi(){ return this->Ki; } long HuboMotor::getKd(){ return this->Kd; } long HuboMotor::getKpt(){ return this->Kpt; } long HuboMotor::getKdt(){ return this->Kdt; } long HuboMotor::getKf(){ return this->Kf; } long HuboMotor::getDz(){ return this->dz; } long HuboMotor::getOff(){ return this->off; } long HuboMotor::getHlim(){ return this->hlim; } long HuboMotor::getHld(){ return this->hld; } long HuboMotor::getHv1(){ return this->hv1; } long HuboMotor::getHv2(){ return this->hv2; } long HuboMotor::getHma(){ return this->hma; } long HuboMotor::getSm(){ return this->sm; } long HuboMotor::getErs(){ return this->ers; } long HuboMotor::getAs(){ return this->as; } long HuboMotor::getMd(){ return this->md; } long HuboMotor::getVmax(){ return this->v_max; } long HuboMotor::getAmax(){ return this->a_max; } long HuboMotor::getJamLim(){ return this->jam_lim; } long HuboMotor::getJamd(){ return this->jamd; } long HuboMotor::getPwmLim(){ return this->pwm_lim; } long HuboMotor::getIerr(){ return i_err; } long HuboMotor::getBerr(){ return b_err; } long HuboMotor::getTicksPosition(){ return this->ticks_position; } long HuboMotor::getDesiredPosition(){ return this->desired_position; } bool HuboMotor::requiresMotion(){ return desired_position - ticks_position != 0; } double HuboMotor::ticksToRadians(long ticks){ return (ticks * (double)(this->drive * 2 * M_PI))/(this->driven * this->harm * this->enc); } long HuboMotor::radiansToTicks(double rad){ return (long)(rad * ((double)(this->driven * this->harm * this->enc))/(this->drive * 2 * M_PI)); } long HuboMotor::interpolate(int MAX_STEP, int MIN_STEP){ const float LEAP_PERCENTAGE = .5; const int FREQUENCY = 100; //Hertz if (MAX_STEP == 0) MAX_STEP = radiansToTicks(omega) / 100; int error = desired_position - ticks_position; int output = desired_position; if((abs(error) > MIN_STEP)){ output = (int)(LEAP_PERCENTAGE * error); if(abs(output) > MAX_STEP) output = output < 0 ? -MAX_STEP : MAX_STEP; } else output = error; output += ticks_position; ticks_position = output; return output; } double HuboMotor::interpolate(){ const float LEAP_PERCENTAGE = .5; const double MIN_STEP = .00000001; const double MAX_STEP = interVel/100; //Radians per second, divided by our operating frequency. double error = currGoal - interStep; if (error == 0) return currGoal; std::cout << MAX_STEP << std::endl; std::cout << error << std::endl; double output = currGoal; if((abs(error) > MIN_STEP)){ output = (LEAP_PERCENTAGE * error); if(abs(output) > MAX_STEP) output = output < 0 ? -MAX_STEP : MAX_STEP; } else output = error; output += interStep; interStep = output; cout << output << std::endl; return interStep; } void HuboMotor::setName(string name){ this->name = name; } void HuboMotor::setGoalPosition(double rads){ currGoal = rads; } void HuboMotor::setInterVelocity(double omega){ interVel = omega; } void HuboMotor::update(double position, double velocity, double temperature, double current){ currPos = position; currVel = velocity; currTemp = temperature; currCurrent = current; } void HuboMotor::setEnabled(bool enabled){ this->enabled = enabled; interStep = currPos; //If we have recently changed from non-interpolation to interpolation, the step MUST be updated. } void HuboMotor::setHomed(bool homed){ this->homed = homed; } void HuboMotor::setZeroed(bool zeroed){ this->zeroed = zeroed; } string HuboMotor::getName(){ return name; } double HuboMotor::getGoalPosition(){ return currGoal; } double HuboMotor::getPosition(){ return currPos; } double HuboMotor::getVelocity(){ return currVel; } double HuboMotor::getTemperature(){ return currTemp; } double HuboMotor::getCurrent(){ return currCurrent; } bool HuboMotor::isEnabled(){ return enabled; } bool HuboMotor::isHomed(){ return homed; } bool HuboMotor::isZeroed(){ return zeroed; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Line.h" const float Line::kLineWidth = 0.0025f; const float Line::kMinLineWidth = 0.001f; const float Line::kNeighborInterpolationDistance = 0.03f; Line::Line() { } Line::~Line() { } void Line::AddNode(float x, float y) { nodes_.push_back(std::make_pair(x, y)); } int Line::Save(FILE * file) { fwrite(&kMagicNumber, sizeof(kMagicNumber), 1, file); int num_elements = nodes_.size(); fwrite(&num_elements, sizeof(num_elements), 1, file); for (int i = 0; i < num_elements; i++) { fwrite(&(nodes_[i].first), sizeof(float), 1, file); fwrite(&(nodes_[i].second), sizeof(float), 1, file); } return 0; } int Line::Load(FILE * file) { unsigned int ref_val; fread(&ref_val, sizeof(ref_val), 1, file); if (ref_val != kMagicNumber) { // Not the correct thing. return -1; } int num_elements; fread(&num_elements, sizeof(num_elements), 1, file); for (int i = 0; i < num_elements; i++) { float pos[2]; fread(pos, sizeof(float), 2, file); AddNode(pos[0], pos[1]); } return 0; } void Line::DrawFancy(void) { if (nodes_.size() < 2) return; // Create fancy nodes by interpolating borders std::vector< std::pair<float, float> >fancy_nodes; for (int i = 0; i < (int)nodes_.size(); i++) { fancy_nodes.push_back(nodes_[i]); } #if 0 for (int i = 0; i < (int)nodes_.size(); i++) { // Check how much weight I get total float weight = 0.0f; for (int j = 0; j < (int)nodes_.size(); j++) { float dx = nodes_[i].first - nodes_[j].first; float dy = nodes_[i].second - nodes_[j].second; float dist = sqrtf(dx * dx + dy * dy); float amount = kNeighborInterpolationDistance - dist; if (amount < 0.0f) amount = 0.0f; weight += amount; } // Interpolate fancy_nodes[i].first = 0; fancy_nodes[i].second = 0; for (int j = 0; j < (int)nodes_.size(); j++) { float dx = nodes_[i].first - nodes_[j].first; float dy = nodes_[i].second - nodes_[j].second; float dist = sqrtf(dx * dx + dy * dy); float amount = kNeighborInterpolationDistance - dist; if (amount < 0.0f) amount = 0.0f; fancy_nodes[i].first += amount * nodes_[j].first / weight; fancy_nodes[i].second += amount * nodes_[j].second / weight; } } #endif // Get the length of the line float length = 0.0f; for (int i = 0; i < (int)fancy_nodes.size() - 1; i++) { float dx = fancy_nodes[i + 1].first - fancy_nodes[i].first; float dy = fancy_nodes[i + 1].second - fancy_nodes[i].second; length += sqrtf(dx * dx + dy * dy); } if (length < 0.001f) length = 0.001f; float width = kLineWidth * 2.0f; glBegin(GL_QUADS); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Start is just a point int index = 0; glTexCoord2f(0.0f, 1.0f); // top glVertex3f(fancy_nodes[index].first, fancy_nodes[index].second, 0.9f); glTexCoord2f(0.0f, 1.0f); // bottom glVertex3f(fancy_nodes[index].first, fancy_nodes[index].second, 0.9f); // Draw middle lines float current_length = 0.0f; for (int i = 1; i < (int)fancy_nodes.size() - 1; i++) { float dif_x = fancy_nodes[i + 1].first - fancy_nodes[i - 1].first; float dif_y = fancy_nodes[i + 1].second - fancy_nodes[i - 1].second; float dx = fancy_nodes[i].first - fancy_nodes[i - 1].first; float dy = fancy_nodes[i].second - fancy_nodes[i - 1].second; current_length += sqrtf(dx * dx + dy * dy); //float t = 2.0f * current_length / length; //if (t > 1.0f) t = 2.0f - t; float t = current_length / length; if (t > 1.0f) t = 1.0f; t = 0.5f * t + 0.5f * t * t; t = t * t; t = sin(t * 3.1415f); float current_width = width * t; if (current_width < kMinLineWidth) current_width = kMinLineWidth; float normal_x = -dif_y; float normal_y = dif_x; float inv_normal_length = 1.0f / sqrtf(normal_x * normal_x + normal_y * normal_y); normal_x *= inv_normal_length * current_width; normal_y *= inv_normal_length * current_width; float up_x = fancy_nodes[i].first - normal_x; float up_y = fancy_nodes[i].second - normal_y; float down_x = fancy_nodes[i].first + normal_x; float down_y = fancy_nodes[i].second + normal_y; glTexCoord2f(0.5f, 0.0f); // bottom glVertex3f(down_x, down_y, 0.9f); glTexCoord2f(0.5f, 1.0f); // top glVertex3f(up_x, up_y, 0.9f); glTexCoord2f(0.5f, 1.0f); // top glVertex3f(up_x, up_y, 0.9f); glTexCoord2f(0.5f, 0.0f); // bottom glVertex3f(down_x, down_y, 0.9f); } // End is just a point index = fancy_nodes.size() - 1; glTexCoord2f(1.0f, 1.0f); // bottom glVertex3f(fancy_nodes[index].first, fancy_nodes[index].second, 0.9f); glTexCoord2f(1.0f, 1.0f); // top glVertex3f(fancy_nodes[index].first, fancy_nodes[index].second, 0.9f); glEnd(); } void Line::Draw(float alpha) { if (nodes_.size() < 2) return; glBegin(GL_QUADS); float color_alpha = (alpha - 0.3f) / 0.7f; glColor4f(color_alpha * color_alpha, color_alpha, 1.0f, alpha); // Start is just a point int index = 0; glTexCoord2f(0.0f, 1.0f); // top glVertex3f(nodes_[index].first, nodes_[index].second, 0.9f); glTexCoord2f(0.0f, 1.0f); // bottom glVertex3f(nodes_[index].first, nodes_[index].second, 0.9f); // Draw middle lines for (int i = 1; i < (int)nodes_.size() - 1; i++) { float dif_x = nodes_[i + 1].first - nodes_[i - 1].first; float dif_y = nodes_[i + 1].second - nodes_[i - 1].second; float normal_x = -dif_y; float normal_y = dif_x; float inv_normal_length = 1.0f / sqrtf(normal_x * normal_x + normal_y * normal_y); normal_x *= inv_normal_length * kLineWidth; normal_y *= inv_normal_length * kLineWidth; float up_x = nodes_[i].first - normal_x; float up_y = nodes_[i].second - normal_y; float down_x = nodes_[i].first + normal_x; float down_y = nodes_[i].second + normal_y; glTexCoord2f(0.5f, 0.0f); // bottom glVertex3f(down_x, down_y, 0.9f); glTexCoord2f(0.5f, 1.0f); // top glVertex3f(up_x, up_y, 0.9f); glTexCoord2f(0.5f, 1.0f); // top glVertex3f(up_x, up_y, 0.9f); glTexCoord2f(0.5f, 0.0f); // bottom glVertex3f(down_x, down_y, 0.9f); } // End is just a point index = nodes_.size() - 1; glTexCoord2f(1.0f, 1.0f); // bottom glVertex3f(nodes_[index].first, nodes_[index].second, 0.9f); glTexCoord2f(1.0f, 1.0f); // top glVertex3f(nodes_[index].first, nodes_[index].second, 0.9f); glEnd(); } <commit_msg>Think line part on the other end<commit_after>#include "stdafx.h" #include "Line.h" const float Line::kLineWidth = 0.0025f; const float Line::kMinLineWidth = 0.001f; const float Line::kNeighborInterpolationDistance = 0.03f; Line::Line() { } Line::~Line() { } void Line::AddNode(float x, float y) { nodes_.push_back(std::make_pair(x, y)); } int Line::Save(FILE * file) { fwrite(&kMagicNumber, sizeof(kMagicNumber), 1, file); int num_elements = nodes_.size(); fwrite(&num_elements, sizeof(num_elements), 1, file); for (int i = 0; i < num_elements; i++) { fwrite(&(nodes_[i].first), sizeof(float), 1, file); fwrite(&(nodes_[i].second), sizeof(float), 1, file); } return 0; } int Line::Load(FILE * file) { unsigned int ref_val; fread(&ref_val, sizeof(ref_val), 1, file); if (ref_val != kMagicNumber) { // Not the correct thing. return -1; } int num_elements; fread(&num_elements, sizeof(num_elements), 1, file); for (int i = 0; i < num_elements; i++) { float pos[2]; fread(pos, sizeof(float), 2, file); AddNode(pos[0], pos[1]); } return 0; } void Line::DrawFancy(void) { if (nodes_.size() < 2) return; // Create fancy nodes by interpolating borders std::vector< std::pair<float, float> >fancy_nodes; for (int i = 0; i < (int)nodes_.size(); i++) { fancy_nodes.push_back(nodes_[i]); } #if 0 for (int i = 0; i < (int)nodes_.size(); i++) { // Check how much weight I get total float weight = 0.0f; for (int j = 0; j < (int)nodes_.size(); j++) { float dx = nodes_[i].first - nodes_[j].first; float dy = nodes_[i].second - nodes_[j].second; float dist = sqrtf(dx * dx + dy * dy); float amount = kNeighborInterpolationDistance - dist; if (amount < 0.0f) amount = 0.0f; weight += amount; } // Interpolate fancy_nodes[i].first = 0; fancy_nodes[i].second = 0; for (int j = 0; j < (int)nodes_.size(); j++) { float dx = nodes_[i].first - nodes_[j].first; float dy = nodes_[i].second - nodes_[j].second; float dist = sqrtf(dx * dx + dy * dy); float amount = kNeighborInterpolationDistance - dist; if (amount < 0.0f) amount = 0.0f; fancy_nodes[i].first += amount * nodes_[j].first / weight; fancy_nodes[i].second += amount * nodes_[j].second / weight; } } #endif // Get the length of the line float length = 0.0f; for (int i = 0; i < (int)fancy_nodes.size() - 1; i++) { float dx = fancy_nodes[i + 1].first - fancy_nodes[i].first; float dy = fancy_nodes[i + 1].second - fancy_nodes[i].second; length += sqrtf(dx * dx + dy * dy); } if (length < 0.001f) length = 0.001f; float width = kLineWidth * 2.0f; glBegin(GL_QUADS); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Start is just a point int index = 0; glTexCoord2f(0.0f, 1.0f); // top glVertex3f(fancy_nodes[index].first, fancy_nodes[index].second, 0.9f); glTexCoord2f(0.0f, 1.0f); // bottom glVertex3f(fancy_nodes[index].first, fancy_nodes[index].second, 0.9f); // Draw middle lines float current_length = 0.0f; for (int i = 1; i < (int)fancy_nodes.size() - 1; i++) { float dif_x = fancy_nodes[i + 1].first - fancy_nodes[i - 1].first; float dif_y = fancy_nodes[i + 1].second - fancy_nodes[i - 1].second; float dx = fancy_nodes[i].first - fancy_nodes[i - 1].first; float dy = fancy_nodes[i].second - fancy_nodes[i - 1].second; current_length += sqrtf(dx * dx + dy * dy); //float t = 2.0f * current_length / length; //if (t > 1.0f) t = 2.0f - t; float t = 1.0f - current_length / length; if (t > 1.0f) t = 1.0f; t = 0.5f * t + 0.5f * t * t; t = t * t; t = sin(t * 3.1415f); float current_width = width * t; if (current_width < kMinLineWidth) current_width = kMinLineWidth; float normal_x = -dif_y; float normal_y = dif_x; float inv_normal_length = 1.0f / sqrtf(normal_x * normal_x + normal_y * normal_y); normal_x *= inv_normal_length * current_width; normal_y *= inv_normal_length * current_width; float up_x = fancy_nodes[i].first - normal_x; float up_y = fancy_nodes[i].second - normal_y; float down_x = fancy_nodes[i].first + normal_x; float down_y = fancy_nodes[i].second + normal_y; glTexCoord2f(0.5f, 0.0f); // bottom glVertex3f(down_x, down_y, 0.9f); glTexCoord2f(0.5f, 1.0f); // top glVertex3f(up_x, up_y, 0.9f); glTexCoord2f(0.5f, 1.0f); // top glVertex3f(up_x, up_y, 0.9f); glTexCoord2f(0.5f, 0.0f); // bottom glVertex3f(down_x, down_y, 0.9f); } // End is just a point index = fancy_nodes.size() - 1; glTexCoord2f(1.0f, 1.0f); // bottom glVertex3f(fancy_nodes[index].first, fancy_nodes[index].second, 0.9f); glTexCoord2f(1.0f, 1.0f); // top glVertex3f(fancy_nodes[index].first, fancy_nodes[index].second, 0.9f); glEnd(); } void Line::Draw(float alpha) { if (nodes_.size() < 2) return; glBegin(GL_QUADS); float color_alpha = (alpha - 0.3f) / 0.7f; glColor4f(color_alpha * color_alpha, color_alpha, 1.0f, alpha); // Start is just a point int index = 0; glTexCoord2f(0.0f, 1.0f); // top glVertex3f(nodes_[index].first, nodes_[index].second, 0.9f); glTexCoord2f(0.0f, 1.0f); // bottom glVertex3f(nodes_[index].first, nodes_[index].second, 0.9f); // Draw middle lines for (int i = 1; i < (int)nodes_.size() - 1; i++) { float dif_x = nodes_[i + 1].first - nodes_[i - 1].first; float dif_y = nodes_[i + 1].second - nodes_[i - 1].second; float normal_x = -dif_y; float normal_y = dif_x; float inv_normal_length = 1.0f / sqrtf(normal_x * normal_x + normal_y * normal_y); normal_x *= inv_normal_length * kLineWidth; normal_y *= inv_normal_length * kLineWidth; float up_x = nodes_[i].first - normal_x; float up_y = nodes_[i].second - normal_y; float down_x = nodes_[i].first + normal_x; float down_y = nodes_[i].second + normal_y; glTexCoord2f(0.5f, 0.0f); // bottom glVertex3f(down_x, down_y, 0.9f); glTexCoord2f(0.5f, 1.0f); // top glVertex3f(up_x, up_y, 0.9f); glTexCoord2f(0.5f, 1.0f); // top glVertex3f(up_x, up_y, 0.9f); glTexCoord2f(0.5f, 0.0f); // bottom glVertex3f(down_x, down_y, 0.9f); } // End is just a point index = nodes_.size() - 1; glTexCoord2f(1.0f, 1.0f); // bottom glVertex3f(nodes_[index].first, nodes_[index].second, 0.9f); glTexCoord2f(1.0f, 1.0f); // top glVertex3f(nodes_[index].first, nodes_[index].second, 0.9f); glEnd(); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <ctime> //for seeding srand #define WORDLIST_LENGTH 20 #define MAX_INCORRECT_GUESSES 6 using namespace std; enum EGameState : int { WaitingToStart, InProgress, Over }; //draws the current state of the hangman void DrawHangman(int IncorrectGuesses) { //draw hangman char Face = (IncorrectGuesses > 0) ? 'O' : ' '; char Torso = (IncorrectGuesses > 1) ? '|' : ' '; char ArmR = (IncorrectGuesses > 2) ? '/' : ' '; char ArmL = (IncorrectGuesses > 3) ? '\\' : ' '; char LegR = (IncorrectGuesses > 4) ? '/' : ' '; char LegL = (IncorrectGuesses > 5) ? '\\' : ' '; cout << endl << "\t +----+" << endl << "\t | |" << endl << "\t " << Face << " |" << endl << "\t " << ArmR << Torso << ArmL << " |" << endl << "\t " << LegR << " " << LegL << " |" << endl << "\t |" << endl << "\t==========" << endl << endl; } //print guesses void PrintGuesses(string &ChosenWord, string &CorrectGuesses, string &IncorrectGuesses) { cout << "Word: "; for (int i = 0; i < ChosenWord.length(); i++) { if (CorrectGuesses.find(ChosenWord[i]) != string::npos) { cout << ChosenWord[i] << " "; } else { cout << "_ "; } } cout << endl << endl; cout << "Incorrect Guesses: " << endl; for (int i = 0; i < IncorrectGuesses.length(); i++) { cout << IncorrectGuesses[i] << " "; } cout << endl; } //determines if the player's guess was correct or not void HandlePlayerGuess(char PlayerGuess, string ChosenWord, string *CorrectGuesses, string *IncorrectGuesses) { //see if we've guessed this letter already if (CorrectGuesses->find(PlayerGuess) != string::npos || IncorrectGuesses->find(PlayerGuess) != string::npos) { cout << "You've already guessed " << PlayerGuess << "!" << endl; cout << "Try again." << endl; } else if (ChosenWord.find(PlayerGuess) != string::npos) { //letter is in word cout << "Correct! There is a " << PlayerGuess << " in the word." << endl; *CorrectGuesses += PlayerGuess; } else { //letter is not in word cout << "WROOONG" << endl; *IncorrectGuesses += PlayerGuess; } } int main() { cout << "Hangman!" << endl << endl; EGameState GameState = EGameState::WaitingToStart; //20 most common english words over 3 letters long string Worldlist[WORDLIST_LENGTH] = { "time", "year", "people", "thing", "woman", "life", "child", "world", "school", "state", "family", "student", "group", "country", "problem", "hand", "part", "place", "case", "week" }; //choose a random word within that list srand(time(0)); string ChosenWord = Worldlist[rand() % int(WORDLIST_LENGTH)]; string CorrectGuesses; string IncorrectGuesses; //start game GameState = EGameState::InProgress; bool bWonLastGame = false; //game loop while (GameState == InProgress) { system("cls"); //windows-only, sorry; //update the player on how they're doing DrawHangman(IncorrectGuesses.length()); PrintGuesses(ChosenWord, CorrectGuesses, IncorrectGuesses); //cout << " ((DEBUG)) word is: " << ChosenWord << endl; cout << "Make a guess: "; string PlayerGuess; getline(cin, PlayerGuess); HandlePlayerGuess(PlayerGuess[0], ChosenWord, &CorrectGuesses, &IncorrectGuesses); if (IncorrectGuesses.length() >= MAX_INCORRECT_GUESSES) { GameState = EGameState::Over; bWonLastGame = false; } else if (CorrectGuesses.length() == ChosenWord.length()) { GameState = EGameState::Over; bWonLastGame = true; } } //draw end screen system("cls"); DrawHangman(IncorrectGuesses.length()); cout << endl << "Game over: " << (bWonLastGame ? "You won!" : "You lost.") << endl; if (!bWonLastGame) { cout << "The word was \"" << ChosenWord << "\"." << endl; } cout << "Want to try again? "; cout << endl << endl; } <commit_msg>added 20 more words, spiced up intro a little<commit_after>#include <iostream> #include <string> #include <ctime> //for seeding srand #define WORDLIST_LENGTH 40 #define MAX_INCORRECT_GUESSES 6 using namespace std; enum EGameState : int { WaitingToStart, InProgress, Over }; //draws the current state of the hangman void DrawHangman(int IncorrectGuesses) { //draw hangman char Face = (IncorrectGuesses > 0) ? 'O' : ' '; char Torso = (IncorrectGuesses > 1) ? '|' : ' '; char ArmR = (IncorrectGuesses > 2) ? '/' : ' '; char ArmL = (IncorrectGuesses > 3) ? '\\' : ' '; char LegR = (IncorrectGuesses > 4) ? '/' : ' '; char LegL = (IncorrectGuesses > 5) ? '\\' : ' '; cout << endl << "\t +----+" << endl << "\t | |" << endl << "\t " << Face << " |" << endl << "\t " << ArmR << Torso << ArmL << " |" << endl << "\t " << LegR << " " << LegL << " |" << endl << "\t |" << endl << "\t==========" << endl << endl; } //print guesses void PrintGuesses(string &ChosenWord, string &CorrectGuesses, string &IncorrectGuesses) { cout << "Word: "; for (int i = 0; i < ChosenWord.length(); i++) { if (CorrectGuesses.find(ChosenWord[i]) != string::npos) { cout << ChosenWord[i] << " "; } else { cout << "_ "; } } cout << endl << endl; cout << "Incorrect Guesses: " << endl; for (int i = 0; i < IncorrectGuesses.length(); i++) { cout << IncorrectGuesses[i] << " "; } cout << endl; } //determines if the player's guess was correct or not void HandlePlayerGuess(char PlayerGuess, string ChosenWord, string *CorrectGuesses, string *IncorrectGuesses) { //see if we've guessed this letter already if (CorrectGuesses->find(PlayerGuess) != string::npos || IncorrectGuesses->find(PlayerGuess) != string::npos) { cout << "You've already guessed " << PlayerGuess << "!" << endl; cout << "Try again." << endl; } else if (ChosenWord.find(PlayerGuess) != string::npos) { //letter is in word cout << "Correct! There is a " << PlayerGuess << " in the word." << endl; *CorrectGuesses += PlayerGuess; } else { //letter is not in word cout << "WROOONG" << endl; *IncorrectGuesses += PlayerGuess; } } int main() { cout << endl << " ==========" << endl << " Hangman!" << endl << " ==========" << endl << endl; EGameState GameState = EGameState::WaitingToStart; //40 most common english nouns over 3 letters long string Worldlist[WORDLIST_LENGTH] = { "time", "year", "people", "thing", "woman", "life", "child", "world", "school", "state", "family", "student", "group", "country", "problem", "hand", "part", "place", "case", "week", "company", "system", "issue", "side", "kind", "head", "house", "service", "friend", "father", "power", "hour", "game", "line", "member", "city", "community", "name", "president", "team" }; //load notification with title cout << "Loaded default wordlist: " << endl << "\"Top 40 Most Common English Nouns Over 3 Letters Long\"." << endl; //choose a random word within that list cout << endl << "I'm thinking of a word..." << endl; srand(time(0)); string ChosenWord = Worldlist[rand() % int(WORDLIST_LENGTH)]; string CorrectGuesses; string IncorrectGuesses; cout << "Okay, I've got it!" << endl; cout << endl << endl; system("pause"); //start game GameState = EGameState::InProgress; bool bWonLastGame = false; //game loop while (GameState == InProgress) { system("cls"); //windows-only, sorry; //update the player on how they're doing DrawHangman(IncorrectGuesses.length()); PrintGuesses(ChosenWord, CorrectGuesses, IncorrectGuesses); //cout << " ((DEBUG)) word is: " << ChosenWord << endl; cout << "Make a guess: "; string PlayerGuess; getline(cin, PlayerGuess); HandlePlayerGuess(PlayerGuess[0], ChosenWord, &CorrectGuesses, &IncorrectGuesses); if (IncorrectGuesses.length() >= MAX_INCORRECT_GUESSES) { GameState = EGameState::Over; bWonLastGame = false; } else if (CorrectGuesses.length() == ChosenWord.length()) { GameState = EGameState::Over; bWonLastGame = true; } } //draw end screen system("cls"); DrawHangman(IncorrectGuesses.length()); cout << endl << "Game over: " << (bWonLastGame ? "You won!" : "You lost.") << endl; if (!bWonLastGame) { cout << "The word was \"" << ChosenWord << "\"." << endl; } cout << "Want to try again? "; cout << endl << endl; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tablecontainer.hxx,v $ * * $Revision: 1.23 $ * * last change: $Author: rt $ $Date: 2004-10-22 09:00:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBA_CORE_TABLECONTAINER_HXX_ #define _DBA_CORE_TABLECONTAINER_HXX_ #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_ #include <com/sun/star/util/XRefreshable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_ #include <com/sun/star/container/XContainerListener.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX #include "FilteredContainer.hxx" #endif #ifndef DBA_CORE_WARNINGS_HXX #include "warnings.hxx" #endif #ifndef DBA_CORE_REFRESHLISTENER_HXX #include "RefreshListener.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif namespace dbaccess { typedef ::cppu::ImplHelper1< ::com::sun::star::container::XContainerListener> OTableContainer_Base; //========================================================================== //= OTableContainer //========================================================================== class OTable; class OTableContainer; class OContainerMediator; class OTableContainer : public OFilteredContainer, public OTableContainer_Base { protected: ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xTableDefinitions; ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener > m_xTableMediator; OContainerMediator* m_pMediator; sal_Bool m_bInAppend; // true when we are in append mode sal_Bool m_bInDrop; // set when we are in the drop method // OFilteredContainer virtual void addMasterContainerListener(); virtual void removeMasterContainerListener(); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > getTableTypeFilter(const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter) const; // ::connectivity::sdbcx::OCollection virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed > createObject(const ::rtl::OUString& _rName); virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createEmptyObject(); virtual void appendObject( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ); virtual void dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName); virtual sal_Bool isNameValid(const ::rtl::OUString& _rName, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableFilter, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter, const ::std::vector< WildCard >& _rWCSearch) const; virtual void SAL_CALL disposing(); virtual void notifyDataSourceModified(); public: /** ctor of the container. The parent has to support the <type scope="com::sun::star::sdbc">XConnection</type> interface.<BR> @param _rParent the object which acts as parent for the container. all refcounting is rerouted to this object @param _rMutex the access safety object of the parent @param _rTableFilter restricts the visible tables by name @param _rTableTypeFilter restricts the visible tables by type @see construct */ OTableContainer( ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xCon, sal_Bool _bCase, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >& _xTableDefinitions, IRefreshListener* _pRefreshListener = NULL, IWarningsContainer* _pWarningsContainer = NULL ); virtual ~OTableContainer(); inline virtual void SAL_CALL acquire() throw(){ OFilteredContainer::acquire();} inline virtual void SAL_CALL release() throw(){ OFilteredContainer::release();} // ::com::sun::star::lang::XServiceInfo DECLARE_SERVICE_INFO(); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException); // XContainerListener virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException); }; } #endif // _DBA_CORE_TABLECONTAINER_HXX_ <commit_msg>INTEGRATION: CWS dba24 (1.23.50); FILE MERGED 2005/02/10 16:57:14 fs 1.23.50.2: #i15113# introduce a data-source-setting which controls which TableTypeFilter to use to obtain *all* tables - IBM's Universe database doesn't like our default behaviour 2005/02/09 08:13:00 oj 1.23.50.1: #i26950# remove the need for XNamed<commit_after>/************************************************************************* * * $RCSfile: tablecontainer.hxx,v $ * * $Revision: 1.24 $ * * last change: $Author: vg $ $Date: 2005-03-10 16:37:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBA_CORE_TABLECONTAINER_HXX_ #define _DBA_CORE_TABLECONTAINER_HXX_ #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_ #include <com/sun/star/util/XRefreshable.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_ #include <com/sun/star/container/XContainerListener.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef DBACCESS_CORE_FILTERED_CONTAINER_HXX #include "FilteredContainer.hxx" #endif #ifndef DBA_CORE_WARNINGS_HXX #include "warnings.hxx" #endif #ifndef DBA_CORE_REFRESHLISTENER_HXX #include "RefreshListener.hxx" #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif namespace dbaccess { typedef ::cppu::ImplHelper1< ::com::sun::star::container::XContainerListener> OTableContainer_Base; //========================================================================== //= OTableContainer //========================================================================== class OTable; class OTableContainer; class OContainerMediator; class OTableContainer : public OFilteredContainer, public OTableContainer_Base { protected: ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xTableDefinitions; ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener > m_xTableMediator; OContainerMediator* m_pMediator; sal_Bool m_bInAppend; // true when we are in append mode sal_Bool m_bInDrop; // set when we are in the drop method // OFilteredContainer virtual void addMasterContainerListener(); virtual void removeMasterContainerListener(); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > getTableTypeFilter(const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter) const; // ::connectivity::sdbcx::OCollection virtual connectivity::sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createEmptyObject(); virtual void appendObject( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ); virtual void dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName); virtual sal_Bool isNameValid(const ::rtl::OUString& _rName, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableFilter, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rTableTypeFilter, const ::std::vector< WildCard >& _rWCSearch) const; virtual void SAL_CALL disposing(); virtual void notifyDataSourceModified(); /** retrieve a table type filter to pass to <member scope="com::sun::star::sdbc">XDatabaseMetaData::getTables</member>, according to the current data source settings */ void getAllTableTypeFilter( ::com::sun::star::uno::Sequence< ::rtl::OUString >& /* [out] */ _rFilter ) const; public: /** ctor of the container. The parent has to support the <type scope="com::sun::star::sdbc">XConnection</type> interface.<BR> @param _rParent the object which acts as parent for the container. all refcounting is rerouted to this object @param _rMutex the access safety object of the parent @param _rTableFilter restricts the visible tables by name @param _rTableTypeFilter restricts the visible tables by type @see construct */ OTableContainer( ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _xCon, sal_Bool _bCase, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >& _xTableDefinitions, IRefreshListener* _pRefreshListener = NULL, IWarningsContainer* _pWarningsContainer = NULL ); virtual ~OTableContainer(); inline virtual void SAL_CALL acquire() throw(){ OFilteredContainer::acquire();} inline virtual void SAL_CALL release() throw(){ OFilteredContainer::release();} // ::com::sun::star::lang::XServiceInfo DECLARE_SERVICE_INFO(); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException); // XContainerListener virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException); }; } #endif // _DBA_CORE_TABLECONTAINER_HXX_ <|endoftext|>
<commit_before>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@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. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopete.h" #include <dcopclient.h> #include "kopeteiface.h" #define KOPETE_VERSION "0.7.92 >= 20030922" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection." ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2003, Duncan Mac-Vicar Prett\n(c) 2002-2003, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, Developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Developer"), "klingens@kde.org" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Developer, MSN plugin maintainer"), "ogoffart@tiscalinet.be"); aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer, Oscar Maintainer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addAuthor ( "Gav Wood", I18N_NOOP("WinPopup plugin maintainer"), "gjw102@york.ac.uk" ); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin author"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Developer, Gadu plugin author"), "zack@kde.org" ); aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer, Oscar"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net"); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer, IRC maintainer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@pandora.be" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, icons, plugins"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Developer, Yahoo plugin maintainer"), "mattrogers@sbcglobal.net" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancelets"), "pfeiffer@kde.org" ); aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <commit_msg>version date bump<commit_after>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@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. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopete.h" #include <dcopclient.h> #include "kopeteiface.h" #define KOPETE_VERSION "0.7.92 >= 20031007" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection." ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2003, Duncan Mac-Vicar Prett\n(c) 2002-2003, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, Developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Developer"), "klingens@kde.org" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Developer, MSN plugin maintainer"), "ogoffart@tiscalinet.be"); aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer, Oscar Maintainer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addAuthor ( "Gav Wood", I18N_NOOP("WinPopup plugin maintainer"), "gjw102@york.ac.uk" ); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin author"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Developer, Gadu plugin author"), "zack@kde.org" ); aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer, Oscar"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net"); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer, IRC maintainer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@pandora.be" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, icons, plugins"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Developer, Yahoo plugin maintainer"), "mattrogers@sbcglobal.net" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancelets"), "pfeiffer@kde.org" ); aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/pipe.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_encoder_pipe.h> XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec) : encoder_(codec, this), input_buffer_(), input_eos_(false), output_action_(NULL), output_callback_(NULL) { } XCodecEncoderPipe::~XCodecEncoderPipe() { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); } Action * XCodecEncoderPipe::input(Buffer *buf, EventCallback *cb) { if (output_callback_ != NULL) { ASSERT(input_buffer_.empty()); ASSERT(output_action_ == NULL); if (!buf->empty()) { Buffer tmp; encoder_.encode(&tmp, buf); ASSERT(buf->empty()); output_callback_->event(Event(Event::Done, 0, tmp)); } else { input_eos_ = true; output_callback_->event(Event(Event::EOS, 0)); } output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } else { if (!buf->empty()) { encoder_.encode(&input_buffer_, buf); ASSERT(buf->empty()); } else { input_eos_ = true; } } cb->event(Event(Event::Done, 0)); return (EventSystem::instance()->schedule(cb)); } Action * XCodecEncoderPipe::output(EventCallback *cb) { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); if (!input_buffer_.empty() || input_eos_) { if (input_eos_) { cb->event(Event(Event::EOS, 0, input_buffer_)); if (!input_buffer_.empty()) input_buffer_.clear(); } else { cb->event(Event(Event::Done, 0, input_buffer_)); input_buffer_.clear(); } return (EventSystem::instance()->schedule(cb)); } output_callback_ = cb; return (cancellation(this, &XCodecEncoderPipe::output_cancel)); } void XCodecEncoderPipe::output_ready(void) { if (input_eos_) { ERROR("/xcodec/encoder/pipe") << "Ignoring spontaneous output after EOS."; return; } Buffer empty; encoder_.encode(&input_buffer_, &empty); ASSERT(!input_buffer_.empty()); if (output_callback_ != NULL) { ASSERT(output_action_ == NULL); output_callback_->event(Event(Event::Done, 0, input_buffer_)); input_buffer_.clear(); output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } } void XCodecEncoderPipe::output_cancel(void) { if (output_action_ != NULL) { ASSERT(output_callback_ == NULL); output_action_->cancel(); output_action_ = NULL; } if (output_callback_ != NULL) { delete output_callback_; output_callback_ = NULL; } } <commit_msg>Allow data at EOS to get queued data appended to it, too.<commit_after>#include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> #include <io/pipe.h> #include <xcodec/xcodec.h> #include <xcodec/xcodec_encoder.h> #include <xcodec/xcodec_encoder_pipe.h> XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec) : encoder_(codec, this), input_buffer_(), input_eos_(false), output_action_(NULL), output_callback_(NULL) { } XCodecEncoderPipe::~XCodecEncoderPipe() { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); } Action * XCodecEncoderPipe::input(Buffer *buf, EventCallback *cb) { if (output_callback_ != NULL) { ASSERT(input_buffer_.empty()); ASSERT(output_action_ == NULL); if (!buf->empty()) { Buffer tmp; encoder_.encode(&tmp, buf); ASSERT(buf->empty()); output_callback_->event(Event(Event::Done, 0, tmp)); } else { input_eos_ = true; output_callback_->event(Event(Event::EOS, 0)); } output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } else { if (!buf->empty()) { encoder_.encode(&input_buffer_, buf); ASSERT(buf->empty()); } else { input_eos_ = true; } } cb->event(Event(Event::Done, 0)); return (EventSystem::instance()->schedule(cb)); } Action * XCodecEncoderPipe::output(EventCallback *cb) { ASSERT(output_action_ == NULL); ASSERT(output_callback_ == NULL); if (!input_buffer_.empty() || input_eos_) { if (input_eos_) { cb->event(Event(Event::EOS, 0, input_buffer_)); if (!input_buffer_.empty()) input_buffer_.clear(); } else { cb->event(Event(Event::Done, 0, input_buffer_)); input_buffer_.clear(); } return (EventSystem::instance()->schedule(cb)); } output_callback_ = cb; return (cancellation(this, &XCodecEncoderPipe::output_cancel)); } void XCodecEncoderPipe::output_ready(void) { if (input_eos_) { if (input_buffer_.empty()) { ERROR("/xcodec/encoder/pipe") << "Ignoring spontaneous output after EOS."; return; } DEBUG("/xcodec/encoder/pipe") << "Retrieving spontaneous data along with buffered data at EOS."; } Buffer empty; encoder_.encode(&input_buffer_, &empty); ASSERT(!input_buffer_.empty()); if (output_callback_ != NULL) { /* * If EOS has come, we can only get here if it is being serviced * and there is data pending to be pushed before EOS. Make sure * that's the case. */ ASSERT(!input_eos_); ASSERT(output_action_ == NULL); output_callback_->event(Event(Event::Done, 0, input_buffer_)); input_buffer_.clear(); output_action_ = EventSystem::instance()->schedule(output_callback_); output_callback_ = NULL; } } void XCodecEncoderPipe::output_cancel(void) { if (output_action_ != NULL) { ASSERT(output_callback_ == NULL); output_action_->cancel(); output_action_ = NULL; } if (output_callback_ != NULL) { delete output_callback_; output_callback_ = NULL; } } <|endoftext|>
<commit_before>// ascii plain text // Licence: Lesser GNU Public License 2.1 (LGPL) #define BUILDING_XYLIB #include "text.h" #include <cstdlib> #include "util.h" using namespace std; using namespace xylib::util; namespace xylib { const FormatInfo TextDataSet::fmt_info( "text", "ascii text", "", // "txt dat asc", false, // whether binary false, // whether has multi-blocks &TextDataSet::ctor, &TextDataSet::check ); bool TextDataSet::is_valid_option(std::string const& t) { return t == "strict" || t == "first-line-header" || t == "last-line-header" || t == "decimal-comma"; } bool TextDataSet::check(istream & /*f*/, string*) { return true; } namespace { // the title-line is either a name of block or contains names of columns // we assume that it's the latter if the number of words is the same // as number of columns void use_title_line(string const& line, vector<VecColumn*> &cols, Block* blk) { const char* delim = " \t"; vector<string> words; std::string::size_type pos = 0; while (pos != std::string::npos) { std::string::size_type start_pos = line.find_first_not_of(delim, pos); pos = line.find_first_of(delim, start_pos); words.push_back(std::string(line, start_pos, pos-start_pos)); } if (words.size() == cols.size()) { for (size_t i = 0; i < words.size(); ++i) cols[i]->set_name(words[i]); } else blk->set_name(line); } void replace_commas_with_dots(string &s) { for (string::iterator p = s.begin(); p != s.end(); ++p) if (*p == ',') *p = '.'; } } // anonymous namespace void TextDataSet::load_data(std::istream &f) { vector<VecColumn*> cols; vector<double> row; // temporary storage for values from one line string title_line; string s; bool strict = has_option("strict"); bool first_line_header = has_option("first-line-header"); // header is in last comment line - the line before the first data line bool last_line_header = has_option("last-line-header"); bool decimal_comma = has_option("decimal-comma"); if (first_line_header) { title_line = str_trim(read_line(f)); if (!title_line.empty() && title_line[0] == '#') title_line = title_line.substr(1); } // read lines until the first data line is read and columns are created string last_line; while (getline(f, s)) { // Basic support for LAMMPS log file. // There is a chance that output from thermo command will be read // properly, but because the LAMMPS log file doesn't have // a well-defined syntax, it can not be guaranteed. // All data blocks (numeric lines after `run' command) should have // the same columns (do not use thermo_style/thermo_modify between // runs). if (!strict && str_startwith(s, "LAMMPS (")) { last_line_header = true; continue; } if (decimal_comma) replace_commas_with_dots(s); const char *p = read_numbers(s, row); // We skip lines with no data. // If there is only one number in first line, skip it if there // is a text after the number. if (row.size() > 1 || (row.size() == 1 && (strict || *p == '\0' || *p == '#'))) { // columns initialization for (size_t i = 0; i != row.size(); ++i) { cols.push_back(new VecColumn); cols[i]->add_val(row[i]); } break; } if (last_line_header) { string t = str_trim(s); if (!t.empty()) last_line = (t[0] != '#' ? t : t.substr(1)); } } // read all the next data lines (the first data line was read above) while (getline(f, s)) { if (decimal_comma) replace_commas_with_dots(s); read_numbers(s, row); // We silently skip lines with no data. if (row.empty()) continue; if (row.size() < cols.size()) { // Some non-data lines may start with numbers. The example is // LAMMPS log file. The exceptions below are made to allow plotting // such a file. In strict mode, no exceptions are made. if (!strict) { // if it's the last line, we ignore the line if (f.eof()) break; // line with only one number is probably not a data line if (row.size() == 1) continue; // if it's the single line with smaller length, we ignore it vector<double> row2; getline(f, s); if (decimal_comma) replace_commas_with_dots(s); read_numbers(s, row2); if (row2.size() <= 1) continue; if (row2.size() < cols.size()) { // add the previous row for (size_t i = 0; i != row.size(); ++i) cols[i]->add_val(row[i]); // number of columns will be shrinked to the size of the // last row. If the previous row was shorter, shrink // the last row. if (row.size() < row2.size()) row2.resize(row.size()); } // if we are here, row2 needs to be stored row = row2; } // decrease the number of columns to the new minimum of numbers // in line for (size_t i = row.size(); i != cols.size(); ++i) delete cols[i]; cols.resize(row.size()); } else if (row.size() > cols.size()) { // Generally, we ignore extra columns. But if this is the second // data line, we ignore the first line instead. // Rationale: some data files have one or two numbers in the first // line, that can mean number of points or number of colums, and // the real data starts from the next line. if (cols[0]->get_point_count() == 1) { purge_all_elements(cols); for (size_t i = 0; i != row.size(); ++i) cols.push_back(new VecColumn); } } for (size_t i = 0; i != cols.size(); ++i) cols[i]->add_val(row[i]); } format_assert(this, cols.size() >= 1 && cols[0]->get_point_count() >= 2, "data not found in file."); Block* blk = new Block; for (unsigned i = 0; i < cols.size(); ++i) blk->add_column(cols[i]); if (!title_line.empty()) use_title_line(title_line, cols, blk); if (!last_line.empty()) use_title_line(last_line, cols, blk); add_block(blk); } } // end of namespace xylib <commit_msg>text.cpp: fixed bug that caused crash in some cases<commit_after>// ascii plain text // Licence: Lesser GNU Public License 2.1 (LGPL) #define BUILDING_XYLIB #include "text.h" #include <cstdlib> #include "util.h" using namespace std; using namespace xylib::util; namespace xylib { const FormatInfo TextDataSet::fmt_info( "text", "ascii text", "", // "txt dat asc", false, // whether binary false, // whether has multi-blocks &TextDataSet::ctor, &TextDataSet::check ); bool TextDataSet::is_valid_option(std::string const& t) { return t == "strict" || t == "first-line-header" || t == "last-line-header" || t == "decimal-comma"; } bool TextDataSet::check(istream & /*f*/, string*) { return true; } namespace { // the title-line is either a name of block or contains names of columns // we assume that it's the latter if the number of words is the same // as number of columns void use_title_line(string const& line, vector<VecColumn*> &cols, Block* blk) { const char* delim = " \t"; vector<string> words; std::string::size_type pos = 0; while (pos != std::string::npos) { std::string::size_type start_pos = line.find_first_not_of(delim, pos); pos = line.find_first_of(delim, start_pos); words.push_back(std::string(line, start_pos, pos-start_pos)); } if (words.size() == cols.size()) { for (size_t i = 0; i < words.size(); ++i) cols[i]->set_name(words[i]); } else blk->set_name(line); } void replace_commas_with_dots(string &s) { for (string::iterator p = s.begin(); p != s.end(); ++p) if (*p == ',') *p = '.'; } } // anonymous namespace void TextDataSet::load_data(std::istream &f) { vector<VecColumn*> cols; vector<double> row; // temporary storage for values from one line string title_line; string s; bool strict = has_option("strict"); bool first_line_header = has_option("first-line-header"); // header is in last comment line - the line before the first data line bool last_line_header = has_option("last-line-header"); bool decimal_comma = has_option("decimal-comma"); if (first_line_header) { title_line = str_trim(read_line(f)); if (!title_line.empty() && title_line[0] == '#') title_line = title_line.substr(1); } // read lines until the first data line is read and columns are created string last_line; while (getline(f, s)) { // Basic support for LAMMPS log file. // There is a chance that output from thermo command will be read // properly, but because the LAMMPS log file doesn't have // a well-defined syntax, it can not be guaranteed. // All data blocks (numeric lines after `run' command) should have // the same columns (do not use thermo_style/thermo_modify between // runs). if (!strict && str_startwith(s, "LAMMPS (")) { last_line_header = true; continue; } if (decimal_comma) replace_commas_with_dots(s); const char *p = read_numbers(s, row); // We skip lines with no data. // If there is only one number in first line, skip it if there // is a text after the number. if (row.size() > 1 || (row.size() == 1 && (strict || *p == '\0' || *p == '#'))) { // columns initialization for (size_t i = 0; i != row.size(); ++i) { cols.push_back(new VecColumn); cols[i]->add_val(row[i]); } break; } if (last_line_header) { string t = str_trim(s); if (!t.empty()) last_line = (t[0] != '#' ? t : t.substr(1)); } } // read all the next data lines (the first data line was read above) while (getline(f, s)) { if (decimal_comma) replace_commas_with_dots(s); read_numbers(s, row); // We silently skip lines with no data. if (row.empty()) continue; if (row.size() < cols.size()) { // Some non-data lines may start with numbers. The example is // LAMMPS log file. The exceptions below are made to allow plotting // such a file. In strict mode, no exceptions are made. if (!strict) { // if it's the last line, we ignore the line if (f.eof()) break; // line with only one number is probably not a data line if (row.size() == 1) continue; // if it's the single line with smaller length, we ignore it vector<double> row2; getline(f, s); if (decimal_comma) replace_commas_with_dots(s); read_numbers(s, row2); if (row2.size() <= 1) continue; if (row2.size() < cols.size()) { // add the previous row for (size_t i = 0; i != row.size(); ++i) cols[i]->add_val(row[i]); // number of columns will be shrinked to the size of the // last row. If the previous row was shorter, shrink // the last row. if (row.size() < row2.size()) row2.resize(row.size()); } // if we are here, row2 needs to be stored row = row2; } // this check is not redundant, row may have changed if (row.size() < cols.size()) { // decrease the number of columns to the new minimum for (size_t i = row.size(); i != cols.size(); ++i) delete cols[i]; cols.resize(row.size()); } } else if (row.size() > cols.size()) { // Generally, we ignore extra columns. But if this is the second // data line, we ignore the first line instead. // Rationale: some data files have one or two numbers in the first // line, that can mean number of points or number of colums, and // the real data starts from the next line. if (cols[0]->get_point_count() == 1) { purge_all_elements(cols); for (size_t i = 0; i != row.size(); ++i) cols.push_back(new VecColumn); } } for (size_t i = 0; i != cols.size(); ++i) cols[i]->add_val(row[i]); } format_assert(this, cols.size() >= 1 && cols[0]->get_point_count() >= 2, "data not found in file."); Block* blk = new Block; for (unsigned i = 0; i < cols.size(); ++i) blk->add_column(cols[i]); if (!title_line.empty()) use_title_line(title_line, cols, blk); if (!last_line.empty()) use_title_line(last_line, cols, blk); add_block(blk); } } // end of namespace xylib <|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 "remoting/host/screen_recorder.h" #include <algorithm> #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop_proxy.h" #include "base/stl_util.h" #include "base/sys_info.h" #include "base/time.h" #include "remoting/base/capture_data.h" #include "remoting/proto/control.pb.h" #include "remoting/proto/video.pb.h" #include "remoting/protocol/client_stub.h" #include "remoting/protocol/connection_to_client.h" #include "remoting/protocol/message_decoder.h" #include "remoting/protocol/util.h" using remoting::protocol::ConnectionToClient; namespace remoting { // Maximum number of frames that can be processed similtaneously. // TODO(hclam): Move this value to CaptureScheduler. static const int kMaxRecordings = 2; ScreenRecorder::ScreenRecorder( MessageLoop* capture_loop, MessageLoop* encode_loop, base::MessageLoopProxy* network_loop, Capturer* capturer, Encoder* encoder) : capture_loop_(capture_loop), encode_loop_(encode_loop), network_loop_(network_loop), capturer_(capturer), encoder_(encoder), is_recording_(false), network_stopped_(false), encoder_stopped_(false), max_recordings_(kMaxRecordings), recordings_(0), frame_skipped_(false), sequence_number_(0) { DCHECK(capture_loop_); DCHECK(encode_loop_); DCHECK(network_loop_); } ScreenRecorder::~ScreenRecorder() { } // Public methods -------------------------------------------------------------- void ScreenRecorder::Start() { capture_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoStart, this)); } void ScreenRecorder::Stop(const base::Closure& done_task) { if (MessageLoop::current() != capture_loop_) { capture_loop_->PostTask(FROM_HERE, base::Bind( &ScreenRecorder::Stop, this, done_task)); return; } DCHECK(!done_task.is_null()); capture_timer_.Stop(); is_recording_ = false; network_loop_->PostTask(FROM_HERE, base::Bind( &ScreenRecorder::DoStopOnNetworkThread, this, done_task)); } void ScreenRecorder::AddConnection(ConnectionToClient* connection) { DCHECK(network_loop_->BelongsToCurrentThread()); connections_.push_back(connection); capture_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoInvalidateFullScreen, this)); } void ScreenRecorder::RemoveConnection(ConnectionToClient* connection) { DCHECK(network_loop_->BelongsToCurrentThread()); ConnectionToClientList::iterator it = std::find(connections_.begin(), connections_.end(), connection); if (it != connections_.end()) { connections_.erase(it); } } void ScreenRecorder::RemoveAllConnections() { DCHECK(network_loop_->BelongsToCurrentThread()); connections_.clear(); } void ScreenRecorder::UpdateSequenceNumber(int64 sequence_number) { // Sequence number is used and written only on the capture thread. if (MessageLoop::current() != capture_loop_) { capture_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::UpdateSequenceNumber, this, sequence_number)); return; } sequence_number_ = sequence_number; } // Private accessors ----------------------------------------------------------- Capturer* ScreenRecorder::capturer() { DCHECK_EQ(capture_loop_, MessageLoop::current()); DCHECK(capturer_); return capturer_; } Encoder* ScreenRecorder::encoder() { DCHECK_EQ(encode_loop_, MessageLoop::current()); DCHECK(encoder_.get()); return encoder_.get(); } // Capturer thread ------------------------------------------------------------- void ScreenRecorder::DoStart() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (is_recording_) { NOTREACHED() << "Record session already started."; return; } is_recording_ = true; // Capture first frame immedately. DoCapture(); } void ScreenRecorder::StartCaptureTimer() { DCHECK_EQ(capture_loop_, MessageLoop::current()); capture_timer_.Start(FROM_HERE, scheduler_.NextCaptureDelay(), this, &ScreenRecorder::DoCapture); } void ScreenRecorder::DoCapture() { DCHECK_EQ(capture_loop_, MessageLoop::current()); // Make sure we have at most two oustanding recordings. We can simply return // if we can't make a capture now, the next capture will be started by the // end of an encode operation. if (recordings_ >= max_recordings_ || !is_recording_) { frame_skipped_ = true; return; } if (frame_skipped_) frame_skipped_ = false; // At this point we are going to perform one capture so save the current time. ++recordings_; DCHECK_LE(recordings_, max_recordings_); // Before doing a capture schedule for the next one. capture_timer_.Stop(); capture_timer_.Start(FROM_HERE, scheduler_.NextCaptureDelay(), this, &ScreenRecorder::DoCapture); // And finally perform one capture. capture_start_time_ = base::Time::Now(); capturer()->CaptureInvalidRegion( base::Bind(&ScreenRecorder::CaptureDoneCallback, this)); } void ScreenRecorder::CaptureDoneCallback( scoped_refptr<CaptureData> capture_data) { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (!is_recording_) return; if (capture_data) { base::TimeDelta capture_time = base::Time::Now() - capture_start_time_; int capture_time_ms = static_cast<int>(capture_time.InMilliseconds()); capture_data->set_capture_time_ms(capture_time_ms); scheduler_.RecordCaptureTime(capture_time); // The best way to get this value is by binding the sequence number to // the callback when calling CaptureInvalidRects(). However the callback // system doesn't allow this. Reading from the member variable is // accurate as long as capture is synchronous as the following statement // will obtain the most recent sequence number received. capture_data->set_client_sequence_number(sequence_number_); } encode_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoEncode, this, capture_data)); } void ScreenRecorder::DoFinishOneRecording() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (!is_recording_) return; // Decrement the number of recording in process since we have completed // one cycle. --recordings_; DCHECK_GE(recordings_, 0); // Try to do a capture again only if |frame_skipped_| is set to true by // capture timer. if (frame_skipped_) DoCapture(); } void ScreenRecorder::DoInvalidateFullScreen() { DCHECK_EQ(capture_loop_, MessageLoop::current()); capturer_->InvalidateFullScreen(); } // Network thread -------------------------------------------------------------- void ScreenRecorder::DoSendVideoPacket(scoped_ptr<VideoPacket> packet) { DCHECK(network_loop_->BelongsToCurrentThread()); if (network_stopped_ || connections_.empty()) return; // TODO(sergeyu): Currently we send the data only to the first // connection. Send it to all connections if necessary. connections_.front()->video_stub()->ProcessVideoPacket( packet.get(), base::Bind( &ScreenRecorder::VideoPacketSentCallback, this, base::Passed(packet.Pass()))); } void ScreenRecorder::VideoPacketSentCallback(scoped_ptr<VideoPacket> packet) { if (network_stopped_) return; if ((packet->flags() & VideoPacket::LAST_PARTITION) != 0) { // Post DoFinishOneRecording() if that was the last packet for the // frame. capture_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoFinishOneRecording, this)); } } void ScreenRecorder::DoStopOnNetworkThread(const base::Closure& done_task) { DCHECK(network_loop_->BelongsToCurrentThread()); // There could be tasks on the network thread when this method is being // executed. By setting the flag we'll not post anymore tasks from network // thread. // // After that a task is posted on encode thread to continue the stop // sequence. network_stopped_ = true; encode_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoStopOnEncodeThread, this, done_task)); } // Encoder thread -------------------------------------------------------------- void ScreenRecorder::DoEncode( scoped_refptr<CaptureData> capture_data) { DCHECK_EQ(encode_loop_, MessageLoop::current()); // Early out if there's nothing to encode. if (!capture_data || capture_data->dirty_region().isEmpty()) { // Send an empty video packet to keep network active. scoped_ptr<VideoPacket> packet(new VideoPacket()); packet->set_flags(VideoPacket::LAST_PARTITION); network_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoSendVideoPacket, this, base::Passed(packet.Pass()))); return; } encode_start_time_ = base::Time::Now(); encoder()->Encode( capture_data, false, base::Bind(&ScreenRecorder::EncodedDataAvailableCallback, this)); } void ScreenRecorder::DoStopOnEncodeThread(const base::Closure& done_task) { DCHECK_EQ(encode_loop_, MessageLoop::current()); encoder_stopped_ = true; // When this method is being executed there are no more tasks on encode thread // for this object. We can then post a task to capture thread to finish the // stop sequence. capture_loop_->PostTask(FROM_HERE, done_task); } void ScreenRecorder::EncodedDataAvailableCallback( scoped_ptr<VideoPacket> packet) { DCHECK_EQ(encode_loop_, MessageLoop::current()); if (encoder_stopped_) return; bool last = (packet->flags() & VideoPacket::LAST_PACKET) != 0; if (last) { base::TimeDelta encode_time = base::Time::Now() - encode_start_time_; int encode_time_ms = static_cast<int>(encode_time.InMilliseconds()); packet->set_encode_time_ms(encode_time_ms); scheduler_.RecordEncodeTime(encode_time); } network_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoSendVideoPacket, this, base::Passed(packet.Pass()))); } } // namespace remoting <commit_msg>Fix crash caused by r127767 due to undefined order of argument parsing.<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 "remoting/host/screen_recorder.h" #include <algorithm> #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop_proxy.h" #include "base/stl_util.h" #include "base/sys_info.h" #include "base/time.h" #include "remoting/base/capture_data.h" #include "remoting/proto/control.pb.h" #include "remoting/proto/video.pb.h" #include "remoting/protocol/client_stub.h" #include "remoting/protocol/connection_to_client.h" #include "remoting/protocol/message_decoder.h" #include "remoting/protocol/util.h" using remoting::protocol::ConnectionToClient; namespace remoting { // Maximum number of frames that can be processed similtaneously. // TODO(hclam): Move this value to CaptureScheduler. static const int kMaxRecordings = 2; ScreenRecorder::ScreenRecorder( MessageLoop* capture_loop, MessageLoop* encode_loop, base::MessageLoopProxy* network_loop, Capturer* capturer, Encoder* encoder) : capture_loop_(capture_loop), encode_loop_(encode_loop), network_loop_(network_loop), capturer_(capturer), encoder_(encoder), is_recording_(false), network_stopped_(false), encoder_stopped_(false), max_recordings_(kMaxRecordings), recordings_(0), frame_skipped_(false), sequence_number_(0) { DCHECK(capture_loop_); DCHECK(encode_loop_); DCHECK(network_loop_); } ScreenRecorder::~ScreenRecorder() { } // Public methods -------------------------------------------------------------- void ScreenRecorder::Start() { capture_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoStart, this)); } void ScreenRecorder::Stop(const base::Closure& done_task) { if (MessageLoop::current() != capture_loop_) { capture_loop_->PostTask(FROM_HERE, base::Bind( &ScreenRecorder::Stop, this, done_task)); return; } DCHECK(!done_task.is_null()); capture_timer_.Stop(); is_recording_ = false; network_loop_->PostTask(FROM_HERE, base::Bind( &ScreenRecorder::DoStopOnNetworkThread, this, done_task)); } void ScreenRecorder::AddConnection(ConnectionToClient* connection) { DCHECK(network_loop_->BelongsToCurrentThread()); connections_.push_back(connection); capture_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoInvalidateFullScreen, this)); } void ScreenRecorder::RemoveConnection(ConnectionToClient* connection) { DCHECK(network_loop_->BelongsToCurrentThread()); ConnectionToClientList::iterator it = std::find(connections_.begin(), connections_.end(), connection); if (it != connections_.end()) { connections_.erase(it); } } void ScreenRecorder::RemoveAllConnections() { DCHECK(network_loop_->BelongsToCurrentThread()); connections_.clear(); } void ScreenRecorder::UpdateSequenceNumber(int64 sequence_number) { // Sequence number is used and written only on the capture thread. if (MessageLoop::current() != capture_loop_) { capture_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::UpdateSequenceNumber, this, sequence_number)); return; } sequence_number_ = sequence_number; } // Private accessors ----------------------------------------------------------- Capturer* ScreenRecorder::capturer() { DCHECK_EQ(capture_loop_, MessageLoop::current()); DCHECK(capturer_); return capturer_; } Encoder* ScreenRecorder::encoder() { DCHECK_EQ(encode_loop_, MessageLoop::current()); DCHECK(encoder_.get()); return encoder_.get(); } // Capturer thread ------------------------------------------------------------- void ScreenRecorder::DoStart() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (is_recording_) { NOTREACHED() << "Record session already started."; return; } is_recording_ = true; // Capture first frame immedately. DoCapture(); } void ScreenRecorder::StartCaptureTimer() { DCHECK_EQ(capture_loop_, MessageLoop::current()); capture_timer_.Start(FROM_HERE, scheduler_.NextCaptureDelay(), this, &ScreenRecorder::DoCapture); } void ScreenRecorder::DoCapture() { DCHECK_EQ(capture_loop_, MessageLoop::current()); // Make sure we have at most two oustanding recordings. We can simply return // if we can't make a capture now, the next capture will be started by the // end of an encode operation. if (recordings_ >= max_recordings_ || !is_recording_) { frame_skipped_ = true; return; } if (frame_skipped_) frame_skipped_ = false; // At this point we are going to perform one capture so save the current time. ++recordings_; DCHECK_LE(recordings_, max_recordings_); // Before doing a capture schedule for the next one. capture_timer_.Stop(); capture_timer_.Start(FROM_HERE, scheduler_.NextCaptureDelay(), this, &ScreenRecorder::DoCapture); // And finally perform one capture. capture_start_time_ = base::Time::Now(); capturer()->CaptureInvalidRegion( base::Bind(&ScreenRecorder::CaptureDoneCallback, this)); } void ScreenRecorder::CaptureDoneCallback( scoped_refptr<CaptureData> capture_data) { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (!is_recording_) return; if (capture_data) { base::TimeDelta capture_time = base::Time::Now() - capture_start_time_; int capture_time_ms = static_cast<int>(capture_time.InMilliseconds()); capture_data->set_capture_time_ms(capture_time_ms); scheduler_.RecordCaptureTime(capture_time); // The best way to get this value is by binding the sequence number to // the callback when calling CaptureInvalidRects(). However the callback // system doesn't allow this. Reading from the member variable is // accurate as long as capture is synchronous as the following statement // will obtain the most recent sequence number received. capture_data->set_client_sequence_number(sequence_number_); } encode_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoEncode, this, capture_data)); } void ScreenRecorder::DoFinishOneRecording() { DCHECK_EQ(capture_loop_, MessageLoop::current()); if (!is_recording_) return; // Decrement the number of recording in process since we have completed // one cycle. --recordings_; DCHECK_GE(recordings_, 0); // Try to do a capture again only if |frame_skipped_| is set to true by // capture timer. if (frame_skipped_) DoCapture(); } void ScreenRecorder::DoInvalidateFullScreen() { DCHECK_EQ(capture_loop_, MessageLoop::current()); capturer_->InvalidateFullScreen(); } // Network thread -------------------------------------------------------------- void ScreenRecorder::DoSendVideoPacket(scoped_ptr<VideoPacket> packet) { DCHECK(network_loop_->BelongsToCurrentThread()); if (network_stopped_ || connections_.empty()) return; VideoPacket* packet_ptr = packet.get(); // TODO(sergeyu): Currently we send the data only to the first // connection. Send it to all connections if necessary. connections_.front()->video_stub()->ProcessVideoPacket( packet_ptr, base::Bind( &ScreenRecorder::VideoPacketSentCallback, this, base::Passed(packet.Pass()))); } void ScreenRecorder::VideoPacketSentCallback(scoped_ptr<VideoPacket> packet) { if (network_stopped_) return; if ((packet->flags() & VideoPacket::LAST_PARTITION) != 0) { // Post DoFinishOneRecording() if that was the last packet for the // frame. capture_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoFinishOneRecording, this)); } } void ScreenRecorder::DoStopOnNetworkThread(const base::Closure& done_task) { DCHECK(network_loop_->BelongsToCurrentThread()); // There could be tasks on the network thread when this method is being // executed. By setting the flag we'll not post anymore tasks from network // thread. // // After that a task is posted on encode thread to continue the stop // sequence. network_stopped_ = true; encode_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoStopOnEncodeThread, this, done_task)); } // Encoder thread -------------------------------------------------------------- void ScreenRecorder::DoEncode( scoped_refptr<CaptureData> capture_data) { DCHECK_EQ(encode_loop_, MessageLoop::current()); // Early out if there's nothing to encode. if (!capture_data || capture_data->dirty_region().isEmpty()) { // Send an empty video packet to keep network active. scoped_ptr<VideoPacket> packet(new VideoPacket()); packet->set_flags(VideoPacket::LAST_PARTITION); network_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoSendVideoPacket, this, base::Passed(packet.Pass()))); return; } encode_start_time_ = base::Time::Now(); encoder()->Encode( capture_data, false, base::Bind(&ScreenRecorder::EncodedDataAvailableCallback, this)); } void ScreenRecorder::DoStopOnEncodeThread(const base::Closure& done_task) { DCHECK_EQ(encode_loop_, MessageLoop::current()); encoder_stopped_ = true; // When this method is being executed there are no more tasks on encode thread // for this object. We can then post a task to capture thread to finish the // stop sequence. capture_loop_->PostTask(FROM_HERE, done_task); } void ScreenRecorder::EncodedDataAvailableCallback( scoped_ptr<VideoPacket> packet) { DCHECK_EQ(encode_loop_, MessageLoop::current()); if (encoder_stopped_) return; bool last = (packet->flags() & VideoPacket::LAST_PACKET) != 0; if (last) { base::TimeDelta encode_time = base::Time::Now() - encode_start_time_; int encode_time_ms = static_cast<int>(encode_time.InMilliseconds()); packet->set_encode_time_ms(encode_time_ms); scheduler_.RecordEncodeTime(encode_time); } network_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoSendVideoPacket, this, base::Passed(packet.Pass()))); } } // namespace remoting <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <list> #include <windows.h> #include <commctrl.h> #include "app/gfx/native_theme_win.h" #include "base/command_line.h" #include "base/event_recorder.h" #include "base/resource_util.h" #include "base/win_util.h" #include "webkit/tools/test_shell/foreground_helper.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" TestShellPlatformDelegate::TestShellPlatformDelegate( const CommandLine& command_line) : command_line_(command_line) { #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif } TestShellPlatformDelegate::~TestShellPlatformDelegate() { #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif } void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) { } // This test approximates whether you are running the default themes for // your platform by inspecting a couple of metrics. // It does not catch all cases, but it does pick up on classic vs xp, // and normal vs large fonts. Something it misses is changes to the color // scheme (which will infact cause pixel test failures). bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() { std::list<std::string> errors; OSVERSIONINFOEX osvi; ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ::GetVersionEx((OSVERSIONINFO *)&osvi); // default to XP metrics, override if on Vista int requiredVScrollSize = 17; int requiredFontSize = -11; // 8 pt const WCHAR *requiredFont = L"Tahoma"; bool isVista = false; if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0 && osvi.wProductType == VER_NT_WORKSTATION) { requiredFont = L"Segoe UI"; requiredFontSize = -12; // 9 pt isVista = true; } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 && osvi.wProductType == VER_NT_WORKSTATION) { // XP; } else { errors.push_back("Unsupported Operating System version " "(must use XP or Vista)."); } // on both XP and Vista, this metric will be 17 when font size is "Normal". // The size of drop-down menus depends on it. int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL); if (vScrollSize != requiredVScrollSize) { errors.push_back("Must use normal size fonts (96 dpi)."); } // ClearType must be disabled, because the rendering is unpredictable. BOOL bFontSmoothing; SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0, (PVOID)&bFontSmoothing, (UINT)0); int fontSmoothingType; SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, (UINT)0, (PVOID)&fontSmoothingType, (UINT)0); if (bFontSmoothing && (fontSmoothingType == FE_FONTSMOOTHINGCLEARTYPE)) { errors.push_back("ClearType must be disabled."); } // Check that we're using the default system fonts NONCLIENTMETRICS metrics; win_util::GetNonClientMetrics(&metrics); LOGFONTW* system_fonts[] = { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont }; for (size_t i = 0; i < arraysize(system_fonts); ++i) { if (system_fonts[i]->lfHeight != requiredFontSize || wcscmp(requiredFont, system_fonts[i]->lfFaceName)) { if (isVista) errors.push_back("Must use either the Aero or Basic theme."); else errors.push_back("Must use the default XP theme (Luna)."); break; } } if (!errors.empty()) { fprintf(stderr, "%s", "##################################################################\n" "## Layout test system dependencies check failed.\n" "##\n"); for (std::list<std::string>::iterator it = errors.begin(); it != errors.end(); ++it) { fprintf(stderr, "## %s\n", it->c_str()); } fprintf(stderr, "%s", "##\n" "##################################################################\n"); } return errors.empty(); } void TestShellPlatformDelegate::SuppressErrorReporting() { _set_abort_behavior(0, _WRITE_ABORT_MSG); } void TestShellPlatformDelegate::InitializeGUI() { INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); TestShell::RegisterWindowClass(); } void TestShellPlatformDelegate::SelectUnifiedTheme() { gfx::NativeTheme::instance()->DisableTheming(); } void TestShellPlatformDelegate::SetWindowPositionForRecording( TestShell *shell) { // Move the window to the upper left corner for consistent // record/playback mode. For automation, we want this to work // on build systems where the script invoking us is a background // process. So for this case, make our window the topmost window // as well. ForegroundHelper::SetForeground(shell->mainWnd()); ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0); } <commit_msg>Let layout tests run on Windows 7.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <list> #include <windows.h> #include <commctrl.h> #include "app/gfx/native_theme_win.h" #include "base/command_line.h" #include "base/event_recorder.h" #include "base/resource_util.h" #include "base/win_util.h" #include "webkit/tools/test_shell/foreground_helper.h" #include "webkit/tools/test_shell/test_shell.h" #include "webkit/tools/test_shell/test_shell_platform_delegate.h" TestShellPlatformDelegate::TestShellPlatformDelegate( const CommandLine& command_line) : command_line_(command_line) { #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #endif } TestShellPlatformDelegate::~TestShellPlatformDelegate() { #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif } void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) { } // This test approximates whether you are running the default themes for // your platform by inspecting a couple of metrics. // It does not catch all cases, but it does pick up on classic vs xp, // and normal vs large fonts. Something it misses is changes to the color // scheme (which will infact cause pixel test failures). bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() { std::list<std::string> errors; OSVERSIONINFOEX osvi; ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ::GetVersionEx((OSVERSIONINFO *)&osvi); // default to XP metrics, override if on Vista int requiredVScrollSize = 17; int requiredFontSize = -11; // 8 pt const wchar_t* requiredFont = L"Tahoma"; // Consider Windows 7 as Vista. bool isVista = false; if (osvi.dwMajorVersion == 6 && (osvi.dwMinorVersion == 0 || osvi.dwMinorVersion == 1) && osvi.wProductType == VER_NT_WORKSTATION) { requiredFont = L"Segoe UI"; requiredFontSize = -12; // 9 pt isVista = true; } else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 && osvi.wProductType == VER_NT_WORKSTATION) { // XP; } else { errors.push_back("Unsupported Operating System version " "(must use XP or Vista)."); } // on both XP and Vista, this metric will be 17 when font size is "Normal". // The size of drop-down menus depends on it. int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL); if (vScrollSize != requiredVScrollSize) { errors.push_back("Must use normal size fonts (96 dpi)."); } // ClearType must be disabled, because the rendering is unpredictable. BOOL bFontSmoothing; SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0, (PVOID)&bFontSmoothing, (UINT)0); int fontSmoothingType; SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, (UINT)0, (PVOID)&fontSmoothingType, (UINT)0); if (bFontSmoothing && (fontSmoothingType == FE_FONTSMOOTHINGCLEARTYPE)) { errors.push_back("ClearType must be disabled."); } // Check that we're using the default system fonts NONCLIENTMETRICS metrics; win_util::GetNonClientMetrics(&metrics); LOGFONTW* system_fonts[] = { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont }; for (size_t i = 0; i < arraysize(system_fonts); ++i) { if (system_fonts[i]->lfHeight != requiredFontSize || wcscmp(requiredFont, system_fonts[i]->lfFaceName)) { if (isVista) errors.push_back("Must use either the Aero or Basic theme."); else errors.push_back("Must use the default XP theme (Luna)."); break; } } if (!errors.empty()) { fprintf(stderr, "%s", "##################################################################\n" "## Layout test system dependencies check failed.\n" "##\n"); for (std::list<std::string>::iterator it = errors.begin(); it != errors.end(); ++it) { fprintf(stderr, "## %s\n", it->c_str()); } fprintf(stderr, "%s", "##\n" "##################################################################\n"); } return errors.empty(); } void TestShellPlatformDelegate::SuppressErrorReporting() { _set_abort_behavior(0, _WRITE_ABORT_MSG); } void TestShellPlatformDelegate::InitializeGUI() { INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); TestShell::RegisterWindowClass(); } void TestShellPlatformDelegate::SelectUnifiedTheme() { gfx::NativeTheme::instance()->DisableTheming(); } void TestShellPlatformDelegate::SetWindowPositionForRecording( TestShell *shell) { // Move the window to the upper left corner for consistent // record/playback mode. For automation, we want this to work // on build systems where the script invoking us is a background // process. So for this case, make our window the topmost window // as well. ForegroundHelper::SetForeground(shell->mainWnd()); ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.5 1999/12/17 01:28:53 rahulj * Merged in changes submitted for UnixWare 7 port. Platform * specific files are still missing. * * Revision 1.4 1999/12/16 23:47:10 rahulj * Updated for version 1.0.1 * * Revision 1.3 1999/12/01 17:16:16 rahulj * Added support for IRIX 6.5.5 using SGI MIPSpro C++ 7.3 and 7.21 generating 32 bit objects. Changes submitted by Marc Stuessel * * Revision 1.2 1999/11/10 02:02:51 abagchi * Changed version numbers * * Revision 1.1.1.1 1999/11/09 01:05:35 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:19 rahul * Swat for adding in Product name and CVS comment log variable. * */ #if !defined(XML4CDEFS_HPP) #define XML4CDEFS_HPP // --------------------------------------------------------------------------- // These are the various representations of the current version of XML4C. // These are updated for every build. They must be at the top because they // can be used by various per-compiler headers below. // --------------------------------------------------------------------------- #define XML4C_DLLVersionStr "1_0" static const char* const gXML4CVersionStr = "1_0"; static const char* const gXML4CFullVersionStr = "1_0_1"; static const unsigned int gXML4CMajVersion = 1; static const unsigned int gXML4CMinVersion = 0; static const unsigned int gXML4CRevision = 1; // --------------------------------------------------------------------------- // Include the header that does automatic sensing of the current platform // and compiler. // --------------------------------------------------------------------------- #include <util/AutoSense.hpp> // --------------------------------------------------------------------------- // According to the platform we include a platform specific file. This guy // will set up any platform specific stuff, such as character mode. // --------------------------------------------------------------------------- #if defined(XML_WIN32) #include <util/Platforms/Win32/Win32Defs.hpp> #endif #if defined(XML_AIX) #include <util/Platforms/AIX/AIXDefs.hpp> #endif #if defined(XML_SOLARIS) #include <util/Platforms/Solaris/SolarisDefs.hpp> #endif #if defined(XML_UNIXWARE) #include <util/Platforms/UnixWare/UnixWareDefs.hpp> #endif #if defined(XML_HPUX) #include <util/Platforms/HPUX/HPUXDefs.hpp> #endif #if defined(XML_IRIX) #include <util/Platforms/IRIX/IRIXDefs.hpp> #endif #if defined(XML_TANDEM) #include <util/Platforms/Tandem/TandemDefs.hpp> #endif #if defined(XML_LINUX) #include <util/Platforms/Linux/LinuxDefs.hpp> #endif #if defined(XML_OE390) #include <util/Platforms/OS390/OE390Defs.hpp> #endif #if defined(XML_OS2) #include <util/Platforms/OS2/OS2Defs.hpp> #endif #if defined(XML_MACOS) #include <util/Platforms/MaxOS/MacOSDefs.hpp> #endif // --------------------------------------------------------------------------- // And now we subinclude a header according to the development environment // we are on. This guy defines for each platform some basic stuff that is // specific to the development environment. // --------------------------------------------------------------------------- #if defined(XML_VISUALCPP) #include <util/Compilers/VCPPDefs.hpp> #endif #if defined(XML_CSET) #include <util/Compilers/CSetDefs.hpp> #endif #if defined(XML_BORLAND) #include <util/Compilers/BorlandCDefs.hpp> #endif #if defined(XML_SUNCC) #include <util/Compilers/SunCCDefs.hpp> #endif #if defined(XML_SCOCC) #include <util/Compilers/SCOCCDefs.hpp> #endif #if defined(XML_SOLARIS_KAICC) #include <util/Compilers/SunKaiDefs.hpp> #endif #if defined(XML_GNUG) #include <util/Compilers/GNUGDefs.hpp> #endif #if defined(XML_HPUX_CC) || defined(XML_HPUX_aCC) || defined(XML_HPUX_KAICC) #include <util/Compilers/HPCCDefs.hpp> #endif #if defined(XML_MIPSPRO_CC) #include <util/Compilers/MIPSproDefs.hpp> #endif #if defined(XML_TANDEMCC) #include <util/Compilers/TandemCCDefs.hpp> #endif #if defined(XML_GCC) #include <util/Compilers/GCCDefs.hpp> #endif #if defined(XML_MVSCPP) #include <util/Compilers/MVSCPPDefs.hpp> #endif #if defined(XML_IBMVAW32) #include <util/Compilers/IBMVAW32Defs.hpp> #endif #if defined(XML_IBMVAOS2) #include <util/Compilers/IBMVAOS2Defs.hpp> #endif #if defined(XML_METROWERKS) #include <util/Compilers/CodeWarriorDefs.hpp> #endif // --------------------------------------------------------------------------- // Some general typedefs that are defined for internal flexibility. // // Note that UTF16Ch is fixed at 16 bits, whereas XMLCh floats in size per // platform, to whatever is the native wide char format there. UCS4Ch is // fixed at 32 bits. The types we defined them in terms of are defined per // compiler, using whatever types are the right ones for them to get these // 16/32 bit sizes. // --------------------------------------------------------------------------- typedef unsigned char XMLByte; typedef XMLUInt16 UTF16Ch; typedef XMLUInt32 UCS4Ch; // --------------------------------------------------------------------------- // Handle boolean. If the platform can handle booleans itself, then we // map our boolean type to the native type. Otherwise we create a default // one as an int and define const values for true and false. // // This flag will be set in the per-development environment stuff above. // --------------------------------------------------------------------------- #if defined(NO_NATIVE_BOOL) typedef int bool; const bool true = 1; const bool false = 0; #endif // --------------------------------------------------------------------------- // Set up the import/export keyword for our core projects. The // PLATFORM_XXXX keywords are set in the per-development environment // include above. // --------------------------------------------------------------------------- #if defined(PROJ_XMLUTIL) #define XMLUTIL_EXPORT PLATFORM_EXPORT #else #define XMLUTIL_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_XMLPARSER) #define XMLPARSER_EXPORT PLATFORM_EXPORT #else #define XMLPARSER_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_SAX4C) #define SAX_EXPORT PLATFORM_EXPORT #else #define SAX_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_DOM) #define CDOM_EXPORT PLATFORM_EXPORT #else #define CDOM_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_PARSERS) #define PARSERS_EXPORT PLATFORM_EXPORT #else #define PARSERS_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_VALIDATORS) #define VALIDATORS_EXPORT PLATFORM_EXPORT #else #define VALIDATORS_EXPORT PLATFORM_IMPORT #endif #endif <commit_msg>Updated the version information for the next release, i.e. 1.1.0<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.6 2000/01/14 00:52:06 roddey * Updated the version information for the next release, i.e. 1.1.0 * * Revision 1.5 1999/12/17 01:28:53 rahulj * Merged in changes submitted for UnixWare 7 port. Platform * specific files are still missing. * * Revision 1.4 1999/12/16 23:47:10 rahulj * Updated for version 1.0.1 * * Revision 1.3 1999/12/01 17:16:16 rahulj * Added support for IRIX 6.5.5 using SGI MIPSpro C++ 7.3 and 7.21 generating 32 bit objects. Changes submitted by Marc Stuessel * * Revision 1.2 1999/11/10 02:02:51 abagchi * Changed version numbers * * Revision 1.1.1.1 1999/11/09 01:05:35 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:19 rahul * Swat for adding in Product name and CVS comment log variable. * */ #if !defined(XML4CDEFS_HPP) #define XML4CDEFS_HPP // --------------------------------------------------------------------------- // These are the various representations of the current version of XML4C. // These are updated for every build. They must be at the top because they // can be used by various per-compiler headers below. // --------------------------------------------------------------------------- #define XML4C_DLLVersionStr "1_1" static const char* const gXML4CVersionStr = "1_1"; static const char* const gXML4CFullVersionStr = "1_1_0"; static const unsigned int gXML4CMajVersion = 1; static const unsigned int gXML4CMinVersion = 1; static const unsigned int gXML4CRevision = 0; // --------------------------------------------------------------------------- // Include the header that does automatic sensing of the current platform // and compiler. // --------------------------------------------------------------------------- #include <util/AutoSense.hpp> // --------------------------------------------------------------------------- // According to the platform we include a platform specific file. This guy // will set up any platform specific stuff, such as character mode. // --------------------------------------------------------------------------- #if defined(XML_WIN32) #include <util/Platforms/Win32/Win32Defs.hpp> #endif #if defined(XML_AIX) #include <util/Platforms/AIX/AIXDefs.hpp> #endif #if defined(XML_SOLARIS) #include <util/Platforms/Solaris/SolarisDefs.hpp> #endif #if defined(XML_UNIXWARE) #include <util/Platforms/UnixWare/UnixWareDefs.hpp> #endif #if defined(XML_HPUX) #include <util/Platforms/HPUX/HPUXDefs.hpp> #endif #if defined(XML_IRIX) #include <util/Platforms/IRIX/IRIXDefs.hpp> #endif #if defined(XML_TANDEM) #include <util/Platforms/Tandem/TandemDefs.hpp> #endif #if defined(XML_LINUX) #include <util/Platforms/Linux/LinuxDefs.hpp> #endif #if defined(XML_OE390) #include <util/Platforms/OS390/OE390Defs.hpp> #endif #if defined(XML_OS2) #include <util/Platforms/OS2/OS2Defs.hpp> #endif #if defined(XML_MACOS) #include <util/Platforms/MaxOS/MacOSDefs.hpp> #endif // --------------------------------------------------------------------------- // And now we subinclude a header according to the development environment // we are on. This guy defines for each platform some basic stuff that is // specific to the development environment. // --------------------------------------------------------------------------- #if defined(XML_VISUALCPP) #include <util/Compilers/VCPPDefs.hpp> #endif #if defined(XML_CSET) #include <util/Compilers/CSetDefs.hpp> #endif #if defined(XML_BORLAND) #include <util/Compilers/BorlandCDefs.hpp> #endif #if defined(XML_SUNCC) #include <util/Compilers/SunCCDefs.hpp> #endif #if defined(XML_SCOCC) #include <util/Compilers/SCOCCDefs.hpp> #endif #if defined(XML_SOLARIS_KAICC) #include <util/Compilers/SunKaiDefs.hpp> #endif #if defined(XML_GNUG) #include <util/Compilers/GNUGDefs.hpp> #endif #if defined(XML_HPUX_CC) || defined(XML_HPUX_aCC) || defined(XML_HPUX_KAICC) #include <util/Compilers/HPCCDefs.hpp> #endif #if defined(XML_MIPSPRO_CC) #include <util/Compilers/MIPSproDefs.hpp> #endif #if defined(XML_TANDEMCC) #include <util/Compilers/TandemCCDefs.hpp> #endif #if defined(XML_GCC) #include <util/Compilers/GCCDefs.hpp> #endif #if defined(XML_MVSCPP) #include <util/Compilers/MVSCPPDefs.hpp> #endif #if defined(XML_IBMVAW32) #include <util/Compilers/IBMVAW32Defs.hpp> #endif #if defined(XML_IBMVAOS2) #include <util/Compilers/IBMVAOS2Defs.hpp> #endif #if defined(XML_METROWERKS) #include <util/Compilers/CodeWarriorDefs.hpp> #endif // --------------------------------------------------------------------------- // Some general typedefs that are defined for internal flexibility. // // Note that UTF16Ch is fixed at 16 bits, whereas XMLCh floats in size per // platform, to whatever is the native wide char format there. UCS4Ch is // fixed at 32 bits. The types we defined them in terms of are defined per // compiler, using whatever types are the right ones for them to get these // 16/32 bit sizes. // --------------------------------------------------------------------------- typedef unsigned char XMLByte; typedef XMLUInt16 UTF16Ch; typedef XMLUInt32 UCS4Ch; // --------------------------------------------------------------------------- // Handle boolean. If the platform can handle booleans itself, then we // map our boolean type to the native type. Otherwise we create a default // one as an int and define const values for true and false. // // This flag will be set in the per-development environment stuff above. // --------------------------------------------------------------------------- #if defined(NO_NATIVE_BOOL) typedef int bool; const bool true = 1; const bool false = 0; #endif // --------------------------------------------------------------------------- // Set up the import/export keyword for our core projects. The // PLATFORM_XXXX keywords are set in the per-development environment // include above. // --------------------------------------------------------------------------- #if defined(PROJ_XMLUTIL) #define XMLUTIL_EXPORT PLATFORM_EXPORT #else #define XMLUTIL_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_XMLPARSER) #define XMLPARSER_EXPORT PLATFORM_EXPORT #else #define XMLPARSER_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_SAX4C) #define SAX_EXPORT PLATFORM_EXPORT #else #define SAX_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_DOM) #define CDOM_EXPORT PLATFORM_EXPORT #else #define CDOM_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_PARSERS) #define PARSERS_EXPORT PLATFORM_EXPORT #else #define PARSERS_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_VALIDATORS) #define VALIDATORS_EXPORT PLATFORM_EXPORT #else #define VALIDATORS_EXPORT PLATFORM_IMPORT #endif #endif <|endoftext|>