<commit_before>#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <iostream>
#include <linux/i2c-dev.h>

#define I2C_ADDR 0x1E

int file_i2c;
int length;
unsigned int microseconds;
unsigned char buffer[60] = {0};

void compassInit();
void readCompass(int&, int&, int&);

int main()
{
    int x, y, z;
    compassInit();
    while(1)
    {
      readCompass(x, y, z);
      std::cout << "x: " << x/2048.0*360 << " y: " << y/2048.0*360 << " z: " << z/2048.0*360 << std::endl ;
    }
}

void compassInit()
{
  char *filename = (char*)"/dev/i2c-1";
	if ((file_i2c = open(filename, O_RDWR)) < 0)
	{
		//ERROR HANDLING: you can check errno to see what went wrong
		printf("Failed to open the i2c bus");
		return;
	}
  if (ioctl(file_i2c, I2C_SLAVE, I2C_ADDR) < 0)
  {
    printf("Failed to acquire bus access and/or talk to slave.\n");
    //ERROR HANDLING; you can check errno to see what went wrong
    return;
  }
  buffer[0] = 0x00;
  buffer[1] = 0xB8;
  length = 2;			//<<< Number of bytes to write
  if (write(file_i2c, buffer, length) != length)		//write() returns the number of bytes actually written, if it doesn't match then an error occurred (e.g. no response from the device)
  {
  		/* ERROR HANDLING: i2c transaction failed */
  		printf("1) Failed to write to the i2c bus.\n");
  }
  buffer[0] = 0x02;
  buffer[1] = 0x00;
  length = 2;			//<<< Number of bytes to write
  if (write(file_i2c, buffer, length) != length)		//write() returns the number of bytes actually written, if it doesn't match then an error occurred (e.g. no response from the device)
  {
  		/* ERROR HANDLING: i2c transaction failed */
  		printf("2) Failed to write to the i2c bus.\n");
  }
  usleep(100000);
}

void readCompass(int& x, int& y, int& z)
{
  unsigned char value[6]={0};
  buffer[0] = 0x03;
  length = 1;
  if (write(file_i2c, buffer, length) != length)		//write() returns the number of bytes actually written, if it doesn't match then an error occurred (e.g. no response from the device)
  {
  		/* ERROR HANDLING: i2c transaction failed */
  		printf("3) Failed to write to the i2c bus.\n");
  }
  for(int i = 0; i < 6; i++)
  {
    usleep(1000);
    length = 1;			//<<< Number of bytes to read
    if (read(file_i2c, buffer, length) != length)		//read() returns the number of bytes actually read, if it doesn't match then an error occurred (e.g. no response from the device)
    {
      //ERROR HANDLING: i2c transaction failed
      printf("Failed to read from the i2c bus.\n");
    }
    else
    {
      printf("Data read: %x\n", buffer[0]);
      value[i] = buffer[0];
    }
  }
  x = (value[0] << 8) | value[1];
  z = (value[2] << 8) | value[3];
  y = (value[4] << 8) | value[5];
}
<commit_msg>added delay<commit_after>#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <iostream>
#include <linux/i2c-dev.h>

#define I2C_ADDR 0x1E

int file_i2c;
int length;
unsigned int microseconds;
unsigned char buffer[60] = {0};

void compassInit();
void readCompass(int&, int&, int&);

int main()
{
    int x, y, z;
    compassInit();
    while(1)
    {
      readCompass(x, y, z);
      usleep(10000);
      std::cout << "x: " << x/2048.0*360 << " y: " << y/2048.0*360 << " z: " << z/2048.0*360 << std::endl ;
    }
}

void compassInit()
{
  char *filename = (char*)"/dev/i2c-1";
	if ((file_i2c = open(filename, O_RDWR)) < 0)
	{
		//ERROR HANDLING: you can check errno to see what went wrong
		printf("Failed to open the i2c bus");
		return;
	}
  if (ioctl(file_i2c, I2C_SLAVE, I2C_ADDR) < 0)
  {
    printf("Failed to acquire bus access and/or talk to slave.\n");
    //ERROR HANDLING; you can check errno to see what went wrong
    return;
  }
  buffer[0] = 0x00;
  buffer[1] = 0xB8;
  length = 2;			//<<< Number of bytes to write
  if (write(file_i2c, buffer, length) != length)		//write() returns the number of bytes actually written, if it doesn't match then an error occurred (e.g. no response from the device)
  {
  		/* ERROR HANDLING: i2c transaction failed */
  		printf("1) Failed to write to the i2c bus.\n");
  }
  buffer[0] = 0x02;
  buffer[1] = 0x00;
  length = 2;			//<<< Number of bytes to write
  if (write(file_i2c, buffer, length) != length)		//write() returns the number of bytes actually written, if it doesn't match then an error occurred (e.g. no response from the device)
  {
  		/* ERROR HANDLING: i2c transaction failed */
  		printf("2) Failed to write to the i2c bus.\n");
  }
  usleep(100000);
}

void readCompass(int& x, int& y, int& z)
{
  unsigned char value[6]={0};
  buffer[0] = 0x03;
  length = 1;
  if (write(file_i2c, buffer, length) != length)		//write() returns the number of bytes actually written, if it doesn't match then an error occurred (e.g. no response from the device)
  {
  		/* ERROR HANDLING: i2c transaction failed */
  		printf("3) Failed to write to the i2c bus.\n");
  }
  for(int i = 0; i < 6; i++)
  {
    usleep(1000);
    length = 1;			//<<< Number of bytes to read
    if (read(file_i2c, buffer, length) != length)		//read() returns the number of bytes actually read, if it doesn't match then an error occurred (e.g. no response from the device)
    {
      //ERROR HANDLING: i2c transaction failed
      printf("Failed to read from the i2c bus.\n");
    }
    else
    {
      printf("Data read: %x\n", buffer[0]);
      value[i] = buffer[0];
    }
  }
  x = (value[0] << 8) | value[1];
  z = (value[2] << 8) | value[3];
  y = (value[4] << 8) | value[5];
}
<|endoftext|>


<commit_before>#include "SDL.h"
#include "Convert.h"
#include <limits.h>
#include <Windows.h>
#include <XInput.h> // for deadzone stuff
#include "minmax.h"

#include "DreamPad.h"

DreamPad DreamPad::Controllers[PAD_COUNT];

DreamPad::DreamPad() : controller_id(-1), gamepad(nullptr), haptic(nullptr), effect({}),
	effect_id(-1), rumbleTime_L(0), rumbleTime_S(0), rumbleState(Motor::None), pad({})
{
	effect.type = SDL_HAPTIC_SINE;
	effect.leftright.type = SDL_HAPTIC_LEFTRIGHT;
	effect.leftright.length = SDL_HAPTIC_INFINITY;
}
DreamPad::~DreamPad()
{
	Close();
}

/// <summary>
/// Opens the specified controller ID.
/// </summary>
/// <param name="id">Controller ID to open.</param>
/// <returns><c>true</c> on success. Note that haptic can fail and the function will still return true.</returns>
bool DreamPad::Open(int id)
{
	if (isConnected)
		Close();

	this->gamepad = SDL_GameControllerOpen(id);

	if (gamepad == nullptr)
		return isConnected = false;

	pad.Support = (PDD_DEV_SUPPORT_TA | PDD_DEV_SUPPORT_TB | PDD_DEV_SUPPORT_TC | PDD_DEV_SUPPORT_TD
		| PDD_DEV_SUPPORT_TX | PDD_DEV_SUPPORT_TY | PDD_DEV_SUPPORT_TZ | PDD_DEV_SUPPORT_AR | PDD_DEV_SUPPORT_AL
		| PDD_DEV_SUPPORT_ST | PDD_DEV_SUPPORT_KU | PDD_DEV_SUPPORT_KD | PDD_DEV_SUPPORT_KL | PDD_DEV_SUPPORT_KR
		| PDD_DEV_SUPPORT_AX1 | PDD_DEV_SUPPORT_AY1 | PDD_DEV_SUPPORT_AX2 | PDD_DEV_SUPPORT_AY2);

	SDL_Joystick* joystick = SDL_GameControllerGetJoystick(this->gamepad);

	if (joystick == nullptr)
		return isConnected = false;

	controller_id = id;
	this->haptic = SDL_HapticOpenFromJoystick(joystick);

	if (haptic == nullptr)
		return isConnected = true;

	if (SDL_HapticRumbleSupported(haptic))
	{
		effect_id = SDL_HapticNewEffect(haptic, &effect);
	}
	else
	{
		SDL_HapticClose(haptic);
		haptic = nullptr;
	}

	return isConnected = true;
}

/// <summary>
/// Closes this instance.
/// </summary>
void DreamPad::Close()
{
	if (!isConnected)
		return;

	if (haptic != nullptr)
	{
		SDL_HapticDestroyEffect(haptic, effect_id);
		SDL_HapticClose(haptic);

		effect_id = -1;
		haptic = nullptr;
	}

	if (gamepad != nullptr)
	{
		SDL_GameControllerClose(gamepad);
		gamepad = nullptr;
		controller_id = -1;
	}

	isConnected = false;
}

/// <summary>
/// Calls Poll and UpdateMotor automatically.
/// </summary>
void DreamPad::Update()
{
	Poll();
	UpdateMotor();
}

/// <summary>
/// Polls input for this instance.
/// </summary>
void DreamPad::Poll()
{
	if (!isConnected)
		return;

	SDL_GameControllerUpdate();

	short axis[2];

	axis[0] = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTX);
	axis[1] = -SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTY);

	xinput::ConvertAxes(settings.scaleFactor, &pad.LeftStickX, axis, settings.deadzoneL, settings.radialL);

	axis[0] = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_RIGHTX);
	axis[1] = -SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_RIGHTY);

	xinput::ConvertAxes(settings.scaleFactor, &pad.RightStickX, axis, settings.deadzoneR, settings.radialR);

	pad.LTriggerPressure = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_TRIGGERLEFT);
	pad.RTriggerPressure = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);

	int buttons = 0;

	buttons |= DigitalTrigger(pad.LTriggerPressure, settings.triggerThreshold, Buttons_L);
	buttons |= DigitalTrigger(pad.RTriggerPressure, settings.triggerThreshold, Buttons_R);

	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_A))
		buttons |= Buttons_A;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_B))
		buttons |= Buttons_B;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_X))
		buttons |= Buttons_X;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_Y))
		buttons |= Buttons_Y;

	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_START))
		buttons |= Buttons_Start;

	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_LEFTSHOULDER))
		buttons |= Buttons_C;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_BACK))
		buttons |= Buttons_D;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER))
		buttons |= Buttons_Z;

	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_UP))
		buttons |= Buttons_Up;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_DOWN))
		buttons |= Buttons_Down;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
		buttons |= Buttons_Left;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
		buttons |= Buttons_Right;

	pad.HeldButtons		= buttons;
	pad.NotHeldButtons	= ~buttons;
	pad.ReleasedButtons	= pad.Old & (buttons ^ pad.Old);
	pad.PressedButtons	= buttons & (buttons ^ pad.Old);
	pad.Old				= pad.HeldButtons;
}

