<commit_before>

#include <math.h>

#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <Glut/glut.h>
#else
    #define FREEGLUT_STATIC
    #include <GL\glut.h>
#endif

// Initial size of graphics window.
const int WIDTH  = 600;
const int HEIGHT = 400;

// Current size of window.
int width  = WIDTH;
int height = HEIGHT;

// Bounds of viewing frustum.
double nearPlane =  1.0;
double farPlane  = 85.0;

// Viewing angle.
double fovy = 45.0;

static GLint rotX = 0;
static GLint rotY = 0;

static int choice = 0;

void drawRectangle()
{
	//phaser base
	glBegin(GL_TRIANGLE_STRIP);
		glVertex3f(-1.0f, -0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f,  1.0f);
		glVertex3f(-1.0f,  0.5f,  1.0f);
		glVertex3f(1.0f,  0.5f,  1.0f);
		glVertex3f(-1.0f,  0.5f, -1.0f);
		glVertex3f(1.0f,  0.5f, -1.0f);
		glVertex3f(-1.0f, -0.5f, -1.0f);
		glVertex3f(1.0f, -0.5f, -1.0f);
		glVertex3f(-1.0f, -0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f,  1.0f);
	glEnd();

	glBegin(GL_TRIANGLES);
		glVertex3f(1.0f, -0.5f, -1.0f);
		glVertex3f(1.0f,  0.5f, -1.0f);
		glVertex3f(1.0f,  0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f, -1.0f);
		glVertex3f(1.0f,  0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f, -1.0f);
	glEnd();

	glBegin(GL_TRIANGLES);
		glVertex3f(-1.0f, -0.5f, -1.0f);
		glVertex3f(-1.0f,  0.5f, -1.0f);
		glVertex3f(-1.0f,  0.5f,  1.0f);
		glVertex3f(-1.0f, -0.5f, -1.0f);
		glVertex3f(-1.0f,  0.5f,  1.0f);
		glVertex3f(-1.0f, -0.5f,  1.0f);
		glVertex3f(-1.0f, -0.5f, -1.0f);
	glEnd();
}

void drawCylinder(GLint degrees)
{
	const GLfloat PI_TO_DEGREE_RATIO = 3.14159265 / 180;

	GLfloat radius = 1.0f;
	GLfloat height = 1.5f;
	GLint increment = 10;

	glPushMatrix();

		glTranslatef(-radius/2, -height/2, -radius/2);

		glBegin(GL_POLYGON);
			glVertex3f(0.0f, 0.0f, 0.0f);
			for (int i = 0; i <= degrees; i += increment)
			{
				GLfloat angle = i;
				glVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);
			}
		glEnd();

		glBegin(GL_POLYGON);
			glVertex3f(0.0f, height, 0.0f);
			for (int i = 0; i <= degrees; i += increment)
			{
				GLfloat angle = i;
				glVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);
			}
		glEnd();

		glBegin(GL_TRIANGLES); // 2 triangles on the Z axis
			glVertex3f(0.0f, 0.0f, radius);
			glVertex3f(0.0f, height, -radius);
			glVertex3f(0.0f, 0.0f, -radius);
			glVertex3f(0.0f, 0.0f, radius);
			glVertex3f(0.0f, height, radius);
			glVertex3f(0.0f, height, -radius);
			glVertex3f(0.0f, height, radius);
		glEnd();

		/*
		glBegin(GL_TRIANGLES); // 2 triangles on X
			glVertex3f(radius, 0.0f, 0.0f);
			glVertex3f(0.0f, height, 0.0f);
			glVertex3f(0.0f, 0.0f, 0.0f);
			glVertex3f(radius, 0.0f, 0.0f);
			glVertex3f(radius, height, 0.0f);
			glVertex3f(0.0f, height, 0.0f);
			glVertex3f(radius, height, 0.0f);
		glEnd();
		*/

		for (int i = 0; i < degrees; i += increment) //all the triangles along the perimeter
		{
			GLint angleNext = i + increment;
			GLfloat angle = i;

			glBegin(GL_POLYGON);
				glVertex3f(0.0f + sin(angleNext * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angleNext * PI_TO_DEGREE_RATIO) * radius);
				glVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);
				glVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);
				glVertex3f(0.0f + sin(angleNext * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angleNext * PI_TO_DEGREE_RATIO) * radius);
				glVertex3f(0.0f + sin(angleNext * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angleNext * PI_TO_DEGREE_RATIO) * radius);
				glVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);
				glVertex3f(0.0f + sin(angleNext * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angleNext * PI_TO_DEGREE_RATIO) * radius);
			glEnd();
		}

	glPopMatrix();
}

void drawPhaserCannon()
{
	glEnable(GL_DEPTH_TEST);
	//back panel
	glPushMatrix();
		glColor3f(0.0f, 0.0f, 1.0f);
		glTranslatef(1.0f, 0.0f, 0.0f);
		glScalef(1.2f, 1.0f, 1.2f);
		drawCylinder(180);
	glPopMatrix();

	//cannon barrel
	glPushMatrix();
		glColor3f(1.0f, 0.0f, 0.0f);
		glTranslatef(-0.1f, 0.0f, -0.55f);
		glScalef(0.5f, 1.1f, 0.4f);
		drawRectangle();
	glPopMatrix();

	//cannon base
	glPushMatrix();
		glColor3f(0,1,0);
		glTranslatef(1.1f, -1.1f, -0.1f);
		glScalef(0.9f, 0.5f, 0.9f);
		drawCylinder(360);
	glPopMatrix();
}

//sets up rendering context
void render()
{
	//clears the buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	//preps the
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glRotatef(rotX * 10, 1, 0, 0);
	glRotatef(rotY * 10, 0, 1, 0);

	if (choice == 1) //draw a cylinder
		drawRectangle();
	else if (choice == 0) //draw half a cylinder
		drawPhaserCannon();

	glutSwapBuffers();

}

// Respond to window resizing, preserving proportions.
void reshapeMainWindow (int newWidth, int newHeight)
{
	width = newWidth;
	height = newHeight;
	glViewport(0, 0, width, height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(fovy, GLfloat(width) / GLfloat(height), nearPlane, farPlane);
	gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0);
}

void functionKeys(int key, int x, int y)
{
	switch (key)
	{
	case GLUT_KEY_LEFT:
		rotY++;
		break;

	case GLUT_KEY_RIGHT:
		rotY--;
		break;

	case GLUT_KEY_UP:
		rotX++;
		break;

	case GLUT_KEY_DOWN:
		rotX--;
		break;
	}
	glutPostRedisplay();
}

void keyboardKeys(unsigned char key, int x, int y)
{
	switch (key)
	{
	case 'q':
		choice = ++choice % 2;
		break;

	case 27:
		exit(0);
	}

	glutPostRedisplay();
}

int main (int argc, char **argv)
{
	// GLUT initialization.
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowSize(width, height);
	glutCreateWindow("Robot mids");

	//callbacks
	glutReshapeFunc(reshapeMainWindow);
	glutDisplayFunc(render);
	glutSpecialFunc(functionKeys);
	glutKeyboardFunc(keyboardKeys);

	glutMainLoop();

	return 0;
}<commit_msg>cylinder, rectangle, prisms.<commit_after>

#include <math.h>

#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <Glut/glut.h>
#else
    #define FREEGLUT_STATIC
    #include <GL\glut.h>
#endif

// Initial size of graphics window.
const int WIDTH  = 600;
const int HEIGHT = 400;

// Current size of window.
int width  = WIDTH;
int height = HEIGHT;

// Bounds of viewing frustum.
double nearPlane =  1.0;
double farPlane  = 85.0;

// Viewing angle.
double fovy = 45.0;

static GLint rotX = 0;
static GLint rotY = 0;

static int choice = 0;

void drawRectangle()
{
	//phaser base
	glBegin(GL_TRIANGLE_STRIP);
		glVertex3f(-1.0f, -0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f,  1.0f);
		glVertex3f(-1.0f,  0.5f,  1.0f);
		glVertex3f(1.0f,  0.5f,  1.0f);
		glVertex3f(-1.0f,  0.5f, -1.0f);
		glVertex3f(1.0f,  0.5f, -1.0f);
		glVertex3f(-1.0f, -0.5f, -1.0f);
		glVertex3f(1.0f, -0.5f, -1.0f);
		glVertex3f(-1.0f, -0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f,  1.0f);
	glEnd();

	glBegin(GL_TRIANGLES);
		glVertex3f(1.0f, -0.5f, -1.0f);
		glVertex3f(1.0f,  0.5f, -1.0f);
		glVertex3f(1.0f,  0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f, -1.0f);
		glVertex3f(1.0f,  0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f,  1.0f);
		glVertex3f(1.0f, -0.5f, -1.0f);
	glEnd();

	glBegin(GL_TRIANGLES);
		glVertex3f(-1.0f, -0.5f, -1.0f);
		glVertex3f(-1.0f,  0.5f, -1.0f);
		glVertex3f(-1.0f,  0.5f,  1.0f);
		glVertex3f(-1.0f, -0.5f, -1.0f);
		glVertex3f(-1.0f,  0.5f,  1.0f);
		glVertex3f(-1.0f, -0.5f,  1.0f);
		glVertex3f(-1.0f, -0.5f, -1.0f);
	glEnd();
}

void drawCylinder(GLint degrees)
{
	const GLfloat PI_TO_DEGREE_RATIO = 3.14159265 / 180;

	GLfloat radius = 1.0f;
	GLfloat height = 1.5f;
	GLint increment = 10;

	glPushMatrix();

		glTranslatef(-radius/2, -height/2, -radius/2);

		glBegin(GL_POLYGON);
			glVertex3f(0.0f, 0.0f, 0.0f);
			for (int i = 0; i <= degrees; i += increment)
			{
				GLfloat angle = i;
				glVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, 0.0f, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);
			}
		glEnd();

		glBegin(GL_POLYGON);
			glVertex3f(0.0f, height, 0.0f);
			for (int i = 0; i <= degrees; i += increment)
			{
				GLfloat angle = i;
				glVertex3f(0.0f + sin(angle * PI_TO_DEGREE_RATIO) * radius, height, 0.0f + cos(angle * PI_TO_DEGREE_RATIO) * radius);
			}
		glEnd();

		glBegin(GL_TRIANGLES); // 2 triangles on the Z axis
			glVertex3f(0.0f, 0.0f, radius);
			glVertex3f(0.0f, height, -radius);
			glVertex3f(0.0f, 0.0f, -radius);
			glVertex3f(0.0f, 0.0f, radius);
			glVertex3f(0.0f, height, radius);
			glVertex3f(0.0f, height, -radius);
			glVertex3f(0.0f, height, radius);
		glEnd();

		/*
		glBegin(GL_TRIANGLES); // 2 triangles on X
			glVertex3f(radius, 0.0f, 0.0f);
			glVertex3f(0.0f, height, 0.0f);
			glVertex3f(0.0f, 0.0f, 0.0f);
			glVertex3f(radius, 0.0f, 0.0f);
			glVertex3f(radius, height, 0.0f);
			glVertex3f(0.0f, height, 0.0f);
			glVertex3f(radius, height, 0.0f);
		glEnd();
		*/

		for (int i = 0; i < degrees; i += increment) //all the triangles along the perimeter
		{
			GLint angleNext = i + increment;
			GLfloat angle = i;

			GLfloat x0 = sin(angle * PI_TO_DEGREE_RATIO) * radius;
			GLfloat x1 = sin(angleNext * PI_TO_DEGREE_RATIO) * radius;
			GLfloat z0 = cos(angle * PI_TO_DEGREE_RATIO) * radius;
			GLfloat z1 = cos(angleNext * PI_TO_DEGREE_RATIO) * radius;

			glBegin(GL_POLYGON);
				glVertex3f(x1, 0.0f, z1);
				glVertex3f(x0, height, z0);
				glVertex3f(x0, 0.0f, z0);
				glVertex3f(x1, 0.0f, z1);
				glVertex3f(x1, height, z1);
				glVertex3f(x0, height, z0);
				glVertex3f(x1, 0.0f, z1);
			glEnd();
		}

	glPopMatrix();
}

