<commit_before>/*
 * Copyright © 2013 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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.
 */

/**
 * \file opt_cse.cpp
 *
 * constant subexpression elimination at the GLSL IR level.
 *
 * Compare to brw_fs_cse.cpp for a more complete CSE implementation.  This one
 * is generic and handles texture operations, but it's rather simple currently
 * and doesn't support modification of variables in the available expressions
 * list, so it can't do variables other than uniforms or shader inputs.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_rvalue_visitor.h"
#include "ir_basic_block.h"
#include "ir_optimization.h"
#include "ir_builder.h"
#include "glsl_types.h"

using namespace ir_builder;

static bool debug = false;

namespace {

/**
 * This is the record of an available expression for common subexpression
 * elimination.
 */
class ae_entry : public exec_node
{
public:
   ae_entry(ir_instruction *base_ir, ir_rvalue **val)
      : val(val), base_ir(base_ir)
   {
      assert(val);
      assert(*val);
      assert(base_ir);

      var = NULL;
   }

   /**
    * The pointer to the expression that we might be able to reuse
    *
    * Note the double pointer -- this is the place in the base_ir expression
    * tree that we would rewrite to move the expression out to a new variable
    * assignment.
    */
   ir_rvalue **val;

   /**
    * Root instruction in the basic block where the expression appeared.
    *
    * This is used so that we can insert the new variable declaration into the
    * instruction stream (since *val is just somewhere in base_ir's expression
    * tree).
    */
   ir_instruction *base_ir;

   /**
    * The variable that the expression has been stored in, if it's been CSEd
    * once already.
    */
   ir_variable *var;
};

class cse_visitor : public ir_rvalue_visitor {
public:
   cse_visitor(exec_list *validate_instructions)
      : validate_instructions(validate_instructions)
   {
      progress = false;
      mem_ctx = ralloc_context(NULL);
      this->ae = new(mem_ctx) exec_list;
   }
   ~cse_visitor()
   {
      ralloc_free(mem_ctx);
   }

   virtual ir_visitor_status visit_enter(ir_function_signature *ir);
   virtual ir_visitor_status visit_enter(ir_loop *ir);
   virtual ir_visitor_status visit_enter(ir_if *ir);
   virtual ir_visitor_status visit_enter(ir_call *ir);
   virtual void handle_rvalue(ir_rvalue **rvalue);

   bool progress;

private:
   void *mem_ctx;

   ir_rvalue *try_cse(ir_rvalue *rvalue);
   void add_to_ae(ir_rvalue **rvalue);

   /** List of ae_entry: The available expressions to reuse */
   exec_list *ae;

   /**
    * The whole shader, so that we can validate_ir_tree in debug mode.
    *
    * This proved quite useful when trying to get the tree manipulation
    * right.
    */
   exec_list *validate_instructions;
};

/**
 * Visitor to walk an expression tree to check that all variables referenced
 * are constants.
 */
class is_cse_candidate_visitor : public ir_hierarchical_visitor
{
public:

   is_cse_candidate_visitor()
      : ok(true)
   {
   }

   virtual ir_visitor_status visit(ir_dereference_variable *ir);

   bool ok;
};

class contains_rvalue_visitor : public ir_rvalue_visitor
{
public:

   contains_rvalue_visitor(ir_rvalue *val)
      : val(val)
   {
      found = false;
   }

   virtual void handle_rvalue(ir_rvalue **rvalue);

   bool found;

private:
   ir_rvalue *val;
};

} /* unnamed namespace */

static void
dump_ae(exec_list *ae)
{
   int i = 0;

   printf("CSE: AE contents:\n");
   foreach_in_list(ae_entry, entry, ae) {
      printf("CSE:   AE %2d (%p): ", i, entry);
      (*entry->val)->print();
      printf("\n");

      if (entry->var)
         printf("CSE:     in var %p:\n", entry->var);

      i++;
   }
}

ir_visitor_status
is_cse_candidate_visitor::visit(ir_dereference_variable *ir)
{
   /* Currently, since we don't handle kills of the ae based on variables
    * getting assigned, we can only handle constant variables.
    */
   if (ir->var->data.read_only) {
      return visit_continue;
   } else {
      ok = false;
      return visit_stop;
   }
}

void
contains_rvalue_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (*rvalue == val)
      found = true;
}

static bool
contains_rvalue(ir_rvalue *haystack, ir_rvalue *needle)
{
   contains_rvalue_visitor v(needle);
   haystack->accept(&v);
   return v.found;
}

static bool
is_cse_candidate(ir_rvalue *ir)
{
   /* Our temporary variable assignment generation isn't ready to handle
    * anything bigger than a vector.
    */
   if (!ir->type->is_vector() && !ir->type->is_scalar())
      return false;

   /* Only handle expressions and textures currently.  We may want to extend
    * to variable-index array dereferences at some point.
    */
   switch (ir->ir_type) {
   case ir_type_expression:
   case ir_type_texture:
      break;
   default:
      return false;
   }

   is_cse_candidate_visitor v;

   ir->accept(&v);

   return v.ok;
}

/**
 * Tries to find and return a reference to a previous computation of a given
 * expression.
 *
 * Walk the list of available expressions checking if any of them match the
 * rvalue, and if so, move the previous copy of the expression to a temporary
 * and return a reference of the temporary.
 */
ir_rvalue *
cse_visitor::try_cse(ir_rvalue *rvalue)
{
   foreach_in_list(ae_entry, entry, ae) {
      if (debug) {
         printf("Comparing to AE %p: ", entry);
         (*entry->val)->print();
         printf("\n");
      }

      if (!rvalue->equals(*entry->val))
         continue;

      if (debug) {
         printf("CSE: Replacing: ");
         (*entry->val)->print();
         printf("\n");
         printf("CSE:      with: ");
         rvalue->print();
         printf("\n");
      }

      if (!entry->var) {
         ir_instruction *base_ir = entry->base_ir;

         ir_variable *var = new(rvalue) ir_variable(rvalue->type,
                                                    "cse",
                                                    ir_var_temporary);

         /* Write the previous expression result into a new variable. */
         base_ir->insert_before(var);
         ir_assignment *assignment = assign(var, *entry->val);
         base_ir->insert_before(assignment);

         /* Replace the expression in the original tree with a deref of the
          * variable, but keep tracking the expression for further reuse.
          */
         *entry->val = new(rvalue) ir_dereference_variable(var);
         entry->val = &assignment->rhs;

         entry->var = var;

         /* Update the base_irs in the AE list.  We have to be sure that
          * they're correct -- expressions from our base_ir that weren't moved
          * need to stay in this base_ir (so that later consumption of them
          * puts new variables between our new variable and our base_ir), but
          * expressions from our base_ir that we *did* move need base_ir
          * updated so that any further elimination from inside gets its new
          * assignments put before our new assignment.
          */
         foreach_in_list(ae_entry, fixup_entry, ae) {
            if (contains_rvalue(assignment->rhs, *fixup_entry->val))
               fixup_entry->base_ir = assignment;
         }

         if (debug)
            dump_ae(ae);
      }

      /* Replace the expression in our current tree with the variable. */
      return new(rvalue) ir_dereference_variable(entry->var);
   }

   return NULL;
}

/** Add the rvalue to the list of available expressions for CSE. */
void
cse_visitor::add_to_ae(ir_rvalue **rvalue)
{
   if (debug) {
      printf("CSE: Add to AE: ");
      (*rvalue)->print();
      printf("\n");
   }

   ae->push_tail(new(mem_ctx) ae_entry(base_ir, rvalue));

   if (debug)
      dump_ae(ae);
}

void
cse_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (!*rvalue)
      return;

   if (debug) {
      printf("CSE: handle_rvalue ");
      (*rvalue)->print();
      printf("\n");
   }

   if (!is_cse_candidate(*rvalue))
      return;

   ir_rvalue *new_rvalue = try_cse(*rvalue);
   if (new_rvalue) {
      *rvalue = new_rvalue;
      progress = true;

      if (debug)
         validate_ir_tree(validate_instructions);
   } else {
      add_to_ae(rvalue);
   }
}

ir_visitor_status
cse_visitor::visit_enter(ir_if *ir)
{
   handle_rvalue(&ir->condition);

   ae->make_empty();
   visit_list_elements(this, &ir->then_instructions);

   ae->make_empty();
   visit_list_elements(this, &ir->else_instructions);

   ae->make_empty();
   return visit_continue_with_parent;
}

ir_visitor_status
cse_visitor::visit_enter(ir_function_signature *ir)
{
   ae->make_empty();
   visit_list_elements(this, &ir->body);

   ae->make_empty();
   return visit_continue_with_parent;
}

ir_visitor_status
cse_visitor::visit_enter(ir_loop *ir)
{
   ae->make_empty();
   visit_list_elements(this, &ir->body_instructions);

   ae->make_empty();
   return visit_continue_with_parent;
}

ir_visitor_status
cse_visitor::visit_enter(ir_call *)
{
   /* Because call is an exec_list of ir_rvalues, handle_rvalue gets passed a
    * pointer to the (ir_rvalue *) on the stack.  Since we save those pointers
    * in the AE list, we can't let handle_rvalue get called.
    */
   return visit_continue_with_parent;
}

/**
 * Does a (uniform-value) constant subexpression elimination pass on the code
 * present in the instruction stream.
 */
bool
do_cse(exec_list *instructions)
{
   cse_visitor v(instructions);

   visit_list_elements(&v, instructions);

   return v.progress;
}
<commit_msg>glsl: Improve the CSE pass debugging output.<commit_after>/*
 * Copyright © 2013 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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.
 */