void DreamPad::UpdateMotor()
{
	if (effect_id == -1 || haptic == nullptr || rumbleState == Motor::None)
		return;

	Motor turn_off = Motor::None;
	uint now = GetTickCount();

	if (now - rumbleTime_L >= 250)
		turn_off = (Motor)(turn_off | Motor::Large);

	if (now - rumbleTime_S >= 1000)
		turn_off = (Motor)(turn_off | Motor::Small);

	if (turn_off != Motor::None)
		SetActiveMotor(turn_off, 0);
}

void DreamPad::SetActiveMotor(Motor motor, short magnitude)
{
	if (effect_id == -1 || haptic == nullptr)
		return;

	const float f = settings.rumbleFactor;

	if (motor & Motor::Large)
	{
		effect.leftright.large_magnitude = (short)min(SHRT_MAX, (int)(magnitude * f));
		rumbleTime_L = GetTickCount();
		rumbleState = (Motor)((magnitude > 0) ? rumbleState | motor : rumbleState & ~Motor::Large);
	}

	if (motor & Motor::Small)
	{
		effect.leftright.small_magnitude = (short)min(SHRT_MAX, (int)(magnitude * (2 + f)));
		rumbleTime_S = GetTickCount();
		rumbleState = (Motor)((magnitude > 0) ? rumbleState | motor : rumbleState & ~Motor::Small);
	}

	SDL_HapticUpdateEffect(haptic, effect_id, &effect);
	SDL_HapticRunEffect(haptic, effect_id, 1);
}

Motor DreamPad::GetActiveMotor() const
{
	return rumbleState;
}

void DreamPad::Copy(ControllerData& dest) const
{
	dest = pad;
}

inline int DreamPad::DigitalTrigger(ushort trigger, ushort threshold, int button)
{
	return (trigger > threshold) ? button : 0;
}

DreamPad::Settings::Settings()
{
	deadzoneL = XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE;
	deadzoneR = XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE;
	triggerThreshold = XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
	radialL = true;
	radialR = false;
	rumbleFactor = 1.0f;
	scaleFactor = 1.5f;
}
void DreamPad::Settings::apply(short deadzoneL, short deadzoneR, bool radialL, bool radialR, uint8 triggerThreshold, float rumbleFactor, float scaleFactor)
{
	this->deadzoneL = clamp(deadzoneL, (short)0, (short)SHRT_MAX);
	this->deadzoneR = clamp(deadzoneR, (short)0, (short)SHRT_MAX);
	this->radialL = radialL;
	this->radialR = radialR;
	this->triggerThreshold = min((uint8)UCHAR_MAX, triggerThreshold);
	this->rumbleFactor = rumbleFactor;
	this->scaleFactor = max(1.0f, scaleFactor);
}
<commit_msg>Fixed triggers.<commit_after>#include "SDL.h"
#include "Convert.h"
#include <limits.h>
#include <Windows.h>
#include <XInput.h> // for deadzone stuff
#include "minmax.h"

#include "DreamPad.h"

DreamPad DreamPad::Controllers[PAD_COUNT];

DreamPad::DreamPad() : controller_id(-1), gamepad(nullptr), haptic(nullptr), effect({}),
	effect_id(-1), rumbleTime_L(0), rumbleTime_S(0), rumbleState(Motor::None), pad({})
{
	effect.type = SDL_HAPTIC_SINE;
	effect.leftright.type = SDL_HAPTIC_LEFTRIGHT;
	effect.leftright.length = SDL_HAPTIC_INFINITY;
}
DreamPad::~DreamPad()
{
	Close();
}

/// <summary>
/// Opens the specified controller ID.
/// </summary>
/// <param name="id">Controller ID to open.</param>
/// <returns><c>true</c> on success. Note that haptic can fail and the function will still return true.</returns>
bool DreamPad::Open(int id)
{
	if (isConnected)
		Close();

	this->gamepad = SDL_GameControllerOpen(id);

	if (gamepad == nullptr)
		return isConnected = false;

	pad.Support = (PDD_DEV_SUPPORT_TA | PDD_DEV_SUPPORT_TB | PDD_DEV_SUPPORT_TC | PDD_DEV_SUPPORT_TD
		| PDD_DEV_SUPPORT_TX | PDD_DEV_SUPPORT_TY | PDD_DEV_SUPPORT_TZ | PDD_DEV_SUPPORT_AR | PDD_DEV_SUPPORT_AL
		| PDD_DEV_SUPPORT_ST | PDD_DEV_SUPPORT_KU | PDD_DEV_SUPPORT_KD | PDD_DEV_SUPPORT_KL | PDD_DEV_SUPPORT_KR
		| PDD_DEV_SUPPORT_AX1 | PDD_DEV_SUPPORT_AY1 | PDD_DEV_SUPPORT_AX2 | PDD_DEV_SUPPORT_AY2);

	SDL_Joystick* joystick = SDL_GameControllerGetJoystick(this->gamepad);

	if (joystick == nullptr)
		return isConnected = false;

	controller_id = id;
	this->haptic = SDL_HapticOpenFromJoystick(joystick);

	if (haptic == nullptr)
		return isConnected = true;

	if (SDL_HapticRumbleSupported(haptic))
	{
		effect_id = SDL_HapticNewEffect(haptic, &effect);
	}
	else
	{
		SDL_HapticClose(haptic);
		haptic = nullptr;
	}

	return isConnected = true;
}

/// <summary>
/// Closes this instance.
/// </summary>
void DreamPad::Close()
{
	if (!isConnected)
		return;

	if (haptic != nullptr)
	{
		SDL_HapticDestroyEffect(haptic, effect_id);
		SDL_HapticClose(haptic);

		effect_id = -1;
		haptic = nullptr;
	}

	if (gamepad != nullptr)
	{
		SDL_GameControllerClose(gamepad);
		gamepad = nullptr;
		controller_id = -1;
	}

	isConnected = false;
}

/// <summary>
/// Calls Poll and UpdateMotor automatically.
/// </summary>
void DreamPad::Update()
{
	Poll();
	UpdateMotor();
}

