<commit_before>/*
 * FatFind: A Diamond application for adipocyte image exploration
 *
 * Copyright (c) 2006 Carnegie Mellon University. All rights reserved.
 * Additional copyrights may be listed below.
 *
 * This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License v1.0 which accompanies this
 * distribution in the file named LICENSE.
 *
 * Technical and financial contributors are listed in the file named
 * CREDITS.
 */

#include "ltiRGBPixel.h"
#include "ltiScaling.h"
#include "ltiDraw.h"                  // drawing tool
#include "ltiALLFunctor.h"            // image loader
#include "ltiCannyEdges.h"            // edge detector
#include "ltiFastEllipseExtraction.h" // ellipse detector
#include "ltiGaussianPyramid.h"
#include "ltiSplitImageToHSV.h"

#include "circles4.h"
#include "lib_filter.h"

GList *circles;   // for gui only, not filter

typedef struct {
  double minRadius;
  double maxRadius;
  double maxEccentricity;
} circles_state_t;

// helper functions for glist
static void free_1_circle(gpointer data, gpointer user_data) {
  g_free((circle_type *) data);
}

static gint circle_radius_compare(gconstpointer a,
				  gconstpointer b) {
  const circle_type *c1 = (circle_type *) a;
  const circle_type *c2 = (circle_type *) b;

  // assume a and b are positive
  double c1_radius = c1->a + c1->b;
  double c2_radius = c2->a + c2->b;
  if (c1_radius < c2_radius) {
    return 1;
  } else if (c2_radius < c1_radius) {
    return -1;
  } else {
    return 0;
  }
}

static void do_canny(lti::gaussianPyramid<lti::image> &imgPyramid,
		     std::vector<lti::channel8*> &edges) {
  // params
  lti::cannyEdges::parameters cannyParam;
  cannyParam.thresholdMax = 0.10;
  cannyParam.thresholdMin = 0.04;
  cannyParam.kernelSize = 7;

  // run
  lti::cannyEdges canny(cannyParam);
  g_assert(edges.size() == 0);

  for (int i = 0; i < imgPyramid.size(); i++) {
    printf("canny[%d]: %dx%d\n", i, imgPyramid[i].columns(),
	   imgPyramid[i].rows());
    lti::channel8 *c8 = new lti::channel8;
    canny.apply(imgPyramid[i], *c8);
    edges.push_back(c8);
  }
}

static GList *do_fee(std::vector<lti::channel8*> &edges,
		     circles_state_t *ct) {
  GList *result = NULL;

  // create FEE functor
  lti::fastEllipseExtraction::parameters feeParam;
  feeParam.maxArcGap = 120;
  feeParam.minLineLen = 3;

  for (unsigned int i = 0; i < edges.size(); i++) {
    double pyrScale = pow(2, i);

    lti::fastEllipseExtraction fee(feeParam);

    // extract some ellipses
    printf("extracting from pyramid %d\n", i);
    fee.apply(*edges[i]);

    // build list
    std::vector<lti::fastEllipseExtraction::ellipseEntry>
      &ellipses = fee.getEllipseList();

    for(unsigned int j=0; j<ellipses.size(); j++) {
      float a = ellipses[j].a * pyrScale;
      float b = ellipses[j].b * pyrScale;
      gboolean in_result = TRUE;

      // determine if it should go in by radius
      if (!(ct->minRadius < 0 || a >= ct->minRadius || b >= ct->minRadius)) {
	in_result = FALSE;
      } else if (!(ct->maxRadius < 0 || a <= ct->maxRadius || b <= ct->maxRadius)) {
	in_result = FALSE;
      }

      // compute eccentricity
      if (b > a) {
	float c = a;
	a = b;
	b = c;
      }
      float e = sqrt(1 - ((b*b) / (a*a)));
      if (e > ct->maxEccentricity) {
	in_result = FALSE;
      }

      // all set
      circle_type *c = (circle_type *)g_malloc(sizeof(circle_type));

      c->x = ellipses[j].x * pyrScale;
      c->y = ellipses[j].y * pyrScale;
      c->a = ellipses[j].a * pyrScale;
      c->b = ellipses[j].b * pyrScale;
      c->t = ellipses[j].t;
      c->in_result = in_result;

      result = g_list_prepend(result, c);

      // print ellipse data
      printf(" ellipse[%i]: center=(%.0f,%.0f) semiaxis=(%.0f,%.0f) "
	     "angle=%.1f coverage=%.1f%% \n",
	     j, c->x, c->y, c->a, c->b, c->t*180/M_PI,
	     ellipses[j].coverage*100);
    }
  }

  return result;
}

static circles_state_t staticState = {-1, -1, 0.4};
static GList *circlesFromImage2(circles_state_t *ct,
				const int width, const int height,
				const int stride, const int bytesPerPixel,
				void *data) {
  // load image
  g_assert(bytesPerPixel >= 3);
  lti::image img(false, height, width);
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      guchar *d = ((guchar *) data) + (x * bytesPerPixel + y * stride);
      lti::rgbPixel p(d[0], d[1], d[2]);
      img[y][x] = p;
    }
  }

  // make pyramid
  int levels = (int)log2(MIN(img.rows(), img.columns()));
  lti::gaussianPyramid<lti::image> imgPyramid(levels);
  imgPyramid.generate(img);

  // make vector
  std::vector<lti::channel8*> edges;

  // run
  do_canny(imgPyramid, edges);
  GList *result = do_fee(edges, ct);

  // clear vector
  for (unsigned int i = 0; i < edges.size(); i++) {
    delete edges[i];
    edges[i] = NULL;
  }

  // overlap supression
  printf("overlap supression ");
  fflush(stdout);

  result = g_list_sort(result, circle_radius_compare);  // sort

  GList *iter = result;
  while (iter != NULL) {
    // find other centers within this circle (assume no eccentricity)
    circle_type *c1 = (circle_type *) iter->data;
    double c1_radius = (c1->a + c1->b) / 2.0;

    GList *iter2 = g_list_next(iter);
    while (iter2 != NULL) {
      circle_type *c2 = (circle_type *) iter2->data;
      double c2_radius = (c2->a + c2->b) / 2.0;

      // is c2 within c1?
      double xd = c2->x - c1->x;
      double yd = c2->y - c1->y;
      double dist = sqrt((xd * xd) + (yd * yd));

      // maybe delete?
      GList *next = g_list_next(iter2);
      //      printf(" dist: %g, c1_radius: %g, c2_radius: %g\n",
      //	     dist, c1_radius, c2_radius);

      // XXX fudge
      if ((dist + c2_radius) < (c1_radius + 100)) {
	printf("x");
	fflush(stdout);
	result = g_list_delete_link(result, iter2);
      }

      iter2 = next;
    }
    printf(".");
    fflush(stdout);
    iter = g_list_next(iter);
  }
  printf("\n");

  return result;
}

// called from GUI
void circlesFromImage(const int width, const int height,
		      const int stride, const int bytesPerPixel,
		      void *data) {
  circles = circlesFromImage2(&staticState, width,
			      height, stride, bytesPerPixel, data);
}

// 3 functions for diamond filter interface

extern "C" {
  int f_init_circles (int num_arg, char **args,
		      int bloblen, void *blob_data,
		      const char *filter_name,
		      void **filter_args) {
    circles_state_t *cr;

    // check parameters
    if (num_arg != 3) {
      return -1;
    }

    // init state
    cr = (circles_state_t *)g_malloc(sizeof(circles_state_t));

    cr->minRadius = g_ascii_strtod(args[0], NULL);
    cr->maxRadius = g_ascii_strtod(args[1], NULL);
    cr->maxEccentricity = g_ascii_strtod(args[2], NULL);

    // we're good
    *filter_args = cr;
    return 0;
  }

  int f_eval_circles (lf_obj_handle_t ohandle, void *filter_args) {
    // circles
    GList *clist;
    circles_state_t *cr = (circles_state_t *) filter_args;
    int num_circles;
    int num_circles_in_result = 0;

    // for attributes from diamond
    size_t len;
    unsigned char *data;

    // get the data from the ohandle, convert to IplImage
    int w;
    int h;

    // width
    lf_ref_attr(ohandle, "_rows.int", &len, &data);
    h = *((int *) data);

    // height
    lf_ref_attr(ohandle, "_cols.int", &len, &data);
    w = *((int *) data);

    // image data
    lf_ref_attr(ohandle, "_rgb_image.rgbimage", &len, &data);

    // feed it to our processor
    clist = circlesFromImage2(cr, w, h, w * 4, 4, data);

    data = NULL;

    // add the list of circles to the cache and the object
    // XXX !
    num_circles = g_list_length(clist);
    if (num_circles > 0) {
      GList *l = clist;
      int i = 0;
      data = (unsigned char *) g_malloc(sizeof(circle_type) * num_circles);

      // pack in and count
      while (l != NULL) {
	circle_type *p = ((circle_type *) data) + i;
	circle_type *c = (circle_type *) l->data;
	*p = *c;

	if (c->in_result) {
	  num_circles_in_result++;
	}

	i++;
	l = g_list_next(l);
      }
      lf_write_attr(ohandle, "circle-data", sizeof(circle_type) * num_circles, data);
    }

    // free others
    g_list_foreach(clist, free_1_circle, NULL);
    g_list_free(clist);
    clist = NULL;
    g_free(data);
    data = NULL;

    // return number of circles
    return num_circles_in_result;
  }

  int f_fini_circles (void *filter_args) {
    g_free((circles_state_t *) filter_args);

    return 0;
  }
}
<commit_msg>better<commit_after>/*
 * FatFind: A Diamond application for adipocyte image exploration
 *
 * Copyright (c) 2006 Carnegie Mellon University. All rights reserved.
 * Additional copyrights may be listed below.
 *
 * This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License v1.0 which accompanies this
 * distribution in the file named LICENSE.
 *
 * Technical and financial contributors are listed in the file named
 * CREDITS.
 */