/**
 * \file opt_cse.cpp
 *
 * constant subexpression elimination at the GLSL IR level.
 *
 * Compare to brw_fs_cse.cpp for a more complete CSE implementation.  This one
 * is generic and handles texture operations, but it's rather simple currently
 * and doesn't support modification of variables in the available expressions
 * list, so it can't do variables other than uniforms or shader inputs.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_rvalue_visitor.h"
#include "ir_basic_block.h"
#include "ir_optimization.h"
#include "ir_builder.h"
#include "glsl_types.h"

using namespace ir_builder;

static bool debug = false;

namespace {

/**
 * This is the record of an available expression for common subexpression
 * elimination.
 */
class ae_entry : public exec_node
{
public:
   ae_entry(ir_instruction *base_ir, ir_rvalue **val)
      : val(val), base_ir(base_ir)
   {
      assert(val);
      assert(*val);
      assert(base_ir);

      var = NULL;
   }

   /**
    * The pointer to the expression that we might be able to reuse
    *
    * Note the double pointer -- this is the place in the base_ir expression
    * tree that we would rewrite to move the expression out to a new variable
    * assignment.
    */
   ir_rvalue **val;

   /**
    * Root instruction in the basic block where the expression appeared.
    *
    * This is used so that we can insert the new variable declaration into the
    * instruction stream (since *val is just somewhere in base_ir's expression
    * tree).
    */
   ir_instruction *base_ir;

   /**
    * The variable that the expression has been stored in, if it's been CSEd
    * once already.
    */
   ir_variable *var;
};

class cse_visitor : public ir_rvalue_visitor {
public:
   cse_visitor(exec_list *validate_instructions)
      : validate_instructions(validate_instructions)
   {
      progress = false;
      mem_ctx = ralloc_context(NULL);
      this->ae = new(mem_ctx) exec_list;
   }
   ~cse_visitor()
   {
      ralloc_free(mem_ctx);
   }

   virtual ir_visitor_status visit_enter(ir_function_signature *ir);
   virtual ir_visitor_status visit_enter(ir_loop *ir);
   virtual ir_visitor_status visit_enter(ir_if *ir);
   virtual ir_visitor_status visit_enter(ir_call *ir);
   virtual void handle_rvalue(ir_rvalue **rvalue);

   bool progress;

private:
   void *mem_ctx;

   ir_rvalue *try_cse(ir_rvalue *rvalue);
   void add_to_ae(ir_rvalue **rvalue);

   /** List of ae_entry: The available expressions to reuse */
   exec_list *ae;

   /**
    * The whole shader, so that we can validate_ir_tree in debug mode.
    *
    * This proved quite useful when trying to get the tree manipulation
    * right.
    */
   exec_list *validate_instructions;
};

/**
 * Visitor to walk an expression tree to check that all variables referenced
 * are constants.
 */
class is_cse_candidate_visitor : public ir_hierarchical_visitor
{
public:

   is_cse_candidate_visitor()
      : ok(true)
   {
   }

   virtual ir_visitor_status visit(ir_dereference_variable *ir);

   bool ok;
};

class contains_rvalue_visitor : public ir_rvalue_visitor
{
public:

   contains_rvalue_visitor(ir_rvalue *val)
      : val(val)
   {
      found = false;
   }

   virtual void handle_rvalue(ir_rvalue **rvalue);

   bool found;

private:
   ir_rvalue *val;
};

} /* unnamed namespace */

static void
dump_ae(exec_list *ae)
{
   int i = 0;

   printf("CSE: AE contents:\n");
   foreach_in_list(ae_entry, entry, ae) {
      printf("CSE:   AE %2d (%p): ", i, entry);
      (*entry->val)->print();
      printf("\n");

      if (entry->var)
         printf("CSE:     in var %p:\n", entry->var);

      i++;
   }
}

ir_visitor_status
is_cse_candidate_visitor::visit(ir_dereference_variable *ir)
{
   /* Currently, since we don't handle kills of the ae based on variables
    * getting assigned, we can only handle constant variables.
    */
   if (ir->var->data.read_only) {
      return visit_continue;
   } else {
      if (debug)
         printf("CSE: non-candidate: var %s is not read only\n", ir->var->name);
      ok = false;
      return visit_stop;
   }
}

void
contains_rvalue_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (*rvalue == val)
      found = true;
}

static bool
contains_rvalue(ir_rvalue *haystack, ir_rvalue *needle)
{
   contains_rvalue_visitor v(needle);
   haystack->accept(&v);
   return v.found;
}

static bool
is_cse_candidate(ir_rvalue *ir)
{
   /* Our temporary variable assignment generation isn't ready to handle
    * anything bigger than a vector.
    */
   if (!ir->type->is_vector() && !ir->type->is_scalar()) {
      if (debug)
         printf("CSE: non-candidate: not a vector/scalar\n");
      return false;
   }

   /* Only handle expressions and textures currently.  We may want to extend
    * to variable-index array dereferences at some point.
    */
   switch (ir->ir_type) {
   case ir_type_expression:
   case ir_type_texture:
      break;
   default:
      if (debug)
         printf("CSE: non-candidate: not an expression/texture\n");
      return false;
   }

   is_cse_candidate_visitor v;

   ir->accept(&v);

   return v.ok;
}

/**
 * Tries to find and return a reference to a previous computation of a given
 * expression.
 *
 * Walk the list of available expressions checking if any of them match the
 * rvalue, and if so, move the previous copy of the expression to a temporary
 * and return a reference of the temporary.
 */
ir_rvalue *
cse_visitor::try_cse(ir_rvalue *rvalue)
{
   foreach_in_list(ae_entry, entry, ae) {
      if (debug) {
         printf("Comparing to AE %p: ", entry);
         (*entry->val)->print();
         printf("\n");
      }

      if (!rvalue->equals(*entry->val))
         continue;

      if (debug) {
         printf("CSE: Replacing: ");
         (*entry->val)->print();
         printf("\n");
         printf("CSE:      with: ");
         rvalue->print();
         printf("\n");
      }

      if (!entry->var) {
         ir_instruction *base_ir = entry->base_ir;

         ir_variable *var = new(rvalue) ir_variable(rvalue->type,
                                                    "cse",
                                                    ir_var_temporary);

         /* Write the previous expression result into a new variable. */
         base_ir->insert_before(var);
         ir_assignment *assignment = assign(var, *entry->val);
         base_ir->insert_before(assignment);

         /* Replace the expression in the original tree with a deref of the
          * variable, but keep tracking the expression for further reuse.
          */
         *entry->val = new(rvalue) ir_dereference_variable(var);
         entry->val = &assignment->rhs;

         entry->var = var;

         /* Update the base_irs in the AE list.  We have to be sure that
          * they're correct -- expressions from our base_ir that weren't moved
          * need to stay in this base_ir (so that later consumption of them
          * puts new variables between our new variable and our base_ir), but
          * expressions from our base_ir that we *did* move need base_ir
          * updated so that any further elimination from inside gets its new
          * assignments put before our new assignment.
          */
         foreach_in_list(ae_entry, fixup_entry, ae) {
            if (contains_rvalue(assignment->rhs, *fixup_entry->val))
               fixup_entry->base_ir = assignment;
         }

         if (debug)
            dump_ae(ae);
      }

      /* Replace the expression in our current tree with the variable. */
      return new(rvalue) ir_dereference_variable(entry->var);
   }

   return NULL;
}

/** Add the rvalue to the list of available expressions for CSE. */
void
cse_visitor::add_to_ae(ir_rvalue **rvalue)
{
   if (debug) {
      printf("CSE: Add to AE: ");
      (*rvalue)->print();
      printf("\n");
   }

   ae->push_tail(new(mem_ctx) ae_entry(base_ir, rvalue));

   if (debug)
      dump_ae(ae);
}

void
cse_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (!*rvalue)
      return;

   if (debug) {
      printf("CSE: handle_rvalue ");
      (*rvalue)->print();
      printf("\n");
   }

   if (!is_cse_candidate(*rvalue))
      return;

   ir_rvalue *new_rvalue = try_cse(*rvalue);
   if (new_rvalue) {
      *rvalue = new_rvalue;
      progress = true;

      if (debug)
         validate_ir_tree(validate_instructions);
   } else {
      add_to_ae(rvalue);
   }
}

ir_visitor_status
cse_visitor::visit_enter(ir_if *ir)
{
   handle_rvalue(&ir->condition);

   ae->make_empty();
   visit_list_elements(this, &ir->then_instructions);

   ae->make_empty();
   visit_list_elements(this, &ir->else_instructions);

   ae->make_empty();
   return visit_continue_with_parent;
}

ir_visitor_status
cse_visitor::visit_enter(ir_function_signature *ir)
{
   ae->make_empty();
   visit_list_elements(this, &ir->body);

   ae->make_empty();
   return visit_continue_with_parent;
}

ir_visitor_status
cse_visitor::visit_enter(ir_loop *ir)
{
   ae->make_empty();
   visit_list_elements(this, &ir->body_instructions);

   ae->make_empty();
   return visit_continue_with_parent;
}

ir_visitor_status
cse_visitor::visit_enter(ir_call *)
{
   /* Because call is an exec_list of ir_rvalues, handle_rvalue gets passed a
    * pointer to the (ir_rvalue *) on the stack.  Since we save those pointers
    * in the AE list, we can't let handle_rvalue get called.
    */
   return visit_continue_with_parent;
}

/**
 * Does a (uniform-value) constant subexpression elimination pass on the code
 * present in the instruction stream.
 */