/// <summary>
/// Polls input for this instance.
/// </summary>
void DreamPad::Poll()
{
	if (!isConnected)
		return;

	SDL_GameControllerUpdate();

	short axis[2];

	axis[0] = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTX);
	axis[1] = -SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_LEFTY);

	xinput::ConvertAxes(settings.scaleFactor, &pad.LeftStickX, axis, settings.deadzoneL, settings.radialL);

	axis[0] = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_RIGHTX);
	axis[1] = -SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_RIGHTY);

	xinput::ConvertAxes(settings.scaleFactor, &pad.RightStickX, axis, settings.deadzoneR, settings.radialR);

	short lt = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_TRIGGERLEFT);
	short rt = SDL_GameControllerGetAxis(gamepad, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);

	pad.LTriggerPressure = (short)(255.0f * ((float)lt / (float)SHRT_MAX));
	pad.RTriggerPressure = (short)(255.0f * ((float)rt / (float)SHRT_MAX));;

	int buttons = 0;

	buttons |= DigitalTrigger(pad.LTriggerPressure, settings.triggerThreshold, Buttons_L);
	buttons |= DigitalTrigger(pad.RTriggerPressure, settings.triggerThreshold, Buttons_R);

	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_A))
		buttons |= Buttons_A;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_B))
		buttons |= Buttons_B;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_X))
		buttons |= Buttons_X;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_Y))
		buttons |= Buttons_Y;

	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_START))
		buttons |= Buttons_Start;

	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_LEFTSHOULDER))
		buttons |= Buttons_C;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_BACK))
		buttons |= Buttons_D;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER))
		buttons |= Buttons_Z;

	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_UP))
		buttons |= Buttons_Up;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_DOWN))
		buttons |= Buttons_Down;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
		buttons |= Buttons_Left;
	if (SDL_GameControllerGetButton(gamepad, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
		buttons |= Buttons_Right;

	pad.HeldButtons		= buttons;
	pad.NotHeldButtons	= ~buttons;
	pad.ReleasedButtons	= pad.Old & (buttons ^ pad.Old);
	pad.PressedButtons	= buttons & (buttons ^ pad.Old);
	pad.Old				= pad.HeldButtons;
}

void DreamPad::UpdateMotor()
{
	if (effect_id == -1 || haptic == nullptr || rumbleState == Motor::None)
		return;

	Motor turn_off = Motor::None;
	uint now = GetTickCount();

	if (now - rumbleTime_L >= 250)
		turn_off = (Motor)(turn_off | Motor::Large);

	if (now - rumbleTime_S >= 1000)
		turn_off = (Motor)(turn_off | Motor::Small);

	if (turn_off != Motor::None)
		SetActiveMotor(turn_off, 0);
}

void DreamPad::SetActiveMotor(Motor motor, short magnitude)
{
	if (effect_id == -1 || haptic == nullptr)
		return;

	const float f = settings.rumbleFactor;

	if (motor & Motor::Large)
	{
		effect.leftright.large_magnitude = (short)min(SHRT_MAX, (int)(magnitude * f));
		rumbleTime_L = GetTickCount();
		rumbleState = (Motor)((magnitude > 0) ? rumbleState | motor : rumbleState & ~Motor::Large);
	}

	if (motor & Motor::Small)
	{
		effect.leftright.small_magnitude = (short)min(SHRT_MAX, (int)(magnitude * (2 + f)));
		rumbleTime_S = GetTickCount();
		rumbleState = (Motor)((magnitude > 0) ? rumbleState | motor : rumbleState & ~Motor::Small);
	}

	SDL_HapticUpdateEffect(haptic, effect_id, &effect);
	SDL_HapticRunEffect(haptic, effect_id, 1);
}

Motor DreamPad::GetActiveMotor() const
{
	return rumbleState;
}

void DreamPad::Copy(ControllerData& dest) const
{
	dest = pad;
}

inline int DreamPad::DigitalTrigger(ushort trigger, ushort threshold, int button)
{
	return (trigger > threshold) ? button : 0;
}

DreamPad::Settings::Settings()
{
	deadzoneL = XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE;
	deadzoneR = XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE;
	triggerThreshold = XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
	radialL = true;
	radialR = false;
	rumbleFactor = 1.0f;
	scaleFactor = 1.5f;
}
void DreamPad::Settings::apply(short deadzoneL, short deadzoneR, bool radialL, bool radialR, uint8 triggerThreshold, float rumbleFactor, float scaleFactor)
{
	this->deadzoneL = clamp(deadzoneL, (short)0, (short)SHRT_MAX);
	this->deadzoneR = clamp(deadzoneR, (short)0, (short)SHRT_MAX);
	this->radialL = radialL;
	this->radialR = radialR;
	this->triggerThreshold = min((uint8)UCHAR_MAX, triggerThreshold);
	this->rumbleFactor = rumbleFactor;
	this->scaleFactor = max(1.0f, scaleFactor);
}
<|endoftext|>


<commit_before>// ------------------------------------------------------------------------
// ecasound.cpp: Console mode user interface to ecasound.
// Copyright (C) 2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
// ------------------------------------------------------------------------

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <iostream>
#include <string>

#include <unistd.h>    /* POSIX: sleep() */

#include <kvu_dbc.h>
#include <kvu_com_line.h>

#include <eca-control.h>
#include <eca-error.h>
#include <eca-logger.h>
#include <eca-session.h>
#include <eca-version.h>

#include "eca-comhelp.h"
#include "eca-console.h"
#include "eca-curses.h"
#include "eca-neteci-server.h"
#include "eca-plaintext.h"
#include "textdebug.h"
#include "ecasound.h"

/**
 * Static/private function definitions
 */

static void ecasound_create_eca_objects(struct ecasound_state* state, COMMAND_LINE& cline);
static void ecasound_launch_daemon(struct ecasound_state* state);
static void ecasound_main_loop(struct ecasound_state* state);
void ecasound_parse_command_line(struct ecasound_state* state,
				 const COMMAND_LINE& clinein,
				 COMMAND_LINE* clineout);
static void ecasound_print_usage(void);
static void ecasound_print_version_banner(void);
static void ecasound_setup_signals(struct ecasound_state* state);

extern "C" {
  static void ecasound_atexit_cleanup(void);
  static void* ecasound_watchdog_thread(void* arg);
}

static struct ecasound_state ecasound_state_global =
  { 0,        /* ECA_CONSOLE* */
    0,        /* ECA_CONTROL */
    0,        /* ECA_LOGGER_INTERFACE */
    0,        /* ECA_NETECI_SERVER */
    0,        /* ECA_SESSION */
    0,        /* pthread_t */
    0,        /* sig_wait_t */
    0,        /* return value */
    false,    /* daemon mode */
    false,    /* cerr-output-only mode */
    false,    /* interactive mode */
    false     /* quiet mode */
  };

/**
 * Namespace imports
 */
using namespace std;

/**
 * Function definitions
 */
int main(int argc, char *argv[])
{
  struct ecasound_state* state = &ecasound_state_global;

  /* 1. setup signals and watchdog thread */
  ecasound_setup_signals(state);

  /* 2. parse command-line args */
  COMMAND_LINE* cline = new COMMAND_LINE(argc, argv);
  COMMAND_LINE* clineout = new COMMAND_LINE();
  ecasound_parse_command_line(state, *cline, clineout);
  delete cline; cline = 0;

  /* 3. create console interface */
  if (state->retval == 0) {

#if defined(ECA_USE_NCURSES) || defined (ECA_USE_TERMCAP)
    if (state->quiet_mode != true &&
	state->cerr_output_only_mode != true) {
      state->console = new ECA_CURSES();
      state->logger = new TEXTDEBUG();
      ECA_LOGGER::attach_logger(state->logger);
    }
    else
#endif
      {
	ostream* ostr = (state->cerr_output_only_mode == true) ? &cerr : &cout;
	state->console = new ECA_PLAIN_TEXT(ostr);
      }

    /* 4. print banner */
    state->console->print_banner();

    /* 5. set default debug levels */
    ECA_LOGGER::instance().set_log_level(ECA_LOGGER::errors, true);
    ECA_LOGGER::instance().set_log_level(ECA_LOGGER::info, true);
    ECA_LOGGER::instance().set_log_level(ECA_LOGGER::subsystems, true);

    /* 6. create eca objects */
    ecasound_create_eca_objects(state, *clineout);
    delete clineout; clineout = 0;

    /* 7. start ecasound daemon */
    if (state->retval == 0) {
      if (state->daemon_mode == true) {
	ecasound_launch_daemon(state);
      }
    }

    /* 8. start processing */
    if (state->retval == 0) {
      ecasound_main_loop(state);
    }
  }

  // cerr << endl << "ecasound: main() exiting..." << endl;

  return(state->retval);
}

/**
 * Cleanup routine that is run after either exit()
 * is called or ecasound returns from its main().
 */
void ecasound_atexit_cleanup(void)
{
  struct ecasound_state* state = &ecasound_state_global;

  // cerr << endl << "ecasound: atexit cleanup" << endl;

  if (state != 0 &&
      state->control != 0) {

    if (state->control->is_running() == true) {
      state->control->stop_on_condition();
    }

    if (state->control->is_connected() == true) {
      state->control->disconnect_chainsetup();
    }
  }

  if (state != 0) {
    if (state->eciserver != 0) { delete state->eciserver; state->eciserver = 0; }
    if (state->control != 0) { delete state->control; state->control = 0; }
    if (state->session != 0) { delete state->session; state->session = 0; }
    if (state->console != 0) { delete state->console; state->console = 0; }
    if (state->daemon_thread != 0) { delete state->daemon_thread; state->daemon_thread = 0; }
    if (state->lock != 0) { delete state->lock; state->lock = 0; }
  }

  // cerr << "ecasound: atexit cleanup done." << endl << endl;
}

/**
 * Enters the main processing loop.
 */
void ecasound_create_eca_objects(struct ecasound_state* state,
				 COMMAND_LINE& cline)
{
  DBC_REQUIRE(state != 0);
  DBC_REQUIRE(state->console != 0);

  try {
    state->session = new ECA_SESSION(cline);
    state->control = new ECA_CONTROL(state->session);

    DBC_ENSURE(state->session != 0);
    DBC_ENSURE(state->control != 0);
  }
  catch(ECA_ERROR& e) {
    state->console->print("---\necasound: ERROR: [" + e.error_section() + "] : \"" + e.error_message() + "\"\n");
    state->retval = -1;
  }
}

/**
 * Launches a background daemon that allows NetECI
 * clients to connect to the current ecasound
 * session.
 */
void ecasound_launch_daemon(struct ecasound_state* state)
{
  DBC_REQUIRE(state != 0);
  // DBC_REQUIRE(state->console != 0);

  // state->console->print("ecasound: starting the NetECI server.");

  state->daemon_thread = new pthread_t;
  state->lock = new pthread_mutex_t;
  pthread_mutex_init(state->lock, NULL);
  state->eciserver = new ECA_NETECI_SERVER(state);

  int res = pthread_create(state->daemon_thread,
			   NULL,
			   ECA_NETECI_SERVER::launch_server_thread,
			   reinterpret_cast<void*>(state->eciserver));
  if (res != 0) {
    cerr << "ecasound: Warning! Unable to create watchdog thread." << endl;
    delete state->daemon_thread;  state->daemon_thread = 0;
    delete state->lock;  state->lock = 0;
    delete state->eciserver; state->eciserver = 0;
  }

  // state->console->print("ecasound: NetECI server started");
}

/**
 * The main processing loop.
 */
void ecasound_main_loop(struct ecasound_state* state)
{
  DBC_REQUIRE(state != 0);
  DBC_REQUIRE(state->console != 0);

  ECA_CONTROL* ctrl = state->control;

  if (state->interactive_mode == true) {
    while(state->exit_request == 0) {
      state->console->read_command("ecasound ('h' for help)> ");
      const string& cmd = state->console->last_command();
      if (cmd.size() > 0 && state->exit_request == 0) {

	if (state->daemon_mode == true) {
	  int res = pthread_mutex_lock(state->lock);
	  DBC_CHECK(res == 0);
	}

	ctrl->command(cmd);
	ctrl->print_last_error();
	ctrl->print_last_value();

	if (state->daemon_mode == true) {
	  int res = pthread_mutex_unlock(state->lock);
	  DBC_CHECK(res == 0);
	}

	if (cmd == "quit" || cmd == "q") {
	  state->console->print("---\necasound: Exiting...");
	  break;
	}
      }
    }
  }
  else {
    if (state->daemon_mode == true) {
      int res = pthread_mutex_lock(state->lock);
      DBC_CHECK(res == 0);
    }

    ctrl->connect_chainsetup();
    if (ctrl->is_connected() == true) {
      ctrl->run();
    }
    else {
      ctrl->print_last_error();
    }

    if (state->daemon_mode == true) {
      int res = pthread_mutex_unlock(state->lock);
      DBC_CHECK(res == 0);
    }
  }
  // cerr << endl << "ecasound: mainloop exiting..." << endl;
}

/**
 * Parses the command lines options in 'cline'.
 */
void ecasound_parse_command_line(struct ecasound_state* state,
				 const COMMAND_LINE& cline,
				 COMMAND_LINE* clineout)
{
  if (cline.size() < 2) {
    ecasound_print_usage();
    state->retval = -1;
  }
  else {
   cline.begin();
    while(cline.end() != true) {
      if (cline.current() == "-o:stdout" ||
	  cline.current() == "stdout" ||
	  cline.current() == "-d:0" ||
	  cline.current() == "-q") {

	state->quiet_mode = true;
	/* pass option to libecasound */
	clineout->push_back(cline.current());
      }

      else if (cline.current() == "-c") {
	state->interactive_mode = true;
      }

      else if (cline.current() == "-C") {
	state->interactive_mode = true;
      }

      else if (cline.current() == "-D") {
	state->cerr_output_only_mode = true;
      }

      else if (cline.current() == "--daemon") {
	state->daemon_mode = true;
      }

      else if (cline.current() == "-h" ||
	       cline.current() == "--help") {
	ecasound_print_usage();
	state->retval = -1;
	break;
      }

      else if (cline.current() == "--version") {
	ecasound_print_version_banner();
	state->retval = -1;
	break;
      }

      else {
	/* pass rest of the options to libecasound */
	clineout->push_back(cline.current());
      }

      cline.next();
    }
  }
}

void ecasound_print_usage(void)
{
  cout << ecasound_parameter_help();
}

void ecasound_print_version_banner(void)
{
  cout << "ecasound v" << ecasound_library_version << endl;
  cout << "Copyright (C) 1997-2002 Kai Vehmanen" << endl;
  cout << "Ecasound comes with ABSOLUTELY NO WARRANTY." << endl;
  cout << "You may redistribute copies of ecasound under the terms of the GNU" << endl;
  cout << "General Public License. For more information about these matters, see" << endl;
  cout << "the file named COPYING." << endl;
}

/**
 * Sets up a signal mask with sigaction() that blocks
 * all common signals, and then launces an watchdog
 * thread that waits on the blocked signals using
 * sigwait().
 */
void ecasound_setup_signals(struct ecasound_state* state)
{
  pthread_t watchdog;

  /* man pthread_sigmask:
   *  "...signal actions and signal handlers, as set with
   *   sigaction(2), are shared between all threads"
   */

  struct sigaction blockaction;
  blockaction.sa_handler = SIG_IGN;
  sigemptyset(&blockaction.sa_mask);
  blockaction.sa_flags = 0;

  /* ignore the following signals */
  sigaction(SIGTERM, &blockaction, 0);
  sigaction(SIGINT, &blockaction, 0);
  sigaction(SIGHUP, &blockaction, 0);
  sigaction(SIGPIPE, &blockaction, 0);

  int res = pthread_create(&watchdog,
			   NULL,
			   ecasound_watchdog_thread,
			   reinterpret_cast<void*>(state));
  if (res != 0) {
    cerr << "ecasound: Warning! Unable to create watchdog thread." << endl;
  }
}

void* ecasound_watchdog_thread(void* arg)
{
  sigset_t signalset;
  struct ecasound_state* state = reinterpret_cast<struct ecasound_state*>(arg);
  int signalno;

  /* register cleanup routine */
  atexit(&ecasound_atexit_cleanup);

  // cerr << "Watchdog-thread created, pid=" << getpid() << "." << endl;

  sigemptyset(&signalset);

  /* handle the following signals explicitly */
  sigaddset(&signalset, SIGTERM);
  sigaddset(&signalset, SIGINT);
  sigaddset(&signalset, SIGHUP);
  sigaddset(&signalset, SIGPIPE);

  /* block until a signal received */
  sigwait(&signalset, &signalno);

  state->exit_request = 1;

  // cerr << endl << "ecasound: watchdog-thread received signal " << signalno << ". Cleaning up..." << endl;

  /* give time for the console interface thread to die gracefully */
  sleep(1);

  // cerr << endl << "ecasound: watchdog-thread exiting..." << endl;

  exit(state->retval);

  /* to keep the compilers happy; never actually executed */
  return(0);
}
<commit_msg>Changed the default debug mask.<commit_after>// ------------------------------------------------------------------------
// ecasound.cpp: Console mode user interface to ecasound.
// Copyright (C) 2002 Kai Vehmanen (kai.vehmanen@wakkanet.fi)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
// ------------------------------------------------------------------------

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <iostream>
#include <string>

#include <unistd.h>    /* POSIX: sleep() */

#include <kvu_dbc.h>
#include <kvu_com_line.h>

#include <eca-control.h>
#include <eca-error.h>
#include <eca-logger.h>
#include <eca-session.h>
#include <eca-version.h>

#include "eca-comhelp.h"
#include "eca-console.h"
#include "eca-curses.h"
#include "eca-neteci-server.h"
#include "eca-plaintext.h"
#include "textdebug.h"
#include "ecasound.h"

/**
 * Static/private function definitions
 */

static void ecasound_create_eca_objects(struct ecasound_state* state, COMMAND_LINE& cline);
static void ecasound_launch_daemon(struct ecasound_state* state);
static void ecasound_main_loop(struct ecasound_state* state);
void ecasound_parse_command_line(struct ecasound_state* state,
				 const COMMAND_LINE& clinein,
				 COMMAND_LINE* clineout);
static void ecasound_print_usage(void);
static void ecasound_print_version_banner(void);
static void ecasound_setup_signals(struct ecasound_state* state);

extern "C" {
  static void ecasound_atexit_cleanup(void);
  static void* ecasound_watchdog_thread(void* arg);
}

static struct ecasound_state ecasound_state_global =
  { 0,        /* ECA_CONSOLE* */
    0,        /* ECA_CONTROL */
    0,        /* ECA_LOGGER_INTERFACE */
    0,        /* ECA_NETECI_SERVER */
    0,        /* ECA_SESSION */
    0,        /* pthread_t */
    0,        /* sig_wait_t */
    0,        /* return value */
    false,    /* daemon mode */
    false,    /* cerr-output-only mode */
    false,    /* interactive mode */
    false     /* quiet mode */
  };

/**
 * Namespace imports
 */
using namespace std;

/**
 * Function definitions
 */
int main(int argc, char *argv[])
{
  struct ecasound_state* state = &ecasound_state_global;

  /* 1. setup signals and watchdog thread */
  ecasound_setup_signals(state);

  /* 2. parse command-line args */
  COMMAND_LINE* cline = new COMMAND_LINE(argc, argv);
  COMMAND_LINE* clineout = new COMMAND_LINE();
  ecasound_parse_command_line(state, *cline, clineout);
  delete cline; cline = 0;

  /* 3. create console interface */
  if (state->retval == 0) {

#if defined(ECA_USE_NCURSES) || defined (ECA_USE_TERMCAP)
    if (state->quiet_mode != true &&
	state->cerr_output_only_mode != true) {
      state->console = new ECA_CURSES();
      state->logger = new TEXTDEBUG();
      ECA_LOGGER::attach_logger(state->logger);
    }
    else
#endif
      {
	ostream* ostr = (state->cerr_output_only_mode == true) ? &cerr : &cout;
	state->console = new ECA_PLAIN_TEXT(ostr);
      }

    /* 4. print banner */
    state->console->print_banner();

    /* 5. set default debug levels */
    ECA_LOGGER::instance().set_log_level(ECA_LOGGER::errors, true);
    ECA_LOGGER::instance().set_log_level(ECA_LOGGER::info, true);
    ECA_LOGGER::instance().set_log_level(ECA_LOGGER::subsystems, true);
    ECA_LOGGER::instance().set_log_level(ECA_LOGGER::eiam_return_values, true);

    /* 6. create eca objects */
    ecasound_create_eca_objects(state, *clineout);
    delete clineout; clineout = 0;

    /* 7. start ecasound daemon */
    if (state->retval == 0) {
      if (state->daemon_mode == true) {
	ecasound_launch_daemon(state);
      }
    }

    /* 8. start processing */
    if (state->retval == 0) {
      ecasound_main_loop(state);
    }
  }

  // cerr << endl << "ecasound: main() exiting..." << endl;

  return(state->retval);
}

/**
 * Cleanup routine that is run after either exit()
 * is called or ecasound returns from its main().
 */
void ecasound_atexit_cleanup(void)
{
  struct ecasound_state* state = &ecasound_state_global;

  // cerr << endl << "ecasound: atexit cleanup" << endl;

  if (state != 0 &&
      state->control != 0) {

    if (state->control->is_running() == true) {
      state->control->stop_on_condition();
    }

    if (state->control->is_connected() == true) {
      state->control->disconnect_chainsetup();
    }
  }

  if (state != 0) {
    if (state->eciserver != 0) { delete state->eciserver; state->eciserver = 0; }
    if (state->control != 0) { delete state->control; state->control = 0; }
    if (state->session != 0) { delete state->session; state->session = 0; }
    if (state->console != 0) { delete state->console; state->console = 0; }
    if (state->daemon_thread != 0) { delete state->daemon_thread; state->daemon_thread = 0; }
    if (state->lock != 0) { delete state->lock; state->lock = 0; }
  }

  // cerr << "ecasound: atexit cleanup done." << endl << endl;
}

/**
 * Enters the main processing loop.
 */
void ecasound_create_eca_objects(struct ecasound_state* state,
				 COMMAND_LINE& cline)
{
  DBC_REQUIRE(state != 0);
  DBC_REQUIRE(state->console != 0);

  try {
    state->session = new ECA_SESSION(cline);
    state->control = new ECA_CONTROL(state->session);

    DBC_ENSURE(state->session != 0);
    DBC_ENSURE(state->control != 0);
  }
  catch(ECA_ERROR& e) {
    state->console->print("---\necasound: ERROR: [" + e.error_section() + "] : \"" + e.error_message() + "\"\n");
    state->retval = -1;
  }
}

/**
 * Launches a background daemon that allows NetECI
 * clients to connect to the current ecasound
 * session.
 */
void ecasound_launch_daemon(struct ecasound_state* state)
{
  DBC_REQUIRE(state != 0);
  // DBC_REQUIRE(state->console != 0);

  // state->console->print("ecasound: starting the NetECI server.");

  state->daemon_thread = new pthread_t;
  state->lock = new pthread_mutex_t;
  pthread_mutex_init(state->lock, NULL);
  state->eciserver = new ECA_NETECI_SERVER(state);

  int res = pthread_create(state->daemon_thread,
			   NULL,
			   ECA_NETECI_SERVER::launch_server_thread,
			   reinterpret_cast<void*>(state->eciserver));
  if (res != 0) {
    cerr << "ecasound: Warning! Unable to create watchdog thread." << endl;
    delete state->daemon_thread;  state->daemon_thread = 0;
    delete state->lock;  state->lock = 0;
    delete state->eciserver; state->eciserver = 0;
  }

  // state->console->print("ecasound: NetECI server started");
}

/**
 * The main processing loop.
 */
void ecasound_main_loop(struct ecasound_state* state)
{
  DBC_REQUIRE(state != 0);
  DBC_REQUIRE(state->console != 0);

  ECA_CONTROL* ctrl = state->control;

  if (state->interactive_mode == true) {
    while(state->exit_request == 0) {
      state->console->read_command("ecasound ('h' for help)> ");
      const string& cmd = state->console->last_command();
      if (cmd.size() > 0 && state->exit_request == 0) {

	if (state->daemon_mode == true) {
	  int res = pthread_mutex_lock(state->lock);
	  DBC_CHECK(res == 0);
	}

	ctrl->command(cmd);
	ctrl->print_last_error();
	ctrl->print_last_value();

	if (state->daemon_mode == true) {
	  int res = pthread_mutex_unlock(state->lock);
	  DBC_CHECK(res == 0);
	}

	if (cmd == "quit" || cmd == "q") {
	  state->console->print("---\necasound: Exiting...");
	  break;
	}
      }
    }
  }
  else {
    if (state->daemon_mode == true) {
      int res = pthread_mutex_lock(state->lock);
      DBC_CHECK(res == 0);
    }

    ctrl->connect_chainsetup();
    if (ctrl->is_connected() == true) {
      ctrl->run();
    }
    else {
      ctrl->print_last_error();
    }

    if (state->daemon_mode == true) {
      int res = pthread_mutex_unlock(state->lock);
      DBC_CHECK(res == 0);
    }
  }
  // cerr << endl << "ecasound: mainloop exiting..." << endl;
}

/**
 * Parses the command lines options in 'cline'.
 */
void ecasound_parse_command_line(struct ecasound_state* state,
				 const COMMAND_LINE& cline,
				 COMMAND_LINE* clineout)
{
  if (cline.size() < 2) {
    ecasound_print_usage();
    state->retval = -1;
  }
  else {
   cline.begin();
    while(cline.end() != true) {
      if (cline.current() == "-o:stdout" ||
	  cline.current() == "stdout" ||
	  cline.current() == "-d:0" ||
	  cline.current() == "-q") {

	state->quiet_mode = true;
	/* pass option to libecasound */
	clineout->push_back(cline.current());
      }

      else if (cline.current() == "-c") {
	state->interactive_mode = true;
      }

      else if (cline.current() == "-C") {
	state->interactive_mode = true;
      }

      else if (cline.current() == "-D") {
	state->cerr_output_only_mode = true;
      }

      else if (cline.current() == "--daemon") {
	state->daemon_mode = true;
      }

      else if (cline.current() == "-h" ||
	       cline.current() == "--help") {
	ecasound_print_usage();
	state->retval = -1;
	break;
      }

      else if (cline.current() == "--version") {
	ecasound_print_version_banner();
	state->retval = -1;
	break;
      }

      else {
	/* pass rest of the options to libecasound */
	clineout->push_back(cline.current());
      }

      cline.next();
    }
  }
}

void ecasound_print_usage(void)
{
  cout << ecasound_parameter_help();
}

void ecasound_print_version_banner(void)
{
  cout << "ecasound v" << ecasound_library_version << endl;
  cout << "Copyright (C) 1997-2002 Kai Vehmanen" << endl;
  cout << "Ecasound comes with ABSOLUTELY NO WARRANTY." << endl;
  cout << "You may redistribute copies of ecasound under the terms of the GNU" << endl;
  cout << "General Public License. For more information about these matters, see" << endl;
  cout << "the file named COPYING." << endl;
}

/**
 * Sets up a signal mask with sigaction() that blocks
 * all common signals, and then launces an watchdog
 * thread that waits on the blocked signals using
 * sigwait().
 */
void ecasound_setup_signals(struct ecasound_state* state)
{
  pthread_t watchdog;

  /* man pthread_sigmask:
   *  "...signal actions and signal handlers, as set with
   *   sigaction(2), are shared between all threads"
   */

  struct sigaction blockaction;
  blockaction.sa_handler = SIG_IGN;
  sigemptyset(&blockaction.sa_mask);
  blockaction.sa_flags = 0;

  /* ignore the following signals */
  sigaction(SIGTERM, &blockaction, 0);
  sigaction(SIGINT, &blockaction, 0);
  sigaction(SIGHUP, &blockaction, 0);
  sigaction(SIGPIPE, &blockaction, 0);

  int res = pthread_create(&watchdog,
			   NULL,
			   ecasound_watchdog_thread,
			   reinterpret_cast<void*>(state));
  if (res != 0) {
    cerr << "ecasound: Warning! Unable to create watchdog thread." << endl;
  }
}

void* ecasound_watchdog_thread(void* arg)
{
  sigset_t signalset;
  struct ecasound_state* state = reinterpret_cast<struct ecasound_state*>(arg);
  int signalno;

  /* register cleanup routine */
  atexit(&ecasound_atexit_cleanup);

  // cerr << "Watchdog-thread created, pid=" << getpid() << "." << endl;

  sigemptyset(&signalset);

  /* handle the following signals explicitly */
  sigaddset(&signalset, SIGTERM);
  sigaddset(&signalset, SIGINT);
  sigaddset(&signalset, SIGHUP);
  sigaddset(&signalset, SIGPIPE);

  /* block until a signal received */
  sigwait(&signalset, &signalno);

  state->exit_request = 1;

  // cerr << endl << "ecasound: watchdog-thread received signal " << signalno << ". Cleaning up..." << endl;

  /* give time for the console interface thread to die gracefully */
  sleep(1);

  // cerr << endl << "ecasound: watchdog-thread exiting..." << endl;

  exit(state->retval);

  /* to keep the compilers happy; never actually executed */
  return(0);
}
<|endoftext|>


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

#ifndef SENSE_ENTITY_ENTITY_HPP
#define SENSE_ENTITY_ENTITY_HPP

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>
#include <string>
#include <unordered_map>
#include <vector>

class Component;
class CoordinateComponent;
class DrawableComponent;
class PhysicalComponent;

struct Entity
{
  std::string m_type;
  std::string m_name;
  boost::uuids::uuid m_uuid;
  std::vector<Component*> m_components;

  // Components that need to have "quick access"
  // It's a hack, but there's really nothing to do for it.
  CoordinateComponent* m_coord;
  DrawableComponent* m_draw;
  PhysicalComponent* m_phys;
};

// an EntityFactory subclass creates a specific entity by
// building and attaching the needed set of components.

// A factory subclass does not need to set m_type. This is handled
// by the EntityManager. The same goes for generating a new UUID
// for the Entity instance.

// Entity factories can have local data (hence the virtual destructor)
// However, that local data should not effect the creation of an entity
// except in trivial ways (for example, randomly selecting between multiple
// possible mesh designs)
class EntityFactory
{
public:
  virtual ~EntityFactory();

private:
  virtual Entity* create() = 0;
  // TODO: a creation method that can read serialized entity data

  friend class EntityManager;
};

class EntityManager
{
public:
  Entity* createEntity(std::string);
  void destroyEntity(Entity*);

  void addFactory(std::string, EntityFactory*);
private:
  std::unordered_map<std::string, EntityFactory*> m_factories;
  boost::uuids::random_generator m_uuidgen;
};

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

#ifndef SENSE_ENTITY_ENTITY_HPP
#define SENSE_ENTITY_ENTITY_HPP

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>
#include <string>
#include <unordered_map>
#include <vector>

class Component;
class CoordinateComponent;
class DrawableComponent;
class PhysicalComponent;

struct Entity
{
  std::string m_type;
  std::string m_name;
  boost::uuids::uuid m_uuid;
  std::vector<Component*> m_components;

  // Components that need to have "quick access"
  // It's a hack, but there's really nothing to do for it.
  CoordinateComponent* m_coord;
  DrawableComponent* m_draw;
  PhysicalComponent* m_phys;
};

// an EntityFactory subclass creates a specific entity by
// building and attaching the needed set of components.

// A factory subclass does not need to set m_type. This is handled
// by the EntityManager. The same goes for generating a new UUID
// for the Entity instance.

// Entity factories can have local data (hence the virtual destructor)
// However, that local data should not effect the creation of an entity
// except in trivial ways (for example, randomly selecting between multiple
// possible mesh designs)
class EntityFactory
{
public:
  virtual ~EntityFactory();

private:
  virtual Entity* create() = 0;
  // TODO: a creation method that can read serialized entity data

  friend class EntityManager;
};

class EntityManager
{
public:
  Entity* createEntity(std::string);
  void destroyEntity(Entity*);

  void addFactory(std::string, EntityFactory*);
private:
  std::unordered_map<std::string, EntityFactory*> m_factories;
  boost::uuids::random_generator m_uuidgen;
};

#endif // SENSE_ENTITY_ENTITY_HPP
<|endoftext|>


<commit_before>#include <unistd.h>
#include "fileStream.h"
#include "async.h"

#include "../exceptions.h"

namespace simpleServer {

BinaryView FileStream::implRead(bool nonblock) {

	MutableBinaryView b(inputBuffer, inputBufferSize);
	return implRead(b,nonblock);

}

BinaryView FileStream::implWrite(BinaryView buffer, bool nonblock) {
	do {
		int r = ::write(fd, buffer.data, buffer.length);
		if (r < 0) {
			int e = errno;
			if (e == EPIPE) {
				return eofConst;
			}
			throw SystemException(e,__FUNCTION__);
		} else if (r == 0) {
			return eofConst;
		} else {
			return buffer.substr(r);
		}
	} while (true);
}

bool FileStream::implWaitForRead(int timeoutms) {
	return true;
}

bool FileStream::implWaitForWrite(int timeoutms) {
	return true;
}

void FileStream::implCloseInput() {

}

void FileStream::implCloseOutput() {

}

FileStream::FileStream(int fd)
	:fd(fd)
{

}

BinaryView FileStream::implRead(MutableBinaryView buffer, bool nonblock) {
	do {
		int r = ::read(fd,buffer.data, buffer.length);
		if (r < 0) {
			int e = errno;
			throw SystemException(e,__FUNCTION__);
		} else if (r == 0) {
			return eofConst;
		} else {
			return BinaryView(buffer.data, r);
		}
	} while (true);
}

bool FileStream::implWrite(WrBuffer& curBuffer, bool nonblock) {
 if (curBuffer.wrpos == 0) {
	 curBuffer = WrBuffer(outputBuffer,outputBufferSize,0);
 } else {
	 BinaryView v = curBuffer.getView();
	 BinaryView w = implWrite(v, nonblock);
	 if (isEof(w)) return false;
	 if (w.empty()) {
		 curBuffer = WrBuffer(outputBuffer,outputBufferSize,0);
	 } else if (curBuffer.remain()>16) {
		 curBuffer = WrBuffer(curBuffer.ptr+w.length, 0, curBuffer.size-w.length);
	 } else if (w.length != v.length){
		 copydata(curBuffer.ptr, w.data, w.length);
		 curBuffer.wrpos = w.length;
	 }
 }
 return true;
}

void FileStream::implReadAsync(const MutableBinaryView& buffer, const Callback& cb) {
	cb(asyncOK, implRead(buffer,false));
}

void FileStream::implWriteAsync(const BinaryView& data, const Callback& cb) {
	cb(asyncOK, implWrite(data,false));

}

bool FileStream::implFlush() {
	::syncfs(fd);
	return true;
}

FileStream::~FileStream() noexcept {
	if (fd) {
		try {
			flush(writeWholeBuffer);
		} catch (...) {
			//do not try flush on error socket
		}
		close(fd);
	}

}

int FileStream::setIOTimeout(int) {
	return 0;
}

void FileStream::implReadAsync(const Callback& cb) {
	MutableBinaryView b(inputBuffer, inputBufferSize);
	implReadAsync(b,cb);
}
}

<commit_msg>fix warnings<commit_after>#include <unistd.h>
#include "fileStream.h"
#include "async.h"

#include "../exceptions.h"

namespace simpleServer {

BinaryView FileStream::implRead(bool nonblock) {

	MutableBinaryView b(inputBuffer, inputBufferSize);
	return implRead(b,nonblock);

}

BinaryView FileStream::implWrite(BinaryView buffer, bool) {
	do {
		int r = ::write(fd, buffer.data, buffer.length);
		if (r < 0) {
			int e = errno;
			if (e == EPIPE) {
				return eofConst;
			}
			throw SystemException(e,__FUNCTION__);
		} else if (r == 0) {
			return eofConst;
		} else {
			return buffer.substr(r);
		}
	} while (true);
}

bool FileStream::implWaitForRead(int ) {
	return true;
}

bool FileStream::implWaitForWrite(int ) {
	return true;
}

void FileStream::implCloseInput() {

}

void FileStream::implCloseOutput() {

}

FileStream::FileStream(int fd)
	:fd(fd)
{

}

BinaryView FileStream::implRead(MutableBinaryView buffer, bool ) {
	do {
		int r = ::read(fd,buffer.data, buffer.length);
		if (r < 0) {
			int e = errno;
			throw SystemException(e,__FUNCTION__);
		} else if (r == 0) {
			return eofConst;
		} else {
			return BinaryView(buffer.data, r);
		}
	} while (true);
}

bool FileStream::implWrite(WrBuffer& curBuffer, bool nonblock ) {
 if (curBuffer.wrpos == 0) {
	 curBuffer = WrBuffer(outputBuffer,outputBufferSize,0);
 } else {
	 BinaryView v = curBuffer.getView();
	 BinaryView w = implWrite(v, nonblock);
	 if (isEof(w)) return false;
	 if (w.empty()) {
		 curBuffer = WrBuffer(outputBuffer,outputBufferSize,0);
	 } else if (curBuffer.remain()>16) {
		 curBuffer = WrBuffer(curBuffer.ptr+w.length, 0, curBuffer.size-w.length);
	 } else if (w.length != v.length){
		 copydata(curBuffer.ptr, w.data, w.length);
		 curBuffer.wrpos = w.length;
	 }
 }
 return true;
}

void FileStream::implReadAsync(const MutableBinaryView& buffer, const Callback& cb) {
	cb(asyncOK, implRead(buffer,false));
}

void FileStream::implWriteAsync(const BinaryView& data, const Callback& cb) {
	cb(asyncOK, implWrite(data,false));

}

bool FileStream::implFlush() {
	::syncfs(fd);
	return true;
}

FileStream::~FileStream() noexcept {
	if (fd) {
		try {
			flush(writeWholeBuffer);
		} catch (...) {
			//do not try flush on error socket
		}
		close(fd);
	}

}

int FileStream::setIOTimeout(int) {
	return 0;
}

void FileStream::implReadAsync(const Callback& cb) {
	MutableBinaryView b(inputBuffer, inputBufferSize);
	implReadAsync(b,cb);
}
}

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2006 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// object that creates and contains a spawn position

/* interface header */
#include "SpawnPosition.h"

/* implementation headers */
#include "SpawnPolicyFactory.h"

/* no policy by default, constructor will set if unset */
SpawnPolicy *SpawnPosition::policy = (SpawnPolicy*)0;

SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges)
{
  /* if a spawn policy hasn't been set yet, just go with the default */
  if (!SpawnPosition::policy) {
    SpawnPosition::policy = SpawnPolicyFactory::DefaultPolicy();
  }

  SpawnPosition::policy->getPosition(pos, playerId, onGroundOnly, notNearEdges);
  SpawnPosition::policy->getAzimuth(azimuth);
}