#include "ltiRGBPixel.h"
#include "ltiScaling.h"
#include "ltiDraw.h"                  // drawing tool
#include "ltiALLFunctor.h"            // image loader
#include "ltiCannyEdges.h"            // edge detector
#include "ltiFastEllipseExtraction.h" // ellipse detector
#include "ltiGaussianPyramid.h"
#include "ltiSplitImageToHSV.h"

#include "circles4.h"
#include "lib_filter.h"
#include "util.h"

GList *circles;   // for gui only, not filter

typedef struct {
  double minRadius;
  double maxRadius;
  double maxEccentricity;
} circles_state_t;

// helper functions for glist
static void free_1_circle(gpointer data, gpointer user_data) {
  g_free((circle_type *) data);
}

static gint circle_radius_compare(gconstpointer a,
				  gconstpointer b) {
  const circle_type *c1 = (circle_type *) a;
  const circle_type *c2 = (circle_type *) b;

  // assume a and b are positive
  double c1_radius = quadratic_mean_radius(c1->a, c1->b);
  double c2_radius = quadratic_mean_radius(c2->a, c2->b);
  if (c1_radius < c2_radius) {
    return 1;
  } else if (c2_radius < c1_radius) {
    return -1;
  } else {
    return 0;
  }
}

static void do_canny(lti::gaussianPyramid<lti::image> &imgPyramid,
		     std::vector<lti::channel8*> &edges) {
  // params
  lti::cannyEdges::parameters cannyParam;
  cannyParam.thresholdMax = 0.10;
  cannyParam.thresholdMin = 0.04;
  cannyParam.kernelSize = 7;

  // run
  lti::cannyEdges canny(cannyParam);
  g_assert(edges.size() == 0);

  for (int i = 0; i < imgPyramid.size(); i++) {
    printf("canny[%d]: %dx%d\n", i, imgPyramid[i].columns(),
	   imgPyramid[i].rows());
    lti::channel8 *c8 = new lti::channel8;
    canny.apply(imgPyramid[i], *c8);
    edges.push_back(c8);
  }
}

static GList *do_fee(std::vector<lti::channel8*> &edges,
		     circles_state_t *ct) {
  GList *result = NULL;

  // create FEE functor
  lti::fastEllipseExtraction::parameters feeParam;
  feeParam.maxArcGap = 120;
  feeParam.minLineLen = 3;

  for (unsigned int i = 0; i < edges.size(); i++) {
    double pyrScale = pow(2, i);

    lti::fastEllipseExtraction fee(feeParam);

    // extract some ellipses
    printf("extracting from pyramid %d\n", i);
    fee.apply(*edges[i]);

    // build list
    std::vector<lti::fastEllipseExtraction::ellipseEntry>
      &ellipses = fee.getEllipseList();

    for(unsigned int j=0; j<ellipses.size(); j++) {
      float a = ellipses[j].a * pyrScale;
      float b = ellipses[j].b * pyrScale;
      float r = quadratic_mean_radius(a, b);
      gboolean in_result = TRUE;

      // determine if it should go in by radius
      if (!(ct->minRadius < 0 || r >= ct->minRadius)) {
	in_result = FALSE;
      } else if (!(ct->maxRadius < 0 || r <= ct->maxRadius)) {
	in_result = FALSE;
      }

      // compute eccentricity
      float e = compute_eccentricity(a, b);
      if (e > ct->maxEccentricity) {
	in_result = FALSE;
      }

      // all set
      circle_type *c = (circle_type *)g_malloc(sizeof(circle_type));

      c->x = ellipses[j].x * pyrScale;
      c->y = ellipses[j].y * pyrScale;
      c->a = ellipses[j].a * pyrScale;
      c->b = ellipses[j].b * pyrScale;
      c->t = ellipses[j].t;
      c->in_result = in_result;

      result = g_list_prepend(result, c);

      // print ellipse data
      printf(" ellipse[%i]: center=(%.0f,%.0f) semiaxis=(%.0f,%.0f) "
	     "angle=%.1f coverage=%.1f%% \n",
	     j, c->x, c->y, c->a, c->b, c->t*180/M_PI,
	     ellipses[j].coverage*100);
    }
  }

  return result;
}

static circles_state_t staticState = {-1, -1, 0.4};
static GList *circlesFromImage2(circles_state_t *ct,
				const int width, const int height,
				const int stride, const int bytesPerPixel,
				void *data) {
  // load image
  g_assert(bytesPerPixel >= 3);
  lti::image img(false, height, width);
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      guchar *d = ((guchar *) data) + (x * bytesPerPixel + y * stride);
      lti::rgbPixel p(d[0], d[1], d[2]);
      img[y][x] = p;
    }
  }

  // make pyramid
  int levels = (int)log2(MIN(img.rows(), img.columns()));
  lti::gaussianPyramid<lti::image> imgPyramid(levels);
  imgPyramid.generate(img);

  // make vector
  std::vector<lti::channel8*> edges;

  // run
  do_canny(imgPyramid, edges);
  GList *result = do_fee(edges, ct);

  // clear vector
  for (unsigned int i = 0; i < edges.size(); i++) {
    delete edges[i];
    edges[i] = NULL;
  }

  // overlap supression
  printf("overlap supression ");
  fflush(stdout);

  result = g_list_sort(result, circle_radius_compare);  // sort

  GList *iter = result;
  while (iter != NULL) {
    // find other centers within this circle (assume no eccentricity)
    circle_type *c1 = (circle_type *) iter->data;
    double c1_radius = quadratic_mean_radius(c1->a, c1->b);

    GList *iter2 = g_list_next(iter);
    while (iter2 != NULL) {
      circle_type *c2 = (circle_type *) iter2->data;
      double c2_radius = quadratic_mean_radius(c2->a, c2->b);

      // is c2 within c1?
      double xd = c2->x - c1->x;
      double yd = c2->y - c1->y;
      double dist = sqrt((xd * xd) + (yd * yd));

      // maybe delete?
      GList *next = g_list_next(iter2);
      //      printf(" dist: %g, c1_radius: %g, c2_radius: %g\n",
      //	     dist, c1_radius, c2_radius);

      // XXX fudge
      if ((dist + c2_radius) < (c1_radius + 100)) {
	printf("x");
	fflush(stdout);
	result = g_list_delete_link(result, iter2);
      }

      iter2 = next;
    }
    printf(".");
    fflush(stdout);
    iter = g_list_next(iter);
  }
  printf("\n");

  return result;
}

// called from GUI
void circlesFromImage(const int width, const int height,
		      const int stride, const int bytesPerPixel,
		      void *data) {
  circles = circlesFromImage2(&staticState, width,
			      height, stride, bytesPerPixel, data);
}

// 3 functions for diamond filter interface

extern "C" {
  int f_init_circles (int num_arg, char **args,
		      int bloblen, void *blob_data,
		      const char *filter_name,
		      void **filter_args) {
    circles_state_t *cr;

    // check parameters
    if (num_arg != 3) {
      return -1;
    }

    // init state
    cr = (circles_state_t *)g_malloc(sizeof(circles_state_t));

    cr->minRadius = g_ascii_strtod(args[0], NULL);
    cr->maxRadius = g_ascii_strtod(args[1], NULL);
    cr->maxEccentricity = g_ascii_strtod(args[2], NULL);

    // we're good
    *filter_args = cr;
    return 0;
  }

  int f_eval_circles (lf_obj_handle_t ohandle, void *filter_args) {
    // circles
    GList *clist;
    circles_state_t *cr = (circles_state_t *) filter_args;
    int num_circles;
    int num_circles_in_result = 0;

    // for attributes from diamond
    size_t len;
    unsigned char *data;

    // get the data from the ohandle, convert to IplImage
    int w;
    int h;

    // width
    lf_ref_attr(ohandle, "_rows.int", &len, &data);
    h = *((int *) data);

    // height
    lf_ref_attr(ohandle, "_cols.int", &len, &data);
    w = *((int *) data);

    // image data
    lf_ref_attr(ohandle, "_rgb_image.rgbimage", &len, &data);

    // feed it to our processor
    clist = circlesFromImage2(cr, w, h, w * 4, 4, data);

    data = NULL;

    // add the list of circles to the cache and the object
    // XXX !
    num_circles = g_list_length(clist);
    if (num_circles > 0) {
      GList *l = clist;
      int i = 0;
      data = (unsigned char *) g_malloc(sizeof(circle_type) * num_circles);

      // pack in and count
      while (l != NULL) {
	circle_type *p = ((circle_type *) data) + i;
	circle_type *c = (circle_type *) l->data;
	*p = *c;

	if (c->in_result) {
	  num_circles_in_result++;
	}

	i++;
	l = g_list_next(l);
      }
      lf_write_attr(ohandle, "circle-data", sizeof(circle_type) * num_circles, data);
    }

    // free others
    g_list_foreach(clist, free_1_circle, NULL);
    g_list_free(clist);
    clist = NULL;
    g_free(data);
    data = NULL;

    // return number of circles
    return num_circles_in_result;
  }

  int f_fini_circles (void *filter_args) {
    g_free((circles_state_t *) filter_args);

    return 0;
  }
}
<|endoftext|>