void drawTriangularPrism()
{
	glPushMatrix();
		glRotatef(-135.0f, 0.0f, 0.0f, 1.0f);
		glTranslatef(-0.5f, -0.25f, 0.5f);

		glBegin(GL_TRIANGLES); //base 1
			glVertex3f(0.0f, 0.0f, 0.0f);
			glVertex3f(1.0f, 0.0f, 0.0f);
			glVertex3f(0.5f, 0.5f, 0.0f);
			glVertex3f(0.0f, 0.0f, 0.0f);
		glEnd();

		glBegin(GL_TRIANGLES); //base 2
			glVertex3f(0.0f, 0.0f, -1.0f);
			glVertex3f(1.0f, 0.0f, -1.0f);
			glVertex3f(0.5f, 0.5f, -1.0f);
			glVertex3f(0.0f, 0.0f, -1.0f);
		glEnd();

		glBegin(GL_TRIANGLES); //the "under part"
			glVertex3f(1.0f, 0.0f, 0.0f);
			glVertex3f(0.0f, 0.0f, 0.0f);
			glVertex3f(0.0f, 0.0f, -1.0f);
			glVertex3f(1.0f, 0.0f, 0.0f);
			glVertex3f(1.0f, 0.0f, -1.0f);
			glVertex3f(0.0f, 0.0f, -1.0f);
			glVertex3f(1.0f, 0.0f, -1.0f);
		glEnd();

		glBegin(GL_TRIANGLES); //the "top left part"
			glVertex3f(0.5f, 0.5f, 0.0f);
			glVertex3f(0.0f, 0.0f, -1.0f);
			glVertex3f(0.0f, 0.0f, 0.0f);
			glVertex3f(0.5f, 0.5f, 0.0f);
			glVertex3f(0.5f, 0.5f, -1.0f);
			glVertex3f(0.0f, 0.0f, -1.0f);
			glVertex3f(0.5f, 0.5f, 0.0f);
		glEnd();

		glBegin(GL_TRIANGLES); //the "top right part"
			glVertex3f(1.0f, 0.0f, 0.0f);
			glVertex3f(0.5f, 0.5f, 0.0f);
			glVertex3f(0.5f, 0.5f, -1.0f);
			glVertex3f(1.0f, 0.0f, 0.0f);
			glVertex3f(0.5f, 0.5f, -1.0f);
			glVertex3f(1.0f, 0.0f, -1.0f);
			glVertex3f(1.0f, 0.0f, 0.0f);
		glEnd();

	glPopMatrix();
}

void drawTrapezoidalPrism()
{
	glPushMatrix();
		glTranslatef(-0.5f, 0.25f, 0.0f);

		glPushMatrix();
			glTranslatef(0.0f, -0.24f, 0.0f);
			glScalef(1.0f, 1.4f, 2.0f);
			drawTriangularPrism();
		glPopMatrix();

		glPushMatrix();
			glTranslatef(1.0f, 0.0f, 0.0f);
			glScalef(0.8f, 1.0f, 1.0f);
			drawRectangle();
		glPopMatrix();
	glPopMatrix();
}

void drawPhaserCannon()
{
	glEnable(GL_DEPTH_TEST);
	glTranslatef(-0.9f, 0.9f, 0.5f);

	//back panel
	glPushMatrix();
		glColor3f(0.0f, 0.0f, 1.0f);
		glTranslatef(1.0f, 0.0f, 0.0f);
		glScalef(1.2f, 1.0f, 1.2f);
		drawCylinder(180);
	glPopMatrix();

	//cannon barrel
	glPushMatrix();
		glColor3f(1.0f, 0.0f, 0.0f);
		glTranslatef(-0.1f, 0.0f, -0.6f);
		glScalef(0.5f, 1.1f, 0.4f);
		drawRectangle();
	glPopMatrix();

	//cannon base
	glPushMatrix();
		glColor3f(0,1,0);
		glTranslatef(1.1f, -1.1f, -0.125f);
		glScalef(0.9f, 0.5f, 0.9f);
		drawCylinder(360);
	glPopMatrix();
}

void drawMissileLauncher()
{
	glRotatef(-90, 0.0f, 1.0f, 0.0f);

	glPushMatrix();
		glColor3f(1.0f, 4.0f, 0.0f);
		glScalef(1.1f, 0.9f, 0.8f);
		drawRectangle();
	glPopMatrix();

	glPushMatrix();
		glColor3f(0.5f, 0.0f, 0.5f);
		glPushMatrix();
			glTranslatef(-1.3f, -0.5f, 0.0f);
			glRotatef(90, 1.0f, 0.0f, 0.0f);
			glScalef(0.3f, 1.7f, 0.3f);
			drawCylinder(360);
		glPopMatrix();

		glPushMatrix();
			glColor3f(0.5f, 0.0f, 0.5f);
			glTranslatef(1.6f, -0.5f, 0.0f);
			glRotatef(90, 1.0f, 0.0f, 0.0f);
			glScalef(0.3f, 1.7f, 0.3f);
			drawCylinder(360);
		glPopMatrix();
	glPopMatrix();
}

void drawCannon()
{
	glPushMatrix();
		glColor3f(1.0f, 0.0f, 0.0f);
		drawTrapezoidalPrism();
	glPopMatrix();

	glPushMatrix();
		glColor3f(0.0f, 1.0f, 0.0f);
		glTranslatef(-0.9f, 0.35f, 0.5f);
		glRotatef(90, 0.0f, 0.0f, 1.0f);
		glScalef(0.1f, 0.6, 0.1f);
		drawCylinder(360);
	glPopMatrix();

	glPushMatrix();
		glColor3f(0.0f, 1.0f, 0.0f);
		glTranslatef(-0.9f, 0.35f, -0.5f);
		glRotatef(90, 0.0f, 0.0f, 1.0f);
		glScalef(0.1f, 0.6, 0.1f);
		drawCylinder(360);
	glPopMatrix();
}

void render()
{
	//clears the buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glRotatef(rotX * 10, 1, 0, 0);
	glRotatef(rotY * 10, 0, 1, 0);

	switch (choice)
	{
	case 0:
		drawCannon();
		break;
	case 1:
		drawMissileLauncher();
		break;
	case 2:
		drawPhaserCannon();
		break;
	}

	glutSwapBuffers();
}

// Respond to window resizing, preserving proportions.
void reshapeMainWindow (int newWidth, int newHeight)
{
	width = newWidth;
	height = newHeight;
	glViewport(0, 0, width, height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(fovy, GLfloat(width) / GLfloat(height), nearPlane, farPlane);
	gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0);
}

void functionKeys(int key, int x, int y)
{
	switch (key)
	{
	case GLUT_KEY_LEFT:
		rotY++;
		break;

	case GLUT_KEY_RIGHT:
		rotY--;
		break;

	case GLUT_KEY_UP:
		rotX++;
		break;

	case GLUT_KEY_DOWN:
		rotX--;
		break;
	}
	glutPostRedisplay();
}

void keyboardKeys(unsigned char key, int x, int y)
{
	switch (key)
	{
	case 'q':
		choice = ++choice % 3;
		break;

	case 27:
		exit(0);
	}

	glutPostRedisplay();
}

void init()
{
	glEnable(GL_DEPTH_TEST);
}

int main (int argc, char **argv)
{
	// GLUT initialization.
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowSize(width, height);
	glutCreateWindow("Robot mids");

	//callbacks
	glutReshapeFunc(reshapeMainWindow);
	glutDisplayFunc(render);
	glutSpecialFunc(functionKeys);
	glutKeyboardFunc(keyboardKeys);

	init();

	glutMainLoop();

	return 0;
}<|endoftext|>


<commit_before>// Copyright 2010 Chris Williams <chris@iterativedesigns.com>
#include "serialport_native.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h>

#include <node.h>
#include <node_events.h>
#include <node_buffer.h>
#include <v8.h>

using namespace v8;
using namespace node;

// static Persistent<String> encoding_symbol;
// static Persistent<String> errno_symbol;

// #define THROW_BAD_ARGS ThrowException(Exception::TypeError(String::New("Bad argument")))
//
// static inline Local<Value> errno_exception(int errorno) {
//   Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));
//   Local<Object> obj = e->ToObject();
//   obj->Set(errno_symbol, Integer::New(errorno));
//   return e;
// }

static Persistent<String> data_symbol;
static Persistent<String> close_symbol;

class SerialPort : public EventEmitter {
public:
  static void
  Initialize (v8::Handle<v8::Object> target)
  {
    HandleScope scope;
    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->Inherit(EventEmitter::constructor_template);
    t->InstanceTemplate()->SetInternalFieldCount(1);

    data_symbol = NODE_PSYMBOL("data");
	  close_symbol = NODE_PSYMBOL("close");

    NODE_SET_PROTOTYPE_METHOD(t, "open", Open);
    NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
    NODE_SET_PROTOTYPE_METHOD(t, "write", Write);
    target->Set(String::NewSymbol("SerialPort"), t->GetFunction());

  }

  void signal_handler_IO (int status)
  {
		printf("%i", status);
    printf("received SIGIO signal.\n");
  }

  bool Open(const char* path, int baudrate, int databits, int stopbits, int parity) {
		if (fd_) return false;
    struct termios newtio;

    long BAUD;
    long DATABITS;
    long STOPBITS;
    long PARITYON;
    long PARITY;

    switch (baudrate)
      {
      case 38400:
      default:
        BAUD = B38400;
        break;
      case 19200:
        BAUD  = B19200;
        break;
      case 9600:
        BAUD  = B9600;
        break;
      case 4800:
        BAUD  = B4800;
        break;
      case 2400:
        BAUD  = B2400;
        break;
      case 1800:
        BAUD  = B1800;
        break;
      case 1200:
        BAUD  = B1200;
        break;
      case 600:
        BAUD  = B600;
        break;
      case 300:
        BAUD  = B300;
        break;
      case 200:
        BAUD  = B200;
        break;
      case 150:
        BAUD  = B150;
        break;
      case 134:
        BAUD  = B134;
        break;
      case 110:
        BAUD  = B110;
        break;
      case 75:
        BAUD  = B75;
        break;
      case 50:
        BAUD  = B50;
        break;
      }

    switch (databits)
      {
      case 8:
      default:
        DATABITS = CS8;
        break;
      case 7:
        DATABITS = CS7;
        break;
      case 6:
        DATABITS = CS6;
        break;
      case 5:
        DATABITS = CS5;
        break;
      }
    switch (stopbits)
      {
      case 1:
      default:
        STOPBITS = 0;
        break;
      case 2:
        STOPBITS = CSTOPB;
        break;
      }

    switch (parity)
      {
      case 0:
      default:                       //none
        PARITYON = 0;
        PARITY = 0;
        break;
      case 1:                        //odd
        PARITYON = PARENB;
        PARITY = PARODD;
        break;
      case 2:                        //even
        PARITYON = PARENB;
        PARITY = 0;
        break;
      }

    int flags = (O_RDWR | O_NOCTTY | O_NONBLOCK);

    fd_ = open(path, flags);
    if (fd_ < 0) return false;

    struct sigaction saio;

		// TODO: Hook event emitter to signal handler
    // saio.sa_handler = signal_handler_IO;
		// ENDTODO

    sigemptyset(&saio.sa_mask);   //saio.sa_mask = 0;
    saio.sa_flags = 0;
    //    saio.sa_restorer = NULL;
    sigaction(SIGIO,&saio,NULL);

    //all process to receive SIGIO
    fcntl(fd_, F_SETOWN, getpid());
    fcntl(fd_, F_SETFL, FASYNC);

    newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;
    newtio.c_lflag = 0;       //ICANON;
    newtio.c_cc[VMIN]=1;
    newtio.c_cc[VTIME]=0;
    tcflush(fd_, TCIFLUSH);
    tcsetattr(fd_,TCSANOW,&newtio);

		Ref();

    return true;
  }