SpawnPosition::~SpawnPosition()
{
}

void SpawnPosition::SetSpawnPolicy(SpawnPolicy *_policy)
{
  if (SpawnPosition::policy) {
    delete SpawnPosition::policy;
  }
  SpawnPosition::policy = _policy;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>might as well use SetSpawnPolicy()<commit_after>/* bzflag
 * Copyright (c) 1993 - 2006 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// object that creates and contains a spawn position

/* interface header */
#include "SpawnPosition.h"

/* implementation headers */
#include "SpawnPolicyFactory.h"

/* no policy by default, constructor will set if unset */
SpawnPolicy *SpawnPosition::policy = (SpawnPolicy*)0;

SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges)
{
  /* if a spawn policy hasn't been set yet, just go with the default */
  if (!SpawnPosition::policy) {
    SetSpawnPolicy(SpawnPolicyFactory::DefaultPolicy());
  }

  SpawnPosition::policy->getPosition(pos, playerId, onGroundOnly, notNearEdges);
  SpawnPosition::policy->getAzimuth(azimuth);
}

SpawnPosition::~SpawnPosition()
{
}

void SpawnPosition::SetSpawnPolicy(SpawnPolicy *_policy)
{
  if (SpawnPosition::policy) {
    delete SpawnPosition::policy;
  }
  SpawnPosition::policy = _policy;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


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

#include "cplusplus.h"
#include "info.h"

class Cxx : public CPlusPlus
{
    void visitInterfaceElement(const Interface* interface, Node* element)
    {
        if (element->isSequence(interface) || element->isNative(interface))
        {
            return;
        }
        optionalStage = 0;
        do
        {
            optionalCount = 0;
            element->accept(this);
            ++optionalStage;
        } while (optionalStage <= optionalCount);
    }

public:
    Cxx(const char* source, FILE* file, const char* stringTypeName = "char*", bool useExceptions = true, const char* indent = "es") :
        CPlusPlus(source, file, stringTypeName, useExceptions, indent)
    {
    }

    virtual void at(const ExceptDcl* node)
    {
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        write("struct %s {\n", node->getName().c_str());
            printChildren(node);
        writeln("};");
    }

    virtual void at(const Interface* node)
    {
        if (node->getAttr() & Interface::ImplementedOn)
        {
            return;
        }
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        if (node->isLeaf())
        {
            write("class %s;\n", node->getName().c_str());
        }
        else
        {
            write("class %s", node->getName().c_str());
            if (node->getExtends())
            {
                write(" : ");
                for (NodeList::iterator i = node->getExtends()->begin();
                     i != node->getExtends()->end();
                     ++i)
                {
                    if (i != node->getExtends()->begin())
                    {
                        write(", ");
                    }
                    write("public ");
                    (*i)->accept(this);
                }
            }
            write(" {\n");
            unindent();
            writeln("public:");
            indent();

            for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
            {
                visitInterfaceElement(node, *i);
            }

            // Expand mixins
            for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();
                 i != node->getMixins()->end();
                 ++i)
            {
                writeln("// %s", (*i)->getName().c_str());
                for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
                {
                    visitInterfaceElement(*i, *j);
                }
            }

            writeln("static const char* iid() {");
                writeln("static const char* const name = \"%s\";",
                        node->getQualifiedName().c_str());
                writeln("return name;");
            writeln("}");

            writeln("static const char* info() {");
                writetab();
                write("static const char* const info =");
                flush();
                indent();
                Info info(this, moduleName);
                const_cast<Interface*>(node)->accept(&info);
                info.flush();
                write(";\n");
                unindent();
                writeln("return info;");
            writeln("}");

            if (Interface* constructor = node->getConstructor())
            {
                // Process constructors.
                constructorMode = true;
                for (NodeList::iterator i = constructor->begin();
                     i != constructor->end();
                     ++i)
                {
                    (*i)->accept(this);
                }
                constructorMode = false;
                writeln("static Constructor* getConstructor() {");
                    writeln("return constructor;");
                writeln("}");
                writeln("static void setConstructor(Constructor* ctor) {");
                    writeln("constructor = ctor;");
                writeln("}");
                unindent();
                writeln("private:");
                indent();
                writeln("static Constructor* constructor;");
            }

            writeln("};");

            if (node->getConstructor())
            {
                // TODO: Control the use of GCC extensions.
                writeln("%s::Constructor* %s::constructor __attribute__((weak));",
                        node->getName().c_str(), node->getName().c_str());
            }
        }
    }

    virtual void at(const BinaryExpr* node)
    {
        node->getLeft()->accept(this);
        write(" %s ", node->getName().c_str());
        node->getRight()->accept(this);
    }

    virtual void at(const UnaryExpr* node)
    {
        write("%s", node->getName().c_str());
        NodeList::iterator elem = node->begin();
        (*elem)->accept(this);
    }

    virtual void at(const GroupingExpression* node)
    {
        write("(");
        NodeList::iterator elem = node->begin();
        (*elem)->accept(this);
        write(")");
    }

    virtual void at(const Literal* node)
    {
        write("%s", node->getName().c_str());
    }

    virtual void at(const Member* node)
    {
        writetab();
        if (node->isTypedef(node->getParent()))
        {
            write("typedef ");
        }
        node->getSpec()->accept(this);
        write(" %s;\n", node->getName().c_str());
    }

    virtual void at(const ArrayDcl* node)
    {
        assert(!node->isLeaf());
        writetab();
        if (node->isTypedef(node->getParent()))
        {
            write("typedef ");
        }
        node->getSpec()->accept(this);
        write(" %s", node->getName().c_str());
        for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
        {
            write("[");
            (*i)->accept(this);
            write("]");
        }
        if (node->isTypedef(node->getParent()))
        {
            write(";\n");
        }
    }

    virtual void at(const ConstDcl* node)
    {
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        write("static const ");
        node->getSpec()->accept(this);
        write(" %s = ", node->getName().c_str());
        node->getExp()->accept(this);
        write(";\n");
    }

    virtual void at(const Attribute* node)
    {
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }

        // getter
        CPlusPlus::getter(node);
        write(" = 0;\n");

        if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
        {
            // setter
            writetab();
            CPlusPlus::setter(node);
            write(" = 0;\n");
        }
    }

    virtual void at(const OpDcl* node)
    {
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }

        CPlusPlus::at(node);

        if (!constructorMode)
        {
            write(" = 0;\n");
        }
        else
        {
            write("{");
            writeln("");
                writeln("if (constructor)");
                indent();
                    writetab();
                    write("return constructor->createInstance(");
                    for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
                    {
                        if (i != node->begin())
                        {
                            write(", ");
                        }
                        write("%s", (*i)->getName().c_str());
                    }
                    write(");");
                    writeln("");
                unindent();
                writeln("else");
                indent();
                    writeln("return 0;");
                unindent();
            writeln("}");
        }
    }
};