<commit_before>/*
* (C) 2010,2014,2015,2018 Jack Lloyd
* (C) 2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "cli.h"

#if defined(BOTAN_HAS_X509_CERTIFICATES) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)

#include <botan/certstor.h>
#include <botan/pk_keys.h>
#include <botan/pkcs8.h>
#include <botan/x509_ca.h>
#include <botan/x509cert.h>
#include <botan/x509path.h>
#include <botan/x509self.h>
#include <botan/data_src.h>
#include <botan/parsing.h>

#if defined(BOTAN_HAS_OCSP)
   #include <botan/ocsp.h>
#endif

namespace Botan_CLI {

class Sign_Cert final : public Command
   {
   public:
      Sign_Cert()
         : Command("sign_cert --ca-key-pass= --hash=SHA-256 "
                   "--duration=365 --emsa= ca_cert ca_key pkcs10_req") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Create a CA-signed X.509 certificate from a PKCS #10 CSR";
         }

      void go() override
         {
         Botan::X509_Certificate ca_cert(get_arg("ca_cert"));
         std::unique_ptr<Botan::Private_Key> key;
         const std::string pass = get_arg("ca-key-pass");
         const std::string emsa = get_arg("emsa");
         const std::string hash = get_arg("hash");

         if(!pass.empty())
            {
            key.reset(Botan::PKCS8::load_key(get_arg("ca_key"), rng(), pass));
            }
         else
            {
            key.reset(Botan::PKCS8::load_key(get_arg("ca_key"), rng()));
            }

         if(!key)
            {
            throw CLI_Error("Failed to load key from " + get_arg("ca_key"));
            }

         std::map<std::string, std::string> options;
         if(emsa.empty() == false)
            options["padding"] = emsa;

         Botan::X509_CA ca(ca_cert, *key, options, hash, rng());

         Botan::PKCS10_Request req(get_arg("pkcs10_req"));

         auto now = std::chrono::system_clock::now();

         Botan::X509_Time start_time(now);

         typedef std::chrono::duration<int, std::ratio<86400>> days;

         Botan::X509_Time end_time(now + days(get_arg_sz("duration")));

         Botan::X509_Certificate new_cert = ca.sign_request(req, rng(), start_time, end_time);

         output() << new_cert.PEM_encode();
         }
   };

BOTAN_REGISTER_COMMAND("sign_cert", Sign_Cert);

class Cert_Info final : public Command
   {
   public:
      Cert_Info() : Command("cert_info --fingerprint file") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Parse X.509 certificate and display data fields";
         }

      void go() override
         {
         const std::string arg_file = get_arg("file");

         std::vector<uint8_t> data = slurp_file(get_arg("file"));

         Botan::DataSource_Memory in(data);

         while(!in.end_of_data())
            {
            try
               {
               Botan::X509_Certificate cert(in);

               try
                  {
                  output() << cert.to_string() << std::endl;
                  }
               catch(Botan::Exception& e)
                  {
                  // to_string failed - report the exception and continue
                  output() << "X509_Certificate::to_string failed: " << e.what() << "\n";
                  }

               if(flag_set("fingerprint"))
                  output() << "Fingerprint: " << cert.fingerprint("SHA-256") << std::endl;
               }
            catch(Botan::Exception& e)
               {
               if(!in.end_of_data())
                  {
                  output() << "X509_Certificate parsing failed " << e.what() << "\n";
                  }
               }
            }
         }
   };

BOTAN_REGISTER_COMMAND("cert_info", Cert_Info);

#if defined(BOTAN_HAS_OCSP) && defined(BOTAN_HAS_HTTP_UTIL)

class OCSP_Check final : public Command
   {
   public:
      OCSP_Check() : Command("ocsp_check --timeout=3000 subject issuer") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Verify an X.509 certificate against the issuers OCSP responder";
         }

      void go() override
         {
         Botan::X509_Certificate subject(get_arg("subject"));
         Botan::X509_Certificate issuer(get_arg("issuer"));
         std::chrono::milliseconds timeout(get_arg_sz("timeout"));

         Botan::Certificate_Store_In_Memory cas;
         cas.add_certificate(issuer);
         Botan::OCSP::Response resp = Botan::OCSP::online_check(issuer, subject, &cas, timeout);

         auto status = resp.status_for(issuer, subject, std::chrono::system_clock::now());

         if(status == Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)
            {
            output() << "OCSP check OK\n";
            }
         else
            {
            output() << "OCSP check failed " << Botan::Path_Validation_Result::status_string(status) << "\n";
            }
         }
   };

BOTAN_REGISTER_COMMAND("ocsp_check", OCSP_Check);

#endif // OCSP && HTTP

class Cert_Verify final : public Command
   {
   public:
      Cert_Verify() : Command("cert_verify subject *ca_certs") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Verify if the passed X.509 certificate passes path validation";
         }

      void go() override
         {
         Botan::X509_Certificate subject_cert(get_arg("subject"));
         Botan::Certificate_Store_In_Memory trusted;

         for(auto const& certfile : get_arg_list("ca_certs"))
            {
            trusted.add_certificate(Botan::X509_Certificate(certfile));
            }

         Botan::Path_Validation_Restrictions restrictions;

         Botan::Path_Validation_Result result =
            Botan::x509_path_validate(subject_cert,
                                      restrictions,
                                      trusted);

         if(result.successful_validation())
            {
            output() << "Certificate passes validation checks\n";
            }
         else
            {
            output() << "Certificate did not validate - " << result.result_string() << "\n";
            }
         }
   };

BOTAN_REGISTER_COMMAND("cert_verify", Cert_Verify);

class Gen_Self_Signed final : public Command
   {
   public:
      Gen_Self_Signed()
         : Command("gen_self_signed key CN --country= --dns= "
                   "--organization= --email= --days=365 --key-pass= --ca --hash=SHA-256 --emsa= --der") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Generate a self signed X.509 certificate";
         }

      void go() override
         {
         std::unique_ptr<Botan::Private_Key> key(Botan::PKCS8::load_key(get_arg("key"), rng(), get_arg("key-pass")));

         if(!key)
            {
            throw CLI_Error("Failed to load key from " + get_arg("key"));
            }

         const size_t days = get_arg_sz("days");

         Botan::X509_Cert_Options opts("", days * 24 * 60 * 60);

         opts.common_name  = get_arg("CN");
         opts.country      = get_arg("country");
         opts.organization = get_arg("organization");
         opts.email        = get_arg("email");
         opts.more_dns = Botan::split_on(get_arg("dns"), ',');
         const bool der_format = flag_set("der");

         std::string emsa = get_arg("emsa");

         if(emsa.empty() == false)
            opts.set_padding_scheme(emsa);

         if(flag_set("ca"))
            {
            opts.CA_key();
            }

         Botan::X509_Certificate cert = Botan::X509::create_self_signed_cert(opts, *key, get_arg("hash"), rng());

         if(der_format)
            {
            auto der = cert.BER_encode();
            output().write(reinterpret_cast<const char*>(der.data()), der.size());
            }
         else
            output() << cert.PEM_encode();
         }
   };

BOTAN_REGISTER_COMMAND("gen_self_signed", Gen_Self_Signed);

class Generate_PKCS10 final : public Command
   {
   public:
      Generate_PKCS10()
         : Command("gen_pkcs10 key CN --country= --organization= "
                   "--email= --dns= --key-pass= --hash=SHA-256 --emsa=") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Generate a PKCS #10 certificate signing request (CSR)";
         }

      void go() override
         {
         std::unique_ptr<Botan::Private_Key> key(Botan::PKCS8::load_key(get_arg("key"), rng(), get_arg("key-pass")));

         if(!key)
            {
            throw CLI_Error("Failed to load key from " + get_arg("key"));
            }

         Botan::X509_Cert_Options opts;

         opts.common_name  = get_arg("CN");
         opts.country      = get_arg("country");
         opts.organization = get_arg("organization");
         opts.email        = get_arg("email");
         opts.more_dns     = Botan::split_on(get_arg("dns"), ',');

         std::string emsa = get_arg("emsa");

         if(emsa.empty() == false)
            opts.set_padding_scheme(emsa);

         Botan::PKCS10_Request req = Botan::X509::create_cert_req(opts, *key, get_arg("hash"), rng());

         output() << req.PEM_encode();
         }
   };

BOTAN_REGISTER_COMMAND("gen_pkcs10", Generate_PKCS10);

}

#endif
<commit_msg>Allow setting extended key usage when generating PKCS10<commit_after>/*
* (C) 2010,2014,2015,2018 Jack Lloyd
* (C) 2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "cli.h"

#if defined(BOTAN_HAS_X509_CERTIFICATES) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)

#include <botan/certstor.h>
#include <botan/pk_keys.h>
#include <botan/pkcs8.h>
#include <botan/x509_ca.h>
#include <botan/x509cert.h>
#include <botan/x509path.h>
#include <botan/x509self.h>
#include <botan/data_src.h>
#include <botan/parsing.h>

#if defined(BOTAN_HAS_OCSP)
   #include <botan/ocsp.h>
#endif

namespace Botan_CLI {

class Sign_Cert final : public Command
   {
   public:
      Sign_Cert()
         : Command("sign_cert --ca-key-pass= --hash=SHA-256 "
                   "--duration=365 --emsa= ca_cert ca_key pkcs10_req") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Create a CA-signed X.509 certificate from a PKCS #10 CSR";
         }

      void go() override
         {
         Botan::X509_Certificate ca_cert(get_arg("ca_cert"));
         std::unique_ptr<Botan::Private_Key> key;
         const std::string pass = get_arg("ca-key-pass");
         const std::string emsa = get_arg("emsa");
         const std::string hash = get_arg("hash");

         if(!pass.empty())
            {
            key.reset(Botan::PKCS8::load_key(get_arg("ca_key"), rng(), pass));
            }
         else
            {
            key.reset(Botan::PKCS8::load_key(get_arg("ca_key"), rng()));
            }

         if(!key)
            {
            throw CLI_Error("Failed to load key from " + get_arg("ca_key"));
            }

         std::map<std::string, std::string> options;
         if(emsa.empty() == false)
            options["padding"] = emsa;

         Botan::X509_CA ca(ca_cert, *key, options, hash, rng());

         Botan::PKCS10_Request req(get_arg("pkcs10_req"));

         auto now = std::chrono::system_clock::now();

         Botan::X509_Time start_time(now);

         typedef std::chrono::duration<int, std::ratio<86400>> days;

         Botan::X509_Time end_time(now + days(get_arg_sz("duration")));

         Botan::X509_Certificate new_cert = ca.sign_request(req, rng(), start_time, end_time);

         output() << new_cert.PEM_encode();
         }
   };

BOTAN_REGISTER_COMMAND("sign_cert", Sign_Cert);

class Cert_Info final : public Command
   {
   public:
      Cert_Info() : Command("cert_info --fingerprint file") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Parse X.509 certificate and display data fields";
         }

      void go() override
         {
         const std::string arg_file = get_arg("file");

         std::vector<uint8_t> data = slurp_file(get_arg("file"));

         Botan::DataSource_Memory in(data);

         while(!in.end_of_data())
            {
            try
               {
               Botan::X509_Certificate cert(in);

               try
                  {
                  output() << cert.to_string() << std::endl;
                  }
               catch(Botan::Exception& e)
                  {
                  // to_string failed - report the exception and continue
                  output() << "X509_Certificate::to_string failed: " << e.what() << "\n";
                  }

               if(flag_set("fingerprint"))
                  output() << "Fingerprint: " << cert.fingerprint("SHA-256") << std::endl;
               }
            catch(Botan::Exception& e)
               {
               if(!in.end_of_data())
                  {
                  output() << "X509_Certificate parsing failed " << e.what() << "\n";
                  }
               }
            }
         }
   };

BOTAN_REGISTER_COMMAND("cert_info", Cert_Info);

#if defined(BOTAN_HAS_OCSP) && defined(BOTAN_HAS_HTTP_UTIL)

class OCSP_Check final : public Command
   {
   public:
      OCSP_Check() : Command("ocsp_check --timeout=3000 subject issuer") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Verify an X.509 certificate against the issuers OCSP responder";
         }

      void go() override
         {
         Botan::X509_Certificate subject(get_arg("subject"));
         Botan::X509_Certificate issuer(get_arg("issuer"));
         std::chrono::milliseconds timeout(get_arg_sz("timeout"));

         Botan::Certificate_Store_In_Memory cas;
         cas.add_certificate(issuer);
         Botan::OCSP::Response resp = Botan::OCSP::online_check(issuer, subject, &cas, timeout);

         auto status = resp.status_for(issuer, subject, std::chrono::system_clock::now());

         if(status == Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)
            {
            output() << "OCSP check OK\n";
            }
         else
            {
            output() << "OCSP check failed " << Botan::Path_Validation_Result::status_string(status) << "\n";
            }
         }
   };

BOTAN_REGISTER_COMMAND("ocsp_check", OCSP_Check);

#endif // OCSP && HTTP

class Cert_Verify final : public Command
   {
   public:
      Cert_Verify() : Command("cert_verify subject *ca_certs") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Verify if the passed X.509 certificate passes path validation";
         }

      void go() override
         {
         Botan::X509_Certificate subject_cert(get_arg("subject"));
         Botan::Certificate_Store_In_Memory trusted;

         for(auto const& certfile : get_arg_list("ca_certs"))
            {
            trusted.add_certificate(Botan::X509_Certificate(certfile));
            }

         Botan::Path_Validation_Restrictions restrictions;

         Botan::Path_Validation_Result result =
            Botan::x509_path_validate(subject_cert,
                                      restrictions,
                                      trusted);

         if(result.successful_validation())
            {
            output() << "Certificate passes validation checks\n";
            }
         else
            {
            output() << "Certificate did not validate - " << result.result_string() << "\n";
            }
         }
   };

BOTAN_REGISTER_COMMAND("cert_verify", Cert_Verify);

class Gen_Self_Signed final : public Command
   {
   public:
      Gen_Self_Signed()
         : Command("gen_self_signed key CN --country= --dns= "
                   "--organization= --email= --days=365 --key-pass= --ca --hash=SHA-256 --emsa= --der") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Generate a self signed X.509 certificate";
         }

      void go() override
         {
         std::unique_ptr<Botan::Private_Key> key(Botan::PKCS8::load_key(get_arg("key"), rng(), get_arg("key-pass")));

         if(!key)
            {
            throw CLI_Error("Failed to load key from " + get_arg("key"));
            }

         const size_t days = get_arg_sz("days");

         Botan::X509_Cert_Options opts("", days * 24 * 60 * 60);

         opts.common_name  = get_arg("CN");
         opts.country      = get_arg("country");
         opts.organization = get_arg("organization");
         opts.email        = get_arg("email");
         opts.more_dns = Botan::split_on(get_arg("dns"), ',');
         const bool der_format = flag_set("der");

         std::string emsa = get_arg("emsa");

         if(emsa.empty() == false)
            opts.set_padding_scheme(emsa);

         if(flag_set("ca"))
            {
            opts.CA_key();
            }

         Botan::X509_Certificate cert = Botan::X509::create_self_signed_cert(opts, *key, get_arg("hash"), rng());

         if(der_format)
            {
            auto der = cert.BER_encode();
            output().write(reinterpret_cast<const char*>(der.data()), der.size());
            }
         else
            output() << cert.PEM_encode();
         }
   };

BOTAN_REGISTER_COMMAND("gen_self_signed", Gen_Self_Signed);

class Generate_PKCS10 final : public Command
   {
   public:
      Generate_PKCS10()
         : Command("gen_pkcs10 key CN --country= --organization= "
                   "--email= --dns= --ext-ku= --key-pass= --hash=SHA-256 --emsa=") {}

      std::string group() const override
         {
         return "x509";
         }

      std::string description() const override
         {
         return "Generate a PKCS #10 certificate signing request (CSR)";
         }

      void go() override
         {
         std::unique_ptr<Botan::Private_Key> key(Botan::PKCS8::load_key(get_arg("key"), rng(), get_arg("key-pass")));

         if(!key)
            {
            throw CLI_Error("Failed to load key from " + get_arg("key"));
            }

         Botan::X509_Cert_Options opts;

         opts.common_name  = get_arg("CN");
         opts.country      = get_arg("country");
         opts.organization = get_arg("organization");
         opts.email        = get_arg("email");
         opts.more_dns     = Botan::split_on(get_arg("dns"), ',');

         for(std::string ext_ku : Botan::split_on(get_arg("ext-ku"), ','))
            {
            opts.add_ex_constraint(ext_ku);
            }

         std::string emsa = get_arg("emsa");

         if(emsa.empty() == false)
            opts.set_padding_scheme(emsa);

         Botan::PKCS10_Request req = Botan::X509::create_cert_req(opts, *key, get_arg("hash"), rng());

         output() << req.PEM_encode();
         }
   };

BOTAN_REGISTER_COMMAND("gen_pkcs10", Generate_PKCS10);

}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLIndexUserSourceContext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: dvo $ $Date: 2002-01-09 12:57: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 _XMLOFF_XMLINDEXUSERSOURCECONTEXT_HXX_
#define _XMLOFF_XMLINDEXUSERSOURCECONTEXT_HXX_

#ifndef _XMLOFF_XMLINDEXSOURCEBASECONTEXT_HXX_
#include "XMLIndexSourceBaseContext.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
    namespace beans { class XPropertySet; }
} } }
namespace rtl { class OUString; }

/**
 * Import user defined index source element
 */