  int Write(char* buf, size_t length) {
    ssize_t written = write(fd_, buf, length);
    return written;
  }

	void Close (Local<Value> exception = Local<Value>())
  {
    HandleScope scope;
		if (fd_)	{
			close(fd_);
			fd_ = NULL;
		}
    Emit(close_symbol, 0, NULL);
    Unref();
  }

protected:

	static Handle<Value>
	New (const Arguments& args)
	{
	  HandleScope scope;

	  SerialPort *serial_port = new SerialPort();
	  serial_port->Wrap(args.This());

	  return scope.Close(args.This());
	}

	static Handle<Value>
	Write (const Arguments& args)
	{
	  HandleScope scope;

	  SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());
		if (!Buffer::HasInstance(args[0])) {
	    return ThrowException(Exception::Error(
	                String::New("Second argument needs to be a buffer")));
	  }

	  Local<Object> buffer_obj = args[0]->ToObject();
	  char *buffer_data = Buffer::Data(buffer_obj);
	  size_t buffer_length = Buffer::Length(buffer_obj);

		if (buffer_length < 0) {
      return ThrowException(Exception::TypeError(String::New("Bad argument")));
    }
		int written = serial_port->Write(buffer_data, buffer_length);
    if (written < 0) return ThrowException(Exception::Error(String::NewSymbol(strerror(errno))));
		return scope.Close(Integer::New(written));
	}

	static Handle<Value>
	Open (const Arguments& args)
	{
	  HandleScope scope;

	  SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());

	  long baudrate = 38400;
	  int databits = 8;
	  int stopbits = 1;
	  int parity = 0;

	  if (!args[0]->IsString()) {
	    return scope.Close(ThrowException(Exception::Error(String::New("Must give serial device string as argument"))));
	  }

	  String::Utf8Value path(args[0]->ToString());

	  // Baud Rate Argument
	  if (args.Length() >= 2 && !args[1]->IsInt32()) {
	    return scope.Close(ThrowException(Exception::Error(
	                                                       String::New("If giving baud rate, must be a integer value."))));
	  } else {
	    baudrate = args[1]->Int32Value();
	  }

	  // Data Bits Argument
	  if (args.Length() >= 3 && !args[2]->IsInt32()) {
	    return scope.Close(ThrowException(Exception::Error(
	                                                       String::New("If giving data bits, must be a integer value."))));
	  } else {
	    databits = args[2]->Int32Value();
	  }

	  // Stop Bits Arguments
	  if (args.Length() >= 4 && !args[3]->IsInt32()) {
	    return scope.Close(ThrowException(Exception::Error(
	                                                       String::New("If giving stop bits, must be a integer value."))));
	  } else {
	    stopbits = args[3]->Int32Value();
	  }

	  // parity Arguments
	  if (args.Length() >= 5 && !args[4]->IsInt32()) {
	    return scope.Close(ThrowException(Exception::Error(
	                                                       String::New("If giving parity, must be a integer value."))));
	  } else {
	    parity = args[4]->Int32Value();
	  }

	  bool r = serial_port->Open(*path, baudrate, databits, stopbits, parity);
	  if (!r) {
	    return ThrowException(Exception::Error(
	                                           String::New("Could not open serial port.")));
	  }

	  return scope.Close(Undefined());
	}

  static Handle<Value>
  Close (const Arguments& args)
  {
    SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());
    HandleScope scope;
    serial_port->Close();
    return scope.Close(Undefined());
  }

	// static Handle<Value>
	// Close (const Arguments& args)
	// {
	//   HandleScope scope;
	// 	if (fd_) {
	//     int ret = close(fd_);
	//     if (ret != 0) return scope.Close(ThrowException(ErrnoException(errno)));
	// 	}
	//     return scope.Close(Undefined());
	// }

	//
	// static Handle<Value>
	// Write (const Arguments& args)
	// {
	//
	// }
	//
	//
	//

	SerialPort () : EventEmitter ()
	{
	  fd_ = NULL;
	}

	~SerialPort ()
	{
		if(fd_) {
			close(fd_);
			fd_ = NULL;
		}
	}
private:
	int fd_;
    //
    //
    //
    // private:
    //   static inline Local<Value> errno_exception(int errorno) {
    //     Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));
    //     Local<Object> obj = e->ToObject();
    //     obj->Set(errno_symbol, Integer::New(errorno));
    //     return e;
    //   }
    // }

};

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;
  SerialPort::Initialize(target);
}

<commit_msg>Removed influx node 0.3.x faster buffer code for existing 0.2.x buffer code.<commit_after>// Copyright 2010 Chris Williams <chris@iterativedesigns.com>
#include "serialport_native.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h>

#include <node.h>
#include <node_events.h>
#include <node_buffer.h>
#include <v8.h>

using namespace v8;
using namespace node;

// static Persistent<String> encoding_symbol;
// static Persistent<String> errno_symbol;

// #define THROW_BAD_ARGS ThrowException(Exception::TypeError(String::New("Bad argument")))
//
// static inline Local<Value> errno_exception(int errorno) {
//   Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));
//   Local<Object> obj = e->ToObject();
//   obj->Set(errno_symbol, Integer::New(errorno));
//   return e;
// }

static Persistent<String> data_symbol;
static Persistent<String> close_symbol;

class SerialPort : public EventEmitter {
public:
  static void
  Initialize (v8::Handle<v8::Object> target)
  {
    HandleScope scope;
    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->Inherit(EventEmitter::constructor_template);
    t->InstanceTemplate()->SetInternalFieldCount(1);

    data_symbol = NODE_PSYMBOL("data");
    close_symbol = NODE_PSYMBOL("close");

    NODE_SET_PROTOTYPE_METHOD(t, "open", Open);
    NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
    NODE_SET_PROTOTYPE_METHOD(t, "write", Write);
    target->Set(String::NewSymbol("SerialPort"), t->GetFunction());

  }

  void signal_handler_IO (int status)
  {
    printf("%i", status);
    printf("received SIGIO signal.\n");
  }

  bool Open(const char* path, int baudrate, int databits, int stopbits, int parity) {
    if (fd_) return false;
    struct termios newtio;

    long BAUD;
    long DATABITS;
    long STOPBITS;
    long PARITYON;
    long PARITY;

    switch (baudrate)
      {
      case 38400:
      default:
        BAUD = B38400;
        break;
      case 19200:
        BAUD  = B19200;
        break;
      case 9600:
        BAUD  = B9600;
        break;
      case 4800:
        BAUD  = B4800;
        break;
      case 2400:
        BAUD  = B2400;
        break;
      case 1800:
        BAUD  = B1800;
        break;
      case 1200:
        BAUD  = B1200;
        break;
      case 600:
        BAUD  = B600;
        break;
      case 300:
        BAUD  = B300;
        break;
      case 200:
        BAUD  = B200;
        break;
      case 150:
        BAUD  = B150;
        break;
      case 134:
        BAUD  = B134;
        break;
      case 110:
        BAUD  = B110;
        break;
      case 75:
        BAUD  = B75;
        break;
      case 50:
        BAUD  = B50;
        break;
      }

    switch (databits)
      {
      case 8:
      default:
        DATABITS = CS8;
        break;
      case 7:
        DATABITS = CS7;
        break;
      case 6:
        DATABITS = CS6;
        break;
      case 5:
        DATABITS = CS5;
        break;
      }
    switch (stopbits)
      {
      case 1:
      default:
        STOPBITS = 0;
        break;
      case 2:
        STOPBITS = CSTOPB;
        break;
      }

    switch (parity)
      {
      case 0:
      default:                       //none
        PARITYON = 0;
        PARITY = 0;
        break;
      case 1:                        //odd
        PARITYON = PARENB;
        PARITY = PARODD;
        break;
      case 2:                        //even
        PARITYON = PARENB;
        PARITY = 0;
        break;
      }

    int flags = (O_RDWR | O_NOCTTY | O_NONBLOCK);

    fd_ = open(path, flags);
    if (fd_ < 0) return false;

    struct sigaction saio;

    // TODO: Hook event emitter to signal handler
    // saio.sa_handler = signal_handler_IO;
    // ENDTODO

    sigemptyset(&saio.sa_mask);   //saio.sa_mask = 0;
    saio.sa_flags = 0;
    //    saio.sa_restorer = NULL;
    sigaction(SIGIO,&saio,NULL);

    //all process to receive SIGIO
    fcntl(fd_, F_SETOWN, getpid());
    fcntl(fd_, F_SETFL, FASYNC);

    newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;
    newtio.c_lflag = 0;       //ICANON;
    newtio.c_cc[VMIN]=1;
    newtio.c_cc[VTIME]=0;
    tcflush(fd_, TCIFLUSH);
    tcsetattr(fd_,TCSANOW,&newtio);

    Ref();

    return true;
  }

  int Write(char* buf, size_t length) {
    ssize_t written = write(fd_, buf, length);
    return written;
  }

  void Close (Local<Value> exception = Local<Value>())
  {
    HandleScope scope;
    if (fd_)  {
      close(fd_);
      fd_ = NULL;
    }
    Emit(close_symbol, 0, NULL);
    Unref();
  }

protected:

  static Handle<Value>
  New (const Arguments& args)
  {
    HandleScope scope;

    SerialPort *serial_port = new SerialPort();
    serial_port->Wrap(args.This());

    return scope.Close(args.This());
  }

  static Handle<Value>
  Write (const Arguments& args)
  {
    HandleScope scope;

    SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());

    if (!Buffer::HasInstance(args[0])) {
      return ThrowException(Exception::Error(String::New("First argument needs to be a buffer")));
    }