bool
do_cse(exec_list *instructions)
{
   cse_visitor v(instructions);

   visit_list_elements(&v, instructions);

   return v.progress;
}
<|endoftext|>


<commit_before>//#include "stdafx.h"
#include <iostream>
//#include <conio.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <string>
#include <sstream>

double alpha = 2.0; /**< Simple contrast control */
int beta = 3;  /**< Simple brightness control */

int HighR = 255;
int LowR = 244;
int HighG = 255;
int LowG = 0;
int HighB = 112;
int LowB = 23;

double iLastX = -1;
double iLastY = -1;

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
	VideoCapture cap(0); //capture the video from webcam

	cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);

	if (!cap.isOpened())  // if not success, exit program
	{
		cout << "Cannot open the web cam" << endl;
		return -1;
	}
	namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
	//Create trackbars in "Control" window
	createTrackbar("LowR", "Control", &LowR, 255); //Hue (0 - 179)
	createTrackbar("HighR", "Control", &HighR, 255);
	createTrackbar("LowG", "Control", &LowG, 255); //Hue (0 - 179)
	createTrackbar("HighG", "Control", &HighG, 255);
	createTrackbar("LowB", "Control", &LowB, 255); //Hue (0 - 179)
	createTrackbar("HighB", "Control", &HighB, 255);
    createTrackbar("Beta", "Control",&beta, 200);

	//Capture a temporary image from the camera
	Mat imgTmp;
	cap.read(imgTmp);	//Create a black image with the size as the camera output
	Mat imgLines = Mat::zeros(imgTmp.size(), CV_8UC3);
	while (true)
	{
		Mat imgOriginal;
		bool bSuccess = cap.read(imgOriginal); // read a new frame from video
		if (!bSuccess) //if not success, break loop
		{
			cout << "Cannot read a frame from video stream" << endl;
			break;
		}

		for (int y = 0; y < imgOriginal.rows; y++){
			for (int x = 0; x < imgOriginal.cols; x++){
				for (int c = 0; c < 3; c++){
					imgOriginal.at<Vec3b>(y, x)[c] =
					saturate_cast<uchar>(alpha*(imgOriginal.at<Vec3b>(y, x)[c]) + beta);
				}
			}
		}

		Mat imgHSV = imgOriginal;
		GaussianBlur(imgOriginal, imgOriginal, Size(0, 0), 4);
		//cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
		Mat imgThresholded;
		inRange(imgHSV, Scalar(LowB, LowG, LowR), Scalar(HighB, HighG, HighR), imgThresholded); //Threshold the image
		//morphological opening (removes small objects from the foreground)
		erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		//morphological closing (removes small holes from the foreground)
		dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

        dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(10, 10)));

        //Calculate the moments of the thresholded image
		Moments oMoments = moments(imgThresholded);
		int dM01 = oMoments.m01;
		int dM10 = oMoments.m10;
		double dArea = oMoments.m00;
		double dArea = oMoments.m00;

		// if the area <= 20000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
		if (dArea > 20000)
		{
			//calculate the position of the ball
			int posX = dM10 / dArea;
			int posY = dM01 / dArea;
			circle(imgOriginal, Point(posX, posY), 30, Scalar(0, 0, 255), 2);
			circle(imgOriginal, Point(posX, posY), 5, Scalar(0, 255, 0), 2);

			if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0)
			{
				//Draw a red line from the previous point to the current point		B, G, R     Diamiter
				//line(imgLines, Point(posX, posY), Point(iLastX, iLastY), Scalar(0, 0, 255), 2);//  here is the line
			}
			iLastX = posX;
			iLastY = posY;
			std::cout << posX << ", " << posY << std::endl;
			std::cout << std::endl;
			std::cout << "B: " << LowB << ", " << HighB << std::endl;
			std::cout << "G: " << LowG << ", " << HighG << std::endl;
			std::cout << "R: " << LowR << ", " << HighR << std::endl;
 			//std::cout << "Beta: " << beta << std::endl;
		}
        //ok
		imgOriginal = imgOriginal + imgLines;
		Mat outOriginal = imgOriginal;
		flip(outOriginal, outOriginal, 1);
		imshow("Control", imgThresholded); //show the thresholded image
		imshow("Original", outOriginal);
		//show the original image
		//imshow("HSV", imgHSV);

		if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
		{
			cout << "esc key is pressed by user" << endl;
			break;
		}
	}
	return 0;
}<commit_msg>kill me<commit_after>//#include "stdafx.h"
#include <iostream>
//#include <conio.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <string>
#include <sstream>

double alpha = 2.0; /**< Simple contrast control */
int beta = 3;  /**< Simple brightness control */

int HighR = 255;
int LowR = 244;
int HighG = 255;
int LowG = 0;
int HighB = 112;
int LowB = 23;

double iLastX = -1;
double iLastY = -1;

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
	VideoCapture cap(0); //capture the video from webcam

	cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);

	if (!cap.isOpened())  // if not success, exit program
	{
		cout << "Cannot open the web cam" << endl;
		return -1;
	}
	namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
	//Create trackbars in "Control" window
	createTrackbar("LowR", "Control", &LowR, 255); //Hue (0 - 179)
	createTrackbar("HighR", "Control", &HighR, 255);
	createTrackbar("LowG", "Control", &LowG, 255); //Hue (0 - 179)
	createTrackbar("HighG", "Control", &HighG, 255);
	createTrackbar("LowB", "Control", &LowB, 255); //Hue (0 - 179)
	createTrackbar("HighB", "Control", &HighB, 255);
    createTrackbar("Beta", "Control",&beta, 200);

	//Capture a temporary image from the camera
	Mat imgTmp;
	cap.read(imgTmp);	//Create a black image with the size as the camera output
	Mat imgLines = Mat::zeros(imgTmp.size(), CV_8UC3);
	while (true)
	{
		Mat imgOriginal;
		bool bSuccess = cap.read(imgOriginal); // read a new frame from video
		if (!bSuccess) //if not success, break loop
		{
			cout << "Cannot read a frame from video stream" << endl;
			break;
		}

		for (int y = 0; y < imgOriginal.rows; y++){
			for (int x = 0; x < imgOriginal.cols; x++){
				for (int c = 0; c < 3; c++){
					imgOriginal.at<Vec3b>(y, x)[c] =
					saturate_cast<uchar>(alpha*(imgOriginal.at<Vec3b>(y, x)[c]) + beta);
				}
			}
		}

		Mat imgHSV = imgOriginal;
		GaussianBlur(imgOriginal, imgOriginal, Size(0, 0), 4);
		//cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
		Mat imgThresholded;
		inRange(imgHSV, Scalar(LowB, LowG, LowR), Scalar(HighB, HighG, HighR), imgThresholded); //Threshold the image
		//morphological opening (removes small objects from the foreground)
		erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		//morphological closing (removes small holes from the foreground)
		dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
		erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

        dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(10, 10)));

        //Calculate the moments of the thresholded image
		Moments oMoments = moments(imgThresholded);
		int dM01 = oMoments.m01;
		int dM10 = oMoments.m10;
		double dArea = oMoments.m00;
		double dArea = oMoments.m00;

		// if the area <= 20000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
		if (dArea > 20000)
		{
			//calculate the position of the ball
			int posX = dM10 / dArea;
			int posY = dM01 / dArea;
			circle(imgOriginal, Point(posX, posY), 30, Scalar(0, 0, 255), 2);
			circle(imgOriginal, Point(posX, posY), 5, Scalar(0, 255, 0), 2);

			if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0)
			{
				//Draw a red line from the previous point to the current point		B, G, R     Diamiter
				//line(imgLines, Point(posX, posY), Point(iLastX, iLastY), Scalar(0, 0, 255), 2);//  here is the line
			}
			iLastX = posX;
			iLastY = posY;
			std::cout << posX << ", " << posY << std::endl;
			std::cout << std::endl;
			std::cout << "B: " << LowB << ", " << HighB << std::endl;
			std::cout << "G: " << LowG << ", " << HighG << std::endl;
			std::cout << "R: " << LowR << ", " << HighR << std::endl;
 			//std::cout << "Beta: " << beta << std::endl;
		}
        //ok
		imgOriginal = imgOriginal + imgLines;
		Mat outOriginal = imgOriginal;
		flip(outOriginal, outOriginal, 1);
		imshow("Control", imgThresholded); //show the thresholded image
		imshow("Original", outOriginal);
		//show the original image
		//imshow("HSV", imgHSV);

		if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
		{
			cout << "esc key is pressed by user" << endl;
			break;
		} //ok hahahs
	}
	return 0;
}<|endoftext|>


<commit_before>/*
 *  Copyright 2008-2010 NVIDIA 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.
 */

/*! \file reduce.inl
 *  \brief Inline file for reduce.h
 */

#pragma once

#include <thrust/device_ptr.h>
#include <thrust/functional.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/detail/static_assert.h>

#include <thrust/detail/device/cuda/reduce_n.h>

namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
namespace detail
{
//////////////
// Functors //
//////////////
template <typename InputType, typename OutputType, typename BinaryFunction, typename WideType>
  struct wide_unary_op : public thrust::unary_function<WideType,OutputType>
{
    BinaryFunction binary_op;

    __host__ __device__
        wide_unary_op(BinaryFunction binary_op)
            : binary_op(binary_op) {}