class XMLIndexUserSourceContext : public XMLIndexSourceBaseContext
{
    const ::rtl::OUString sCreateFromEmbeddedObjects;
    const ::rtl::OUString sCreateFromGraphicObjects;
    const ::rtl::OUString sCreateFromMarks;
    const ::rtl::OUString sCreateFromTables;
    const ::rtl::OUString sCreateFromTextFrames;
    const ::rtl::OUString sUseLevelFromSource;
    const ::rtl::OUString sCreateFromLevelParagraphStyles;
    const ::rtl::OUString sUserIndexName;

    sal_Bool bUseObjects;
    sal_Bool bUseGraphic;
    sal_Bool bUseMarks;
    sal_Bool bUseTables;
    sal_Bool bUseFrames;
    sal_Bool bUseLevelFromSource;
    sal_Bool bUseLevelParagraphStyles;
    ::rtl::OUString sIndexName;

public:

    TYPEINFO();

    XMLIndexUserSourceContext(
        SvXMLImport& rImport,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLocalName,
        ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet> & rPropSet);

    ~XMLIndexUserSourceContext();

protected:

    virtual void ProcessAttribute(
        enum IndexSourceParamEnum eParam,
        const ::rtl::OUString& rValue);

    virtual void EndElement();

    virtual SvXMLImportContext* CreateChildContext(
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.620); FILE MERGED 2005/09/05 14:39:56 rt 1.3.620.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLIndexUserSourceContext.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:13:23 $
 *
 *  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 _XMLOFF_XMLINDEXUSERSOURCECONTEXT_HXX_
#define _XMLOFF_XMLINDEXUSERSOURCECONTEXT_HXX_

#ifndef _XMLOFF_XMLINDEXSOURCEBASECONTEXT_HXX_
#include "XMLIndexSourceBaseContext.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
    namespace beans { class XPropertySet; }
} } }
namespace rtl { class OUString; }