    Buffer * buffer = ObjectWrap::Unwrap<Buffer>(args[1]->ToObject());
    int buffer_length = buffer->length();
    char * buf = (char*)buffer->data();
    if (buffer_length < 0) {
      return ThrowException(Exception::TypeError(String::New("Bad argument")));
    }
    int written = serial_port->Write(buf, buffer_length);
    if (written < 0) return ThrowException(Exception::Error(String::NewSymbol(strerror(errno))));
    return scope.Close(Integer::New(written));
  }

  static Handle<Value>
  Open (const Arguments& args)
  {
    HandleScope scope;

    SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());

    long baudrate = 38400;
    int databits = 8;
    int stopbits = 1;
    int parity = 0;

    if (!args[0]->IsString()) {
      return scope.Close(ThrowException(Exception::Error(String::New("Must give serial device string as argument"))));
    }

    String::Utf8Value path(args[0]->ToString());

    // Baud Rate Argument
    if (args.Length() >= 2 && !args[1]->IsInt32()) {
      return scope.Close(ThrowException(Exception::Error(
                                                         String::New("If giving baud rate, must be a integer value."))));
    } else {
      baudrate = args[1]->Int32Value();
    }

    // Data Bits Argument
    if (args.Length() >= 3 && !args[2]->IsInt32()) {
      return scope.Close(ThrowException(Exception::Error(
                                                         String::New("If giving data bits, must be a integer value."))));
    } else {
      databits = args[2]->Int32Value();
    }

    // Stop Bits Arguments
    if (args.Length() >= 4 && !args[3]->IsInt32()) {
      return scope.Close(ThrowException(Exception::Error(
                                                         String::New("If giving stop bits, must be a integer value."))));
    } else {
      stopbits = args[3]->Int32Value();
    }

    // parity Arguments
    if (args.Length() >= 5 && !args[4]->IsInt32()) {
      return scope.Close(ThrowException(Exception::Error(
                                                         String::New("If giving parity, must be a integer value."))));
    } else {
      parity = args[4]->Int32Value();
    }

    bool r = serial_port->Open(*path, baudrate, databits, stopbits, parity);
    if (!r) {
      return ThrowException(Exception::Error(
                                             String::New("Could not open serial port.")));
    }

    return scope.Close(Undefined());
  }

  static Handle<Value>
  Close (const Arguments& args)
  {
    SerialPort *serial_port = ObjectWrap::Unwrap<SerialPort>(args.This());
    HandleScope scope;
    serial_port->Close();
    return scope.Close(Undefined());
  }

  // static Handle<Value>
  // Close (const Arguments& args)
  // {
  //   HandleScope scope;
  //  if (fd_) {
  //     int ret = close(fd_);
  //     if (ret != 0) return scope.Close(ThrowException(ErrnoException(errno)));
  //  }
  //     return scope.Close(Undefined());
  // }

  //
  // static Handle<Value>
  // Write (const Arguments& args)
  // {
  //
  // }
  //
  //
  //

  SerialPort () : EventEmitter ()
  {
    fd_ = NULL;
  }

  ~SerialPort ()
  {
    if(fd_) {
      close(fd_);
      fd_ = NULL;
    }
  }
private:
  int fd_;
    //
    //
    //
    // private:
    //   static inline Local<Value> errno_exception(int errorno) {
    //     Local<Value> e = Exception::Error(String::NewSymbol(strerror(errorno)));
    //     Local<Object> obj = e->ToObject();
    //     obj->Set(errno_symbol, Integer::New(errorno));
    //     return e;
    //   }
    // }

};

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;
  SerialPort::Initialize(target);
}

<|endoftext|>