    __host__ __device__
        OutputType operator()(WideType x)
        {
            WideType mask = ((WideType) 1 << (8 * sizeof(InputType))) - 1;

            OutputType sum = static_cast<InputType>(x & mask);

            for(unsigned int n = 1; n < sizeof(WideType) / sizeof(InputType); n++)
                sum = binary_op(sum, static_cast<InputType>( (x >> (8 * n * sizeof(InputType))) & mask ) );

            return sum;
        }
};

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_device(InputIterator first,
                           InputIterator last,
                           OutputType init,
                           BinaryFunction binary_op,
                           thrust::detail::true_type)
{
    // "wide" reduction for small types like char, short, etc.
    typedef typename thrust::iterator_traits<InputIterator>::value_type InputType;
    typedef unsigned int WideType;

    // note: this assumes that InputIterator is a InputType * and can be reinterpret_casted to WideType *

    // TODO use simple threshold and ensure alignment of wide_first

    // process first part
    size_t input_type_per_wide_type = sizeof(WideType) / sizeof(InputType);
    size_t n_wide = (last - first) / input_type_per_wide_type;

    WideType * wide_first = reinterpret_cast<WideType *>(thrust::raw_pointer_cast(&*first));

    OutputType result = thrust::detail::device::cuda::reduce_n
        (thrust::make_transform_iterator(wide_first, wide_unary_op<InputType,OutputType,BinaryFunction,WideType>(binary_op)),
         n_wide, init, binary_op);

    // process tail
    InputIterator tail_first = first + n_wide * input_type_per_wide_type;
    return thrust::detail::device::cuda::reduce_n(tail_first, last - tail_first, result, binary_op);
}

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_device(InputIterator first,
                           InputIterator last,
                           OutputType init,
                           BinaryFunction binary_op,
                           thrust::detail::false_type)
{
    // standard reduction
    return thrust::detail::device::cuda::reduce_n(first, last - first, init, binary_op);
}

} // end namespace detail

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce(InputIterator first,
                    InputIterator last,
                    OutputType init,
                    BinaryFunction binary_op)
{
    // we're attempting to launch a kernel, assert we're compiling with nvcc
    // ========================================================================
    // X Note to the user: If you've found this line due to a compiler error, X
    // X you need to compile your code using nvcc, rather than g++ or cl.exe  X
    // ========================================================================
    THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );

    typedef typename thrust::iterator_traits<InputIterator>::value_type InputType;

    const bool use_wide_load = thrust::detail::is_pod<InputType>::value
                                    && thrust::detail::is_trivial_iterator<InputIterator>::value
                                    && (sizeof(InputType) == 1 || sizeof(InputType) == 2);

    // XXX WAR nvcc 3.0 unused variable warning
    (void) use_wide_load;

    return detail::reduce_device(first, last, init, binary_op, thrust::detail::integral_constant<bool, use_wide_load>());
}

} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust

<commit_msg>Don't cast away const when doing wide CUDA reductions<commit_after>/*
 *  Copyright 2008-2010 NVIDIA 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.
 */

/*! \file reduce.inl
 *  \brief Inline file for reduce.h
 */

#pragma once

#include <thrust/device_ptr.h>
#include <thrust/functional.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/detail/static_assert.h>

#include <thrust/detail/device/cuda/reduce_n.h>

namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
namespace detail
{
//////////////
// Functors //
//////////////
template <typename InputType, typename OutputType, typename BinaryFunction, typename WideType>
  struct wide_unary_op : public thrust::unary_function<WideType,OutputType>
{
    BinaryFunction binary_op;

    __host__ __device__
        wide_unary_op(BinaryFunction binary_op)
            : binary_op(binary_op) {}

    __host__ __device__
        OutputType operator()(WideType x)
        {
            WideType mask = ((WideType) 1 << (8 * sizeof(InputType))) - 1;

            OutputType sum = static_cast<InputType>(x & mask);

            for(unsigned int n = 1; n < sizeof(WideType) / sizeof(InputType); n++)
                sum = binary_op(sum, static_cast<InputType>( (x >> (8 * n * sizeof(InputType))) & mask ) );

            return sum;
        }
};

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_device(InputIterator first,
                           InputIterator last,
                           OutputType init,
                           BinaryFunction binary_op,
                           thrust::detail::true_type)
{
    // "wide" reduction for small types like char, short, etc.
    typedef typename thrust::iterator_traits<InputIterator>::value_type InputType;
    typedef unsigned int WideType;

    // note: this assumes that InputIterator is a InputType * and can be reinterpret_casted to WideType *

    // TODO use simple threshold and ensure alignment of wide_first

    // process first part
    size_t input_type_per_wide_type = sizeof(WideType) / sizeof(InputType);
    size_t n_wide = (last - first) / input_type_per_wide_type;

    const WideType * wide_first = reinterpret_cast<const WideType *>(thrust::raw_pointer_cast(&*first));

    OutputType result = thrust::detail::device::cuda::reduce_n
        (thrust::make_transform_iterator(wide_first, wide_unary_op<InputType,OutputType,BinaryFunction,WideType>(binary_op)),
         n_wide, init, binary_op);

    // process tail
    InputIterator tail_first = first + n_wide * input_type_per_wide_type;
    return thrust::detail::device::cuda::reduce_n(tail_first, last - tail_first, result, binary_op);
}

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_device(InputIterator first,
                           InputIterator last,
                           OutputType init,
                           BinaryFunction binary_op,
                           thrust::detail::false_type)
{
    // standard reduction
    return thrust::detail::device::cuda::reduce_n(first, last - first, init, binary_op);
}

} // end namespace detail

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce(InputIterator first,
                    InputIterator last,
                    OutputType init,
                    BinaryFunction binary_op)
{
    // we're attempting to launch a kernel, assert we're compiling with nvcc
    // ========================================================================
    // X Note to the user: If you've found this line due to a compiler error, X
    // X you need to compile your code using nvcc, rather than g++ or cl.exe  X
    // ========================================================================
    THRUST_STATIC_ASSERT( (depend_on_instantiation<InputIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );

    typedef typename thrust::iterator_traits<InputIterator>::value_type InputType;

    const bool use_wide_load = thrust::detail::is_pod<InputType>::value
                                    && thrust::detail::is_trivial_iterator<InputIterator>::value
                                    && (sizeof(InputType) == 1 || sizeof(InputType) == 2);

    // XXX WAR nvcc 3.0 unused variable warning
    (void) use_wide_load;

    return detail::reduce_device(first, last, init, binary_op, thrust::detail::integral_constant<bool, use_wide_load>());
}

} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: CellColorHandler.hxx,v $
 * $Revision: 1.3 $
 *
 * 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 INCLUDED_CELLCOLORHANDLER_HXX
#define INCLUDED_CELLCOLORHANDLER_HXX

#include <WriterFilterDllApi.hxx>
#include <resourcemodel/WW8ResourceModel.hxx>
#include <boost/shared_ptr.hpp>
//#include <com/sun/star/table/TableBorder.hpp>
#include <com/sun/star/table/BorderLine.hpp>

namespace writerfilter {
namespace dmapper
{
class PropertyMap;
class WRITERFILTER_DLLPRIVATE CellColorHandler : public Properties
{
public:
    sal_Int32 m_nShadowType;
    sal_Int32 m_nColor;
    sal_Int32 m_nFillColor;
    bool      m_bOOXMLColor;
    bool      m_bParagraph;
private:

public:
    CellColorHandler( );
    virtual ~CellColorHandler();

    // Properties
    virtual void attribute(Id Name, Value & val);
    virtual void sprm(Sprm & sprm);

    ::boost::shared_ptr<PropertyMap>            getProperties();

    void setParagraph() { m_bParagraph = true; }
};
typedef boost::shared_ptr< CellColorHandler >          CellColorHandlerPtr;
}}

#endif //
<commit_msg>INTEGRATION: CWS xmlfilter04 (1.2.14); FILE MERGED 2008/02/22 13:07:20 os 1.2.14.1: table width/alignment/indent/cell margin import improved<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: CellColorHandler.hxx,v $
 * $Revision: 1.4 $
 *
 * 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 INCLUDED_CELLCOLORHANDLER_HXX
#define INCLUDED_CELLCOLORHANDLER_HXX

#include <WriterFilterDllApi.hxx>
#include <resourcemodel/WW8ResourceModel.hxx>
#include <boost/shared_ptr.hpp>
//#include <com/sun/star/table/TableBorder.hpp>
#include <com/sun/star/table/BorderLine.hpp>

namespace writerfilter {
namespace dmapper
{
class TablePropertyMap;
class WRITERFILTER_DLLPRIVATE CellColorHandler : public Properties
{
public:
    sal_Int32 m_nShadowType;
    sal_Int32 m_nColor;
    sal_Int32 m_nFillColor;
    bool      m_bOOXMLColor;
    bool      m_bParagraph;
private:

public:
    CellColorHandler( );
    virtual ~CellColorHandler();

    // Properties
    virtual void attribute(Id Name, Value & val);
    virtual void sprm(Sprm & sprm);

    ::boost::shared_ptr<TablePropertyMap>            getProperties();

    void setParagraph() { m_bParagraph = true; }
};
typedef boost::shared_ptr< CellColorHandler >          CellColorHandlerPtr;
}}

#endif //
<|endoftext|>


<commit_before><commit_msg>WaE: narrowing conversion from unsigned int to sal_Int32<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLIndexUserSourceContext.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 16:02:29 $
 *
 *  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_xmloff.hxx"

#ifndef _XMLOFF_XMLINDEXUSERSOURCECONTEXT_HXX_
#include "XMLIndexUserSourceContext.hxx"
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

#ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_
#include "XMLIndexTemplateContext.hxx"
#endif