class Import : public Visitor
{
    const char* source;
    FILE* file;
    bool printed;

public:
    Import(const char* source, FILE* file) :
        source(source),
        file(file),
        printed(false)
    {
    }

    virtual void at(const Node* node)
    {
        visitChildren(node);
    }

    virtual void at(const Include* node)
    {
        if (!node->isDefinedIn(source))
        {
            return;
        }
        if (node->isSystem())
        {
            fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str());
        }
        else
        {
            fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str());
        }
        printed = true;
    }

    bool hasPrinted() const
    {
        return printed;
    }
};

class Predeclaration : public Visitor, public Formatter
{
    const char* source;

public:
    Predeclaration(const char* source, FILE* file, const char* indent) :
        Formatter(file, indent),
        source(source)
    {
    }

    virtual void at(const Node* node)
    {
        if (!node->isDefinedIn(source))
        {
            return;
        }
        visitChildren(node);
    }

    virtual void at(const Module* node)
    {
        if (!node->hasPredeclarations())
        {
            return;
        }
        if (0 < node->getName().size())
        {
            write("namespace %s {\n", node->getName().c_str());
                visitChildren(node);
            writeln("}");
            writeln("");
        }
        else
        {
            visitChildren(node);
        }
    }

    virtual void at(const Interface* node)
    {
        if (!node->isDefinedIn(source) || !node->isLeaf())
        {
            return;
        }
        writeln("class %s;", node->getName().c_str());
    }
};