<commit_before>/**
 * @file remoteSubscriptionHandle.cc
 * @author Krzysztof Trzepla
 * @copyright (C) 2016 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "remoteSubscriptionHandle.h"
#include "helpers/logging.h"

#include "messages.pb.h"

namespace one {
namespace client {
namespace events {

RemoteSubscriptionHandle::RemoteSubscriptionHandle(StreamKey streamKey,
    Streams &streams, std::int64_t subscriptionId, ProtoSubscriptionPtr msg,
    SequencerStream &stream)
    : SubscriptionHandle(streamKey, streams)
    , m_subscriptionId{subscriptionId}
    , m_stream{stream}
{
    LOG_DBG(2) << "Sending subscription with ID: '" << subscriptionId << "'";

    auto clientMsg = std::make_unique<ProtoClient>();
    msg->set_id(m_subscriptionId);
    clientMsg->mutable_subscription()->Swap(msg.release());
    m_stream.send(std::move(clientMsg));
}

RemoteSubscriptionHandle::~RemoteSubscriptionHandle()
{
    LOG_DBG(2) << "Sending cancellation for subscription with ID: '"
               << m_subscriptionId << "'";

    auto clientMsg = std::make_unique<ProtoClient>();
    auto *msg = clientMsg->mutable_subscription_cancellation();
    msg->set_id(m_subscriptionId);
    m_stream.send(std::move(clientMsg));
}

} // namespace events
} // namespace client
} // namespace one
<commit_msg>VFS-9252 Changed subscriptions to sync mode<commit_after>/**
 * @file remoteSubscriptionHandle.cc
 * @author Krzysztof Trzepla
 * @copyright (C) 2016 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "remoteSubscriptionHandle.h"
#include "helpers/logging.h"

#include "messages.pb.h"

namespace one {
namespace client {
namespace events {

RemoteSubscriptionHandle::RemoteSubscriptionHandle(StreamKey streamKey,
    Streams &streams, std::int64_t subscriptionId, ProtoSubscriptionPtr msg,
    SequencerStream &stream)
    : SubscriptionHandle(streamKey, streams)
    , m_subscriptionId{subscriptionId}
    , m_stream{stream}
{
    LOG_DBG(2) << "Sending subscription with ID: '" << subscriptionId << "'";

    auto clientMsg = std::make_unique<ProtoClient>();
    msg->set_id(m_subscriptionId);
    clientMsg->mutable_subscription()->Swap(msg.release());
    m_stream.sendSync(std::move(clientMsg));
}

RemoteSubscriptionHandle::~RemoteSubscriptionHandle()
{
    LOG_DBG(2) << "Sending cancellation for subscription with ID: '"
               << m_subscriptionId << "'";

    auto clientMsg = std::make_unique<ProtoClient>();
    auto *msg = clientMsg->mutable_subscription_cancellation();
    msg->set_id(m_subscriptionId);
    m_stream.sendSync(std::move(clientMsg));
}

} // namespace events
} // namespace client
} // namespace one
<|endoftext|>


<commit_before>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "codec.h"

#include <zlib.h>

using namespace parquet_cpp;

void GZipCodec::Decompress(int input_len, const uint8_t* input,
      int output_len, uint8_t* output_buffer)
{
    z_stream stream;
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
    stream.next_in = (Bytef *)input;
    stream.avail_in = (uInt)input_len;
    stream.next_out = (Bytef*)output_buffer;
    stream.avail_out = output_len;
    int rc = inflateInit2(&stream, 16+MAX_WBITS);
    if (rc != Z_OK) {
        throw ParquetException("zlib internal error.");
    }
    rc = inflate(&stream, Z_FINISH);
    if (rc == Z_STREAM_END) {
        rc = inflateEnd(&stream);
    }
    if (rc != Z_OK) {
        throw ParquetException("Corrupt gzip compressed data.");
    }
}

int GZipCodec::MaxCompressedLen(int input_len, const uint8_t* input) {
  return compressBound(input_len);
}

int GZipCodec::Compress(int input_len, const uint8_t* input,
    int output_buffer_len, uint8_t* output_buffer) {
    uLongf dstLen = output_buffer_len;
    int rc = compress2((Bytef*)output_buffer, &dstLen, (Bytef*)input, input_len, 1);
    return rc == Z_OK ? dstLen : input_len;
}
<commit_msg>Fix code style issues<commit_after>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "parquet/compression/codec.h"

#include <zlib.h>

namespace parquet_cpp {

void GZipCodec::Decompress(int input_len, const uint8_t* input,
						   int output_len, uint8_t* output_buffer)
{
	z_stream stream;
	stream.zalloc = reinterpret_cast<alloc_func>0;
	stream.zfree = reinterpret_cast<free_func>0;
	stream.next_in = reinterpret_cast<Bytef *>input;
	stream.avail_in = reinterpret_cast<uInt>input_len;
	stream.next_out = reinterpret_cast<Bytef*>output_buffer;
	stream.avail_out = output_len;
	int rc = inflateInit2(&stream, 16+MAX_WBITS);
	if (rc != Z_OK)
	{
		throw ParquetException("zlib internal error.");
	}
	rc = inflate(&stream, Z_FINISH);
	if (rc == Z_STREAM_END)
	{
		rc = inflateEnd(&stream);
	}
	if (rc != Z_OK)
	{
		throw ParquetException("Corrupt gzip compressed data.");
	}
}

int GZipCodec::MaxCompressedLen(int input_len, const uint8_t* input)
{
	return compressBound(input_len);
}

int GZipCodec::Compress(int input_len, const uint8_t* input,
						int output_buffer_len, uint8_t* output_buffer)
{
	uLongf dstLen = output_buffer_len;
	int rc = compress2(reinterpret_cast<Bytef*>output_buffer, &dstLen, reinterpret_cast<Bytef*>input, input_len, 1);
	return rc == Z_OK ? dstLen : input_len;
}

} // namespace parquet_cpp
<|endoftext|>


<commit_before>#include "option_manager.hh"

#include "assert.hh"

#include <sstream>

namespace Kakoune
{

OptionDesc::OptionDesc(String name, String docstring, OptionFlags flags)
    : m_name(std::move(name)), m_docstring(std::move(docstring)),
    m_flags(flags) {}

Option::Option(const OptionDesc& desc, OptionManager& manager)
    : m_manager(manager), m_desc(desc) {}

OptionManager::OptionManager(OptionManager& parent)
    : m_parent(&parent)
{
    parent.register_watcher(*this);
}

OptionManager::~OptionManager()
{
    if (m_parent)
        m_parent->unregister_watcher(*this);

    kak_assert(m_watchers.empty());
}

void OptionManager::register_watcher(OptionManagerWatcher& watcher)
{
    kak_assert(not contains(m_watchers, &watcher));
    m_watchers.push_back(&watcher);
}

void OptionManager::unregister_watcher(OptionManagerWatcher& watcher)
{
    auto it = find(m_watchers.begin(), m_watchers.end(), &watcher);
    kak_assert(it != m_watchers.end());
    m_watchers.erase(it);
}

Option& OptionManager::get_local_option(const String& name)
{
    auto it = find_option(m_options, name);
    if (it != m_options.end())
        return **it;
    else if (m_parent)
    {
        m_options.emplace_back((*m_parent)[name].clone(*this));
        return *m_options.back();
    }
    else
        throw option_not_found(name);

}

const Option& OptionManager::operator[](const String& name) const
{
    auto it = find_option(m_options, name);
    if (it != m_options.end())
        return **it;
    else if (m_parent)
        return (*m_parent)[name];
    else
        throw option_not_found(name);
}

template<typename MatchingFunc>
CandidateList OptionManager::get_matching_names(MatchingFunc func)
{
    CandidateList result;
    if (m_parent)
        result = m_parent->get_matching_names(func);
    for (auto& option : m_options)
    {
        if (option->flags() & OptionFlags::Hidden)
            continue;

        const auto& name = option->name();
        if (func(name) and not contains(result, name))
            result.push_back(name);
    }
    return result;
}

CandidateList OptionManager::complete_option_name(StringView prefix,
                                                  ByteCount cursor_pos)
{
    using namespace std::placeholders;
    auto real_prefix = prefix.substr(0, cursor_pos);
    auto result = get_matching_names(std::bind(prefix_match, _1, real_prefix));
    if (result.empty())
        result = get_matching_names(std::bind(subsequence_match, _1, real_prefix));
    return result;
}

OptionManager::OptionList OptionManager::flatten_options() const
{
    OptionList res = m_parent ? m_parent->flatten_options() : OptionList{};
    for (auto& option : m_options)
    {
        auto it = find_option(res, option->name());
        if (it != res.end())
            *it = option.get();
        else
            res.emplace_back(option.get());
    }
    return res;
}

void OptionManager::on_option_changed(const Option& option)
{
    // if parent option changed, but we overrided it, it's like nothing happened
    if (&option.manager() != this and
        find_option(m_options, option.name()) != m_options.end())
        return;

    for (auto watcher : m_watchers)
        watcher->on_option_changed(option);
}

GlobalOptions::GlobalOptions()
    : OptionManager()
{
    declare_option("tabstop", "size of a tab character", 8);
    declare_option("indentwidth", "indentation width", 4);
    declare_option("scrolloff",
                   "number of lines to keep visible main cursor when scrolling",
                   0);
    declare_option("eolformat", "end of line format: 'crlf' or 'lf'", "lf"_str);
    declare_option("BOM", "insert a byte order mark when writing buffer",
                   "no"_str);
    declare_option("complete_prefix",
                   "complete up to common prefix in tab completion",
                   true);
    declare_option("incsearch",
                   "incrementaly apply search/select/split regex",
                   true);
    declare_option("autoinfo",
                   "automatically display contextual help",
                   true);
    declare_option("autoshowcompl",
                   "automatically display possible completions for prompts",
                   true);
    declare_option("aligntab",
                   "use tab characters when possible for alignement",
                   false);
    declare_option("ignored_files",
                   "patterns to ignore when completing filenames",
                   Regex{R"(^(\..*|.*\.(o|so|a))$)"});
    declare_option("filetype", "buffer filetype", ""_str);
    declare_option("path", "path to consider when trying to find a file",
                   std::vector<String>({ "./", "/usr/include" }));
    declare_option("completers", "insert mode completers to execute.",
                    std::vector<String>({"filename", "word=buffer"}),
                    OptionFlags::None,
                    OptionChecker<std::vector<String>>([](const std::vector<String>& s) {
                        static const auto values = {"word=buffer", "word=all", "filename"};
                        for (auto& v : s)
                        {
                            if (v.substr(0_byte, 7_byte) == "option=")
                                continue;
                            if (not contains(values, v))
                                throw runtime_error(v + " is not a recognised value for completers");
                        }
                    }));
    declare_option("autoreload",
                   "autoreload buffer when a filesystem modification is detected",
                    Ask);
}

}
<commit_msg>use words=all rather than words=buffer for default insert word completion<commit_after>#include "option_manager.hh"

#include "assert.hh"

#include <sstream>

namespace Kakoune
{

OptionDesc::OptionDesc(String name, String docstring, OptionFlags flags)
    : m_name(std::move(name)), m_docstring(std::move(docstring)),
    m_flags(flags) {}

Option::Option(const OptionDesc& desc, OptionManager& manager)
    : m_manager(manager), m_desc(desc) {}

OptionManager::OptionManager(OptionManager& parent)
    : m_parent(&parent)
{
    parent.register_watcher(*this);
}

OptionManager::~OptionManager()
{
    if (m_parent)
        m_parent->unregister_watcher(*this);

    kak_assert(m_watchers.empty());
}

void OptionManager::register_watcher(OptionManagerWatcher& watcher)
{
    kak_assert(not contains(m_watchers, &watcher));
    m_watchers.push_back(&watcher);
}

void OptionManager::unregister_watcher(OptionManagerWatcher& watcher)
{
    auto it = find(m_watchers.begin(), m_watchers.end(), &watcher);
    kak_assert(it != m_watchers.end());
    m_watchers.erase(it);
}

Option& OptionManager::get_local_option(const String& name)
{
    auto it = find_option(m_options, name);
    if (it != m_options.end())
        return **it;
    else if (m_parent)
    {
        m_options.emplace_back((*m_parent)[name].clone(*this));
        return *m_options.back();
    }
    else
        throw option_not_found(name);

}

const Option& OptionManager::operator[](const String& name) const
{
    auto it = find_option(m_options, name);
    if (it != m_options.end())
        return **it;
    else if (m_parent)
        return (*m_parent)[name];
    else
        throw option_not_found(name);
}

template<typename MatchingFunc>
CandidateList OptionManager::get_matching_names(MatchingFunc func)
{
    CandidateList result;
    if (m_parent)
        result = m_parent->get_matching_names(func);
    for (auto& option : m_options)
    {
        if (option->flags() & OptionFlags::Hidden)
            continue;

        const auto& name = option->name();
        if (func(name) and not contains(result, name))
            result.push_back(name);
    }
    return result;
}

CandidateList OptionManager::complete_option_name(StringView prefix,
                                                  ByteCount cursor_pos)
{
    using namespace std::placeholders;
    auto real_prefix = prefix.substr(0, cursor_pos);
    auto result = get_matching_names(std::bind(prefix_match, _1, real_prefix));
    if (result.empty())
        result = get_matching_names(std::bind(subsequence_match, _1, real_prefix));
    return result;
}

OptionManager::OptionList OptionManager::flatten_options() const
{
    OptionList res = m_parent ? m_parent->flatten_options() : OptionList{};
    for (auto& option : m_options)
    {
        auto it = find_option(res, option->name());
        if (it != res.end())
            *it = option.get();
        else
            res.emplace_back(option.get());
    }
    return res;
}

void OptionManager::on_option_changed(const Option& option)
{
    // if parent option changed, but we overrided it, it's like nothing happened
    if (&option.manager() != this and
        find_option(m_options, option.name()) != m_options.end())
        return;

    for (auto watcher : m_watchers)
        watcher->on_option_changed(option);
}

GlobalOptions::GlobalOptions()
    : OptionManager()
{
    declare_option("tabstop", "size of a tab character", 8);
    declare_option("indentwidth", "indentation width", 4);
    declare_option("scrolloff",
                   "number of lines to keep visible main cursor when scrolling",
                   0);
    declare_option("eolformat", "end of line format: 'crlf' or 'lf'", "lf"_str);
    declare_option("BOM", "insert a byte order mark when writing buffer",
                   "no"_str);
    declare_option("complete_prefix",
                   "complete up to common prefix in tab completion",
                   true);
    declare_option("incsearch",
                   "incrementaly apply search/select/split regex",
                   true);
    declare_option("autoinfo",
                   "automatically display contextual help",
                   true);
    declare_option("autoshowcompl",
                   "automatically display possible completions for prompts",
                   true);
    declare_option("aligntab",
                   "use tab characters when possible for alignement",
                   false);
    declare_option("ignored_files",
                   "patterns to ignore when completing filenames",
                   Regex{R"(^(\..*|.*\.(o|so|a))$)"});
    declare_option("filetype", "buffer filetype", ""_str);
    declare_option("path", "path to consider when trying to find a file",
                   std::vector<String>({ "./", "/usr/include" }));
    declare_option("completers", "insert mode completers to execute.",
                    std::vector<String>({"filename", "word=all"}),
                    OptionFlags::None,
                    OptionChecker<std::vector<String>>([](const std::vector<String>& s) {
                        static const auto values = {"word=buffer", "word=all", "filename"};
                        for (auto& v : s)
                        {
                            if (v.substr(0_byte, 7_byte) == "option=")
                                continue;
                            if (not contains(values, v))
                                throw runtime_error(v + " is not a recognised value for completers");
                        }
                    }));
    declare_option("autoreload",
                   "autoreload buffer when a filesystem modification is detected",
                    Ask);
}

}
<|endoftext|>


<commit_before>#include "protagonist.h"
#include "snowcrash.h"

using namespace v8;
using namespace protagonist;

//static const std::string RenderDescriptionsOptionKey = "renderDescriptions";
static const std::string RequireBlueprintNameOptionKey = "requireBlueprintName";
static const std::string ExportSourcemapOptionKey = "exportSourcemap";
static const std::string TypeOptionKey = "type";

static const std::string TypeOptionAst = "ast";
static const std::string TypeOptionRefract = "refract";

OptionsResult* protagonist::ParseOptionsObject(Handle<Object> optionsObject) {
    OptionsResult *optionsResult = (OptionsResult *) malloc(sizeof(OptionsResult));

    optionsResult->options = 0;
    optionsResult->astType = drafter::RefractASTType;
    optionsResult->error = NULL;

    const Local<Array> properties = optionsObject->GetPropertyNames();
    const uint32_t length = properties->Length();

    for (uint32_t i = 0 ; i < length ; ++i) {
        const Local<Value> key = properties->Get(i);
        const Local<Value> value = optionsObject->Get(key);

        if (RequireBlueprintNameOptionKey == *String::Utf8Value(key)) {
            // RequireBlueprintNameOption
            if (value->IsTrue())
                optionsResult->options |= snowcrash::RequireBlueprintNameOption;
            else
                optionsResult->options &= snowcrash::RequireBlueprintNameOption;
        }
        else if (ExportSourcemapOptionKey == *String::Utf8Value(key)) {
            // ExportSourcemapOption
            if (value->IsTrue())
                optionsResult->options |= snowcrash::ExportSourcemapOption;
            else
                optionsResult->options &= snowcrash::ExportSourcemapOption;
        }
        else if (TypeOptionKey == *String::Utf8Value(key)) {
            // TypeOption
            if (TypeOptionAst == *String::Utf8Value(value)) {
                optionsResult->astType = drafter::NormalASTType;
            } else if (TypeOptionRefract == *String::Utf8Value(value)) {
                optionsResult->astType = drafter::RefractASTType;
            } else {
                std::stringstream ss;
                ss << "unrecognized type '" << *String::Utf8Value(value) << "', expected '";
                ss << TypeOptionAst << "' or '" << TypeOptionRefract << "'";

                optionsResult->error = ss.str().c_str();
                return optionsResult;
            }
        }
        else {
            // Unrecognized option
            std::stringstream ss;
            ss << "unrecognized option '" << *String::Utf8Value(key) << "', expected: ";
            ss << "'" << RequireBlueprintNameOptionKey << "', '";
            ss << ExportSourcemapOptionKey << "' or '" << TypeOptionKey << '"';

            optionsResult->error = ss.str().c_str();
            return optionsResult;
        }
    }

    return optionsResult;
}
<commit_msg>Code improvement and optimization in options_parser.cc<commit_after>#include "protagonist.h"
#include "snowcrash.h"

using namespace v8;
using namespace protagonist;

//static const std::string RenderDescriptionsOptionKey = "renderDescriptions";
static const std::string RequireBlueprintNameOptionKey = "requireBlueprintName";
static const std::string ExportSourcemapOptionKey = "exportSourcemap";
static const std::string TypeOptionKey = "type";

static const std::string TypeOptionAst = "ast";
static const std::string TypeOptionRefract = "refract";

OptionsResult* protagonist::ParseOptionsObject(Handle<Object> optionsObject) {
    OptionsResult *optionsResult = (OptionsResult *) malloc(sizeof(OptionsResult));

    optionsResult->options = 0;
    optionsResult->astType = drafter::RefractASTType;
    optionsResult->error = NULL;

    const Local<Array> properties = optionsObject->GetPropertyNames();
    const uint32_t length = properties->Length();

    for (uint32_t i = 0 ; i < length ; ++i) {
        const Local<Value> key = properties->Get(i);
        const Local<Value> value = optionsObject->Get(key);

        const String::Utf8Value strKey(key);

        if (RequireBlueprintNameOptionKey == *strKey) {
            // RequireBlueprintNameOption
            if (value->IsTrue())
                optionsResult->options |= snowcrash::RequireBlueprintNameOption;
            else
                optionsResult->options &= snowcrash::RequireBlueprintNameOption;
        }
        else if (ExportSourcemapOptionKey == *strKey) {
            // ExportSourcemapOption
            if (value->IsTrue())
                optionsResult->options |= snowcrash::ExportSourcemapOption;
            else
                optionsResult->options &= snowcrash::ExportSourcemapOption;
        }
        else if (TypeOptionKey == *strKey) {
            // TypeOption
            const String::Utf8Value strValue(value);

            if (TypeOptionAst == *strValue) {
                optionsResult->astType = drafter::NormalASTType;
            } else if (TypeOptionRefract == *strValue) {
                optionsResult->astType = drafter::RefractASTType;
            } else {
                std::stringstream ss;
                ss << "unrecognized type '" << *strValue << "', expected '";
                ss << TypeOptionAst << "' or '" << TypeOptionRefract << "'";

                optionsResult->error = ss.str().c_str();
                return optionsResult;
            }
        }
        else {
            // Unrecognized option
            std::stringstream ss;
            ss << "unrecognized option '" << *strKey << "', expected: ";
            ss << "'" << RequireBlueprintNameOptionKey << "', '";
            ss << ExportSourcemapOptionKey << "' or '" << TypeOptionKey << '"';

            optionsResult->error = ss.str().c_str();
            return optionsResult;
        }
    }

    return optionsResult;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#ifndef itkConnectedThresholdImageFilter_hxx
#define itkConnectedThresholdImageFilter_hxx

#include "itkConnectedThresholdImageFilter.h"
#include "itkBinaryThresholdImageFunction.h"
#include "itkFloodFilledImageFunctionConditionalIterator.h"
#include "itkProgressReporter.h"

#include "itkShapedFloodFilledImageFunctionConditionalIterator.h"
#include "itkMath.h"

namespace itk
{

template< typename TInputImage, typename TOutputImage >
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::ConnectedThresholdImageFilter() :
  m_Lower( NumericTraits< InputImagePixelType >::NonpositiveMin() ),
  m_Upper( NumericTraits< InputImagePixelType >::max() ),
  m_ReplaceValue( NumericTraits< OutputImagePixelType >::OneValue() ),
  m_Connectivity( FaceConnectivity )
{
  typename InputPixelObjectType::Pointer lower = InputPixelObjectType::New();
  lower->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );
  this->ProcessObject::SetNthInput(1, lower);

  typename InputPixelObjectType::Pointer upper = InputPixelObjectType::New();
  upper->Set( NumericTraits< InputImagePixelType >::max() );
  this->ProcessObject::SetNthInput(2, upper);
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetSeed(const IndexType & seed)
{
  this->ClearSeeds();
  this->AddSeed( seed );
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::AddSeed(const IndexType & seed)
{
  this->m_Seeds.push_back(seed);
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::ClearSeeds()
{
  if ( m_Seeds.size() > 0 )
    {
    this->m_Seeds.clear();
    this->Modified();
    }
}

template< typename TInputImage, typename TOutputImage >
const typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::SeedContainerType &
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetSeeds() const
{
  return this->m_Seeds;
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
  Superclass::GenerateInputRequestedRegion();
  if ( this->GetInput() )
    {
    InputImagePointer image =
      const_cast< InputImageType * >( this->GetInput() );
    image->SetRequestedRegionToLargestPossibleRegion();
    }
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::EnlargeOutputRequestedRegion(DataObject *output)
{
  Superclass::EnlargeOutputRequestedRegion(output);
  output->SetRequestedRegionToLargestPossibleRegion();
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetLowerInput(const InputPixelObjectType *input)
{
  if ( input != this->GetLowerInput() )
    {
    this->ProcessObject::SetNthInput( 1,
                                      const_cast< InputPixelObjectType * >( input ) );
    this->Modified();
    }
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetUpperInput(const InputPixelObjectType *input)
{
  if ( input != this->GetUpperInput() )
    {
    this->ProcessObject::SetNthInput( 2,
                                      const_cast< InputPixelObjectType * >( input ) );
    this->Modified();
    }
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetUpper(const InputImagePixelType threshold)
{
  // first check to see if anything changed
  typename InputPixelObjectType::Pointer upper = this->GetUpperInput();
  if ( upper && Math::ExactlyEquals(upper->Get(), threshold) )
    {
    return;
    }

  // Create a data object to use as the input and to store this
  // threshold. we always create a new data object to use as the input
  // since we do not want to change the value in any current input
  // (the current input could be the output of another filter or the
  // current input could be used as an input to several filters).
  upper = InputPixelObjectType::New();
  this->ProcessObject::SetNthInput(2, upper);

  upper->Set(threshold);
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetLower(const InputImagePixelType threshold)
{
  // first check to see if anything changed
  typename InputPixelObjectType::Pointer lower = this->GetLowerInput();
  if ( lower && Math::ExactlyEquals(lower->Get(), threshold) )
    {
    return;
    }

  // Create a data object to use as the input and to store this
  // threshold. we always create a new data object to use as the input
  // since we do not want to change the value in any current input
  // (the current input could be the output of another filter or the
  // current input could be used as an input to several filters).
  lower = InputPixelObjectType::New();
  this->ProcessObject::SetNthInput(1, lower);

  lower->Set(threshold);
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputPixelObjectType *
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetLowerInput()
{
  typename InputPixelObjectType::Pointer lower =
    static_cast< InputPixelObjectType * >( this->ProcessObject::GetInput(1) );
  if ( !lower )
    {
    // No input object available, create a new one and set it to the
    // default threshold
    lower = InputPixelObjectType::New();
    lower->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );
    this->ProcessObject::SetNthInput(1, lower);
    }

  return lower;
}

template< typename TInputImage, typename TOutputImage >
typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputPixelObjectType *
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetUpperInput()
{
  typename InputPixelObjectType::Pointer upper =
    static_cast< InputPixelObjectType * >( this->ProcessObject::GetInput(2) );
  if ( !upper )
    {
    // No input object available, create a new one and set it to the
    // default threshold
    upper = InputPixelObjectType::New();
    upper->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );
    this->ProcessObject::SetNthInput(2, upper);
    }

  return upper;
}

template< typename TInputImage, typename TOutputImage >
typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputImagePixelType
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetLower() const
{
  typename InputPixelObjectType::Pointer lower =
    const_cast< Self * >( this )->GetLowerInput();

  return lower->Get();
}

template< typename TInputImage, typename TOutputImage >
typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputImagePixelType
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetUpper() const
{
  typename InputPixelObjectType::Pointer upper =
    const_cast< Self * >( this )->GetUpperInput();

  return upper->Get();
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GenerateData()
{
  InputImageConstPointer inputImage = this->GetInput();
  OutputImagePointer     outputImage = this->GetOutput();

  typename InputPixelObjectType::Pointer lowerThreshold = this->GetLowerInput();
  typename InputPixelObjectType::Pointer upperThreshold = this->GetUpperInput();

  m_Lower = lowerThreshold->Get();
  m_Upper = upperThreshold->Get();

  // Zero the output
  OutputImageRegionType region = outputImage->GetRequestedRegion();
  outputImage->SetBufferedRegion(region);
  outputImage->Allocate();
  outputImage->FillBuffer(NumericTraits< OutputImagePixelType >::ZeroValue());

  typedef BinaryThresholdImageFunction< InputImageType, double > FunctionType;

  typename FunctionType::Pointer function = FunctionType::New();
  function->SetInputImage( inputImage );
  function->ThresholdBetween( m_Lower, m_Upper );

  ProgressReporter progress( this, 0, region.GetNumberOfPixels() );

  if ( this->m_Connectivity == FaceConnectivity )
    {
    typedef FloodFilledImageFunctionConditionalIterator< OutputImageType, FunctionType > IteratorType;
    IteratorType it (outputImage, function, m_Seeds);
    it.GoToBegin();

    while ( !it.IsAtEnd() )
      {
      it.Set(m_ReplaceValue);
      ++it;
      progress.CompletedPixel();  // potential exception thrown here
      }
    }
  else if ( this->m_Connectivity == FullConnectivity )
    {
    // Use the fully connected iterator here. The fully connected iterator
    // below is a superset of the above. However, it is reported to be 20%
    // slower. Hence we use this "if" block to use the old iterator when
    // we don't need full connectivity.

    typedef ShapedFloodFilledImageFunctionConditionalIterator< OutputImageType, FunctionType > IteratorType;
    IteratorType it (outputImage, function, m_Seeds);
    it.FullyConnectedOn();
    it.GoToBegin();

    while ( !it.IsAtEnd() )
      {
      it.Set(m_ReplaceValue);
      ++it;
      progress.CompletedPixel();  // potential exception thrown here
      }
    }
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Upper: "
     << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_Upper )
     << std::endl;
  os << indent << "Lower: "
     << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_Lower )
     << std::endl;
  os << indent << "ReplaceValue: "
     << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_ReplaceValue )
     << std::endl;
  os << indent << "Connectivity: " << m_Connectivity << std::endl;
}
} // end namespace itk

#endif
<commit_msg>BUG: Print missing Seeds parameter and values used for Upper/Lower<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#ifndef itkConnectedThresholdImageFilter_hxx
#define itkConnectedThresholdImageFilter_hxx

#include "itkConnectedThresholdImageFilter.h"
#include "itkBinaryThresholdImageFunction.h"
#include "itkFloodFilledImageFunctionConditionalIterator.h"
#include "itkProgressReporter.h"

#include "itkShapedFloodFilledImageFunctionConditionalIterator.h"
#include "itkMath.h"

namespace itk
{

template< typename TInputImage, typename TOutputImage >
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::ConnectedThresholdImageFilter() :
  m_Lower( NumericTraits< InputImagePixelType >::NonpositiveMin() ),
  m_Upper( NumericTraits< InputImagePixelType >::max() ),
  m_ReplaceValue( NumericTraits< OutputImagePixelType >::OneValue() ),
  m_Connectivity( FaceConnectivity )
{
  typename InputPixelObjectType::Pointer lower = InputPixelObjectType::New();
  lower->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );
  this->ProcessObject::SetNthInput(1, lower);

  typename InputPixelObjectType::Pointer upper = InputPixelObjectType::New();
  upper->Set( NumericTraits< InputImagePixelType >::max() );
  this->ProcessObject::SetNthInput(2, upper);
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetSeed(const IndexType & seed)
{
  this->ClearSeeds();
  this->AddSeed( seed );
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::AddSeed(const IndexType & seed)
{
  this->m_Seeds.push_back(seed);
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::ClearSeeds()
{
  if ( m_Seeds.size() > 0 )
    {
    this->m_Seeds.clear();
    this->Modified();
    }
}

template< typename TInputImage, typename TOutputImage >
const typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::SeedContainerType &
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetSeeds() const
{
  return this->m_Seeds;
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GenerateInputRequestedRegion()
{
  Superclass::GenerateInputRequestedRegion();
  if ( this->GetInput() )
    {
    InputImagePointer image =
      const_cast< InputImageType * >( this->GetInput() );
    image->SetRequestedRegionToLargestPossibleRegion();
    }
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::EnlargeOutputRequestedRegion(DataObject *output)
{
  Superclass::EnlargeOutputRequestedRegion(output);
  output->SetRequestedRegionToLargestPossibleRegion();
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetLowerInput(const InputPixelObjectType *input)
{
  if ( input != this->GetLowerInput() )
    {
    this->ProcessObject::SetNthInput( 1,
                                      const_cast< InputPixelObjectType * >( input ) );
    this->Modified();
    }
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetUpperInput(const InputPixelObjectType *input)
{
  if ( input != this->GetUpperInput() )
    {
    this->ProcessObject::SetNthInput( 2,
                                      const_cast< InputPixelObjectType * >( input ) );
    this->Modified();
    }
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetUpper(const InputImagePixelType threshold)
{
  // first check to see if anything changed
  typename InputPixelObjectType::Pointer upper = this->GetUpperInput();
  if ( upper && Math::ExactlyEquals(upper->Get(), threshold) )
    {
    return;
    }

  // Create a data object to use as the input and to store this
  // threshold. we always create a new data object to use as the input
  // since we do not want to change the value in any current input
  // (the current input could be the output of another filter or the
  // current input could be used as an input to several filters).
  upper = InputPixelObjectType::New();
  this->ProcessObject::SetNthInput(2, upper);

  upper->Set(threshold);
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::SetLower(const InputImagePixelType threshold)
{
  // first check to see if anything changed
  typename InputPixelObjectType::Pointer lower = this->GetLowerInput();
  if ( lower && Math::ExactlyEquals(lower->Get(), threshold) )
    {
    return;
    }

  // Create a data object to use as the input and to store this
  // threshold. we always create a new data object to use as the input
  // since we do not want to change the value in any current input
  // (the current input could be the output of another filter or the
  // current input could be used as an input to several filters).
  lower = InputPixelObjectType::New();
  this->ProcessObject::SetNthInput(1, lower);

  lower->Set(threshold);
  this->Modified();
}

template< typename TInputImage, typename TOutputImage >
typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputPixelObjectType *
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetLowerInput()
{
  typename InputPixelObjectType::Pointer lower =
    static_cast< InputPixelObjectType * >( this->ProcessObject::GetInput(1) );
  if ( !lower )
    {
    // No input object available, create a new one and set it to the
    // default threshold
    lower = InputPixelObjectType::New();
    lower->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );
    this->ProcessObject::SetNthInput(1, lower);
    }

  return lower;
}

template< typename TInputImage, typename TOutputImage >
typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputPixelObjectType *
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetUpperInput()
{
  typename InputPixelObjectType::Pointer upper =
    static_cast< InputPixelObjectType * >( this->ProcessObject::GetInput(2) );
  if ( !upper )
    {
    // No input object available, create a new one and set it to the
    // default threshold
    upper = InputPixelObjectType::New();
    upper->Set( NumericTraits< InputImagePixelType >::NonpositiveMin() );
    this->ProcessObject::SetNthInput(2, upper);
    }

  return upper;
}

template< typename TInputImage, typename TOutputImage >
typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputImagePixelType
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetLower() const
{
  typename InputPixelObjectType::Pointer lower =
    const_cast< Self * >( this )->GetLowerInput();

  return lower->Get();
}

template< typename TInputImage, typename TOutputImage >
typename ConnectedThresholdImageFilter< TInputImage, TOutputImage >::InputImagePixelType
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GetUpper() const
{
  typename InputPixelObjectType::Pointer upper =
    const_cast< Self * >( this )->GetUpperInput();

  return upper->Get();
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::GenerateData()
{
  InputImageConstPointer inputImage = this->GetInput();
  OutputImagePointer     outputImage = this->GetOutput();

  typename InputPixelObjectType::Pointer lowerThreshold = this->GetLowerInput();
  typename InputPixelObjectType::Pointer upperThreshold = this->GetUpperInput();

  m_Lower = lowerThreshold->Get();
  m_Upper = upperThreshold->Get();

  // Zero the output
  OutputImageRegionType region = outputImage->GetRequestedRegion();
  outputImage->SetBufferedRegion(region);
  outputImage->Allocate();
  outputImage->FillBuffer(NumericTraits< OutputImagePixelType >::ZeroValue());

  typedef BinaryThresholdImageFunction< InputImageType, double > FunctionType;

  typename FunctionType::Pointer function = FunctionType::New();
  function->SetInputImage( inputImage );
  function->ThresholdBetween( m_Lower, m_Upper );

  ProgressReporter progress( this, 0, region.GetNumberOfPixels() );

  if ( this->m_Connectivity == FaceConnectivity )
    {
    typedef FloodFilledImageFunctionConditionalIterator< OutputImageType, FunctionType > IteratorType;
    IteratorType it (outputImage, function, m_Seeds);
    it.GoToBegin();

    while ( !it.IsAtEnd() )
      {
      it.Set(m_ReplaceValue);
      ++it;
      progress.CompletedPixel();  // potential exception thrown here
      }
    }
  else if ( this->m_Connectivity == FullConnectivity )
    {
    // Use the fully connected iterator here. The fully connected iterator
    // below is a superset of the above. However, it is reported to be 20%
    // slower. Hence we use this "if" block to use the old iterator when
    // we don't need full connectivity.

    typedef ShapedFloodFilledImageFunctionConditionalIterator< OutputImageType, FunctionType > IteratorType;
    IteratorType it (outputImage, function, m_Seeds);
    it.FullyConnectedOn();
    it.GoToBegin();

    while ( !it.IsAtEnd() )
      {
      it.Set(m_ReplaceValue);
      ++it;
      progress.CompletedPixel();  // potential exception thrown here
      }
    }
}

template< typename TInputImage, typename TOutputImage >
void
ConnectedThresholdImageFilter< TInputImage, TOutputImage >
::PrintSelf(std::ostream & os, Indent indent) const
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Upper: "
     << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( this->GetUpper() )
     << std::endl;
  os << indent << "Lower: "
     << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( this->GetLower() )
     << std::endl;
  os << indent << "ReplaceValue: "
     << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_ReplaceValue )
     << std::endl;
  os << indent << "Seeds: ";
  for (unsigned int i = 0; i < this->m_Seeds.size(); ++i)
    {
    os << "  " << this->m_Seeds[i] << std::endl;
    }
  os << std::endl;
  os << indent << "Connectivity: " << m_Connectivity << std::endl;
}
} // end namespace itk

#endif
<|endoftext|>


<commit_before>
#include <math.h>
#include <netdb.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "statsd_client.h"

using namespace std;
namespace statsd {

inline bool fequal(float a, float b)
{
    const float epsilon = 0.0001;
    return ( fabs(a - b) < epsilon );
}

inline bool should_send(float sample_rate)
{
    if ( fequal(sample_rate, 1.0) )
    {
        return true;
    }

    float p = ((float)random() / RAND_MAX);
    return sample_rate > p;
}

struct _StatsdClientData {
    int     sock;
    struct  sockaddr_in server;

    string  ns;
    string  host;
    short   port;
    bool    init;

    char    errmsg[1024];
};

StatsdClient::StatsdClient(const string& host, int port, const string& ns)
{
    d = new _StatsdClientData;
    config(host, port, ns);
    srandom(time(NULL));
}

StatsdClient::~StatsdClient()
{
    // close socket
    if (d->sock >= 0) {
        close(d->sock);
        d->sock = -1;
    }
}

void StatsdClient::config(const string& host, int port, const string& ns)
{
    d->ns = ns;
    d->host = host;
    d->port = port;
    d->init = false;
    if ( d->sock >= 0 ) {
        close(d->sock);
    }
    d->sock = -1;
}

int StatsdClient::init()
{
    if ( d->init ) return 0;

    d->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if ( d->sock == -1 ) {
        snprintf(d->errmsg, sizeof(d->errmsg), "could not create socket, err=%m");
        return -1;
    }

    memset(&d->server, 0, sizeof(d->server));
    d->server.sin_family = AF_INET;
    d->server.sin_port = htons(d->port);

    int ret = inet_aton(d->host.c_str(), &d->server.sin_addr);
    if ( ret == 0 )
    {
        // host must be a domain, get it from internet
        struct addrinfo hints, *result = NULL;
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_DGRAM;

        ret = getaddrinfo(d->host.c_str(), NULL, &hints, &result);
        if ( ret ) {
            snprintf(d->errmsg, sizeof(d->errmsg),
                    "getaddrinfo fail, error=%d, msg=%s", ret, gai_strerror(ret) );
            return -2;
        }
        struct sockaddr_in* host_addr = (struct sockaddr_in*)result->ai_addr;
        memcpy(&d->server.sin_addr, &host_addr->sin_addr, sizeof(struct in_addr));
        freeaddrinfo(result);
    }

    d->init = true;
    return 0;
}

/* will change the original string */
void StatsdClient::cleanup(string& key)
{
    size_t pos = key.find_first_of(":|@");
    while ( pos != string::npos )
    {
        key[pos] = '_';
        pos = key.find_first_of(":|@");
    }
}