#ifndef _XMLOFF_XMLINDEXTITLETEMPLATECONTEXT_HXX_
#include "XMLIndexTitleTemplateContext.hxx"
#endif

#ifndef _XMLOFF_XMLINDEXTOCSTYLESCONTEXT_HXX_
#include "XMLIndexTOCStylesContext.hxx"
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

#ifndef _XMLOFF_TEXTIMP_HXX_
#include <xmloff/txtimp.hxx>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

using ::rtl::OUString;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::com::sun::star::xml::sax::XAttributeList;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_USER_INDEX_ENTRY_TEMPLATE;
using ::xmloff::token::XML_OUTLINE_LEVEL;

const sal_Char sAPI_CreateFromEmbeddedObjects[] = "CreateFromEmbeddedObjects";
const sal_Char sAPI_CreateFromGraphicObjects[] = "CreateFromGraphicObjects";
const sal_Char sAPI_CreateFromMarks[] = "CreateFromMarks";
const sal_Char sAPI_CreateFromTables[] = "CreateFromTables";
const sal_Char sAPI_CreateFromTextFrames[] = "CreateFromTextFrames";
const sal_Char sAPI_UseLevelFromSource[] = "UseLevelFromSource";
const sal_Char sAPI_CreateFromLevelParagraphStyles[] = "CreateFromLevelParagraphStyles";
const sal_Char sAPI_UserIndexName[] = "UserIndexName";

TYPEINIT1(XMLIndexUserSourceContext, XMLIndexSourceBaseContext);

XMLIndexUserSourceContext::XMLIndexUserSourceContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrfx,
    const OUString& rLocalName,
    Reference<XPropertySet> & rPropSet) :
        XMLIndexSourceBaseContext(rImport, nPrfx, rLocalName,
                                  rPropSet, sal_True),
        sCreateFromEmbeddedObjects(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_CreateFromEmbeddedObjects)),
        sCreateFromGraphicObjects(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_CreateFromGraphicObjects)),
        sCreateFromMarks(RTL_CONSTASCII_USTRINGPARAM(sAPI_CreateFromMarks)),
        sCreateFromTables(RTL_CONSTASCII_USTRINGPARAM(sAPI_CreateFromTables)),
        sCreateFromTextFrames(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_CreateFromTextFrames)),
        sUseLevelFromSource(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_UseLevelFromSource)),
        sCreateFromLevelParagraphStyles(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_CreateFromLevelParagraphStyles)),
        sUserIndexName(RTL_CONSTASCII_USTRINGPARAM(sAPI_UserIndexName)),
        bUseObjects(sal_False),
        bUseGraphic(sal_False),
        bUseMarks(sal_False),
        bUseTables(sal_False),
        bUseFrames(sal_False),
        bUseLevelFromSource(sal_False),
        bUseLevelParagraphStyles(sal_False)
{
}

XMLIndexUserSourceContext::~XMLIndexUserSourceContext()
{
}

void XMLIndexUserSourceContext::ProcessAttribute(
    enum IndexSourceParamEnum eParam,
    const OUString& rValue)
{
    sal_Bool bTmp;

    switch (eParam)
    {
        case XML_TOK_INDEXSOURCE_USE_INDEX_MARKS:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseMarks = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_OBJECTS:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseObjects = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_GRAPHICS:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseGraphic = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_TABLES:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseTables = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_FRAMES:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseFrames = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_COPY_OUTLINE_LEVELS:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseLevelFromSource = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_INDEX_SOURCE_STYLES:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseLevelParagraphStyles = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USER_INDEX_NAME:
            sIndexName = rValue;
            break;

        default:
            XMLIndexSourceBaseContext::ProcessAttribute(eParam, rValue);
            break;
    }
}

void XMLIndexUserSourceContext::EndElement()
{
    Any aAny;

    aAny.setValue(&bUseObjects, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromEmbeddedObjects, aAny);

    aAny.setValue(&bUseGraphic, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromGraphicObjects, aAny);

    aAny.setValue(&bUseLevelFromSource, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sUseLevelFromSource, aAny);

    aAny.setValue(&bUseMarks, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromMarks, aAny);

    aAny.setValue(&bUseTables, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromTables, aAny);

    aAny.setValue(&bUseFrames, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromTextFrames, aAny);

    aAny.setValue(&bUseLevelParagraphStyles, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromLevelParagraphStyles, aAny);

    if( sIndexName.getLength() > 0 )
    {
        aAny <<= sIndexName;
        rIndexPropertySet->setPropertyValue(sUserIndexName, aAny);
    }

    XMLIndexSourceBaseContext::EndElement();
}

SvXMLImportContext* XMLIndexUserSourceContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference<XAttributeList> & xAttrList )
{
    if ( (XML_NAMESPACE_TEXT == nPrefix) &&
         (IsXMLToken(rLocalName, XML_USER_INDEX_ENTRY_TEMPLATE)) )
    {
        return new XMLIndexTemplateContext(GetImport(), rIndexPropertySet,
                                           nPrefix, rLocalName,
                                           aLevelNameTOCMap,
                                           XML_OUTLINE_LEVEL,
                                           aLevelStylePropNameTOCMap,
                                           aAllowedTokenTypesUser);
    }
    else
    {
        return XMLIndexSourceBaseContext::CreateChildContext(nPrefix,
                                                             rLocalName,
                                                             xAttrList);
    }

}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.162); FILE MERGED 2008/04/01 16:10:09 thb 1.7.162.3: #i85898# Stripping all external header guards 2008/04/01 13:05:27 thb 1.7.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:34 rt 1.7.162.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: XMLIndexUserSourceContext.cxx,v $
 * $Revision: 1.8 $
 *
 * 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_xmloff.hxx"

#include "XMLIndexUserSourceContext.hxx"
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XIndexReplace.hpp>
#include "XMLIndexTemplateContext.hxx"
#include "XMLIndexTitleTemplateContext.hxx"
#include "XMLIndexTOCStylesContext.hxx"
#include <xmloff/xmlictxt.hxx>
#include <xmloff/xmlimp.hxx>
#include <xmloff/txtimp.hxx>
#include "xmlnmspe.hxx"
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmluconv.hxx>
#include <tools/debug.hxx>
#include <rtl/ustring.hxx>

using ::rtl::OUString;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Any;
using ::com::sun::star::xml::sax::XAttributeList;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_USER_INDEX_ENTRY_TEMPLATE;
using ::xmloff::token::XML_OUTLINE_LEVEL;

const sal_Char sAPI_CreateFromEmbeddedObjects[] = "CreateFromEmbeddedObjects";
const sal_Char sAPI_CreateFromGraphicObjects[] = "CreateFromGraphicObjects";
const sal_Char sAPI_CreateFromMarks[] = "CreateFromMarks";
const sal_Char sAPI_CreateFromTables[] = "CreateFromTables";
const sal_Char sAPI_CreateFromTextFrames[] = "CreateFromTextFrames";
const sal_Char sAPI_UseLevelFromSource[] = "UseLevelFromSource";
const sal_Char sAPI_CreateFromLevelParagraphStyles[] = "CreateFromLevelParagraphStyles";
const sal_Char sAPI_UserIndexName[] = "UserIndexName";

TYPEINIT1(XMLIndexUserSourceContext, XMLIndexSourceBaseContext);

XMLIndexUserSourceContext::XMLIndexUserSourceContext(
    SvXMLImport& rImport,
    sal_uInt16 nPrfx,
    const OUString& rLocalName,
    Reference<XPropertySet> & rPropSet) :
        XMLIndexSourceBaseContext(rImport, nPrfx, rLocalName,
                                  rPropSet, sal_True),
        sCreateFromEmbeddedObjects(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_CreateFromEmbeddedObjects)),
        sCreateFromGraphicObjects(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_CreateFromGraphicObjects)),
        sCreateFromMarks(RTL_CONSTASCII_USTRINGPARAM(sAPI_CreateFromMarks)),
        sCreateFromTables(RTL_CONSTASCII_USTRINGPARAM(sAPI_CreateFromTables)),
        sCreateFromTextFrames(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_CreateFromTextFrames)),
        sUseLevelFromSource(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_UseLevelFromSource)),
        sCreateFromLevelParagraphStyles(RTL_CONSTASCII_USTRINGPARAM(
            sAPI_CreateFromLevelParagraphStyles)),
        sUserIndexName(RTL_CONSTASCII_USTRINGPARAM(sAPI_UserIndexName)),
        bUseObjects(sal_False),
        bUseGraphic(sal_False),
        bUseMarks(sal_False),
        bUseTables(sal_False),
        bUseFrames(sal_False),
        bUseLevelFromSource(sal_False),
        bUseLevelParagraphStyles(sal_False)
{
}

XMLIndexUserSourceContext::~XMLIndexUserSourceContext()
{
}

void XMLIndexUserSourceContext::ProcessAttribute(
    enum IndexSourceParamEnum eParam,
    const OUString& rValue)
{
    sal_Bool bTmp;

    switch (eParam)
    {
        case XML_TOK_INDEXSOURCE_USE_INDEX_MARKS:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseMarks = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_OBJECTS:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseObjects = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_GRAPHICS:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseGraphic = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_TABLES:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseTables = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_FRAMES:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseFrames = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_COPY_OUTLINE_LEVELS:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseLevelFromSource = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USE_INDEX_SOURCE_STYLES:
            if (SvXMLUnitConverter::convertBool(bTmp, rValue))
            {
                bUseLevelParagraphStyles = bTmp;
            }
            break;

        case XML_TOK_INDEXSOURCE_USER_INDEX_NAME:
            sIndexName = rValue;
            break;

        default:
            XMLIndexSourceBaseContext::ProcessAttribute(eParam, rValue);
            break;
    }
}