void printCxx(const char* source, const char* stringTypeName, bool useExceptions, const char* indent)
{
    const std::string filename = getOutputFilename(source, "h");
    printf("# %s\n", filename.c_str());

    FILE* file = fopen(filename.c_str(), "w");
    if (!file)
    {
        return;
    }

    std::string included = getIncludedName(filename);
    fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
    fprintf(file, "#ifndef %s\n", included.c_str());
    fprintf(file, "#define %s\n\n", included.c_str());

    Import import(source, file);
    getSpecification()->accept(&import);
    if (import.hasPrinted())
    {
        fprintf(file, "\n");
    }

    if (!Node::getFlatNamespace())
    {
        Predeclaration predeclaration(source, file, indent);
        getSpecification()->accept(&predeclaration);
    }

    Cxx cxx(source, file, stringTypeName, useExceptions, indent);
    getSpecification()->accept(&cxx);

    fprintf(file, "#endif  // %s\n", included.c_str());

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

#include "cplusplus.h"
#include "info.h"

class Cxx : public CPlusPlus
{
    void visitInterfaceElement(const Interface* interface, Node* element)
    {
        optionalStage = 0;
        do
        {
            optionalCount = 0;
            element->accept(this);
            ++optionalStage;
        } while (optionalStage <= optionalCount);
    }

public:
    Cxx(const char* source, FILE* file, const char* stringTypeName = "char*", bool useExceptions = true, const char* indent = "es") :
        CPlusPlus(source, file, stringTypeName, useExceptions, indent)
    {
    }

    virtual void at(const ExceptDcl* node)
    {
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        write("struct %s {\n", node->getName().c_str());
            printChildren(node);
        writeln("};");
    }

    virtual void at(const Interface* node)
    {
        if (node->getAttr() & Interface::ImplementedOn)
        {
            return;
        }
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        if (node->isLeaf())
        {
            write("class %s;\n", node->getName().c_str());
        }
        else
        {
            write("class %s", node->getName().c_str());
            if (node->getExtends())
            {
                write(" : ");
                for (NodeList::iterator i = node->getExtends()->begin();
                     i != node->getExtends()->end();
                     ++i)
                {
                    if (i != node->getExtends()->begin())
                    {
                        write(", ");
                    }
                    write("public ");
                    (*i)->accept(this);
                }
            }
            write(" {\n");
            unindent();
            writeln("public:");
            indent();

            for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
            {
                visitInterfaceElement(node, *i);
            }

            // Expand mixins
            for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();
                 i != node->getMixins()->end();
                 ++i)
            {
                writeln("// %s", (*i)->getName().c_str());
                for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)
                {
                    visitInterfaceElement(*i, *j);
                }
            }

            writeln("static const char* iid() {");
                writeln("static const char* const name = \"%s\";",
                        node->getQualifiedName().c_str());
                writeln("return name;");
            writeln("}");

            writeln("static const char* info() {");
                writetab();
                write("static const char* const info =");
                flush();
                indent();
                Info info(this, moduleName);
                const_cast<Interface*>(node)->accept(&info);
                info.flush();
                write(";\n");
                unindent();
                writeln("return info;");
            writeln("}");

            if (Interface* constructor = node->getConstructor())
            {
                // Process constructors.
                constructorMode = true;
                for (NodeList::iterator i = constructor->begin();
                     i != constructor->end();
                     ++i)
                {
                    (*i)->accept(this);
                }
                constructorMode = false;
                writeln("static Constructor* getConstructor() {");
                    writeln("return constructor;");
                writeln("}");
                writeln("static void setConstructor(Constructor* ctor) {");
                    writeln("constructor = ctor;");
                writeln("}");
                unindent();
                writeln("private:");
                indent();
                writeln("static Constructor* constructor;");
            }

            writeln("};");

            if (node->getConstructor())
            {
                // TODO: Control the use of GCC extensions.
                writeln("%s::Constructor* %s::constructor __attribute__((weak));",
                        node->getName().c_str(), node->getName().c_str());
            }
        }
    }

    virtual void at(const BinaryExpr* node)
    {
        node->getLeft()->accept(this);
        write(" %s ", node->getName().c_str());
        node->getRight()->accept(this);
    }

    virtual void at(const UnaryExpr* node)
    {
        write("%s", node->getName().c_str());
        NodeList::iterator elem = node->begin();
        (*elem)->accept(this);
    }

    virtual void at(const GroupingExpression* node)
    {
        write("(");
        NodeList::iterator elem = node->begin();
        (*elem)->accept(this);
        write(")");
    }

    virtual void at(const Literal* node)
    {
        write("%s", node->getName().c_str());
    }

    virtual void at(const Member* node)
    {
        writetab();
        if (node->isTypedef(node->getParent()))
        {
            write("typedef ");
        }
        node->getSpec()->accept(this);
        write(" %s;\n", node->getName().c_str());
    }

    virtual void at(const ArrayDcl* node)
    {
        assert(!node->isLeaf());
        writetab();
        if (node->isTypedef(node->getParent()))
        {
            write("typedef ");
        }
        node->getSpec()->accept(this);
        write(" %s", node->getName().c_str());
        for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
        {
            write("[");
            (*i)->accept(this);
            write("]");
        }
        if (node->isTypedef(node->getParent()))
        {
            write(";\n");
        }
    }

    virtual void at(const ConstDcl* node)
    {
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }
        write("static const ");
        node->getSpec()->accept(this);
        write(" %s = ", node->getName().c_str());
        node->getExp()->accept(this);
        write(";\n");
    }

    virtual void at(const Attribute* node)
    {
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }

        // getter
        CPlusPlus::getter(node);
        write(" = 0;\n");

        if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())
        {
            // setter
            writetab();
            CPlusPlus::setter(node);
            write(" = 0;\n");
        }
    }

    virtual void at(const OpDcl* node)
    {
        writetab();
        if (node->getJavadoc().size())
        {
            write("%s\n", node->getJavadoc().c_str());
            writetab();
        }

        CPlusPlus::at(node);

        if (!constructorMode)
        {
            write(" = 0;\n");
        }
        else
        {
            write("{");
            writeln("");
                writeln("if (constructor)");
                indent();
                    writetab();
                    write("return constructor->createInstance(");
                    for (NodeList::iterator i = node->begin(); i != node->end(); ++i)
                    {
                        if (i != node->begin())
                        {
                            write(", ");
                        }
                        write("%s", (*i)->getName().c_str());
                    }
                    write(");");
                    writeln("");
                unindent();
                writeln("else");
                indent();
                    writeln("return 0;");
                unindent();
            writeln("}");
        }
    }
};