/**
 * Import user defined index source element
 */
class XMLIndexUserSourceContext : public XMLIndexSourceBaseContext
{
    const ::rtl::OUString sCreateFromEmbeddedObjects;
    const ::rtl::OUString sCreateFromGraphicObjects;
    const ::rtl::OUString sCreateFromMarks;
    const ::rtl::OUString sCreateFromTables;
    const ::rtl::OUString sCreateFromTextFrames;
    const ::rtl::OUString sUseLevelFromSource;
    const ::rtl::OUString sCreateFromLevelParagraphStyles;
    const ::rtl::OUString sUserIndexName;

    sal_Bool bUseObjects;
    sal_Bool bUseGraphic;
    sal_Bool bUseMarks;
    sal_Bool bUseTables;
    sal_Bool bUseFrames;
    sal_Bool bUseLevelFromSource;
    sal_Bool bUseLevelParagraphStyles;
    ::rtl::OUString sIndexName;

public:

    TYPEINFO();

    XMLIndexUserSourceContext(
        SvXMLImport& rImport,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLocalName,
        ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet> & rPropSet);

    ~XMLIndexUserSourceContext();

protected:

    virtual void ProcessAttribute(
        enum IndexSourceParamEnum eParam,
        const ::rtl::OUString& rValue);

    virtual void EndElement();

    virtual SvXMLImportContext* CreateChildContext(
        sal_uInt16 nPrefix,
        const ::rtl::OUString& rLocalName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList );
};