void XMLIndexUserSourceContext::EndElement()
{
    Any aAny;

    aAny.setValue(&bUseObjects, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromEmbeddedObjects, aAny);

    aAny.setValue(&bUseGraphic, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromGraphicObjects, aAny);

    aAny.setValue(&bUseLevelFromSource, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sUseLevelFromSource, aAny);

    aAny.setValue(&bUseMarks, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromMarks, aAny);

    aAny.setValue(&bUseTables, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromTables, aAny);

    aAny.setValue(&bUseFrames, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromTextFrames, aAny);

    aAny.setValue(&bUseLevelParagraphStyles, ::getBooleanCppuType());
    rIndexPropertySet->setPropertyValue(sCreateFromLevelParagraphStyles, aAny);

    if( sIndexName.getLength() > 0 )
    {
        aAny <<= sIndexName;
        rIndexPropertySet->setPropertyValue(sUserIndexName, aAny);
    }

    XMLIndexSourceBaseContext::EndElement();
}

SvXMLImportContext* XMLIndexUserSourceContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference<XAttributeList> & xAttrList )
{
    if ( (XML_NAMESPACE_TEXT == nPrefix) &&
         (IsXMLToken(rLocalName, XML_USER_INDEX_ENTRY_TEMPLATE)) )
    {
        return new XMLIndexTemplateContext(GetImport(), rIndexPropertySet,
                                           nPrefix, rLocalName,
                                           aLevelNameTOCMap,
                                           XML_OUTLINE_LEVEL,
                                           aLevelStylePropNameTOCMap,
                                           aAllowedTokenTypesUser);
    }
    else
    {
        return XMLIndexSourceBaseContext::CreateChildContext(nPrefix,
                                                             rLocalName,
                                                             xAttrList);
    }

}
<|endoftext|>


<commit_before>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_HTTP_HEADERS_HXX
#define BENG_PROXY_HTTP_HEADERS_HXX

#include "strmap.hxx"
#include "growing_buffer.hxx"
#include "header_writer.hxx"
#include "header_parser.hxx"

#include <inline/compiler.h>

/**
 * A class that stores HTTP headers in a map and a buffer.  Some
 * libraries want a map, some want a buffer, and this class attempts
 * to give each of them what they can cope with best.
 */
class HttpHeaders {
    struct pool &pool;

    StringMap map;

    GrowingBuffer *buffer;

public:
    explicit HttpHeaders(struct pool &_pool)
        :pool(_pool), map(pool), buffer(nullptr) {}

    explicit HttpHeaders(StringMap &&_map)
        :pool(_map.GetPool()), map(std::move(_map)), buffer(nullptr) {}

    explicit HttpHeaders(GrowingBuffer &_buffer)
        :pool(_buffer.GetPool()), map(pool), buffer(&_buffer) {}

    HttpHeaders(HttpHeaders &&) = default;
    HttpHeaders &operator=(HttpHeaders &&) = default;

    const StringMap &GetMap() const {
        return map;
    }

    StringMap &&ToMap() {
        if (buffer != nullptr)
            header_parse_buffer(pool, map, *buffer);
        return std::move(map);
    }

    gcc_pure
    const char *Get(const char *key) const {
        return map.Get(key);
    }

    GrowingBuffer &MakeBuffer(size_t initial_size=1024) {
        if (buffer == nullptr)
            buffer = growing_buffer_new(&pool, initial_size);
        return *buffer;
    }

    void Write(const char *name, const char *value) {
        header_write(&MakeBuffer(), name, value);
    }

    /**
     * Move a (hop-by-hop) header from the map to the buffer.
     */
    void MoveToBuffer(const char *name) {
        const char *value = map.Get(name);
        if (value != nullptr)
            Write(name, value);
    }

    void MoveToBuffer(const char *const*names) {
        for (; *names != nullptr; ++names)
            MoveToBuffer(*names);
    }

    GrowingBuffer ToBuffer(size_t initial_size=2048) {
        GrowingBuffer &gb = MakeBuffer(initial_size);
        headers_copy_most(&map, &gb);
        return std::move(gb);
    }
};

#endif
<commit_msg>http_headers: add method GetPool()<commit_after>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_HTTP_HEADERS_HXX
#define BENG_PROXY_HTTP_HEADERS_HXX

#include "strmap.hxx"
#include "growing_buffer.hxx"
#include "header_writer.hxx"
#include "header_parser.hxx"

#include <inline/compiler.h>

/**
 * A class that stores HTTP headers in a map and a buffer.  Some
 * libraries want a map, some want a buffer, and this class attempts
 * to give each of them what they can cope with best.
 */
class HttpHeaders {
    struct pool &pool;

    StringMap map;

    GrowingBuffer *buffer;

public:
    explicit HttpHeaders(struct pool &_pool)
        :pool(_pool), map(pool), buffer(nullptr) {}

    explicit HttpHeaders(StringMap &&_map)
        :pool(_map.GetPool()), map(std::move(_map)), buffer(nullptr) {}

    explicit HttpHeaders(GrowingBuffer &_buffer)
        :pool(_buffer.GetPool()), map(pool), buffer(&_buffer) {}

    HttpHeaders(HttpHeaders &&) = default;
    HttpHeaders &operator=(HttpHeaders &&) = default;

    struct pool &GetPool() {
        return pool;
    }

    const StringMap &GetMap() const {
        return map;
    }

    StringMap &&ToMap() {
        if (buffer != nullptr)
            header_parse_buffer(GetPool(), map, *buffer);
        return std::move(map);
    }

    gcc_pure
    const char *Get(const char *key) const {
        return map.Get(key);
    }

    GrowingBuffer &MakeBuffer(size_t initial_size=1024) {
        if (buffer == nullptr)
            buffer = growing_buffer_new(&GetPool(), initial_size);
        return *buffer;
    }

    void Write(const char *name, const char *value) {
        header_write(&MakeBuffer(), name, value);
    }

    /**
     * Move a (hop-by-hop) header from the map to the buffer.
     */
    void MoveToBuffer(const char *name) {
        const char *value = map.Get(name);
        if (value != nullptr)
            Write(name, value);
    }

    void MoveToBuffer(const char *const*names) {
        for (; *names != nullptr; ++names)
            MoveToBuffer(*names);
    }

    GrowingBuffer ToBuffer(size_t initial_size=2048) {
        GrowingBuffer &gb = MakeBuffer(initial_size);
        headers_copy_most(&map, &gb);
        return std::move(gb);
    }
};

#endif
<|endoftext|>


<commit_before>// RUN: %llvmgxx %s -S -o - | FileCheck %s
// The store of p.y into the temporary was not
// getting extended to 32 bits, so uninitialized
// bits of the temporary were used.  7366161.
struct foo {
  char x:8;
  signed int y:24;
};
int bar(struct foo p, int x) {
// CHECK: bar
// CHECK: sext
// CHECK: sext
  x = (p.y > x ? x : p.y);
  return x;
// CHECK: return
}
<commit_msg>Remove migrated test.<commit_after><|endoftext|>


<commit_before>//== ObjCContainersChecker.cpp - Path sensitive checker for CFArray *- C++ -*=//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Performs path sensitive checks of Core Foundation static containers like
// CFArray.
// 1) Check for buffer overflows:
//      In CFArrayGetArrayAtIndex( myArray, index), if the index is outside the
//      index space of theArray (0 to N-1 inclusive (where N is the count of
//      theArray), the behavior is undefined.
//
//===----------------------------------------------------------------------===//

#include "ClangSACheckers.h"
#include "clang/AST/ParentMap.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"

using namespace clang;
using namespace ento;

namespace {
class ObjCContainersChecker : public Checker< check::PreStmt<CallExpr>,
                                             check::PostStmt<CallExpr> > {
  mutable std::unique_ptr<BugType> BT;
  inline void initBugType() const {
    if (!BT)
      BT.reset(new BugType(this, "CFArray API",
                           categories::CoreFoundationObjectiveC));
  }

  inline SymbolRef getArraySym(const Expr *E, CheckerContext &C) const {
    SVal ArrayRef = C.getState()->getSVal(E, C.getLocationContext());
    SymbolRef ArraySym = ArrayRef.getAsSymbol();
    return ArraySym;
  }

  void addSizeInfo(const Expr *Array, const Expr *Size,
                   CheckerContext &C) const;

public:
  /// A tag to id this checker.
  static void *getTag() { static int Tag; return &Tag; }

  void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
};
} // end anonymous namespace

// ProgramState trait - a map from array symbol to its state.
REGISTER_MAP_WITH_PROGRAMSTATE(ArraySizeMap, SymbolRef, DefinedSVal)

void ObjCContainersChecker::addSizeInfo(const Expr *Array, const Expr *Size,
                                        CheckerContext &C) const {
  ProgramStateRef State = C.getState();
  SVal SizeV = State->getSVal(Size, C.getLocationContext());
  // Undefined is reported by another checker.
  if (SizeV.isUnknownOrUndef())
    return;

  // Get the ArrayRef symbol.
  SVal ArrayRef = State->getSVal(Array, C.getLocationContext());
  SymbolRef ArraySym = ArrayRef.getAsSymbol();
  if (!ArraySym)
    return;

  C.addTransition(
      State->set<ArraySizeMap>(ArraySym, SizeV.castAs<DefinedSVal>()));
  return;
}