class Import : public Visitor
{
    const char* source;
    FILE* file;
    bool printed;

public:
    Import(const char* source, FILE* file) :
        source(source),
        file(file),
        printed(false)
    {
    }

    virtual void at(const Node* node)
    {
        visitChildren(node);
    }

    virtual void at(const Include* node)
    {
        if (!node->isDefinedIn(source))
        {
            return;
        }
        if (node->isSystem())
        {
            fprintf(file, "#include <%s>\n", getOutputFilename(node->getName().c_str(), "h").c_str());
        }
        else
        {
            fprintf(file, "#include \"%s\"\n", getOutputFilename(node->getName().c_str(), "h").c_str());
        }
        printed = true;
    }

    bool hasPrinted() const
    {
        return printed;
    }
};

class Predeclaration : public Visitor, public Formatter
{
    const char* source;

public:
    Predeclaration(const char* source, FILE* file, const char* indent) :
        Formatter(file, indent),
        source(source)
    {
    }

    virtual void at(const Node* node)
    {
        if (!node->isDefinedIn(source))
        {
            return;
        }
        visitChildren(node);
    }

    virtual void at(const Module* node)
    {
        if (!node->hasPredeclarations())
        {
            return;
        }
        if (0 < node->getName().size())
        {
            write("namespace %s {\n", node->getName().c_str());
                visitChildren(node);
            writeln("}");
            writeln("");
        }
        else
        {
            visitChildren(node);
        }
    }

    virtual void at(const Interface* node)
    {
        if (!node->isDefinedIn(source) || !node->isLeaf())
        {
            return;
        }
        writeln("class %s;", node->getName().c_str());
    }
};

void printCxx(const char* source, const char* stringTypeName, bool useExceptions, const char* indent)
{
    const std::string filename = getOutputFilename(source, "h");
    printf("# %s\n", filename.c_str());

    FILE* file = fopen(filename.c_str(), "w");
    if (!file)
    {
        return;
    }

    std::string included = getIncludedName(filename);
    fprintf(file, "// Generated by esidl %s.\n\n", VERSION);
    fprintf(file, "#ifndef %s\n", included.c_str());
    fprintf(file, "#define %s\n\n", included.c_str());

    Import import(source, file);
    getSpecification()->accept(&import);
    if (import.hasPrinted())
    {
        fprintf(file, "\n");
    }

    if (!Node::getFlatNamespace())
    {
        Predeclaration predeclaration(source, file, indent);
        getSpecification()->accept(&predeclaration);
    }

    Cxx cxx(source, file, stringTypeName, useExceptions, indent);
    getSpecification()->accept(&cxx);

    fprintf(file, "#endif  // %s\n", included.c_str());

    fclose(file);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007 Apple Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "LocalizedStrings.h"
#include "PlatformString.h"
#include "IntSize.h"

#undef LOG

#include "base/logging.h"
#include "base/file_util.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "grit/webkit_strings.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webkit_glue.h"

using namespace WebCore;

inline String GetLocalizedString(int message_id) {
  const string16& str = webkit_glue::GetLocalizedString(message_id);
  return webkit_glue::String16ToString(str);
}

String WebCore::searchableIndexIntroduction() {
  return GetLocalizedString(IDS_SEARCHABLE_INDEX_INTRO);
}
String WebCore::submitButtonDefaultLabel() {
  return GetLocalizedString(IDS_FORM_SUBMIT_LABEL);
}
String WebCore::inputElementAltText() {
  return GetLocalizedString(IDS_FORM_INPUT_ALT);
}
String WebCore::resetButtonDefaultLabel() {
  return GetLocalizedString(IDS_FORM_RESET_LABEL);
}
String WebCore::fileButtonChooseFileLabel() {
  return GetLocalizedString(IDS_FORM_FILE_BUTTON_LABEL);
}
String WebCore::fileButtonNoFileSelectedLabel() {
  return GetLocalizedString(IDS_FORM_FILE_NO_FILE_LABEL);
}

String WebCore::searchMenuNoRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES_NONE);
}
String WebCore::searchMenuRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES);
}
String WebCore::searchMenuClearRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES_CLEAR);
}

// A11y strings.
String WebCore::AXWebAreaText() {
  return GetLocalizedString(IDS_AX_ROLE_WEB_AREA);
}
String WebCore::AXLinkText() {
  return GetLocalizedString(IDS_AX_ROLE_LINK);
}
String WebCore::AXListMarkerText() {
  return GetLocalizedString(IDS_AX_ROLE_LIST_MARKER);
}
String WebCore::AXImageMapText() {
  return GetLocalizedString(IDS_AX_ROLE_IMAGE_MAP);
}
String WebCore::AXHeadingText() {
  return GetLocalizedString(IDS_AX_ROLE_HEADING);
}
String WebCore::AXDefinitionListTermText() {
  NOTIMPLEMENTED();
  return String("term");
}
String WebCore::AXDefinitionListDefinitionText() {
  NOTIMPLEMENTED();
  return String("definition");
}
String WebCore::AXButtonActionVerb() {
  return GetLocalizedString(IDS_AX_BUTTON_ACTION_VERB);
}
String WebCore::AXRadioButtonActionVerb() {
  return GetLocalizedString(IDS_AX_RADIO_BUTTON_ACTION_VERB);
}
String WebCore::AXTextFieldActionVerb() {
  return GetLocalizedString(IDS_AX_TEXT_FIELD_ACTION_VERB);
}
String WebCore::AXCheckedCheckBoxActionVerb() {
  return GetLocalizedString(IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB);
}
String WebCore::AXUncheckedCheckBoxActionVerb() {
  return GetLocalizedString(IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB);
}
String WebCore::AXLinkActionVerb() {
  return GetLocalizedString(IDS_AX_LINK_ACTION_VERB);
}

String WebCore::multipleFileUploadText(unsigned number_of_files) {
  return webkit_glue::String16ToString(ReplaceStringPlaceholders(
      webkit_glue::GetLocalizedString(IDS_FORM_FILE_MULTIPLE_UPLOAD),
      WideToUTF16Hack(UintToWString(number_of_files)),
      NULL));
}
// Used in FTPDirectoryDocument.cpp
String WebCore::unknownFileSizeText() {
  return String();
}