#endif
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs        */
/*                                                                            */
/* 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 "RequestManagerProxy.h"
#include "Nebula.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

RequestManagerProxy::RequestManagerProxy(string _method)
    :Request("RequestManagerProxy", "?",
            "Forwards the request to another OpenNebula")
{
    Nebula& nd = Nebula::instance();

    long long msg_size;
    const string& master_endpoint = nd.get_master_oned();

    nd.get_configuration_attribute("MESSAGE_SIZE", msg_size);

    method = _method;
    client = new Client("none", master_endpoint, msg_size);

    method_name = ("Proxy - " + method);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

RequestManagerProxy::~RequestManagerProxy()
{
    delete client;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RequestManagerProxy::request_execute(xmlrpc_c::paramList const& _paramList,
        RequestAttributes& att)
{
    xmlrpc_c::value return_value;

    try
    {
        client->call(client->get_endpoint(), method, _paramList, &return_value);

        *(att.retval) = return_value;
    }
    catch(exception const& e)
    {
        failure_response(INTERNAL, request_error("Could not connect to the federation master oned", ""), att);
    }
}
<commit_msg>Feature #2665: Rename proxy methods to one.proxy.<remote method name><commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs        */
/*                                                                            */
/* 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 "RequestManagerProxy.h"
#include "Nebula.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

RequestManagerProxy::RequestManagerProxy(string _method)
    :Request("RequestManagerProxy", "?",
            "Forwards the request to another OpenNebula")
{
    Nebula& nd = Nebula::instance();

    long long msg_size;
    const string& master_endpoint = nd.get_master_oned();

    nd.get_configuration_attribute("MESSAGE_SIZE", msg_size);

    method = _method;
    client = new Client("none", master_endpoint, msg_size);

    method_name = ("one.proxy." + method);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

RequestManagerProxy::~RequestManagerProxy()
{
    delete client;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RequestManagerProxy::request_execute(xmlrpc_c::paramList const& _paramList,
        RequestAttributes& att)
{
    xmlrpc_c::value return_value;

    try
    {
        client->call(client->get_endpoint(), method, _paramList, &return_value);

        *(att.retval) = return_value;
    }
    catch(exception const& e)
    {
        failure_response(INTERNAL, request_error("Could not connect to the federation master oned", ""), att);
    }
}
<|endoftext|>


<commit_before>/**********************************************************************
 * File:        params.cpp
 * Description: Initialization and setting of Tesseract parameters.
 * Author:      Ray Smith
 * Created:     Fri Feb 22 16:22:34 GMT 1991
 *
 * (C) Copyright 1991, Hewlett-Packard Ltd.
 ** 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          <stdio.h>
#include          <string.h>
#include          <stdlib.h>

#include          "genericvector.h"
#include          "scanutils.h"
#include          "tprintf.h"
#include          "params.h"

#define PLUS          '+'        //flag states
#define MINUS         '-'
#define EQUAL         '='

tesseract::ParamsVectors *GlobalParams() {
  static tesseract::ParamsVectors *global_params =
    new tesseract::ParamsVectors();
  return global_params;
}

namespace tesseract {

bool ParamUtils::ReadParamsFile(const char *file,
                                SetParamConstraint constraint,
                                ParamsVectors *member_params) {
  inT16 nameoffset;              // offset for real name
  FILE *fp;                      // file pointer
                                 // iterators

  if (*file == PLUS) {
    nameoffset = 1;
  } else if (*file == MINUS) {
    nameoffset = 1;
  } else {
    nameoffset = 0;
  }

  fp = fopen(file + nameoffset, "rb");
  if (fp == NULL) {
    tprintf("read_params_file: Can't open %s\n", file + nameoffset);
    return true;
  }
  const bool anyerr = ReadParamsFromFp(fp, -1, constraint, member_params);
  fclose(fp);
  return anyerr;
}

bool ParamUtils::ReadParamsFromFp(FILE *fp, inT64 end_offset,
                                  SetParamConstraint constraint,
                                  ParamsVectors *member_params) {
  char line[MAX_PATH];           // input line
  bool anyerr = false;           // true if any error
  bool foundit;                  // found parameter
  char *valptr;                  // value field

  while ((end_offset < 0 || ftell(fp) < end_offset) &&
         fgets(line, MAX_PATH, fp)) {
    if (line[0] != '\n' && line[0] != '#') {
      chomp_string(line);  // remove newline
      for (valptr = line; *valptr && *valptr != ' ' && *valptr != '\t';
        valptr++);
      if (*valptr) {             // found blank
        *valptr = '\0';          // make name a string
        do
          valptr++;              // find end of blanks
        while (*valptr == ' ' || *valptr == '\t');
      }
      foundit = SetParam(line, valptr, constraint, member_params);

      if (!foundit) {
        anyerr = true;         // had an error
        tprintf("read_params_file: parameter not found: %s\n", line);
        exit(1);
      }
    }
  }
  return anyerr;
}

bool ParamUtils::SetParam(const char *name, const char* value,
                          SetParamConstraint constraint,
                          ParamsVectors *member_params) {
  // Look for the parameter among string parameters.
  StringParam *sp = FindParam<StringParam>(name, GlobalParams()->string_params,
                                           member_params->string_params);
  if (sp != NULL && sp->constraint_ok(constraint)) sp->set_value(value);
  if (*value == '\0') return (sp != NULL);

  // Look for the parameter among int parameters.
  int intval;
  IntParam *ip = FindParam<IntParam>(name, GlobalParams()->int_params,
                                     member_params->int_params);
  if (ip && ip->constraint_ok(constraint) &&
      sscanf(value, INT32FORMAT, &intval) == 1) ip->set_value(intval);

  // Look for the parameter among bool parameters.
  BoolParam *bp = FindParam<BoolParam>(name, GlobalParams()->bool_params,
                                       member_params->bool_params);
  if (bp != NULL && bp->constraint_ok(constraint)) {
    if (*value == 'T' || *value == 't' ||
        *value == 'Y' || *value == 'y' || *value == '1') {
      bp->set_value(true);
    } else if (*value == 'F' || *value == 'f' ||
                *value == 'N' || *value == 'n' || *value == '0') {
      bp->set_value(false);
    }
  }

  // Look for the parameter among double parameters.
  double doubleval;
  DoubleParam *dp = FindParam<DoubleParam>(name, GlobalParams()->double_params,
                                           member_params->double_params);
  if (dp != NULL && dp->constraint_ok(constraint)) {
#ifdef EMBEDDED
      doubleval = strtofloat(value);
#else
      if (sscanf(value, "%lf", &doubleval) == 1)
#endif
      dp->set_value(doubleval);
  }
  return (sp || ip || bp || dp);
}

bool ParamUtils::GetParamAsString(const char *name,
                                  const ParamsVectors* member_params,
                                  STRING *value) {
  // Look for the parameter among string parameters.
  StringParam *sp = FindParam<StringParam>(name, GlobalParams()->string_params,
                                           member_params->string_params);
  if (sp) {
    *value = sp->string();
    return true;
  }
  // Look for the parameter among int parameters.
  IntParam *ip = FindParam<IntParam>(name, GlobalParams()->int_params,
                                     member_params->int_params);
  if (ip) {
    char buf[128];
    snprintf(buf, sizeof(buf), "%d", inT32(*ip));
    *value = buf;
    return true;
  }
  // Look for the parameter among bool parameters.
  BoolParam *bp = FindParam<BoolParam>(name, GlobalParams()->bool_params,
                                       member_params->bool_params);
  if (bp != NULL) {
    *value = BOOL8(*bp) ? "1": "0";
    return true;
  }
  // Look for the parameter among double parameters.
  DoubleParam *dp = FindParam<DoubleParam>(name, GlobalParams()->double_params,
                                           member_params->double_params);
  if (dp != NULL) {
    char buf[128];
    snprintf(buf, sizeof(buf), "%g", double(*dp));
    *value = buf;
    return true;
  }
  return false;
}

void ParamUtils::PrintParams(FILE *fp, const ParamsVectors *member_params) {
  int v, i;
  int num_iterations = (member_params == NULL) ? 1 : 2;
  for (v = 0; v < num_iterations; ++v) {
    const ParamsVectors *vec = (v == 0) ? GlobalParams() : member_params;
    for (i = 0; i < vec->int_params.size(); ++i) {
      fprintf(fp, "%s\t%d\t%s\n", vec->int_params[i]->name_str(),
              (inT32)(*vec->int_params[i]), vec->int_params[i]->info_str());
    }
    for (i = 0; i < vec->bool_params.size(); ++i) {
      fprintf(fp, "%s\t%d\t%s\n", vec->bool_params[i]->name_str(),
              (BOOL8)(*vec->bool_params[i]), vec->bool_params[i]->info_str());
    }
    for (int i = 0; i < vec->string_params.size(); ++i) {
      fprintf(fp, "%s\t%s\t%s\n", vec->string_params[i]->name_str(),
              vec->string_params[i]->string(), vec->string_params[i]->info_str());
    }
    for (int i = 0; i < vec->double_params.size(); ++i) {
      fprintf(fp, "%s\t%g\t%s\n", vec->double_params[i]->name_str(),
              (double)(*vec->double_params[i]), vec->double_params[i]->info_str());
    }
  }
}

// Resets all parameters back to default values;
void ParamUtils::ResetToDefaults(ParamsVectors* member_params) {
  int v, i;
  int num_iterations = (member_params == NULL) ? 1 : 2;
  for (v = 0; v < num_iterations; ++v) {
    ParamsVectors *vec = (v == 0) ? GlobalParams() : member_params;
    for (i = 0; i < vec->int_params.size(); ++i) {
      vec->int_params[i]->ResetToDefault();
    }
    for (i = 0; i < vec->bool_params.size(); ++i) {
      vec->bool_params[i]->ResetToDefault();
    }
    for (int i = 0; i < vec->string_params.size(); ++i) {
      vec->string_params[i]->ResetToDefault();
    }
    for (int i = 0; i < vec->double_params.size(); ++i) {
      vec->double_params[i]->ResetToDefault();
    }
  }
}

}  // namespace tesseract
<commit_msg>ccutils/params: Fix memory leak for static variable global_params<commit_after>/**********************************************************************
 * File:        params.cpp
 * Description: Initialization and setting of Tesseract parameters.
 * Author:      Ray Smith
 * Created:     Fri Feb 22 16:22:34 GMT 1991
 *
 * (C) Copyright 1991, Hewlett-Packard Ltd.
 ** 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          <stdio.h>
#include          <string.h>
#include          <stdlib.h>

#include          "genericvector.h"
#include          "scanutils.h"
#include          "tprintf.h"
#include          "params.h"

#define PLUS          '+'        //flag states
#define MINUS         '-'
#define EQUAL         '='

tesseract::ParamsVectors *GlobalParams() {
  static tesseract::ParamsVectors global_params =
    tesseract::ParamsVectors();
  return &global_params;
}

namespace tesseract {

bool ParamUtils::ReadParamsFile(const char *file,
                                SetParamConstraint constraint,
                                ParamsVectors *member_params) {
  inT16 nameoffset;              // offset for real name
  FILE *fp;                      // file pointer
                                 // iterators

  if (*file == PLUS) {
    nameoffset = 1;
  } else if (*file == MINUS) {
    nameoffset = 1;
  } else {
    nameoffset = 0;
  }

  fp = fopen(file + nameoffset, "rb");
  if (fp == NULL) {
    tprintf("read_params_file: Can't open %s\n", file + nameoffset);
    return true;
  }
  const bool anyerr = ReadParamsFromFp(fp, -1, constraint, member_params);
  fclose(fp);
  return anyerr;
}

bool ParamUtils::ReadParamsFromFp(FILE *fp, inT64 end_offset,
                                  SetParamConstraint constraint,
                                  ParamsVectors *member_params) {
  char line[MAX_PATH];           // input line
  bool anyerr = false;           // true if any error
  bool foundit;                  // found parameter
  char *valptr;                  // value field

  while ((end_offset < 0 || ftell(fp) < end_offset) &&
         fgets(line, MAX_PATH, fp)) {
    if (line[0] != '\n' && line[0] != '#') {
      chomp_string(line);  // remove newline
      for (valptr = line; *valptr && *valptr != ' ' && *valptr != '\t';
        valptr++);
      if (*valptr) {             // found blank
        *valptr = '\0';          // make name a string
        do
          valptr++;              // find end of blanks
        while (*valptr == ' ' || *valptr == '\t');
      }
      foundit = SetParam(line, valptr, constraint, member_params);

      if (!foundit) {
        anyerr = true;         // had an error
        tprintf("read_params_file: parameter not found: %s\n", line);
        exit(1);
      }
    }
  }
  return anyerr;
}

bool ParamUtils::SetParam(const char *name, const char* value,
                          SetParamConstraint constraint,
                          ParamsVectors *member_params) {
  // Look for the parameter among string parameters.
  StringParam *sp = FindParam<StringParam>(name, GlobalParams()->string_params,
                                           member_params->string_params);
  if (sp != NULL && sp->constraint_ok(constraint)) sp->set_value(value);
  if (*value == '\0') return (sp != NULL);

  // Look for the parameter among int parameters.
  int intval;
  IntParam *ip = FindParam<IntParam>(name, GlobalParams()->int_params,
                                     member_params->int_params);
  if (ip && ip->constraint_ok(constraint) &&
      sscanf(value, INT32FORMAT, &intval) == 1) ip->set_value(intval);

  // Look for the parameter among bool parameters.
  BoolParam *bp = FindParam<BoolParam>(name, GlobalParams()->bool_params,
                                       member_params->bool_params);
  if (bp != NULL && bp->constraint_ok(constraint)) {
    if (*value == 'T' || *value == 't' ||
        *value == 'Y' || *value == 'y' || *value == '1') {
      bp->set_value(true);
    } else if (*value == 'F' || *value == 'f' ||
                *value == 'N' || *value == 'n' || *value == '0') {
      bp->set_value(false);
    }
  }

  // Look for the parameter among double parameters.
  double doubleval;
  DoubleParam *dp = FindParam<DoubleParam>(name, GlobalParams()->double_params,
                                           member_params->double_params);
  if (dp != NULL && dp->constraint_ok(constraint)) {
#ifdef EMBEDDED
      doubleval = strtofloat(value);
#else
      if (sscanf(value, "%lf", &doubleval) == 1)
#endif
      dp->set_value(doubleval);
  }
  return (sp || ip || bp || dp);
}

bool ParamUtils::GetParamAsString(const char *name,
                                  const ParamsVectors* member_params,
                                  STRING *value) {
  // Look for the parameter among string parameters.
  StringParam *sp = FindParam<StringParam>(name, GlobalParams()->string_params,
                                           member_params->string_params);
  if (sp) {
    *value = sp->string();
    return true;
  }
  // Look for the parameter among int parameters.
  IntParam *ip = FindParam<IntParam>(name, GlobalParams()->int_params,
                                     member_params->int_params);
  if (ip) {
    char buf[128];
    snprintf(buf, sizeof(buf), "%d", inT32(*ip));
    *value = buf;
    return true;
  }
  // Look for the parameter among bool parameters.
  BoolParam *bp = FindParam<BoolParam>(name, GlobalParams()->bool_params,
                                       member_params->bool_params);
  if (bp != NULL) {
    *value = BOOL8(*bp) ? "1": "0";
    return true;
  }
  // Look for the parameter among double parameters.
  DoubleParam *dp = FindParam<DoubleParam>(name, GlobalParams()->double_params,
                                           member_params->double_params);
  if (dp != NULL) {
    char buf[128];
    snprintf(buf, sizeof(buf), "%g", double(*dp));
    *value = buf;
    return true;
  }
  return false;
}

void ParamUtils::PrintParams(FILE *fp, const ParamsVectors *member_params) {
  int v, i;
  int num_iterations = (member_params == NULL) ? 1 : 2;
  for (v = 0; v < num_iterations; ++v) {
    const ParamsVectors *vec = (v == 0) ? GlobalParams() : member_params;
    for (i = 0; i < vec->int_params.size(); ++i) {
      fprintf(fp, "%s\t%d\t%s\n", vec->int_params[i]->name_str(),
              (inT32)(*vec->int_params[i]), vec->int_params[i]->info_str());
    }
    for (i = 0; i < vec->bool_params.size(); ++i) {
      fprintf(fp, "%s\t%d\t%s\n", vec->bool_params[i]->name_str(),
              (BOOL8)(*vec->bool_params[i]), vec->bool_params[i]->info_str());
    }
    for (int i = 0; i < vec->string_params.size(); ++i) {
      fprintf(fp, "%s\t%s\t%s\n", vec->string_params[i]->name_str(),
              vec->string_params[i]->string(), vec->string_params[i]->info_str());
    }
    for (int i = 0; i < vec->double_params.size(); ++i) {
      fprintf(fp, "%s\t%g\t%s\n", vec->double_params[i]->name_str(),
              (double)(*vec->double_params[i]), vec->double_params[i]->info_str());
    }
  }
}

// Resets all parameters back to default values;
void ParamUtils::ResetToDefaults(ParamsVectors* member_params) {
  int v, i;
  int num_iterations = (member_params == NULL) ? 1 : 2;
  for (v = 0; v < num_iterations; ++v) {
    ParamsVectors *vec = (v == 0) ? GlobalParams() : member_params;
    for (i = 0; i < vec->int_params.size(); ++i) {
      vec->int_params[i]->ResetToDefault();
    }
    for (i = 0; i < vec->bool_params.size(); ++i) {
      vec->bool_params[i]->ResetToDefault();
    }
    for (int i = 0; i < vec->string_params.size(); ++i) {
      vec->string_params[i]->ResetToDefault();
    }
    for (int i = 0; i < vec->double_params.size(); ++i) {
      vec->double_params[i]->ResetToDefault();
    }
  }
}

}  // namespace tesseract
<|endoftext|>


<commit_before>#include <qpainter.h>
#include <qpushbutton.h>
#include <qframe.h>
#include <qlayout.h>
#include <qwhatsthis.h>

#include "ui/Application.hpp"

extern pthread_cond_t cond;
extern pthread_mutex_t mutex;
extern int again;

/*
 *  Constructs a Application as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
Application::Application(const StatisticalSerie2D* serie2D)
    : QDialog(NULL, NULL, false, 0),
      serie2D(serie2D) {
    setName("Application");

    doneButton = new QPushButton("doneButton", this);
    doneButton->setGeometry(QRect(360, 280, 100, 29));
    doneButton->setAutoDefault(FALSE);

    drawButton = new QPushButton("drawButton", this);
    drawButton->setGeometry(QRect(240, 280, 100, 29));
    drawButton->setAutoDefault(FALSE);

    selectButton = new QPushButton("selectButton", this);
    selectButton->setGeometry(QRect(130, 280, 100, 29));
    selectButton->setAutoDefault(FALSE);

    refreshButton = new QPushButton("refreshButton", this);
    refreshButton->setGeometry(QRect(10, 280, 100, 29));
    refreshButton->setAutoDefault(FALSE);

    aRandomFrameWhichWeDontKnowWhatToDoWith = new QFrame(this);
    aRandomFrameWhichWeDontKnowWhatToDoWith->setGeometry(QRect(20, 20, 440, 240));
    aRandomFrameWhichWeDontKnowWhatToDoWith->setFrameShape(QFrame::StyledPanel);
    aRandomFrameWhichWeDontKnowWhatToDoWith->setFrameShadow(QFrame::Raised);
    languageChange();
    resize(QSize(475, 327).expandedTo(minimumSizeHint()));
    clearWState(WState_Polished);

    // signals and slots connections
    connect(refreshButton, SIGNAL(clicked()), this, SLOT(refresh()));
    connect(doneButton, SIGNAL(clicked()), this, SLOT(done()));
    connect(drawButton, SIGNAL(clicked()), this, SLOT(drawLine()));
    connect(selectButton, SIGNAL(clicked()), this, SLOT(select()));

    this->minX = serie2D->getData().getMinX();
    this->minY = serie2D->getData().getMinY();
    this->maxX = serie2D->getData().getMaxX();
    this->maxY = serie2D->getData().getMaxY();
}

/*
 *  Destroys the object and frees any allocated resources
 */