void ObjCContainersChecker::checkPostStmt(const CallExpr *CE,
                                          CheckerContext &C) const {
  StringRef Name = C.getCalleeName(CE);
  if (Name.empty() || CE->getNumArgs() < 1)
    return;

  // Add array size information to the state.
  if (Name.equals("CFArrayCreate")) {
    if (CE->getNumArgs() < 3)
      return;
    // Note, we can visit the Create method in the post-visit because
    // the CFIndex parameter is passed in by value and will not be invalidated
    // by the call.
    addSizeInfo(CE, CE->getArg(2), C);
    return;
  }

  if (Name.equals("CFArrayGetCount")) {
    addSizeInfo(CE->getArg(0), CE, C);
    return;
  }
}

void ObjCContainersChecker::checkPreStmt(const CallExpr *CE,
                                         CheckerContext &C) const {
  StringRef Name = C.getCalleeName(CE);
  if (Name.empty() || CE->getNumArgs() < 2)
    return;

  // Check the array access.
  if (Name.equals("CFArrayGetValueAtIndex")) {
    ProgramStateRef State = C.getState();
    // Retrieve the size.
    // Find out if we saw this array symbol before and have information about it.
    const Expr *ArrayExpr = CE->getArg(0);
    SymbolRef ArraySym = getArraySym(ArrayExpr, C);
    if (!ArraySym)
      return;

    const DefinedSVal *Size = State->get<ArraySizeMap>(ArraySym);

    if (!Size)
      return;

    // Get the index.
    const Expr *IdxExpr = CE->getArg(1);
    SVal IdxVal = State->getSVal(IdxExpr, C.getLocationContext());
    if (IdxVal.isUnknownOrUndef())
      return;
    DefinedSVal Idx = IdxVal.castAs<DefinedSVal>();

    // Now, check if 'Idx in [0, Size-1]'.
    const QualType T = IdxExpr->getType();
    ProgramStateRef StInBound = State->assumeInBound(Idx, *Size, true, T);
    ProgramStateRef StOutBound = State->assumeInBound(Idx, *Size, false, T);
    if (StOutBound && !StInBound) {
      ExplodedNode *N = C.generateSink(StOutBound);
      if (!N)
        return;
      initBugType();
      BugReport *R = new BugReport(*BT, "Index is out of bounds", N);
      R->addRange(IdxExpr->getSourceRange());
      C.emitReport(R);
      return;
    }
  }
}

/// Register checker.
void ento::registerObjCContainersChecker(CheckerManager &mgr) {
  mgr.registerChecker<ObjCContainersChecker>();
}
<commit_msg>[analyzer]Test commit fixing 80-column violation in comment. NFC.<commit_after>//== ObjCContainersChecker.cpp - Path sensitive checker for CFArray *- C++ -*=//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Performs path sensitive checks of Core Foundation static containers like
// CFArray.
// 1) Check for buffer overflows:
//      In CFArrayGetArrayAtIndex( myArray, index), if the index is outside the
//      index space of theArray (0 to N-1 inclusive (where N is the count of
//      theArray), the behavior is undefined.
//
//===----------------------------------------------------------------------===//

#include "ClangSACheckers.h"
#include "clang/AST/ParentMap.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"

using namespace clang;
using namespace ento;

namespace {
class ObjCContainersChecker : public Checker< check::PreStmt<CallExpr>,
                                             check::PostStmt<CallExpr> > {
  mutable std::unique_ptr<BugType> BT;
  inline void initBugType() const {
    if (!BT)
      BT.reset(new BugType(this, "CFArray API",
                           categories::CoreFoundationObjectiveC));
  }

  inline SymbolRef getArraySym(const Expr *E, CheckerContext &C) const {
    SVal ArrayRef = C.getState()->getSVal(E, C.getLocationContext());
    SymbolRef ArraySym = ArrayRef.getAsSymbol();
    return ArraySym;
  }

  void addSizeInfo(const Expr *Array, const Expr *Size,
                   CheckerContext &C) const;

public:
  /// A tag to id this checker.
  static void *getTag() { static int Tag; return &Tag; }

  void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
};
} // end anonymous namespace

// ProgramState trait - a map from array symbol to its state.
REGISTER_MAP_WITH_PROGRAMSTATE(ArraySizeMap, SymbolRef, DefinedSVal)

void ObjCContainersChecker::addSizeInfo(const Expr *Array, const Expr *Size,
                                        CheckerContext &C) const {
  ProgramStateRef State = C.getState();
  SVal SizeV = State->getSVal(Size, C.getLocationContext());
  // Undefined is reported by another checker.
  if (SizeV.isUnknownOrUndef())
    return;

  // Get the ArrayRef symbol.
  SVal ArrayRef = State->getSVal(Array, C.getLocationContext());
  SymbolRef ArraySym = ArrayRef.getAsSymbol();
  if (!ArraySym)
    return;

  C.addTransition(
      State->set<ArraySizeMap>(ArraySym, SizeV.castAs<DefinedSVal>()));
  return;
}

void ObjCContainersChecker::checkPostStmt(const CallExpr *CE,
                                          CheckerContext &C) const {
  StringRef Name = C.getCalleeName(CE);
  if (Name.empty() || CE->getNumArgs() < 1)
    return;

  // Add array size information to the state.
  if (Name.equals("CFArrayCreate")) {
    if (CE->getNumArgs() < 3)
      return;
    // Note, we can visit the Create method in the post-visit because
    // the CFIndex parameter is passed in by value and will not be invalidated
    // by the call.
    addSizeInfo(CE, CE->getArg(2), C);
    return;
  }

  if (Name.equals("CFArrayGetCount")) {
    addSizeInfo(CE->getArg(0), CE, C);
    return;
  }
}

void ObjCContainersChecker::checkPreStmt(const CallExpr *CE,
                                         CheckerContext &C) const {
  StringRef Name = C.getCalleeName(CE);
  if (Name.empty() || CE->getNumArgs() < 2)
    return;

  // Check the array access.
  if (Name.equals("CFArrayGetValueAtIndex")) {
    ProgramStateRef State = C.getState();
    // Retrieve the size.
    // Find out if we saw this array symbol before and have information about
    // it.
    const Expr *ArrayExpr = CE->getArg(0);
    SymbolRef ArraySym = getArraySym(ArrayExpr, C);
    if (!ArraySym)
      return;

    const DefinedSVal *Size = State->get<ArraySizeMap>(ArraySym);

    if (!Size)
      return;

    // Get the index.
    const Expr *IdxExpr = CE->getArg(1);
    SVal IdxVal = State->getSVal(IdxExpr, C.getLocationContext());
    if (IdxVal.isUnknownOrUndef())
      return;
    DefinedSVal Idx = IdxVal.castAs<DefinedSVal>();

    // Now, check if 'Idx in [0, Size-1]'.
    const QualType T = IdxExpr->getType();
    ProgramStateRef StInBound = State->assumeInBound(Idx, *Size, true, T);
    ProgramStateRef StOutBound = State->assumeInBound(Idx, *Size, false, T);
    if (StOutBound && !StInBound) {
      ExplodedNode *N = C.generateSink(StOutBound);
      if (!N)
        return;
      initBugType();
      BugReport *R = new BugReport(*BT, "Index is out of bounds", N);
      R->addRange(IdxExpr->getSourceRange());
      C.emitReport(R);
      return;
    }
  }
}

/// Register checker.
void ento::registerObjCContainersChecker(CheckerManager &mgr) {
  mgr.registerChecker<ObjCContainersChecker>();
}
<|endoftext|>


<commit_before>#pragma once

#include <vector>

#include "Runtime/CToken.hpp"
#include "Runtime/GCNTypes.hpp"
#include "Runtime/IObj.hpp"
#include "Runtime/IObjFactory.hpp"
#include "Runtime/IOStreams.hpp"
#include "Runtime/World/CAiFuncMap.hpp"

namespace urde {
class CAiState;
class CStateManager;

class CAiTrigger {
  CAiTriggerFunc x0_func;
  float xc_arg = 0.f;
  CAiTrigger* x10_andTrig = nullptr;
  CAiState* x14_state = nullptr;
  bool x18_lNot = false;

public:
  CAiTrigger() = default;
  CAiTrigger* GetAnd() const { return x10_andTrig; }
  CAiState* GetState() const { return x14_state; }
  bool CallFunc(CStateManager& mgr, CAi& ai) const {
    if (x0_func) {
      bool ret = (ai.*x0_func)(mgr, xc_arg);
      return x18_lNot == !ret;
    }
    return true;
  }

  void Setup(CAiTriggerFunc func, bool lnot, float arg, CAiTrigger* andTrig) {
    x0_func = func;
    x18_lNot = lnot;
    xc_arg = arg;
    x10_andTrig = andTrig;
  }
  void Setup(CAiTriggerFunc func, bool lnot, float arg, CAiState* state) {
    x0_func = func;
    x18_lNot = lnot;
    xc_arg = arg;
    x14_state = state;
  }
};

class CAiState {
  friend class CStateMachineState;
  CAiStateFunc x0_func;
  char xc_name[32] = {};
  u32 x2c_numTriggers;
  CAiTrigger* x30_firstTrigger;

public:
  CAiState(CAiStateFunc func, const char* name) {
    x0_func = func;
    strncpy(xc_name, name, 31);
  }