int StatsdClient::dec(const string& key, float sample_rate)
{
    return count(key, -1, sample_rate);
}

int StatsdClient::inc(const string& key, float sample_rate)
{
    return count(key, 1, sample_rate);
}

int StatsdClient::count(const string& key, size_t value, float sample_rate)
{
    return send(key, value, "c", sample_rate);
}

int StatsdClient::gauge(const string& key, size_t value, float sample_rate)
{
    return send(key, value, "g", sample_rate);
}

int StatsdClient::timing(const string& key, size_t ms, float sample_rate)
{
    return send(key, ms, "ms", sample_rate);
}

int StatsdClient::send(string key, size_t value, const string &type, float sample_rate)
{
    if (!should_send(sample_rate)) {
        return 0;
    }

    cleanup(key);

    char buf[256];
    if ( fequal( sample_rate, 1.0 ) )
    {
        snprintf(buf, sizeof(buf), "%s%s:%zd|%s",
                d->ns.c_str(), key.c_str(), value, type.c_str());
    }
    else
    {
        snprintf(buf, sizeof(buf), "%s%s:%zd|%s|@%.2f",
                d->ns.c_str(), key.c_str(), value, type.c_str(), sample_rate);
    }

    return send(buf);
}

int StatsdClient::send(const string &message)
{
    int ret = init();
    if ( ret )
    {
        return ret;
    }
    ret = sendto(d->sock, message.data(), message.size(), 0, (struct sockaddr *) &d->server, sizeof(d->server));
    if ( ret == -1) {
        snprintf(d->errmsg, sizeof(d->errmsg),
                "sendto server fail, host=%s:%d, err=%m", d->host.c_str(), d->port);
        return -1;
    }
    return 0;
}