// The following two functions are not declared in LocalizedStrings.h.
// They are used by the menu for the HTML keygen tag.
namespace WebCore {
String keygenMenuHighGradeKeySize() {
  return GetLocalizedString(IDS_KEYGEN_HIGH_GRADE_KEY);
}
String keygenMenuMediumGradeKeySize() {
  return GetLocalizedString(IDS_KEYGEN_MED_GRADE_KEY);
}

// Used in ImageDocument.cpp as the title for pages when that page is an image.
String imageTitle(const String& filename, const IntSize& size) {
  // C3 97 is UTF-8 for U+00D7 (multiplication sign).
  std::string size_str = StringPrintf(" (%d\xC3\x97%d)",
                                      size.width(), size.height());
  return filename + webkit_glue::StdStringToString(size_str);
}

} //namespace WebCore

// We don't use these strings, so they return an empty String. We can't just
// make them asserts because webcore still calls them.
String WebCore::contextMenuItemTagOpenLinkInNewWindow() { return String(); }
String WebCore::contextMenuItemTagDownloadLinkToDisk() { return String(); }
String WebCore::contextMenuItemTagCopyLinkToClipboard() { return String(); }
String WebCore::contextMenuItemTagOpenImageInNewWindow() { return String(); }
String WebCore::contextMenuItemTagDownloadImageToDisk() { return String(); }
String WebCore::contextMenuItemTagCopyImageToClipboard() { return String(); }
String WebCore::contextMenuItemTagOpenFrameInNewWindow() { return String(); }
String WebCore::contextMenuItemTagCopy() { return String(); }
String WebCore::contextMenuItemTagGoBack() { return String(); }
String WebCore::contextMenuItemTagGoForward() { return String(); }
String WebCore::contextMenuItemTagStop() { return String(); }
String WebCore::contextMenuItemTagReload() { return String(); }
String WebCore::contextMenuItemTagCut() { return String(); }
String WebCore::contextMenuItemTagPaste() { return String(); }
String WebCore::contextMenuItemTagNoGuessesFound() { return String(); }
String WebCore::contextMenuItemTagIgnoreSpelling() { return String(); }
String WebCore::contextMenuItemTagLearnSpelling() { return String(); }
String WebCore::contextMenuItemTagSearchWeb() { return String(); }
String WebCore::contextMenuItemTagLookUpInDictionary() { return String(); }
String WebCore::contextMenuItemTagOpenLink() { return String(); }
String WebCore::contextMenuItemTagIgnoreGrammar() { return String(); }
String WebCore::contextMenuItemTagSpellingMenu() { return String(); }
String WebCore::contextMenuItemTagCheckSpelling() { return String(); }
String WebCore::contextMenuItemTagCheckSpellingWhileTyping() { return String(); }
String WebCore::contextMenuItemTagCheckGrammarWithSpelling() { return String(); }
String WebCore::contextMenuItemTagFontMenu() { return String(); }
String WebCore::contextMenuItemTagBold() { return String(); }
String WebCore::contextMenuItemTagItalic() { return String(); }
String WebCore::contextMenuItemTagUnderline() { return String(); }
String WebCore::contextMenuItemTagOutline() { return String(); }
String WebCore::contextMenuItemTagWritingDirectionMenu() { return String(); }
String WebCore::contextMenuItemTagTextDirectionMenu() { return String(); }
String WebCore::contextMenuItemTagDefaultDirection() { return String(); }
String WebCore::contextMenuItemTagLeftToRight() { return String(); }
String WebCore::contextMenuItemTagRightToLeft() { return String(); }
String WebCore::contextMenuItemTagInspectElement() { return String(); }
String WebCore::contextMenuItemTagShowSpellingPanel(bool show) { return String(); }
// TODO(scherkus): These should return something.
String WebCore::mediaElementLiveBroadcastStateText() { return String(); }
String WebCore::mediaElementLoadingStateText() { return String(); }
<commit_msg>Reverting 19834. Review URL: http://codereview.chromium.org/149137<commit_after>/*
 * Copyright (C) 2007 Apple Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "LocalizedStrings.h"
#include "PlatformString.h"
#include "IntSize.h"

#undef LOG

#include "base/logging.h"
#include "base/file_util.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "grit/webkit_strings.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webkit_glue.h"

using namespace WebCore;

inline String GetLocalizedString(int message_id) {
  const string16& str = webkit_glue::GetLocalizedString(message_id);
  return webkit_glue::String16ToString(str);
}

String WebCore::searchableIndexIntroduction() {
  return GetLocalizedString(IDS_SEARCHABLE_INDEX_INTRO);
}
String WebCore::submitButtonDefaultLabel() {
  return GetLocalizedString(IDS_FORM_SUBMIT_LABEL);
}
String WebCore::inputElementAltText() {
  return GetLocalizedString(IDS_FORM_INPUT_ALT);
}
String WebCore::resetButtonDefaultLabel() {
  return GetLocalizedString(IDS_FORM_RESET_LABEL);
}
String WebCore::fileButtonChooseFileLabel() {
  return GetLocalizedString(IDS_FORM_FILE_BUTTON_LABEL);
}
String WebCore::fileButtonNoFileSelectedLabel() {
  return GetLocalizedString(IDS_FORM_FILE_NO_FILE_LABEL);
}

String WebCore::searchMenuNoRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES_NONE);
}
String WebCore::searchMenuRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES);
}
String WebCore::searchMenuClearRecentSearchesText() {
  return GetLocalizedString(IDS_RECENT_SEARCHES_CLEAR);
}

// A11y strings.
String WebCore::AXWebAreaText() {
  return GetLocalizedString(IDS_AX_ROLE_WEB_AREA);
}
String WebCore::AXLinkText() {
  return GetLocalizedString(IDS_AX_ROLE_LINK);
}
String WebCore::AXListMarkerText() {
  return GetLocalizedString(IDS_AX_ROLE_LIST_MARKER);
}
String WebCore::AXImageMapText() {
  return GetLocalizedString(IDS_AX_ROLE_IMAGE_MAP);
}
String WebCore::AXHeadingText() {
  return GetLocalizedString(IDS_AX_ROLE_HEADING);
}
String WebCore::AXDefinitionListTermText() {
  NOTIMPLEMENTED();
  return String("term");
}
String WebCore::AXDefinitionListDefinitionText() {
  NOTIMPLEMENTED();
  return String("definition");
}
String WebCore::AXButtonActionVerb() {
  return GetLocalizedString(IDS_AX_BUTTON_ACTION_VERB);
}
String WebCore::AXRadioButtonActionVerb() {
  return GetLocalizedString(IDS_AX_RADIO_BUTTON_ACTION_VERB);
}
String WebCore::AXTextFieldActionVerb() {
  return GetLocalizedString(IDS_AX_TEXT_FIELD_ACTION_VERB);
}
String WebCore::AXCheckedCheckBoxActionVerb() {
  return GetLocalizedString(IDS_AX_CHECKED_CHECK_BOX_ACTION_VERB);
}
String WebCore::AXUncheckedCheckBoxActionVerb() {
  return GetLocalizedString(IDS_AX_UNCHECKED_CHECK_BOX_ACTION_VERB);
}
String WebCore::AXLinkActionVerb() {
  return GetLocalizedString(IDS_AX_LINK_ACTION_VERB);
}

String WebCore::multipleFileUploadText(unsigned number_of_files) {
  return webkit_glue::String16ToString(ReplaceStringPlaceholders(
      webkit_glue::GetLocalizedString(IDS_FORM_FILE_MULTIPLE_UPLOAD),
      WideToUTF16Hack(UintToWString(number_of_files)),
      NULL));
}
// Used in FTPDirectoryDocument.cpp
String WebCore::unknownFileSizeText() {
  return String();
}

// The following two functions are not declared in LocalizedStrings.h.
// They are used by the menu for the HTML keygen tag.
namespace WebCore {
String keygenMenuHighGradeKeySize() {
  return GetLocalizedString(IDS_KEYGEN_HIGH_GRADE_KEY);
}
String keygenMenuMediumGradeKeySize() {
  return GetLocalizedString(IDS_KEYGEN_MED_GRADE_KEY);
}

// Used in ImageDocument.cpp as the title for pages when that page is an image.
String imageTitle(const String& filename, const IntSize& size) {
  // C3 97 is UTF-8 for U+00D7 (multiplication sign).
  std::string size_str = StringPrintf(" (%d\xC3\x97%d)",
                                      size.width(), size.height());
  return filename + webkit_glue::StdStringToString(size_str);
}

} //namespace WebCore

// We don't use these strings, so they return an empty String. We can't just
// make them asserts because webcore still calls them.
String WebCore::contextMenuItemTagOpenLinkInNewWindow() { return String(); }
String WebCore::contextMenuItemTagDownloadLinkToDisk() { return String(); }
String WebCore::contextMenuItemTagCopyLinkToClipboard() { return String(); }
String WebCore::contextMenuItemTagOpenImageInNewWindow() { return String(); }
String WebCore::contextMenuItemTagDownloadImageToDisk() { return String(); }
String WebCore::contextMenuItemTagCopyImageToClipboard() { return String(); }
String WebCore::contextMenuItemTagOpenFrameInNewWindow() { return String(); }
String WebCore::contextMenuItemTagCopy() { return String(); }
String WebCore::contextMenuItemTagGoBack() { return String(); }
String WebCore::contextMenuItemTagGoForward() { return String(); }
String WebCore::contextMenuItemTagStop() { return String(); }
String WebCore::contextMenuItemTagReload() { return String(); }
String WebCore::contextMenuItemTagCut() { return String(); }
String WebCore::contextMenuItemTagPaste() { return String(); }
String WebCore::contextMenuItemTagNoGuessesFound() { return String(); }
String WebCore::contextMenuItemTagIgnoreSpelling() { return String(); }
String WebCore::contextMenuItemTagLearnSpelling() { return String(); }
String WebCore::contextMenuItemTagSearchWeb() { return String(); }
String WebCore::contextMenuItemTagLookUpInDictionary() { return String(); }
String WebCore::contextMenuItemTagOpenLink() { return String(); }
String WebCore::contextMenuItemTagIgnoreGrammar() { return String(); }
String WebCore::contextMenuItemTagSpellingMenu() { return String(); }
String WebCore::contextMenuItemTagCheckSpelling() { return String(); }
String WebCore::contextMenuItemTagCheckSpellingWhileTyping() { return String(); }
String WebCore::contextMenuItemTagCheckGrammarWithSpelling() { return String(); }
String WebCore::contextMenuItemTagFontMenu() { return String(); }
String WebCore::contextMenuItemTagBold() { return String(); }
String WebCore::contextMenuItemTagItalic() { return String(); }
String WebCore::contextMenuItemTagUnderline() { return String(); }
String WebCore::contextMenuItemTagOutline() { return String(); }
String WebCore::contextMenuItemTagWritingDirectionMenu() { return String(); }
String WebCore::contextMenuItemTagTextDirectionMenu() { return String(); }
String WebCore::contextMenuItemTagDefaultDirection() { return String(); }
String WebCore::contextMenuItemTagLeftToRight() { return String(); }
String WebCore::contextMenuItemTagRightToLeft() { return String(); }
String WebCore::contextMenuItemTagInspectElement() { return String(); }
String WebCore::contextMenuItemTagShowSpellingPanel(bool show) { return String(); }
<|endoftext|>