  s32 GetNumTriggers() const { return x2c_numTriggers; }
  CAiTrigger* GetTrig(s32 i) const { return &x30_firstTrigger[i]; }
  const char* GetName() const { return xc_name; }
  void SetTriggers(CAiTrigger* triggers) { x30_firstTrigger = triggers; }
  void SetNumTriggers(s32 numTriggers) { x2c_numTriggers = numTriggers; }
  void CallFunc(CStateManager& mgr, CAi& ai, EStateMsg msg, float delta) const {
    if (x0_func)
      (ai.*x0_func)(mgr, msg, delta);
  }
};

class CStateMachine {
  std::vector<CAiState> x0_states;
  std::vector<CAiTrigger> x10_triggers;

public:
  explicit CStateMachine(CInputStream& in);

  s32 GetStateIndex(std::string_view state) const;
  const std::vector<CAiState>& GetStateVector() const { return x0_states; }
};

class CStateMachineState {
  friend class CPatterned;
  const CStateMachine* x0_machine = nullptr;
  CAiState* x4_state = nullptr;
  float x8_time = 0.f;
  float xc_random = 0.f;
  float x10_delay = 0.f;
  float x14_;
  bool x18_24_codeTrigger : 1;

public:
  CStateMachineState() : x18_24_codeTrigger(false) {}

  CAiState* GetActorState() const { return x4_state; }

  void Update(CStateManager& mgr, CAi& ai, float delta);
  void SetState(CStateManager&, CAi&, s32);
  void SetState(CStateManager&, CAi&, const CStateMachine*, std::string_view);
  const std::vector<CAiState>* GetStateVector() const;
  void Setup(const CStateMachine* machine);
  void SetDelay(float delay) { x10_delay = delay; }
  float GetTime() const { return x8_time; }
  float GetRandom() const { return xc_random; }
  float GetDelay() const { return x10_delay; }
  void SetCodeTrigger() { x18_24_codeTrigger = true; }

  const char* GetName() const {
    if (x4_state)
      return x4_state->GetName();
    return nullptr;
  }
};

CFactoryFnReturn FAiFiniteStateMachineFactory(const SObjectTag& tag, CInputStream& in, const CVParamTransfer& vparms,
                                              CObjectReference*);

} // namespace urde
<commit_msg>CStateMachine: Initialize data members where applicable<commit_after>#pragma once

#include <vector>

#include "Runtime/CToken.hpp"
#include "Runtime/GCNTypes.hpp"
#include "Runtime/IObj.hpp"
#include "Runtime/IObjFactory.hpp"
#include "Runtime/IOStreams.hpp"
#include "Runtime/World/CAiFuncMap.hpp"

namespace urde {
class CAiState;
class CStateManager;

class CAiTrigger {
  CAiTriggerFunc x0_func;
  float xc_arg = 0.f;
  CAiTrigger* x10_andTrig = nullptr;
  CAiState* x14_state = nullptr;
  bool x18_lNot = false;

public:
  CAiTrigger() = default;
  CAiTrigger* GetAnd() const { return x10_andTrig; }
  CAiState* GetState() const { return x14_state; }
  bool CallFunc(CStateManager& mgr, CAi& ai) const {
    if (x0_func) {
      bool ret = (ai.*x0_func)(mgr, xc_arg);
      return x18_lNot == !ret;
    }
    return true;
  }

  void Setup(CAiTriggerFunc func, bool lnot, float arg, CAiTrigger* andTrig) {
    x0_func = func;
    x18_lNot = lnot;
    xc_arg = arg;
    x10_andTrig = andTrig;
  }
  void Setup(CAiTriggerFunc func, bool lnot, float arg, CAiState* state) {
    x0_func = func;
    x18_lNot = lnot;
    xc_arg = arg;
    x14_state = state;
  }
};

class CAiState {
  friend class CStateMachineState;
  CAiStateFunc x0_func;
  char xc_name[32] = {};
  u32 x2c_numTriggers = 0;
  CAiTrigger* x30_firstTrigger = nullptr;

public:
  CAiState(CAiStateFunc func, const char* name) {
    x0_func = func;
    strncpy(xc_name, name, 31);
  }

  s32 GetNumTriggers() const { return x2c_numTriggers; }
  CAiTrigger* GetTrig(s32 i) const { return &x30_firstTrigger[i]; }
  const char* GetName() const { return xc_name; }
  void SetTriggers(CAiTrigger* triggers) { x30_firstTrigger = triggers; }
  void SetNumTriggers(s32 numTriggers) { x2c_numTriggers = numTriggers; }
  void CallFunc(CStateManager& mgr, CAi& ai, EStateMsg msg, float delta) const {
    if (x0_func)
      (ai.*x0_func)(mgr, msg, delta);
  }
};

class CStateMachine {
  std::vector<CAiState> x0_states;
  std::vector<CAiTrigger> x10_triggers;

public:
  explicit CStateMachine(CInputStream& in);

  s32 GetStateIndex(std::string_view state) const;
  const std::vector<CAiState>& GetStateVector() const { return x0_states; }
};

class CStateMachineState {
  friend class CPatterned;
  const CStateMachine* x0_machine = nullptr;
  CAiState* x4_state = nullptr;
  float x8_time = 0.f;
  float xc_random = 0.f;
  float x10_delay = 0.f;
  float x14_ = 0.f;
  bool x18_24_codeTrigger : 1;

public:
  CStateMachineState() : x18_24_codeTrigger(false) {}

  CAiState* GetActorState() const { return x4_state; }

  void Update(CStateManager& mgr, CAi& ai, float delta);
  void SetState(CStateManager&, CAi&, s32);
  void SetState(CStateManager&, CAi&, const CStateMachine*, std::string_view);
  const std::vector<CAiState>* GetStateVector() const;
  void Setup(const CStateMachine* machine);
  void SetDelay(float delay) { x10_delay = delay; }
  float GetTime() const { return x8_time; }
  float GetRandom() const { return xc_random; }
  float GetDelay() const { return x10_delay; }
  void SetCodeTrigger() { x18_24_codeTrigger = true; }

  const char* GetName() const {
    if (x4_state)
      return x4_state->GetName();
    return nullptr;
  }
};

CFactoryFnReturn FAiFiniteStateMachineFactory(const SObjectTag& tag, CInputStream& in, const CVParamTransfer& vparms,
                                              CObjectReference*);

} // namespace urde
<|endoftext|>


<commit_before>/* Copyright 2017 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 <cstdio>
#include <memory>
#include <string>

#include "tensorflow/lite/toco/model_cmdline_flags.h"
#include "tensorflow/lite/toco/toco_cmdline_flags.h"
#include "tensorflow/lite/toco/toco_convert.h"

int main(int argc, char** argv) {
  toco::string msg;
  toco::ParsedTocoFlags parsed_toco_flags;
  toco::ParsedModelFlags parsed_model_flags;

  // If no args were specified, give a help string to be helpful.
  int* effective_argc = &argc;
  char** effective_argv = argv;
  if (argc == 1) {
    // No arguments, so manufacture help argv.
    static int dummy_argc = 2;
    static char* dummy_argv[] = {argv[0], const_cast<char*>("--help")};
    effective_argc = &dummy_argc;
    effective_argv = dummy_argv;
  }

  // Parse toco flags and command flags in sequence, each one strips off args,
  // giving InitGoogle a chance to handle all remaining arguments.
  bool toco_success = toco::ParseTocoFlagsFromCommandLineFlags(
      effective_argc, effective_argv, &msg, &parsed_toco_flags);
  bool model_success = toco::ParseModelFlagsFromCommandLineFlags(
      effective_argc, effective_argv, &msg, &parsed_model_flags);
  if (!toco_success || !model_success || !msg.empty()) {
    fprintf(stderr, "%s", msg.c_str());
    fflush(stderr);
    return 1;
  }
  toco::port::InitGoogle(argv[0], effective_argc, &effective_argv, true);
  auto status = toco::Convert(parsed_toco_flags, parsed_model_flags);
  return status.ok() ? 0 : -1;
}
<commit_msg>TOCO: Print error message if conversion fails.<commit_after>/* Copyright 2017 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 <cstdio>
#include <memory>
#include <string>

#include "tensorflow/lite/toco/model_cmdline_flags.h"
#include "tensorflow/lite/toco/toco_cmdline_flags.h"
#include "tensorflow/lite/toco/toco_convert.h"

int main(int argc, char** argv) {
  toco::string msg;
  toco::ParsedTocoFlags parsed_toco_flags;
  toco::ParsedModelFlags parsed_model_flags;

  // If no args were specified, give a help string to be helpful.
  int* effective_argc = &argc;
  char** effective_argv = argv;
  if (argc == 1) {
    // No arguments, so manufacture help argv.
    static int dummy_argc = 2;
    static char* dummy_argv[] = {argv[0], const_cast<char*>("--help")};
    effective_argc = &dummy_argc;
    effective_argv = dummy_argv;
  }

  // Parse toco flags and command flags in sequence, each one strips off args,
  // giving InitGoogle a chance to handle all remaining arguments.
  bool toco_success = toco::ParseTocoFlagsFromCommandLineFlags(
      effective_argc, effective_argv, &msg, &parsed_toco_flags);
  bool model_success = toco::ParseModelFlagsFromCommandLineFlags(
      effective_argc, effective_argv, &msg, &parsed_model_flags);
  if (!toco_success || !model_success || !msg.empty()) {
    fprintf(stderr, "%s", msg.c_str());
    fflush(stderr);
    return 1;
  }
  toco::port::InitGoogle(argv[0], effective_argc, &effective_argv, true);
  auto status = toco::Convert(parsed_toco_flags, parsed_model_flags);
  if (!status.ok()) {
    fprintf(stderr, "%s\n", status.error_message().c_str());
    fflush(stderr);
    return 1;
  }
  return 0;
}
<|endoftext|>