const char* StatsdClient::errmsg()
{
    return d->errmsg;
}

}

<commit_msg>add delete d<commit_after>
#include <math.h>
#include <netdb.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "statsd_client.h"

using namespace std;
namespace statsd {

inline bool fequal(float a, float b)
{
    const float epsilon = 0.0001;
    return ( fabs(a - b) < epsilon );
}

inline bool should_send(float sample_rate)
{
    if ( fequal(sample_rate, 1.0) )
    {
        return true;
    }

    float p = ((float)random() / RAND_MAX);
    return sample_rate > p;
}

struct _StatsdClientData {
    int     sock;
    struct  sockaddr_in server;

    string  ns;
    string  host;
    short   port;
    bool    init;

    char    errmsg[1024];
};

StatsdClient::StatsdClient(const string& host, int port, const string& ns)
{
    d = new _StatsdClientData;
    config(host, port, ns);
    srandom(time(NULL));
}

StatsdClient::~StatsdClient()
{
    // close socket
    if (d->sock >= 0) {
        close(d->sock);
        d->sock = -1;
        delete d;
        d = NULL;
    }
}

void StatsdClient::config(const string& host, int port, const string& ns)
{
    d->ns = ns;
    d->host = host;
    d->port = port;
    d->init = false;
    if ( d->sock >= 0 ) {
        close(d->sock);
    }
    d->sock = -1;
}

int StatsdClient::init()
{
    if ( d->init ) return 0;

    d->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if ( d->sock == -1 ) {
        snprintf(d->errmsg, sizeof(d->errmsg), "could not create socket, err=%m");
        return -1;
    }

    memset(&d->server, 0, sizeof(d->server));
    d->server.sin_family = AF_INET;
    d->server.sin_port = htons(d->port);

    int ret = inet_aton(d->host.c_str(), &d->server.sin_addr);
    if ( ret == 0 )
    {
        // host must be a domain, get it from internet
        struct addrinfo hints, *result = NULL;
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_DGRAM;

        ret = getaddrinfo(d->host.c_str(), NULL, &hints, &result);
        if ( ret ) {
            snprintf(d->errmsg, sizeof(d->errmsg),
                    "getaddrinfo fail, error=%d, msg=%s", ret, gai_strerror(ret) );
            return -2;
        }
        struct sockaddr_in* host_addr = (struct sockaddr_in*)result->ai_addr;
        memcpy(&d->server.sin_addr, &host_addr->sin_addr, sizeof(struct in_addr));
        freeaddrinfo(result);
    }

    d->init = true;
    return 0;
}

/* will change the original string */
void StatsdClient::cleanup(string& key)
{
    size_t pos = key.find_first_of(":|@");
    while ( pos != string::npos )
    {
        key[pos] = '_';
        pos = key.find_first_of(":|@");
    }
}

int StatsdClient::dec(const string& key, float sample_rate)
{
    return count(key, -1, sample_rate);
}

int StatsdClient::inc(const string& key, float sample_rate)
{
    return count(key, 1, sample_rate);
}

int StatsdClient::count(const string& key, size_t value, float sample_rate)
{
    return send(key, value, "c", sample_rate);
}

int StatsdClient::gauge(const string& key, size_t value, float sample_rate)
{
    return send(key, value, "g", sample_rate);
}

int StatsdClient::timing(const string& key, size_t ms, float sample_rate)
{
    return send(key, ms, "ms", sample_rate);
}

int StatsdClient::send(string key, size_t value, const string &type, float sample_rate)
{
    if (!should_send(sample_rate)) {
        return 0;
    }

    cleanup(key);

    char buf[256];
    if ( fequal( sample_rate, 1.0 ) )
    {
        snprintf(buf, sizeof(buf), "%s%s:%zd|%s",
                d->ns.c_str(), key.c_str(), value, type.c_str());
    }
    else
    {
        snprintf(buf, sizeof(buf), "%s%s:%zd|%s|@%.2f",
                d->ns.c_str(), key.c_str(), value, type.c_str(), sample_rate);
    }

    return send(buf);
}

int StatsdClient::send(const string &message)
{
    int ret = init();
    if ( ret )
    {
        return ret;
    }
    ret = sendto(d->sock, message.data(), message.size(), 0, (struct sockaddr *) &d->server, sizeof(d->server));
    if ( ret == -1) {
        snprintf(d->errmsg, sizeof(d->errmsg),
                "sendto server fail, host=%s:%d, err=%m", d->host.c_str(), d->port);
        return -1;
    }
    return 0;
}

const char* StatsdClient::errmsg()
{
    return d->errmsg;
}

}