Application::~Application() {
    // no need to delete child widgets, Qt does it all for us
    cout << "dans destructeur FAffiche" << endl;
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void Application::languageChange() {
    setCaption(tr("Data display"));
    doneButton->setText(tr("Done"));
    drawButton->setText(tr("Draw line"));
    selectButton->setText(tr("Select"));
    refreshButton->setText(tr("Refresh"));
}

void Application::refresh() {
    qWarning("Application::refresh()");
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);

    Data2DIterator it(this->serie2D->getData().getData());

    while(!it.end()) {
        paint.drawText(transformX(it.getX()), transformY(it.getY()), "x");
        ++it;
    }
}

void Application::drawLine() {
    qWarning("Application::drawLine()");
    /*
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);
    paint.drawLine(,,,);
    */

}

void Application::done() {
    qWarning("Application::done(): Not implemented yet");
    /*
    place une variable continue a 0 et signale au main
    ...
    */
    close();
}

void Application::select() {
    qWarning("Application::select() ");
    /*
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);
    paint.setPen(Qt::black);
    paint.drawRect(startingPoint.x(),startingPoint.y(),
            endingPoint.x()-startingPoint.x(),endingPoint.y()-startingPoint.y());
    ...
    classes les 2 point selectionnes
    ...
    retire les points de la zone selectionnee de la liste

    place une variable continue a 1 et signale au main
    ...
    */
}

void Application::mouseMoveEvent(QMouseEvent* e) {
}

void Application::mouseReleaseEvent(QMouseEvent* e) {
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);
    if(isMouseButtonDown) {
        endingPoint = e->pos();
        endingPoint.setX(endingPoint.x() - 20);
        endingPoint.setY(endingPoint.y() - 20);
        paint.drawText(endingPoint.x() - 4, endingPoint.y() + 4, "x");
        isMouseButtonDown = false;
    }
    cout << "Start: " << startingPoint.x() << " - " << startingPoint.y() << endl;
    cout << "End: " << endingPoint.x() << " - " << endingPoint.y() << endl;
}

void Application::mousePressEvent(QMouseEvent* e) {
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);
    if(!isMouseButtonDown) {
        startingPoint = e->pos();
        startingPoint.setX(startingPoint.x() - 20);
        startingPoint.setY(startingPoint.y() - 20);
        paint.drawText(startingPoint.x() - 4, startingPoint.y() + 4, "x");
        isMouseButtonDown = true;
    }
}

unsigned Application::transformX(float pX) const {
    return (unsigned) round((pX - minX) / (maxX - minX) * 400);
}

unsigned Application::transformY(float pY) const {
    return (unsigned) round((pY - minY) / (maxY - minY) * 200);
}

/************************************
 * Do not touch below here, teacher
 * did stuff, you don't want to know
 * anything more.
 ************************************/
const char* Application::className() const {
    return "Application";
}

QMetaObject* Application::metaObj = 0;
static QMetaObjectCleanUp cleanUp_FAffichage("Application", &Application::staticMetaObject);

QString Application::tr(const char* s, const char* c) {
    if(qApp) {
        return qApp->translate("Application", s, c, QApplication::DefaultCodec);
    } else {
        return QString::fromLatin1(s);
    }
}

QString Application::trUtf8(const char* s, const char* c) {
    if(qApp) {
        return qApp->translate("Application", s, c, QApplication::UnicodeUTF8);
    } else {
        return QString::fromUtf8(s);
    }
}

QMetaObject* Application::staticMetaObject() {
    if(metaObj) {
        return metaObj;
    }
    QMetaObject* parentObject = QDialog::staticMetaObject();
    static const QUMethod slot_0 = {"refresh", 0, 0};
    static const QUMethod slot_1 = {"drawLine", 0, 0};
    static const QUMethod slot_2 = {"done", 0, 0};
    static const QUMethod slot_3 = {"select", 0, 0};
    static const QUMethod slot_4 = {"languageChange", 0, 0};
    static const QMetaData slot_tbl[] = {
        {"refresh()", &slot_0, QMetaData::Public},
        {"drawLine()", &slot_1, QMetaData::Public},
        {"done()", &slot_2, QMetaData::Public},
        {"select()", &slot_3, QMetaData::Public},
        {"languageChange()", &slot_4, QMetaData::Protected}
    };
    metaObj = QMetaObject::new_metaobject(
        "Application", parentObject,
        slot_tbl, 5,
        0, 0,
#ifndef QT_NO_PROPERTIES
        0, 0,
        0, 0,
#endif // QT_NO_PROPERTIES
        0, 0);
    cleanUp_FAffichage.setMetaObject(metaObj);
    return metaObj;
}

void* Application::qt_cast(const char* clname) {
    if(!qstrcmp(clname, "Application")) {
        return this;
    }
    return QDialog::qt_cast(clname);
}