<|endoftext|>


<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <iomanip>
#include <iostream>
#include <string>

#include "flutter/flow/layers/performance_overlay_layer.h"

namespace flow {
namespace {

void DrawStatisticsText(SkCanvas& canvas,
                        const std::string& string,
                        int x,
                        int y) {
  SkPaint paint;
  paint.setTextSize(15);
  paint.setLinearText(false);
  paint.setColor(SK_ColorGRAY);
  paint.setAntiAlias(true);
  canvas.drawText(string.c_str(), string.size(), x, y, paint);
}

void VisualizeStopWatch(SkCanvas& canvas,
                        const Stopwatch& stopwatch,
                        SkScalar x,
                        SkScalar y,
                        SkScalar width,
                        SkScalar height,
                        bool show_graph,
                        bool show_labels,
                        const std::string& label_prefix) {
  const int label_x = 8;    // distance from x
  const int label_y = -10;  // distance from y+height

  if (show_graph) {
    SkRect visualization_rect = SkRect::MakeXYWH(x, y, width, height);
    stopwatch.Visualize(canvas, visualization_rect);
  }

  if (show_labels) {
    double ms_per_frame = stopwatch.MaxDelta().ToMillisecondsF();
    double fps;
    if (ms_per_frame < kOneFrameMS) {
      fps = 1e3 / kOneFrameMS;
    } else {
      fps = 1e3 / ms_per_frame;
    }

    std::stringstream stream;
    stream.setf(std::ios::fixed | std::ios::showpoint);
    stream << std::setprecision(1);
    stream << label_prefix << "  " << fps << " fps  " << ms_per_frame
           << "ms/frame";
    DrawStatisticsText(canvas, stream.str(), x + label_x, y + height + label_y);
  }
}

}  // namespace

PerformanceOverlayLayer::PerformanceOverlayLayer(uint64_t options)
    : options_(options) {}

void PerformanceOverlayLayer::Paint(PaintContext& context) const {
  const int padding = 8;

  if (!options_)
    return;

  TRACE_EVENT0("flutter", "PerformanceOverlayLayer::Paint");
  SkScalar x = paint_bounds().x() + padding;
  SkScalar y = paint_bounds().y() + padding;
  SkScalar width = paint_bounds().width() - (padding * 2);
  SkScalar height = paint_bounds().height() / 2;
  SkAutoCanvasRestore save(context.leaf_nodes_canvas, true);

  VisualizeStopWatch(*context.leaf_nodes_canvas, context.frame_time, x, y,
                     width, height - padding,
                     options_ & kVisualizeRasterizerStatistics,
                     options_ & kDisplayRasterizerStatistics, "GPU");

  VisualizeStopWatch(*context.leaf_nodes_canvas, context.engine_time, x,
                     y + height, width, height - padding,
                     options_ & kVisualizeEngineStatistics,
                     options_ & kDisplayEngineStatistics, "UI");
}

}  // namespace flow
<commit_msg>update site to use SkFont for text fields (#7464)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <iomanip>
#include <iostream>
#include <string>

#include "flutter/flow/layers/performance_overlay_layer.h"
#include "third_party/skia/include/core/SkFont.h"

namespace flow {
namespace {

void DrawStatisticsText(SkCanvas& canvas,
                        const std::string& string,
                        int x,
                        int y) {
  SkFont font;
  font.setSize(15);
  font.setLinearMetrics(false);
  SkPaint paint;
  paint.setColor(SK_ColorGRAY);
  canvas.drawSimpleText(string.c_str(), string.size(), kUTF8_SkTextEncoding, x,
                        y, font, paint);
}

void VisualizeStopWatch(SkCanvas& canvas,
                        const Stopwatch& stopwatch,
                        SkScalar x,
                        SkScalar y,
                        SkScalar width,
                        SkScalar height,
                        bool show_graph,
                        bool show_labels,
                        const std::string& label_prefix) {
  const int label_x = 8;    // distance from x
  const int label_y = -10;  // distance from y+height

  if (show_graph) {
    SkRect visualization_rect = SkRect::MakeXYWH(x, y, width, height);
    stopwatch.Visualize(canvas, visualization_rect);
  }

  if (show_labels) {
    double ms_per_frame = stopwatch.MaxDelta().ToMillisecondsF();
    double fps;
    if (ms_per_frame < kOneFrameMS) {
      fps = 1e3 / kOneFrameMS;
    } else {
      fps = 1e3 / ms_per_frame;
    }

    std::stringstream stream;
    stream.setf(std::ios::fixed | std::ios::showpoint);
    stream << std::setprecision(1);
    stream << label_prefix << "  " << fps << " fps  " << ms_per_frame
           << "ms/frame";
    DrawStatisticsText(canvas, stream.str(), x + label_x, y + height + label_y);
  }
}

}  // namespace

PerformanceOverlayLayer::PerformanceOverlayLayer(uint64_t options)
    : options_(options) {}

void PerformanceOverlayLayer::Paint(PaintContext& context) const {
  const int padding = 8;

  if (!options_)
    return;

  TRACE_EVENT0("flutter", "PerformanceOverlayLayer::Paint");
  SkScalar x = paint_bounds().x() + padding;
  SkScalar y = paint_bounds().y() + padding;
  SkScalar width = paint_bounds().width() - (padding * 2);
  SkScalar height = paint_bounds().height() / 2;
  SkAutoCanvasRestore save(context.leaf_nodes_canvas, true);

  VisualizeStopWatch(*context.leaf_nodes_canvas, context.frame_time, x, y,
                     width, height - padding,
                     options_ & kVisualizeRasterizerStatistics,
                     options_ & kDisplayRasterizerStatistics, "GPU");

  VisualizeStopWatch(*context.leaf_nodes_canvas, context.engine_time, x,
                     y + height, width, height - padding,
                     options_ & kVisualizeEngineStatistics,
                     options_ & kDisplayEngineStatistics, "UI");
}

}  // namespace flow
<|endoftext|>


<commit_before>
#include "cpu.h"

#if defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)
# include <sys/param.h>
# include <sys/sysctl.h>
#endif
#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_CYGWIN)
# include <unistd.h>
#endif
#include "windows.hdr.h"

namespace Yuni
{
namespace System
{
namespace CPU
{

	#if defined(YUNI_OS_WINDOWS) || defined(YUNI_OS_CYGWIN)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		SYSTEM_INFO si;
		GetSystemInfo(&si);
		return si.dwNumberOfProcessors;
	}
	#endif

	#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		// The number of processors online (capable of running processes)
		long cpus = sysconf(_SC_NPROCESSORS_ONLN);
		return (cpus < 1) ? 1 : (uint) cpus;
	}
	#endif

	#ifndef YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	#  warning "The method Yuni::System::CPU::Count() has not been implemented for the current platform"
	uint Count()
	{
		return 1; // Default value
	}
	#endif

} // namespace CPU
} // namespace System
} // namespace Yuni

<commit_msg>CPU::Count: fixed compilation on MacOS<commit_after>
#include "cpu.h"
#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)
#include <unistd.h>
#endif
#include "windows.hdr.h"

namespace Yuni
{
namespace System
{
namespace CPU
{

	#if defined(YUNI_OS_WINDOWS) || defined(YUNI_OS_CYGWIN)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		SYSTEM_INFO si;
		GetSystemInfo(&si);
		return si.dwNumberOfProcessors;
	}
	#endif

	#if defined(YUNI_OS_LINUX) || defined(YUNI_OS_DARWIN) || defined(YUNI_OS_FREEBSD) || defined(YUNI_OS_NETBSD) || defined(YUNI_OS_OPENBSD)
	# define YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	uint Count()
	{
		// The number of processors online (capable of running processes)
		long cpus = sysconf(_SC_NPROCESSORS_ONLN);
		return (cpus < 1) ? 1 : (uint) cpus;
	}
	#endif

	#ifndef YUNI_CPU_COUNT_HAS_IMPLEMENTATION
	#  warning "The method Yuni::System::CPU::Count() has not been implemented for the current platform"
	uint Count()
	{
		return 1; // Default value
	}
	#endif

} // namespace CPU
} // namespace System
} // namespace Yuni

<|endoftext|>