bool Application::qt_invoke(int _id, QUObject* _o) {
    switch(_id - staticMetaObject()->slotOffset()) {
        case 0:
            refresh();
            break;
        case 1:
            drawLine();
            break;
        case 2:
            done();
            break;
        case 3:
            select();
            break;
        case 4:
            languageChange();
            break;
        default:
            return QDialog::qt_invoke(_id, _o);
    }
    return true;
}

bool Application::qt_emit(int _id, QUObject* _o) {
    return QDialog::qt_emit(_id, _o);
}

#ifndef QT_NO_PROPERTIES

bool Application::qt_property(int id, int f, QVariant* v) {
    return QDialog::qt_property(id, f, v);
}

bool Application::qt_static_property(QObject*, int, int, QVariant*) {
    return false;
}

#endif // QT_NO_PROPERTIES
<commit_msg>Draw some lines yoh o/<commit_after>#include <qpainter.h>
#include <qpushbutton.h>
#include <qframe.h>
#include <qlayout.h>
#include <qwhatsthis.h>

#include "ui/Application.hpp"

extern pthread_cond_t cond;
extern pthread_mutex_t mutex;
extern int again;

/*
 *  Constructs a Application as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
Application::Application(const StatisticalSerie2D* serie2D)
    : QDialog(NULL, NULL, false, 0),
      serie2D(serie2D) {
    setName("Application");

    doneButton = new QPushButton("doneButton", this);
    doneButton->setGeometry(QRect(360, 280, 100, 29));
    doneButton->setAutoDefault(FALSE);

    drawButton = new QPushButton("drawButton", this);
    drawButton->setGeometry(QRect(240, 280, 100, 29));
    drawButton->setAutoDefault(FALSE);

    selectButton = new QPushButton("selectButton", this);
    selectButton->setGeometry(QRect(130, 280, 100, 29));
    selectButton->setAutoDefault(FALSE);

    refreshButton = new QPushButton("refreshButton", this);
    refreshButton->setGeometry(QRect(10, 280, 100, 29));
    refreshButton->setAutoDefault(FALSE);

    aRandomFrameWhichWeDontKnowWhatToDoWith = new QFrame(this);
    aRandomFrameWhichWeDontKnowWhatToDoWith->setGeometry(QRect(20, 20, 440, 240));
    aRandomFrameWhichWeDontKnowWhatToDoWith->setFrameShape(QFrame::StyledPanel);
    aRandomFrameWhichWeDontKnowWhatToDoWith->setFrameShadow(QFrame::Raised);
    languageChange();
    resize(QSize(475, 327).expandedTo(minimumSizeHint()));
    clearWState(WState_Polished);

    // signals and slots connections
    connect(refreshButton, SIGNAL(clicked()), this, SLOT(refresh()));
    connect(doneButton, SIGNAL(clicked()), this, SLOT(done()));
    connect(drawButton, SIGNAL(clicked()), this, SLOT(drawLine()));
    connect(selectButton, SIGNAL(clicked()), this, SLOT(select()));

    this->minX = serie2D->getData().getMinX();
    this->minY = serie2D->getData().getMinY();
    this->maxX = serie2D->getData().getMaxX();
    this->maxY = serie2D->getData().getMaxY();
}

/*
 *  Destroys the object and frees any allocated resources
 */
Application::~Application() {
    // no need to delete child widgets, Qt does it all for us
    cout << "dans destructeur FAffiche" << endl;
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void Application::languageChange() {
    setCaption(tr("Data display"));
    doneButton->setText(tr("Done"));
    drawButton->setText(tr("Draw line"));
    selectButton->setText(tr("Select"));
    refreshButton->setText(tr("Refresh"));
}

void Application::refresh() {
    qWarning("Application::refresh()");
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);

    Data2DIterator it(this->serie2D->getData().getData());

    while(!it.end()) {
        paint.drawText(transformX(it.getX()), transformY(it.getY()), "x");
        ++it;
    }
}

void Application::drawLine() {
    qWarning("Application::drawLine()");

    float a = this->serie2D->getCoefficientA();
    float b = this->serie2D->getCoefficientB();

    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);

    paint.drawLine(
        transformX(this->minX),
        transformY(a * this->minX + b),
        transformX(this->maxX),
        transformY(a * this->maxX + b)
    );
}

void Application::done() {
    qWarning("Application::done(): Not implemented yet");
    /*
    place une variable continue a 0 et signale au main
    ...
    */
    close();
}

void Application::select() {
    qWarning("Application::select() ");
    /*
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);
    paint.setPen(Qt::black);
    paint.drawRect(startingPoint.x(),startingPoint.y(),
            endingPoint.x()-startingPoint.x(),endingPoint.y()-startingPoint.y());
    ...
    classes les 2 point selectionnes
    ...
    retire les points de la zone selectionnee de la liste

    place une variable continue a 1 et signale au main
    ...
    */
}

void Application::mouseMoveEvent(QMouseEvent* e) {
}

void Application::mouseReleaseEvent(QMouseEvent* e) {
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);
    if(isMouseButtonDown) {
        endingPoint = e->pos();
        endingPoint.setX(endingPoint.x() - 20);
        endingPoint.setY(endingPoint.y() - 20);
        paint.drawText(endingPoint.x() - 4, endingPoint.y() + 4, "x");
        isMouseButtonDown = false;
    }
    cout << "Start: " << startingPoint.x() << " - " << startingPoint.y() << endl;
    cout << "End: " << endingPoint.x() << " - " << endingPoint.y() << endl;
}

void Application::mousePressEvent(QMouseEvent* e) {
    QPainter paint(aRandomFrameWhichWeDontKnowWhatToDoWith);
    if(!isMouseButtonDown) {
        startingPoint = e->pos();
        startingPoint.setX(startingPoint.x() - 20);
        startingPoint.setY(startingPoint.y() - 20);
        paint.drawText(startingPoint.x() - 4, startingPoint.y() + 4, "x");
        isMouseButtonDown = true;
    }
}

unsigned Application::transformX(float pX) const {
    return (unsigned) round((pX - minX) / (maxX - minX) * 400) + 10;
}

unsigned Application::transformY(float pY) const {
    return (unsigned) round((pY - minY) / (maxY - minY) * 200) + 20;
}

/************************************
 * Do not touch below here, teacher
 * did stuff, you don't want to know
 * anything more.
 ************************************/
const char* Application::className() const {
    return "Application";
}

QMetaObject* Application::metaObj = 0;
static QMetaObjectCleanUp cleanUp_FAffichage("Application", &Application::staticMetaObject);

QString Application::tr(const char* s, const char* c) {
    if(qApp) {
        return qApp->translate("Application", s, c, QApplication::DefaultCodec);
    } else {
        return QString::fromLatin1(s);
    }
}

QString Application::trUtf8(const char* s, const char* c) {
    if(qApp) {
        return qApp->translate("Application", s, c, QApplication::UnicodeUTF8);
    } else {
        return QString::fromUtf8(s);
    }
}

QMetaObject* Application::staticMetaObject() {
    if(metaObj) {
        return metaObj;
    }
    QMetaObject* parentObject = QDialog::staticMetaObject();
    static const QUMethod slot_0 = {"refresh", 0, 0};
    static const QUMethod slot_1 = {"drawLine", 0, 0};
    static const QUMethod slot_2 = {"done", 0, 0};
    static const QUMethod slot_3 = {"select", 0, 0};
    static const QUMethod slot_4 = {"languageChange", 0, 0};
    static const QMetaData slot_tbl[] = {
        {"refresh()", &slot_0, QMetaData::Public},
        {"drawLine()", &slot_1, QMetaData::Public},
        {"done()", &slot_2, QMetaData::Public},
        {"select()", &slot_3, QMetaData::Public},
        {"languageChange()", &slot_4, QMetaData::Protected}
    };
    metaObj = QMetaObject::new_metaobject(
        "Application", parentObject,
        slot_tbl, 5,
        0, 0,
#ifndef QT_NO_PROPERTIES
        0, 0,
        0, 0,
#endif // QT_NO_PROPERTIES
        0, 0);
    cleanUp_FAffichage.setMetaObject(metaObj);
    return metaObj;
}

void* Application::qt_cast(const char* clname) {
    if(!qstrcmp(clname, "Application")) {
        return this;
    }
    return QDialog::qt_cast(clname);
}

bool Application::qt_invoke(int _id, QUObject* _o) {
    switch(_id - staticMetaObject()->slotOffset()) {
        case 0:
            refresh();
            break;
        case 1:
            drawLine();
            break;
        case 2:
            done();
            break;
        case 3:
            select();
            break;
        case 4:
            languageChange();
            break;
        default:
            return QDialog::qt_invoke(_id, _o);
    }
    return true;
}

bool Application::qt_emit(int _id, QUObject* _o) {
    return QDialog::qt_emit(_id, _o);
}

#ifndef QT_NO_PROPERTIES

bool Application::qt_property(int id, int f, QVariant* v) {
    return QDialog::qt_property(id, f, v);
}

bool Application::qt_static_property(QObject*, int, int, QVariant*) {
    return false;
}

#endif // QT_NO_PROPERTIES
<|endoftext|>


<commit_before><commit_msg>Create 1240 - Fit or Dont Fit I.cpp<commit_after><|endoftext|>