<commit_before>/*
 * PWMController.cpp
 *
 *  Created on: Jun 26, 2015
 *      Author: Rahul
 */

#include "PWMController.h"

PWMController::PWMController(NetworkClient *networkClient,
		  	  	  	  	  	 IMUController *imuController,
		  	  	  	  	  	 PSController *psController,
		  	  	  	  	  	 uint32_t pwmAddr,
		  	  	  	  	  	 uint32_t pwmMap[NUMMOTORS],
		  	  	  	  	  	 double combinerRatio,
		  	  	  	  	  	 double xP,
		  	  	  	  	  	 double xI,
		  	  	  	  	  	 double xD,
		  	  	  	  	  	 double xF,
		  	  	  	  	  	 double yP,
		  	  	  	  	  	 double yI,
		  	  	  	  	  	 double yD,
		  	  	  	  	  	 double yF,
		  	  	  	  	  	 double zP,
		  	  	  	  	  	 double zI,
		  	  	  	  	  	 double zD,
		  	  	  	  	  	 double zF,
		  	  	  	  	  	 double dP,
		  	  	  	  	  	 double dI,
		  	  	  	  	  	 double dD,
		  	  	  	  	  	 double dF) :
		  	  	  	  	  	 _networkClient(networkClient),
		  	  	  	  	  	 _imuController(imuController),
		  	  	  	  	  	 _psController(psController),
		  	  	  	  	  	 _pwmAddr(pwmAddr),
		  	  	  	  	  	 _combinerRatio(combinerRatio) {
	_xRotationController.setPIDF(xP, xI, xD, xF);
	_xRotationController.setInputLimits(-180, 180);
	_xRotationController.setOutputLimits(PWMMINOUTPUT, PWMMAXOUTPUT);
	_xRotationController.setContinuous(true);

	_yRotationController.setPIDF(yP, yI, yD, yF);
	_yRotationController.setInputLimits(-180, 180);
	_yRotationController.setOutputLimits(PWMMINOUTPUT, PWMMAXOUTPUT);
	_yRotationController.setContinuous(true);

	_zRotationController.setPIDF(zP, zI, zD, zF);
	_zRotationController.setInputLimits(-180, 180);
	_zRotationController.setOutputLimits(PWMMINOUTPUT, PWMMAXOUTPUT);
	_zRotationController.setContinuous(true);

	_depthController.setPIDF(dP, dI, dD, dF);
	_depthController.setOutputLimits(PWMMINOUTPUT, PWMMAXOUTPUT);
	_depthController.setContinuous(false);

	for (int i = 0;i < NUMMOTORS;i++) {
		_pwmMap[i] = pwmMap[i];
	}

	for (int i = 0;i < NUMMOTORS;i++) {
		_pwmOutputs[i] = 0;
	}

	initPWM();
}

PWMController::~PWMController() {
	delete _pwm;
}

void PWMController::start() {
	_xRotationController.start();
	_yRotationController.start();
	_zRotationController.start();
	_depthController.start();
	run();
}

void PWMController::stop() {
	for (int i = 0;i < NUMMOTORS;i++) {
		_pwmOutputs[i] = 0;
	}
	_pwm->setDuty(_pwmOutputs);
	_pwm->disable();
}

void PWMController::initPWM() {
	_pwm = new PWM(_pwmAddr);
	_pwm->setMap(_pwmMap);
	_pwm->enable();
	_pwm->setDuty(_pwmOutputs);
}

void PWMController::pollData() {
	_velX = _networkClient->get_n2m_standard_packet()->get_vel_x();
	_velY = _networkClient->get_n2m_standard_packet()->get_vel_y();
	_posZ = _networkClient->get_n2m_standard_packet()->get_pos_z();
	_rotX = _networkClient->get_n2m_standard_packet()->get_rot_x();
	_rotY = _networkClient->get_n2m_standard_packet()->get_rot_y();
	_rotZ = _networkClient->get_n2m_standard_packet()->get_rot_z();
	_xAngle = _imuController->getXRotation();
	_yAngle = _imuController->getYRotation();
	_zAngle = _imuController->getZRotation();
	_depth = _psController->getDepthInMeters();
}

void PWMController::calculateOutputs() {
	_linearMotion(XAXIS) = _velX;
	_linearMotion(YAXIS) = _velY;
	_linearMotion(ZAXIS) = _depthController.calculateOutput(_depth, _posZ);

	Eigen::AngleAxisd xRotationMatrix(_xAngle, Eigen::Vector3d::UnitX());
	Eigen::AngleAxisd yRotationMatrix(_yAngle, Eigen::Vector3d::UnitY());
	Eigen::AngleAxisd zRotationMatrix(_zAngle, Eigen::Vector3d::UnitZ());

	_linearMotion = xRotationMatrix.toRotationMatrix() *
					yRotationMatrix.toRotationMatrix() *
					zRotationMatrix.toRotationMatrix() *
					_linearMotion;

	_rotationalMotion(XAXIS) = _xRotationController.calculateOutput(_xAngle, _rotX);
	_rotationalMotion(YAXIS) = _yRotationController.calculateOutput(_yAngle, _rotY);
	_rotationalMotion(ZAXIS) = _zRotationController.calculateOutput(_zAngle, _rotZ);

	_pwmOutputs[MXF1] = combineMotion(_linearMotion(XAXIS),
									  -_rotationalMotion(YAXIS),
									  _rotationalMotion(ZAXIS));
	_pwmOutputs[MXF2] = combineMotion(_linearMotion(XAXIS),
									  _rotationalMotion(YAXIS),
									  _rotationalMotion(ZAXIS));
	_pwmOutputs[MXF3] = combineMotion(_linearMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MXF4] = combineMotion(_linearMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));

	_pwmOutputs[MXR1] = combineMotion(-_linearMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MXR2] = combineMotion(-_linearMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MXR3] = combineMotion(-_linearMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));
	_pwmOutputs[MXR4] = combineMotion(_linearMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));

	_pwmOutputs[MYF1] = combineMotion(_linearMotion(YAXIS),
									  _rotationalMotion(XAXIS),
									  _rotationalMotion(ZAXIS));
	_pwmOutputs[MYF2] = combineMotion(_linearMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));
	_pwmOutputs[MYF3] = combineMotion(_linearMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MYF4] = combineMotion(_linearMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));

	_pwmOutputs[MYR1] = combineMotion(-_linearMotion(YAXIS),
									  -_rotationalMotion(XAXIS),
									  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MYR2] = combineMotion(-_linearMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MYR3] = combineMotion(-_linearMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));
	_pwmOutputs[MYR4] = combineMotion(-_linearMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));

	_pwmOutputs[MZF1] = combineMotion(_linearMotion(ZAXIS),
									  -_rotationalMotion(XAXIS),
									  -_rotationalMotion(YAXIS));
	_pwmOutputs[MZF2] = combineMotion(_linearMotion(ZAXIS),
									  -_rotationalMotion(XAXIS),
									  _rotationalMotion(YAXIS));
	_pwmOutputs[MZF3] = combineMotion(_linearMotion(ZAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS));
	_pwmOutputs[MZF4] = combineMotion(_linearMotion(ZAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS));

	_pwmOutputs[MZR1] = combineMotion(-_linearMotion(ZAXIS),
									  _rotationalMotion(XAXIS),
									  _rotationalMotion(YAXIS));
	_pwmOutputs[MZR2] = combineMotion(-_linearMotion(ZAXIS),
									  _rotationalMotion(XAXIS),
									  -_rotationalMotion(YAXIS));
	_pwmOutputs[MZR3] = combineMotion(-_linearMotion(ZAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS));
	_pwmOutputs[MZR4] = combineMotion(-_linearMotion(ZAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS));

	for (int i = 0;i < NUMMOTORS;i++) {
		if (_pwmOutputs[i] < 0) {
			_pwmOutputs[i] = 0;
		}
	}
}

void PWMController::writeOutputs() {
	_pwm->setDuty(_pwmOutputs);

	_networkClient->get_m2n_standard_packet()->set_orient_x(_xAngle);
	_networkClient->get_m2n_standard_packet()->set_orient_y(_yAngle);
	_networkClient->get_m2n_standard_packet()->set_orient_z(_zAngle);
	_networkClient->get_m2n_standard_packet()->set_pos_z(_depth);
}

double PWMController::combineMotion(double linear, double rotational1, double rotational2) {
	return ((_combinerRatio * linear) +
			(((1 - _combinerRatio) / 2) * rotational1) +
			(((1 - _combinerRatio) / 2) * rotational2));
}

void PWMController::run() {
	while(1) {
		pollData();
		calculateOutputs();
		writeOutputs();
		std::this_thread::sleep_for(std::chrono::milliseconds(PWMLOOPTIME));
	}
}
<commit_msg>small fix<commit_after>/*
 * PWMController.cpp
 *
 *  Created on: Jun 26, 2015
 *      Author: Rahul
 */

#include "PWMController.h"

PWMController::PWMController(NetworkClient *networkClient,
		  	  	  	  	  	 IMUController *imuController,
		  	  	  	  	  	 PSController *psController,
		  	  	  	  	  	 uint32_t pwmAddr,
		  	  	  	  	  	 uint32_t pwmMap[NUMMOTORS],
		  	  	  	  	  	 double combinerRatio,
		  	  	  	  	  	 double xP,
		  	  	  	  	  	 double xI,
		  	  	  	  	  	 double xD,
		  	  	  	  	  	 double xF,
		  	  	  	  	  	 double yP,
		  	  	  	  	  	 double yI,
		  	  	  	  	  	 double yD,
		  	  	  	  	  	 double yF,
		  	  	  	  	  	 double zP,
		  	  	  	  	  	 double zI,
		  	  	  	  	  	 double zD,
		  	  	  	  	  	 double zF,
		  	  	  	  	  	 double dP,
		  	  	  	  	  	 double dI,
		  	  	  	  	  	 double dD,
		  	  	  	  	  	 double dF) :
		  	  	  	  	  	 _networkClient(networkClient),
		  	  	  	  	  	 _imuController(imuController),
		  	  	  	  	  	 _psController(psController),
		  	  	  	  	  	 _pwmAddr(pwmAddr),
		  	  	  	  	  	 _combinerRatio(combinerRatio) {
	_xRotationController.setPIDF(xP, xI, xD, xF);
	_xRotationController.setInputLimits(-180, 180);
	_xRotationController.setOutputLimits(PWMMINOUTPUT, PWMMAXOUTPUT);
	_xRotationController.setContinuous(true);

	_yRotationController.setPIDF(yP, yI, yD, yF);
	_yRotationController.setInputLimits(-180, 180);
	_yRotationController.setOutputLimits(PWMMINOUTPUT, PWMMAXOUTPUT);
	_yRotationController.setContinuous(true);

	_zRotationController.setPIDF(zP, zI, zD, zF);
	_zRotationController.setInputLimits(-180, 180);
	_zRotationController.setOutputLimits(PWMMINOUTPUT, PWMMAXOUTPUT);
	_zRotationController.setContinuous(true);

	_depthController.setPIDF(dP, dI, dD, dF);
	_depthController.setOutputLimits(PWMMINOUTPUT, PWMMAXOUTPUT);
	_depthController.setContinuous(false);

	for (int i = 0;i < NUMMOTORS;i++) {
		_pwmMap[i] = pwmMap[i];
	}

	for (int i = 0;i < NUMMOTORS;i++) {
		_pwmOutputs[i] = 0;
	}

	initPWM();
}

PWMController::~PWMController() {
	delete _pwm;
}

void PWMController::start() {
	_xRotationController.start();
	_yRotationController.start();
	_zRotationController.start();
	_depthController.start();
	run();
}

void PWMController::stop() {
	for (int i = 0;i < NUMMOTORS;i++) {
		_pwmOutputs[i] = 0;
	}
	_pwm->setDuty(_pwmOutputs);
	_pwm->disable();
}

void PWMController::initPWM() {
	_pwm = new PWM(_pwmAddr);
	_pwm->setMap(_pwmMap);
	_pwm->enable();
	_pwm->setDuty(_pwmOutputs);
}

void PWMController::pollData() {
	_velX = _networkClient->get_n2m_standard_packet()->get_vel_x();
	_velY = _networkClient->get_n2m_standard_packet()->get_vel_y();
	_posZ = _networkClient->get_n2m_standard_packet()->get_pos_z();
	_rotX = _networkClient->get_n2m_standard_packet()->get_rot_x();
	_rotY = _networkClient->get_n2m_standard_packet()->get_rot_y();
	_rotZ = _networkClient->get_n2m_standard_packet()->get_rot_z();
	_xAngle = _imuController->getXRotation();
	_yAngle = _imuController->getYRotation();
	_zAngle = _imuController->getZRotation();
	_depth = _psController->getDepthInMeters();
}

void PWMController::calculateOutputs() {
	_linearMotion(XAXIS) = _velX;
	_linearMotion(YAXIS) = _velY;
	_linearMotion(ZAXIS) = _depthController.calculateOutput(_depth, _posZ);

	Eigen::AngleAxisd xRotationMatrix(_xAngle, Eigen::Vector3d::UnitX());
	Eigen::AngleAxisd yRotationMatrix(_yAngle, Eigen::Vector3d::UnitY());
	Eigen::AngleAxisd zRotationMatrix(_zAngle, Eigen::Vector3d::UnitZ());

	_linearMotion = xRotationMatrix.toRotationMatrix() *
					yRotationMatrix.toRotationMatrix() *
					zRotationMatrix.toRotationMatrix() *
					_linearMotion;

	_rotationalMotion(XAXIS) = _xRotationController.calculateOutput(-_xAngle, _rotX);
	_rotationalMotion(YAXIS) = _yRotationController.calculateOutput(-_yAngle, _rotY);
	_rotationalMotion(ZAXIS) = _zRotationController.calculateOutput(-_zAngle, _rotZ);

	_pwmOutputs[MXF1] = combineMotion(_linearMotion(XAXIS),
									  -_rotationalMotion(YAXIS),
									  _rotationalMotion(ZAXIS));
	_pwmOutputs[MXF2] = combineMotion(_linearMotion(XAXIS),
									  _rotationalMotion(YAXIS),
									  _rotationalMotion(ZAXIS));
	_pwmOutputs[MXF3] = combineMotion(_linearMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MXF4] = combineMotion(_linearMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));

	_pwmOutputs[MXR1] = combineMotion(-_linearMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MXR2] = combineMotion(-_linearMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MXR3] = combineMotion(-_linearMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));
	_pwmOutputs[MXR4] = combineMotion(_linearMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));

	_pwmOutputs[MYF1] = combineMotion(_linearMotion(YAXIS),
									  _rotationalMotion(XAXIS),
									  _rotationalMotion(ZAXIS));
	_pwmOutputs[MYF2] = combineMotion(_linearMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));
	_pwmOutputs[MYF3] = combineMotion(_linearMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MYF4] = combineMotion(_linearMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));

	_pwmOutputs[MYR1] = combineMotion(-_linearMotion(YAXIS),
									  -_rotationalMotion(XAXIS),
									  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MYR2] = combineMotion(-_linearMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(ZAXIS));
	_pwmOutputs[MYR3] = combineMotion(-_linearMotion(YAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));
	_pwmOutputs[MYR4] = combineMotion(-_linearMotion(YAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(ZAXIS));

	_pwmOutputs[MZF1] = combineMotion(_linearMotion(ZAXIS),
									  -_rotationalMotion(XAXIS),
									  -_rotationalMotion(YAXIS));
	_pwmOutputs[MZF2] = combineMotion(_linearMotion(ZAXIS),
									  -_rotationalMotion(XAXIS),
									  _rotationalMotion(YAXIS));
	_pwmOutputs[MZF3] = combineMotion(_linearMotion(ZAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS));
	_pwmOutputs[MZF4] = combineMotion(_linearMotion(ZAXIS),
			  	  	  	  	  	  	  _rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS));

	_pwmOutputs[MZR1] = combineMotion(-_linearMotion(ZAXIS),
									  _rotationalMotion(XAXIS),
									  _rotationalMotion(YAXIS));
	_pwmOutputs[MZR2] = combineMotion(-_linearMotion(ZAXIS),
									  _rotationalMotion(XAXIS),
									  -_rotationalMotion(YAXIS));
	_pwmOutputs[MZR3] = combineMotion(-_linearMotion(ZAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(YAXIS));
	_pwmOutputs[MZR4] = combineMotion(-_linearMotion(ZAXIS),
			  	  	  	  	  	  	  -_rotationalMotion(XAXIS),
			  	  	  	  	  	  	  _rotationalMotion(YAXIS));

	for (int i = 0;i < NUMMOTORS;i++) {
		if (_pwmOutputs[i] < 0) {
			_pwmOutputs[i] = 0;
		}
	}
}

void PWMController::writeOutputs() {
	_pwm->setDuty(_pwmOutputs);

	_networkClient->get_m2n_standard_packet()->set_orient_x(_xAngle);
	_networkClient->get_m2n_standard_packet()->set_orient_y(_yAngle);
	_networkClient->get_m2n_standard_packet()->set_orient_z(_zAngle);
	_networkClient->get_m2n_standard_packet()->set_pos_z(_depth);
}

double PWMController::combineMotion(double linear, double rotational1, double rotational2) {
	return ((_combinerRatio * linear) +
			(((1 - _combinerRatio) / 2) * rotational1) +
			(((1 - _combinerRatio) / 2) * rotational2));
}

void PWMController::run() {
	while(1) {
		pollData();
		calculateOutputs();
		writeOutputs();
		std::this_thread::sleep_for(std::chrono::milliseconds(PWMLOOPTIME));
	}
}
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          stc.cpp
* Purpose:       Implementation of class 'wxExSTCWithFrame'
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/extension/configdialog.h>
#include <wx/extension/extension.h>
#include <wx/extension/header.h>
#include <wx/extension/svn.h>
#include <wx/extension/report/report.h>

BEGIN_EVENT_TABLE(wxExSTCWithFrame, wxExSTC)
  EVT_MENU_RANGE(ID_EDIT_SVN_LOWEST, ID_EDIT_SVN_HIGHEST, wxExSTCWithFrame::OnCommand)
  EVT_MENU_RANGE(ID_STC_LOWEST, ID_STC_HIGHEST, wxExSTCWithFrame::OnCommand)
  EVT_MENU_RANGE(ID_TOOL_LOWEST, ID_TOOL_HIGHEST, wxExSTCWithFrame::OnCommand)
END_EVENT_TABLE()

#if wxUSE_DRAG_AND_DROP
class STCDropTarget : public wxFileDropTarget
{
public:
  STCDropTarget(wxExFrameWithHistory* owner) {m_Owner = owner;}
private:
  virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames)
  {
    wxExOpenFiles(m_Owner, filenames);
    return true;
  }

  wxExFrameWithHistory* m_Owner;
};
#endif

wxExSTCWithFrame::wxExSTCWithFrame(wxWindow* parent,
  const wxString& value,
  long type,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size,
  long style,
  const wxString& name)
  : wxExSTC(parent, value, type, id, pos, size, style, name)
{
  Initialize();
}

wxExSTCWithFrame::wxExSTCWithFrame(wxWindow* parent,
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags,
  long type,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size,
  long style,
  const wxString& name)
  : wxExSTC(parent, filename, line_number, match, flags, type, id, pos, size, style, name)
{
  if (Initialize())
  {
    m_Frame->SetRecentFile(GetFileName().GetFullPath());
  }
}

wxExSTCWithFrame::wxExSTCWithFrame(const wxExSTC& stc)
  : wxExSTC(stc)
{
  Initialize();
}

void wxExSTCWithFrame::BuildPopupMenu(wxExMenu& menu)
{
  wxExSTC::BuildPopupMenu(menu);

  // Add tools if we have at least some text, the tool flag,
  // and a lexer.
  if (GetSelectedText().empty() && GetTextLength() > 0 &&
     (GetMenuFlags() & STC_MENU_TOOL) &&
      !GetFileName().GetLexer().GetScintillaLexer().empty())
  {
    menu.AppendSeparator();
    menu.AppendTools();
  }

  if (GetMenuFlags() & (STC_MENU_REPORT_FIND | STC_MENU_REPORT_REPLACE))
  {
    menu.AppendSeparator();

    if (GetMenuFlags() & STC_MENU_REPORT_FIND)
    {
      menu.Append(ID_STC_FIND_FILES, wxExEllipsed(_("Find &In Files")));
    }

    if (GetMenuFlags() & STC_MENU_REPORT_REPLACE)
    {
      menu.Append(ID_STC_REPLACE_FILES, wxExEllipsed(_("&Replace In Files")));
    }
  }

  if (m_FileName.FileExists() && GetSelectedText().empty())
  {
    if (GetMenuFlags() & STC_MENU_COMPARE_OR_SVN)
    {
      if (!menu.AppendSVN(GetFileName()) &&
          !wxExApp::GetConfig(_("Comparator")).empty())
      {
        menu.AppendSeparator();
        menu.Append(ID_STC_COMPARE, wxExEllipsed(_("&Compare Recent Version")));
      }
    }
  }

  if (!GetReadOnly())
  {
    menu.AppendSeparator();
    menu.Append(ID_STC_ADD_HEADER, wxExEllipsed(_("&Add Header")));
  }
}

bool wxExSTCWithFrame::Initialize()
{
  wxASSERT(wxTheApp != NULL);
  wxWindow* window = wxTheApp->GetTopWindow();
  m_Frame = wxDynamicCast(window, wxExFrameWithHistory);

  if (m_Frame == NULL)
  {
    wxFAIL;
    return false;
  }

#if wxUSE_DRAG_AND_DROP
  // Now DnD normal text inside the editor does not work.
  // Adding a wxTextDropTarget works a little, but does not move text.
  SetDropTarget(new STCDropTarget(m_Frame));
#endif

  return true;
}

void wxExSTCWithFrame::OnCommand(wxCommandEvent& command)
{
  if (!Continue())
  {
    return;
  }

  if (command.GetId() > ID_TOOL_LOWEST && command.GetId() < ID_TOOL_HIGHEST)
  {
    const wxExTool tool(command.GetId());

    if (wxExTextFileWithListView::SetupTool(tool))
    {
      wxExTextFileWithListView report(m_FileName, tool);
      report.RunTool();
      report.GetStatistics().Log(tool);

      if (tool.IsCount())
      {
        wxExOpenFile(
          report.GetStatistics().GetLogfileName(),
          STC_OPEN_FROM_STATISTICS | STC_OPEN_IS_SYNCED);
      }
    }

    return;
  }

  if (command.GetId() > ID_EDIT_SVN_LOWEST &&
      command.GetId() < ID_EDIT_SVN_HIGHEST)
  {
    wxExSVN svn(command.GetId(), m_FileName.GetFullPath());

    if (command.GetId() == ID_EDIT_SVN_CAT ||
        command.GetId() == ID_EDIT_SVN_BLAME)
    {
      if (svn.Execute(this) == 0)
      {
        m_Frame->OpenFile(
          m_FileName,
          svn.GetCommandWithFlags(),
          svn.GetOutput());
      }
      else
      {
        svn.ShowOutput(this);
      }
    }
    else
    {
      svn.ExecuteAndShowOutput(this);
    }

    return;
  }

  switch (command.GetId())
  {
  case ID_STC_ADD_HEADER:
    {
      wxExHeader header(wxExApp::GetConfig());

      if (header.ShowDialog(this) != wxID_CANCEL)
      {
        if (m_FileName.GetLexer().GetScintillaLexer() == "hypertext")
        {
          GotoLine(1);
        }
        else
        {
          DocumentStart();
        }

        AddText(header.Get(&m_FileName));
      }
    }
    break;

  case ID_STC_COMPARE:
    {
      wxFileName lastfile;

      if (wxExFindOtherFileName(m_FileName, NULL, &lastfile))
      {
        wxExCompareFile(m_FileName, lastfile);
      }
    }
    break;

  case ID_STC_FIND_FILES:
    GetSearchText();
    wxExFindInFiles();
    break;

  case ID_STC_REPLACE_FILES:
    GetSearchText();
    wxExFindInFiles(true);
    break;

  default: wxFAIL;
    break;
  }
}

bool wxExSTCWithFrame::Open(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  bool retValue;

  if (flags & (STC_OPEN_FROM_LINK | STC_OPEN_FROM_STATISTICS))
  {
    retValue = m_Frame->OpenFile(filename, line_number, match, flags);
  }
  else
  {
    retValue = wxExSTC::Open(filename, line_number, match, flags);

    if (retValue)
    {
      m_Frame->SetRecentFile(filename.GetFullPath());
    }
  }

  return retValue;
}

void wxExSTCWithFrame::PropertiesMessage()
{
  wxExSTC::PropertiesMessage();

  const wxString ro = (m_FileName.GetStat().IsReadOnly() ?
    " [" + _("Readonly") + "]":
    wxString(wxEmptyString));

  m_Frame->SetTitle(m_FileName.GetFullPath() + ro, wxEmptyString);
}
<commit_msg>the wxExHeader is a const<commit_after>/******************************************************************************\
* File:          stc.cpp
* Purpose:       Implementation of class 'wxExSTCWithFrame'
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/extension/configdialog.h>
#include <wx/extension/extension.h>
#include <wx/extension/header.h>
#include <wx/extension/svn.h>
#include <wx/extension/report/report.h>

BEGIN_EVENT_TABLE(wxExSTCWithFrame, wxExSTC)
  EVT_MENU_RANGE(ID_EDIT_SVN_LOWEST, ID_EDIT_SVN_HIGHEST, wxExSTCWithFrame::OnCommand)
  EVT_MENU_RANGE(ID_STC_LOWEST, ID_STC_HIGHEST, wxExSTCWithFrame::OnCommand)
  EVT_MENU_RANGE(ID_TOOL_LOWEST, ID_TOOL_HIGHEST, wxExSTCWithFrame::OnCommand)
END_EVENT_TABLE()

#if wxUSE_DRAG_AND_DROP
class STCDropTarget : public wxFileDropTarget
{
public:
  STCDropTarget(wxExFrameWithHistory* owner) {m_Owner = owner;}
private:
  virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames)
  {
    wxExOpenFiles(m_Owner, filenames);
    return true;
  }

  wxExFrameWithHistory* m_Owner;
};
#endif

wxExSTCWithFrame::wxExSTCWithFrame(wxWindow* parent,
  const wxString& value,
  long type,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size,
  long style,
  const wxString& name)
  : wxExSTC(parent, value, type, id, pos, size, style, name)
{
  Initialize();
}

wxExSTCWithFrame::wxExSTCWithFrame(wxWindow* parent,
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags,
  long type,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size,
  long style,
  const wxString& name)
  : wxExSTC(parent, filename, line_number, match, flags, type, id, pos, size, style, name)
{
  if (Initialize())
  {
    m_Frame->SetRecentFile(GetFileName().GetFullPath());
  }
}

wxExSTCWithFrame::wxExSTCWithFrame(const wxExSTC& stc)
  : wxExSTC(stc)
{
  Initialize();
}

void wxExSTCWithFrame::BuildPopupMenu(wxExMenu& menu)
{
  wxExSTC::BuildPopupMenu(menu);

  // Add tools if we have at least some text, the tool flag,
  // and a lexer.
  if (GetSelectedText().empty() && GetTextLength() > 0 &&
     (GetMenuFlags() & STC_MENU_TOOL) &&
      !GetFileName().GetLexer().GetScintillaLexer().empty())
  {
    menu.AppendSeparator();
    menu.AppendTools();
  }

  if (GetMenuFlags() & (STC_MENU_REPORT_FIND | STC_MENU_REPORT_REPLACE))
  {
    menu.AppendSeparator();

    if (GetMenuFlags() & STC_MENU_REPORT_FIND)
    {
      menu.Append(ID_STC_FIND_FILES, wxExEllipsed(_("Find &In Files")));
    }

    if (GetMenuFlags() & STC_MENU_REPORT_REPLACE)
    {
      menu.Append(ID_STC_REPLACE_FILES, wxExEllipsed(_("&Replace In Files")));
    }
  }

  if (m_FileName.FileExists() && GetSelectedText().empty())
  {
    if (GetMenuFlags() & STC_MENU_COMPARE_OR_SVN)
    {
      if (!menu.AppendSVN(GetFileName()) &&
          !wxExApp::GetConfig(_("Comparator")).empty())
      {
        menu.AppendSeparator();
        menu.Append(ID_STC_COMPARE, wxExEllipsed(_("&Compare Recent Version")));
      }
    }
  }

  if (!GetReadOnly())
  {
    menu.AppendSeparator();
    menu.Append(ID_STC_ADD_HEADER, wxExEllipsed(_("&Add Header")));
  }
}

bool wxExSTCWithFrame::Initialize()
{
  wxASSERT(wxTheApp != NULL);
  wxWindow* window = wxTheApp->GetTopWindow();
  m_Frame = wxDynamicCast(window, wxExFrameWithHistory);

  if (m_Frame == NULL)
  {
    wxFAIL;
    return false;
  }

#if wxUSE_DRAG_AND_DROP
  // Now DnD normal text inside the editor does not work.
  // Adding a wxTextDropTarget works a little, but does not move text.
  SetDropTarget(new STCDropTarget(m_Frame));
#endif

  return true;
}

void wxExSTCWithFrame::OnCommand(wxCommandEvent& command)
{
  if (!Continue())
  {
    return;
  }

  if (command.GetId() > ID_TOOL_LOWEST && command.GetId() < ID_TOOL_HIGHEST)
  {
    const wxExTool tool(command.GetId());

    if (wxExTextFileWithListView::SetupTool(tool))
    {
      wxExTextFileWithListView report(m_FileName, tool);
      report.RunTool();
      report.GetStatistics().Log(tool);

      if (tool.IsCount())
      {
        wxExOpenFile(
          report.GetStatistics().GetLogfileName(),
          STC_OPEN_FROM_STATISTICS | STC_OPEN_IS_SYNCED);
      }
    }

    return;
  }

  if (command.GetId() > ID_EDIT_SVN_LOWEST &&
      command.GetId() < ID_EDIT_SVN_HIGHEST)
  {
    wxExSVN svn(command.GetId(), m_FileName.GetFullPath());

    if (command.GetId() == ID_EDIT_SVN_CAT ||
        command.GetId() == ID_EDIT_SVN_BLAME)
    {
      if (svn.Execute(this) == 0)
      {
        m_Frame->OpenFile(
          m_FileName,
          svn.GetCommandWithFlags(),
          svn.GetOutput());
      }
      else
      {
        svn.ShowOutput(this);
      }
    }
    else
    {
      svn.ExecuteAndShowOutput(this);
    }

    return;
  }

  switch (command.GetId())
  {
  case ID_STC_ADD_HEADER:
    {
      const wxExHeader header(wxExApp::GetConfig());

      if (header.ShowDialog(this) != wxID_CANCEL)
      {
        if (m_FileName.GetLexer().GetScintillaLexer() == "hypertext")
        {
          GotoLine(1);
        }
        else
        {
          DocumentStart();
        }

        AddText(header.Get(&m_FileName));
      }
    }
    break;

  case ID_STC_COMPARE:
    {
      wxFileName lastfile;

      if (wxExFindOtherFileName(m_FileName, NULL, &lastfile))
      {
        wxExCompareFile(m_FileName, lastfile);
      }
    }
    break;

  case ID_STC_FIND_FILES:
    GetSearchText();
    wxExFindInFiles();
    break;

  case ID_STC_REPLACE_FILES:
    GetSearchText();
    wxExFindInFiles(true);
    break;

  default: wxFAIL;
    break;
  }
}

bool wxExSTCWithFrame::Open(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  bool retValue;

  if (flags & (STC_OPEN_FROM_LINK | STC_OPEN_FROM_STATISTICS))
  {
    retValue = m_Frame->OpenFile(filename, line_number, match, flags);
  }
  else
  {
    retValue = wxExSTC::Open(filename, line_number, match, flags);

    if (retValue)
    {
      m_Frame->SetRecentFile(filename.GetFullPath());
    }
  }

  return retValue;
}

void wxExSTCWithFrame::PropertiesMessage()
{
  wxExSTC::PropertiesMessage();

  const wxString ro = (m_FileName.GetStat().IsReadOnly() ?
    " [" + _("Readonly") + "]":
    wxString(wxEmptyString));

  m_Frame->SetTitle(m_FileName.GetFullPath() + ro, wxEmptyString);
}
<|endoftext|>


<commit_before>#include <SFML\Graphics.hpp>

#include <memory>
#include <string>
#include <iostream>

#include "Game.h"
#include "Ball.h"
#include "Paddle.h"
#include "GameScreen.h"

const float Game::WallSize = 20.f;
std::shared_ptr<Screen> Game::Screen = std::make_shared<GameScreen>();

Game::Game()
: window_(sf::VideoMode(Game::Width, Game::Height), "Pong!")
{

}

void Game::handleInput()
{
	sf::Event event;
	while (window_.pollEvent(event))
	{
		if (event.type == sf::Event::Closed)
			window_.close();
	}

	Game::Screen->handleInput();
}

void Game::update(sf::Time delta)
{
	Game::Screen->update(delta);
}

void Game::render()
{
	Game::Screen->render(window_);
}

void Game::run()
{
	sf::Clock clock;
	sf::Time timeSinceLastUpdate = sf::Time::Zero;

	while (window_.isOpen())
	{
		sf::Time delta = clock.restart();
		timeSinceLastUpdate += delta;

		while (timeSinceLastUpdate > TimePerFrame)
		{
			timeSinceLastUpdate -= TimePerFrame;
			handleInput();
			update(TimePerFrame);
		}

		render();
	}
}<commit_msg>Added clear and display calls to the render function.<commit_after>#include <SFML\Graphics.hpp>

#include <memory>
#include <string>
#include <iostream>

#include "Game.h"
#include "Ball.h"
#include "Paddle.h"
#include "GameScreen.h"
#include "MenuScreen.h"

const float Game::WallSize = 20.f;
std::shared_ptr<Screen> Game::Screen = std::make_shared<MenuScreen>();

Game::Game()
: window_(sf::VideoMode(Game::Width, Game::Height), "Pong!")
{

}

void Game::handleInput()
{
	sf::Event event;
	while (window_.pollEvent(event))
	{
		if (event.type == sf::Event::Closed)
			window_.close();
	}

	Game::Screen->handleInput();
}

void Game::update(sf::Time delta)
{
	Game::Screen->update(delta);
}

void Game::render()
{
	window_.clear();
	Game::Screen->render(window_);
	window_.display();
}

void Game::run()
{
	sf::Clock clock;
	sf::Time timeSinceLastUpdate = sf::Time::Zero;

	while (window_.isOpen())
	{
		sf::Time delta = clock.restart();
		timeSinceLastUpdate += delta;

		while (timeSinceLastUpdate > TimePerFrame)
		{
			timeSinceLastUpdate -= TimePerFrame;
			handleInput();
			update(TimePerFrame);
		}

		render();
	}
}<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include "Prague/Sys/DLL.hh"
#if 1
#include <dlfcn.h>
#else /* _aix_ */
#include <dl.h>
#endif

using namespace Prague;

/* @Method{void DLL::open(const string &name, bool now = true)}
 *
 * @Description{open the library @var{name}}}
 */
void DLL::open(const string &name, bool now = true)
{
  lib = name;
#if 1
  handle = dlopen(lib.c_str(), now ? RTLD_NOW : RTLD_LAZY);
  if (!handle) err = dlerror();
#else /* _aix_ */
  shl_t shl_handle = shl_load (lib.c_str(), (now ? BIND_DEFERRED : BIND_IMMEDIATE) | BIND_NONFATAL | BIND_VERBOSE, 0);
  if (!shl_handle) err = strerror(errno);
  else handle = shl_handle;
#endif
}

/* @Method{void DLL::close()}
 *
 * @Description{close the library}
 */
void DLL::close()
{
#if 1
  if (handle) dlclose(handle);
#else /* _aix_ */
  if (handle) shl_unload (reinterpret_cast<shl_t>(handle));
#endif
  handle = 0;
}

/* @Method{void *DLL::resolve(const string &symbol)}
 *
 * @Description{return a reference to an object with name @var{symbol}}
 */
void *DLL::resolve(const string &symbol)
{
  if (!handle) return 0;
#if 1
  void *tmp = dlsym(handle, symbol.c_str());
  if (!tmp) err = dlerror();
#else /* _aix_ */
  void *tmp;
  if (shl_findsym (reinterpret_cast<shl_t *>(&handle), symbol.c_str(), TYPE_UNDEFINED, &tmp) != 0 || handle == 0 || tmp == 0)
    err = strerror(errno);
#endif
  return tmp;
};
<commit_msg><commit_after>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include "Prague/Sys/DLL.hh"
#if 1
#include <dlfcn.h>
#else /* _aix_ */
#include <dl.h>
#endif

using namespace Prague;

/* @Method{void DLL::open(const string &name, bool now = true)}
 *
 * @Description{open the library @var{name}}}
 */
void DLL::open(const string &name, bool now = true)
{
  lib = name;
  if (lib != "") {
#if 1
    handle = dlopen(lib.c_str(), now ? RTLD_NOW : RTLD_LAZY);
    if (!handle) err = dlerror();
#else /* _aix_ */
    shl_t shl_handle = shl_load (lib.c_str(), (now ? BIND_DEFERRED : BIND_IMMEDIATE) | BIND_NONFATAL | BIND_VERBOSE, 0);
    if (!shl_handle) err = strerror(errno);
    else handle = shl_handle;
#endif
  } else {
    handle = 0;
    err = "Empty Filename given.";
  }
}

/* @Method{void DLL::close()}
 *
 * @Description{close the library}
 */
void DLL::close()
{
#if 1
  if (handle) dlclose(handle);
#else /* _aix_ */
  if (handle) shl_unload (reinterpret_cast<shl_t>(handle));
#endif
  handle = 0;
}

/* @Method{void *DLL::resolve(const string &symbol)}
 *
 * @Description{return a reference to an object with name @var{symbol}}
 */
void *DLL::resolve(const string &symbol)
{
  if (!handle) return 0;
#if 1
  void *tmp = dlsym(handle, symbol.c_str());
  if (!tmp) err = dlerror();
#else /* _aix_ */
  void *tmp;
  if (shl_findsym (reinterpret_cast<shl_t *>(&handle), symbol.c_str(), TYPE_UNDEFINED, &tmp) != 0 || handle == 0 || tmp == 0)
    err = strerror(errno);
#endif
  return tmp;
};
<|endoftext|>


<commit_before>#include "TestReporterStdout.h"
#include <cstdio>

#include "TestDetails.h"

// cstdio doesn't pull in namespace std on VC6, so we do it here.
#if defined(UNITTEST_WIN32) && (_MSC_VER == 1200)
	namespace std {}
#endif

namespace UnitTest {

void TestReporterStdout::ReportFailure(TestDetails const& details, char const* failure)
{
#if defined(__APPLE__) || defined(__GNUG__)
    char const* const errorFormat = "%s:%d:%d: error: Failure in %s: %s\n";
#else
    char const* const errorFormat = "%s(%d): error: Failure in %s: %s\n";
#endif

	using namespace std;
    fprintf(stderr, errorFormat, details.filename, details.lineNumber, details.testName, failure);
}

void TestReporterStdout::ReportTestStart(TestDetails const& /*test*/)
{
}

void TestReporterStdout::ReportTestFinish(TestDetails const& /*test*/, float)
{
}

void TestReporterStdout::ReportSummary(int const totalTestCount, int const failedTestCount,
                                       int const failureCount, float const secondsElapsed)
{
	using namespace std;

    if (failureCount > 0)
        printf("FAILURE: %d out of %d tests failed (%d failures).\n", failedTestCount, totalTestCount, failureCount);
    else
        printf("Success: %d tests passed.\n", totalTestCount);

    printf("Test time: %.2f seconds.\n", secondsElapsed);
}

}
<commit_msg>- fixed (?) crash on Mac if test fails<commit_after>#include "TestReporterStdout.h"
#include <cstdio>

#include "TestDetails.h"

// cstdio doesn't pull in namespace std on VC6, so we do it here.
#if defined(UNITTEST_WIN32) && (_MSC_VER == 1200)
	namespace std {}
#endif

namespace UnitTest {

void TestReporterStdout::ReportFailure(TestDetails const& details, char const* failure)
{
#if defined(__APPLE__) || defined(__GNUG__)
    char const* const errorFormat = "%s:%d: error: Failure in %s: %s\n";
#else
    char const* const errorFormat = "%s(%d): error: Failure in %s: %s\n";
#endif

	using namespace std;
    fprintf(stderr, errorFormat, details.filename, details.lineNumber, details.testName, failure);
}

void TestReporterStdout::ReportTestStart(TestDetails const& /*test*/)
{
}

void TestReporterStdout::ReportTestFinish(TestDetails const& /*test*/, float)
{
}

void TestReporterStdout::ReportSummary(int const totalTestCount, int const failedTestCount,
                                       int const failureCount, float const secondsElapsed)
{
	using namespace std;

    if (failureCount > 0)
        printf("FAILURE: %d out of %d tests failed (%d failures).\n", failedTestCount, totalTestCount, failureCount);
    else
        printf("Success: %d tests passed.\n", totalTestCount);

    printf("Test time: %.2f seconds.\n", secondsElapsed);
}

}
<|endoftext|>


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

/*
 * XSEC
 *
 * DSIGTransformXSL := Class that Handles DSIG XSLT Transforms
 *
 * $Id$
 *
 */

// XSEC

#include <xsec/dsig/DSIGTransformXSL.hpp>
#include <xsec/dsig/DSIGSignature.hpp>
#include <xsec/transformers/TXFMXSL.hpp>
#include <xsec/transformers/TXFMC14n.hpp>
#include <xsec/transformers/TXFMChain.hpp>
#include <xsec/framework/XSECException.hpp>
#include <xsec/framework/XSECEnv.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
#include <xsec/framework/XSECError.hpp>

XERCES_CPP_NAMESPACE_USE

// --------------------------------------------------------------------------------
//           Constructors and Destructors
// --------------------------------------------------------------------------------

DSIGTransformXSL::DSIGTransformXSL(const XSECEnv * env, DOMNode * node) :
DSIGTransform(env, node),
mp_stylesheetNode(NULL) {};

DSIGTransformXSL::DSIGTransformXSL(const XSECEnv * env) :
DSIGTransform(env),
mp_stylesheetNode(NULL) {};

DSIGTransformXSL::~DSIGTransformXSL() {};

// --------------------------------------------------------------------------------
//           Interface Methods
// --------------------------------------------------------------------------------

transformType DSIGTransformXSL::getTransformType() {

	return TRANSFORM_XSLT;

}

void DSIGTransformXSL::appendTransformer(TXFMChain * input) {

#ifdef XSEC_NO_XSLT

	throw XSECException(XSECException::UnsupportedFunction,
		"XSLT Transforms not supported in this compilation of the library");
#else

	if (mp_stylesheetNode == 0)
		throw XSECException(XSECException::XSLError, "Style Sheet not found for XSL Transform");

	TXFMBase * nextInput;

	// XSLT Transform - requires a byte stream input

	if (input->getLastTxfm()->getOutputType() == TXFMBase::DOM_NODES) {

		// Use c14n to translate to BYTES

		XSECnew(nextInput, TXFMC14n(mp_txfmNode->getOwnerDocument()));
		input->appendTxfm(nextInput);
	}

	TXFMXSL * x;

	// Create the XSLT transform
	XSECnew(x, TXFMXSL(mp_txfmNode->getOwnerDocument()));
	input->appendTxfm(x);

	// Again use C14n (convenient) to translate to a SafeBuffer

	XSECC14n20010315 c14n(mp_txfmNode->getOwnerDocument(), mp_stylesheetNode);
	safeBuffer sbStyleSheet;
	unsigned int size, count;
	unsigned char buf[512];
	size = 0;

	while ((count = c14n.outputBuffer(buf, 512)) != 0) {

		sbStyleSheet.sbMemcpyIn(size, buf, count);
		size += count;

	}

	sbStyleSheet[size] = '\0';		// Terminate as though a string

	x->evaluateStyleSheet(sbStyleSheet);

#endif /* NO_XSLT */

}

DOMElement * DSIGTransformXSL::createBlankTransform(DOMDocument * parentDoc) {

	safeBuffer str;
	const XMLCh * prefix;
	DOMElement *ret;
	DOMDocument *doc = mp_env->getParentDocument();

	prefix = mp_env->getDSIGNSPrefix();

	// Create the transform node
	makeQName(str, prefix, "Transform");
	ret = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer());
	ret->setAttributeNS(NULL,DSIGConstants::s_unicodeStrAlgorithm, DSIGConstants::s_unicodeStrURIXSLT);

	mp_txfmNode = ret;
	mp_stylesheetNode = NULL;

	return ret;

}

void DSIGTransformXSL::load(void) {

	// find the style sheet
	mp_stylesheetNode = mp_txfmNode->getFirstChild();
	while (mp_stylesheetNode != 0 &&
		mp_stylesheetNode->getNodeType() != DOMNode::ELEMENT_NODE && !strEquals(mp_stylesheetNode->getNodeName(), "xsl:stylesheet"))
		mp_stylesheetNode = mp_stylesheetNode->getNextSibling();

	if (mp_stylesheetNode == 0)
		throw XSECException(XSECException::XSLError, "Style Sheet not found for XSL Transform");

}
// --------------------------------------------------------------------------------
//           XSLT Specific Methods
// --------------------------------------------------------------------------------

DOMNode * DSIGTransformXSL::setStylesheet(DOMNode * stylesheet) {

	DOMNode * ret = mp_stylesheetNode;

	if (mp_stylesheetNode) {
		mp_txfmNode->insertBefore(stylesheet, mp_stylesheetNode);
		mp_txfmNode->removeChild(mp_stylesheetNode);
	}
	else {
	    mp_txfmNode->appendChild(stylesheet);
	}

	mp_stylesheetNode = stylesheet;

	return ret;

}

DOMNode * DSIGTransformXSL::getStylesheet(void) {

	return mp_stylesheetNode;

}
<commit_msg>https://issues.apache.org/bugzilla/show_bug.cgi?id=49257<commit_after>/*
 * Copyright 2002-2010 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * XSEC
 *
 * DSIGTransformXSL := Class that Handles DSIG XSLT Transforms
 *
 * $Id$
 *
 */

// XSEC

#include <xsec/dsig/DSIGTransformXSL.hpp>
#include <xsec/dsig/DSIGSignature.hpp>
#include <xsec/transformers/TXFMXSL.hpp>
#include <xsec/transformers/TXFMC14n.hpp>
#include <xsec/transformers/TXFMChain.hpp>
#include <xsec/framework/XSECException.hpp>
#include <xsec/framework/XSECEnv.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
#include <xsec/framework/XSECError.hpp>

XERCES_CPP_NAMESPACE_USE

// --------------------------------------------------------------------------------
//           Constructors and Destructors
// --------------------------------------------------------------------------------

DSIGTransformXSL::DSIGTransformXSL(const XSECEnv * env, DOMNode * node) :
DSIGTransform(env, node),
mp_stylesheetNode(NULL) {};

DSIGTransformXSL::DSIGTransformXSL(const XSECEnv * env) :
DSIGTransform(env),
mp_stylesheetNode(NULL) {};

DSIGTransformXSL::~DSIGTransformXSL() {};

// --------------------------------------------------------------------------------
//           Interface Methods
// --------------------------------------------------------------------------------

transformType DSIGTransformXSL::getTransformType() {

	return TRANSFORM_XSLT;

}

void DSIGTransformXSL::appendTransformer(TXFMChain * input) {

#ifdef XSEC_NO_XSLT

	throw XSECException(XSECException::UnsupportedFunction,
		"XSLT Transforms not supported in this compilation of the library");
#else

	if (mp_stylesheetNode == 0)
		throw XSECException(XSECException::XSLError, "Style Sheet not found for XSL Transform");

	TXFMBase * nextInput;

	// XSLT Transform - requires a byte stream input

	if (input->getLastTxfm()->getOutputType() == TXFMBase::DOM_NODES) {

		// Use c14n to translate to BYTES

		XSECnew(nextInput, TXFMC14n(mp_txfmNode->getOwnerDocument()));
		input->appendTxfm(nextInput);
	}

	TXFMXSL * x;

	// Create the XSLT transform
	XSECnew(x, TXFMXSL(mp_txfmNode->getOwnerDocument()));
	input->appendTxfm(x);

	// Again use C14n (convenient) to translate to a SafeBuffer

	XSECC14n20010315 c14n(mp_txfmNode->getOwnerDocument(), mp_stylesheetNode);
	safeBuffer sbStyleSheet;
	unsigned int size, count;
	unsigned char buf[512];
	size = 0;

	while ((count = c14n.outputBuffer(buf, 512)) != 0) {

		sbStyleSheet.sbMemcpyIn(size, buf, count);
		size += count;

	}

	sbStyleSheet[size] = '\0';		// Terminate as though a string

	x->evaluateStyleSheet(sbStyleSheet);

#endif /* NO_XSLT */

}

DOMElement * DSIGTransformXSL::createBlankTransform(DOMDocument * parentDoc) {

	safeBuffer str;
	const XMLCh * prefix;
	DOMElement *ret;
	DOMDocument *doc = mp_env->getParentDocument();

	prefix = mp_env->getDSIGNSPrefix();

	// Create the transform node
	makeQName(str, prefix, "Transform");
	ret = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer());
	ret->setAttributeNS(NULL,DSIGConstants::s_unicodeStrAlgorithm, DSIGConstants::s_unicodeStrURIXSLT);

	mp_txfmNode = ret;
	mp_stylesheetNode = NULL;

	return ret;

}

void DSIGTransformXSL::load(void) {

	// find the style sheet
	mp_stylesheetNode = mp_txfmNode->getFirstChild();
	while (mp_stylesheetNode != 0 &&
		mp_stylesheetNode->getNodeType() != DOMNode::ELEMENT_NODE && !strEquals(mp_stylesheetNode->getNodeName(), "xsl:stylesheet"))
		mp_stylesheetNode = mp_stylesheetNode->getNextSibling();

	if (mp_stylesheetNode == 0)
		throw XSECException(XSECException::XSLError, "Style Sheet not found for XSL Transform");

}
// --------------------------------------------------------------------------------
//           XSLT Specific Methods
// --------------------------------------------------------------------------------

DOMNode * DSIGTransformXSL::setStylesheet(DOMNode * stylesheet) {

	DOMNode * ret = mp_stylesheetNode;

	if (mp_stylesheetNode) {
	    if (stylesheet)
	        mp_txfmNode->insertBefore(stylesheet, mp_stylesheetNode);
		mp_txfmNode->removeChild(mp_stylesheetNode);
	}
	else if (stylesheet) {
	    mp_txfmNode->appendChild(stylesheet);
	}

	mp_stylesheetNode = stylesheet;

	return ret;

}

DOMNode * DSIGTransformXSL::getStylesheet(void) {

	return mp_stylesheetNode;

}
<|endoftext|>


<commit_before>#include "Deck.h"

Deck::Deck()
{
    for (size_t i = 1; i <= 52; i++)
    {
        int k = 0;
        switch(i/4)
        {
            case 0: k = 13;
                break;
            case 1: k = 14;
                break;
            default: k = i/4;
        }

        cards.push_back(Card((k/4),Suit(i%4)));
    }

}

void Deck::Display()
{
    for(Card card : cards)
    {
        card.Display();
        std::cout << " ";
        if (card.get == Card::KING)
            std::cout << "\n";
    }
}<commit_msg>fixed build<commit_after>#include "Deck.h"

Deck::Deck()
{
    for (size_t i = 1; i <= 52; i++)
    {
        cards.push_back(Card(11, SPADES));
    }

}

void Deck::Display()
{
    for(Card card : cards)
    {
        card.Display();
        std::cout << " ";
        if (card.GetValue() == Card::KING)
            std::cout << "\n";
    }
}<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 HTTP_REQUEST_LINE_HPP
#define HTTP_REQUEST_LINE_HPP

#include <cctype>
#include <regex>
#include "common.hpp"
#include "methods.hpp"
#include "version.hpp"

namespace http {

//-----------------------------------
// This class represents the request-line
// of an incoming http request message
//-----------------------------------
class Request_Line {
public:
  //-----------------------------------
  // Constructor to create a default
  // request-line which is as follows:
  //
  // <GET / HTTP/1.1>
  //-----------------------------------
  explicit Request_Line() = default;

  //-----------------------------------
  // Constructor to construct a request-line
  // from the incoming character stream of
  // data which is a <std::string> object
  //
  // @tparam (std::string) request - The character stream of
  //                                 data
  //-----------------------------------
  template <typename Request>
  explicit Request_Line(Request&& request);

  // Copy / move constructors
  Request_Line(Request_Line&) = default;
  Request_Line(Request_Line&&) = default;
  ~Request_Line() noexcept = default;
  Request_Line& operator = (Request_Line&) = default;
  Request_Line& operator = (Request_Line&&) = default;

  //-----------------------------------
  // Get the method of the message
  //
  // @return - The method of the message
  //-----------------------------------
  const Method& get_method() const noexcept;

  //-----------------------------------
  // Set the method of the message
  //
  // @param method - The method of the message
  //-----------------------------------
  void set_method(const Method& method);

  //-----------------------------------
  // Get the URI of the message
  //
  // @return - The URI of the message
  //-----------------------------------
  const URI& get_uri() const noexcept;

  //-----------------------------------
  // Set the URI of the message
  //
  // @param uri - The URI of the message
  //-----------------------------------
  void set_uri(const URI& uri);

  //-----------------------------------
  // Get the version of the message
  //
  // @return - The version of the message
  //-----------------------------------
  const Version& get_version() const noexcept;

  //-----------------------------------
  // Set the version of the message
  //
  // @param version - The version of the message
  //-----------------------------------
  void set_version(const Version& version) noexcept;

  //-----------------------------------
  // Get a string representation of this
  // class
  //
  // @return - A string representation
  //-----------------------------------
  std::string to_string() const;

  //-----------------------------------
  // Operator to transform this class
  // into string form
  //-----------------------------------
  operator std::string () const;
  //-----------------------------------
private:
  //-----------------------------------
  // Class data members
  //-----------------------------------
  Method  method_  { GET };
  URI     uri_     {"/"};
  Version version_ {1U, 1U};
}; //< class Request_Line

  class Request_line_error : public std::runtime_error {
    using runtime_error::runtime_error;
  };

/**--v----------- Implementation Details -----------v--**/

template <typename Request>
inline Request_Line::Request_Line(Request&& request) {
  if (request.empty() or request.size() < 15 /*<-(15) minimum request length */) {
    throw Request_line_error("Invalid request line: " + request_line);
  }

  // Extract HTTP method
  std::string request_line;
  std::size_t index;

  if ((index = request.find("\r\n")) != std::string::npos) {
    request_line = {request.substr(0, index)};
  } else if ((index = request.find('\n')) != std::string::npos) {
    request_line = {request.substr(0, index)};
  } else {
    throw Request_line_error("Invalid line-ending");
  }

  // Should identify strings according to RFC 2616 sect.5.1
  // https://tools.ietf.org/html/rfc2616#section-5.1
  std::regex re_request_line {
    "\\s*(GET|POST|PUT|DELETE|OPTIONS|HEAD|TRACE|CONNECT) " // Method
      "(\\S+) " // URI
      "HTTP/(\\d+)\\.(\\d+)" // Version Major.Minor
      };

  std::smatch m;
  auto matched = std::regex_match(request_line,m, re_request_line);

  if (not matched)
    throw Request_line_error("Invalid request line: " + request_line);

  method_ = method::code(m[1]);
  //uri_ = URI {m[2]};
  new (&uri_) URI(m[2]);
  unsigned maj = static_cast<unsigned>(std::stoul(m[3]));
  unsigned min = static_cast<unsigned>(std::stoul(m[4]));
  version_ = Version{maj, min};

  // Trim the request for further processing
  request = request.substr(request.find("\r\n") + 2);
}

inline const Method& Request_Line::get_method() const noexcept {
  return method_;
}

inline void Request_Line::set_method(const Method& method) {
  method_ = method;
}

inline const URI& Request_Line::get_uri() const noexcept {
  return uri_;
}

inline void Request_Line::set_uri(const URI& uri) {
  //uri_ = uri;
  new (&uri_) URI(uri);
}

inline const Version& Request_Line::get_version() const noexcept {
  return version_;
}

inline void Request_Line::set_version(const Version& version) noexcept {
  version_ = version;
}

inline std::string Request_Line::to_string() const {
  return method::str(method_)+" "+uri_.to_string()+" "
    +version_.to_string();
}

inline Request_Line::operator std::string () const {
  std::ostringstream req_line;
  //-----------------------------
  req_line << method_  << " "
           << uri_     << " "
           << version_ << "\r\n";
 //------------------------------
  return req_line.str();
}

inline std::ostream& operator << (std::ostream& output_device, const Request_Line& req_line) {
  return output_device << req_line.to_string();
}

/**--^----------- Implementation Details -----------^--**/

} //< namespace http

#endif //< HTTP_REQUEST_LINE_HPP
<commit_msg>Refer to already found index<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 HTTP_REQUEST_LINE_HPP
#define HTTP_REQUEST_LINE_HPP

#include <cctype>
#include <regex>
#include "common.hpp"
#include "methods.hpp"
#include "version.hpp"

namespace http {

//-----------------------------------
// This class represents the request-line
// of an incoming http request message
//-----------------------------------
class Request_Line {
public:
  //-----------------------------------
  // Constructor to create a default
  // request-line which is as follows:
  //
  // <GET / HTTP/1.1>
  //-----------------------------------
  explicit Request_Line() = default;

  //-----------------------------------
  // Constructor to construct a request-line
  // from the incoming character stream of
  // data which is a <std::string> object
  //
  // @tparam (std::string) request - The character stream of
  //                                 data
  //-----------------------------------
  template <typename Request>
  explicit Request_Line(Request&& request);

  // Copy / move constructors
  Request_Line(Request_Line&) = default;
  Request_Line(Request_Line&&) = default;
  ~Request_Line() noexcept = default;
  Request_Line& operator = (Request_Line&) = default;
  Request_Line& operator = (Request_Line&&) = default;

  //-----------------------------------
  // Get the method of the message
  //
  // @return - The method of the message
  //-----------------------------------
  const Method& get_method() const noexcept;

  //-----------------------------------
  // Set the method of the message
  //
  // @param method - The method of the message
  //-----------------------------------
  void set_method(const Method& method);

  //-----------------------------------
  // Get the URI of the message
  //
  // @return - The URI of the message
  //-----------------------------------
  const URI& get_uri() const noexcept;

  //-----------------------------------
  // Set the URI of the message
  //
  // @param uri - The URI of the message
  //-----------------------------------
  void set_uri(const URI& uri);

  //-----------------------------------
  // Get the version of the message
  //
  // @return - The version of the message
  //-----------------------------------
  const Version& get_version() const noexcept;

  //-----------------------------------
  // Set the version of the message
  //
  // @param version - The version of the message
  //-----------------------------------
  void set_version(const Version& version) noexcept;

  //-----------------------------------
  // Get a string representation of this
  // class
  //
  // @return - A string representation
  //-----------------------------------
  std::string to_string() const;

  //-----------------------------------
  // Operator to transform this class
  // into string form
  //-----------------------------------
  operator std::string () const;
  //-----------------------------------
private:
  //-----------------------------------
  // Class data members
  //-----------------------------------
  Method  method_  { GET };
  URI     uri_     {"/"};
  Version version_ {1U, 1U};
}; //< class Request_Line

  class Request_line_error : public std::runtime_error {
    using runtime_error::runtime_error;
  };

/**--v----------- Implementation Details -----------v--**/

template <typename Request>
inline Request_Line::Request_Line(Request&& request) {
  if (request.empty() or request.size() < 15 /*<-(15) minimum request length */) {
    throw Request_line_error("Invalid request line: " + request_line);
  }

  // Extract HTTP method
  std::string request_line;
  std::size_t index;

  if ((index = request.find("\r\n")) != std::string::npos) {
    request_line = {request.substr(0, index)};
  } else if ((index = request.find('\n')) != std::string::npos) {
    request_line = {request.substr(0, index)};
  } else {
    throw Request_line_error("Invalid line-ending");
  }

  // Should identify strings according to RFC 2616 sect.5.1
  // https://tools.ietf.org/html/rfc2616#section-5.1
  std::regex re_request_line {
    "\\s*(GET|POST|PUT|DELETE|OPTIONS|HEAD|TRACE|CONNECT) " // Method
      "(\\S+) " // URI
      "HTTP/(\\d+)\\.(\\d+)" // Version Major.Minor
      };

  std::smatch m;
  auto matched = std::regex_match(request_line,m, re_request_line);

  if (not matched)
    throw Request_line_error("Invalid request line: " + request_line);

  method_ = method::code(m[1]);
  //uri_ = URI {m[2]};
  new (&uri_) URI(m[2]);
  unsigned maj = static_cast<unsigned>(std::stoul(m[3]));
  unsigned min = static_cast<unsigned>(std::stoul(m[4]));
  version_ = Version{maj, min};

  // Trim the request for further processing
  request = request.substr(index + 2);
}

inline const Method& Request_Line::get_method() const noexcept {
  return method_;
}

inline void Request_Line::set_method(const Method& method) {
  method_ = method;
}

inline const URI& Request_Line::get_uri() const noexcept {
  return uri_;
}

inline void Request_Line::set_uri(const URI& uri) {
  //uri_ = uri;
  new (&uri_) URI(uri);
}

inline const Version& Request_Line::get_version() const noexcept {
  return version_;
}

inline void Request_Line::set_version(const Version& version) noexcept {
  version_ = version;
}

inline std::string Request_Line::to_string() const {
  return method::str(method_)+" "+uri_.to_string()+" "
    +version_.to_string();
}

inline Request_Line::operator std::string () const {
  std::ostringstream req_line;
  //-----------------------------
  req_line << method_  << " "
           << uri_     << " "
           << version_ << "\r\n";
 //------------------------------
  return req_line.str();
}

inline std::ostream& operator << (std::ostream& output_device, const Request_Line& req_line) {
  return output_device << req_line.to_string();
}

/**--^----------- Implementation Details -----------^--**/

} //< namespace http

#endif //< HTTP_REQUEST_LINE_HPP
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 HTTP_REQUEST_LINE_HPP
#define HTTP_REQUEST_LINE_HPP

#include <cctype>

#include "common.hpp"
#include "methods.hpp"
#include "version.hpp"

namespace http {

//-----------------------------------
// This class represents the request-line
// of an incoming http request message
//-----------------------------------
class Request_Line {
public:
  //-----------------------------------
  // Constructor to create a default
  // request-line which is as follows:
  //
  // <GET / HTTP/1.1>
  //-----------------------------------
  explicit Request_Line() = default;

  //-----------------------------------
  // Constructor to construct a request-line
  // from the incoming character stream of
  // data which is a <std::string> object
  //
  // @tparam (std::string) request - The character stream of
  //                                 data
  //-----------------------------------
  template <typename Request>
  explicit Request_Line(Request&& request);

  //-----------------------------------
  // Default copy constructor
  //-----------------------------------
  Request_Line(const Request_Line&) = default;

  //-----------------------------------
  // Default move constructor
  //-----------------------------------
  Request_Line(Request_Line&&) = default;

  //-----------------------------------
  // Default destructor
  //-----------------------------------
  ~Request_Line() noexcept = default;

  //-----------------------------------
  // Default copy assignment operator
  //-----------------------------------
  Request_Line& operator = (const Request_Line&) = default;

  //-----------------------------------
  // Default move assignment operator
  //-----------------------------------
  Request_Line& operator = (Request_Line&&) = default;

  //-----------------------------------
  // Get the method of the message
  //
  // @return - The method of the message
  //-----------------------------------
  const Method& get_method() const noexcept;

  //-----------------------------------
  // Set the method of the message
  //
  // @param method - The method of the message
  //-----------------------------------
  void set_method(const Method& method);

  //-----------------------------------
  // Get the URI of the message
  //
  // @return - The URI of the message
  //-----------------------------------
  const URI& get_uri() const noexcept;

  //-----------------------------------
  // Set the URI of the message
  //
  // @param uri - The URI of the message
  //-----------------------------------
  void set_uri(const URI& uri);

  //-----------------------------------
  // Get the version of the message
  //
  // @return - The version of the message
  //-----------------------------------
  const Version& get_version() const noexcept;

  //-----------------------------------
  // Set the version of the message
  //
  // @param version - The version of the message
  //-----------------------------------
  void set_version(const Version& version) noexcept;

  //-----------------------------------
  // Get a string representation of this
  // class
  //
  // @return - A string representation
  //-----------------------------------
  std::string to_string() const;

  //-----------------------------------
  // Operator to transform this class
  // into string form
  //-----------------------------------
  operator std::string () const;
  //-----------------------------------
private:
  //-----------------------------------
  // Class data members
  //-----------------------------------
  Method  method_  {method::GET};
  URI     uri_     {"/"};
  Version version_ {1U, 1U};
}; //< class Request_Line

/**--v----------- Implementation Details -----------v--**/

template <typename Request>
inline Request_Line::Request_Line(Request&& request) {
  if (request.empty() or request.size() < 16 /*<-(16) minimum request length */) {
    return;
  }
  //-----------------------------------
  std::string start {request.substr(request.find_first_not_of("\f\t\v "))};
  //-----------------------------------
  std::string rl {start.substr(0, start.find("\r\n"))};
  //-----------------------------------
  method_ = rl.substr(0, rl.find_first_of(" "));
  //-----------------------------------
  rl = rl.substr(rl.find_first_of(" ") + 1);
  //-----------------------------------
  uri_ = rl.substr(0, rl.find_last_of(" "));
  //-----------------------------------
  rl = rl.substr(rl.find_last_of(" ") + 1);
  //-----------------------------------
  std::string major {rl.substr(rl.find("/") + 1, rl.find("."))};
  std::string minor {rl.substr(rl.find(".") + 1)};
  //-----------------------------------
  unsigned maj = static_cast<unsigned>(std::stoul(major));
  unsigned min = static_cast<unsigned>(std::stoul(minor));
  //-----------------------------------
  version_ = Version{maj, min};
  //-----------------------------------
  request = request.substr(request.find("\r\n") + 2);
}

inline const Method& Request_Line::get_method() const noexcept {
  return method_;
}

inline void Request_Line::set_method(const Method& method) {
  method_ = method;
}

inline const URI& Request_Line::get_uri() const noexcept {
  return uri_;
}

inline void Request_Line::set_uri(const URI& uri) {
  uri_ = uri;
}

inline const Version& Request_Line::get_version() const noexcept {
  return version_;
}

inline void Request_Line::set_version(const Version& version) noexcept {
  version_ = version;
}

inline std::string Request_Line::to_string() const {
  return *this;
}

inline Request_Line::operator std::string () const {
  std::ostringstream req_line;
  //-----------------------------
  req_line << method_  << " "
           << uri_     << " "
           << version_ << "\r\n";
 //------------------------------
  return req_line.str();
}

inline std::ostream& operator << (std::ostream& output_device, const Request_Line& req_line) {
  return output_device << req_line.to_string();
}

/**--^----------- Implementation Details -----------^--**/

} //< namespace http

#endif //< HTTP_REQUEST_LINE_HPP
<commit_msg>Detecting request-line using std::regex<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 HTTP_REQUEST_LINE_HPP
#define HTTP_REQUEST_LINE_HPP

#include <cctype>

#include "common.hpp"
#include "methods.hpp"
#include "version.hpp"

namespace http {

//-----------------------------------
// This class represents the request-line
// of an incoming http request message
//-----------------------------------
class Request_Line {
public:
  //-----------------------------------
  // Constructor to create a default
  // request-line which is as follows:
  //
  // <GET / HTTP/1.1>
  //-----------------------------------
  explicit Request_Line() = default;

  //-----------------------------------
  // Constructor to construct a request-line
  // from the incoming character stream of
  // data which is a <std::string> object
  //
  // @tparam (std::string) request - The character stream of
  //                                 data
  //-----------------------------------
  template <typename Request>
  explicit Request_Line(Request&& request);

  // Copy / move constructors
  Request_Line(Request_Line&) = default;
  Request_Line(Request_Line&&) = default;
  ~Request_Line() noexcept = default;
  Request_Line& operator = (Request_Line&) = default;
  Request_Line& operator = (Request_Line&&) = default;

  //-----------------------------------
  // Get the method of the message
  //
  // @return - The method of the message
  //-----------------------------------
  const Method& get_method() const noexcept;

  //-----------------------------------
  // Set the method of the message
  //
  // @param method - The method of the message
  //-----------------------------------
  void set_method(const Method& method);

  //-----------------------------------
  // Get the URI of the message
  //
  // @return - The URI of the message
  //-----------------------------------
  const URI& get_uri() const noexcept;

  //-----------------------------------
  // Set the URI of the message
  //
  // @param uri - The URI of the message
  //-----------------------------------
  void set_uri(const URI& uri);

  //-----------------------------------
  // Get the version of the message
  //
  // @return - The version of the message
  //-----------------------------------
  const Version& get_version() const noexcept;

  //-----------------------------------
  // Set the version of the message
  //
  // @param version - The version of the message
  //-----------------------------------
  void set_version(const Version& version) noexcept;

  //-----------------------------------
  // Get a string representation of this
  // class
  //
  // @return - A string representation
  //-----------------------------------
  std::string to_string() const;

  //-----------------------------------
  // Operator to transform this class
  // into string form
  //-----------------------------------
  operator std::string () const;
  //-----------------------------------
private:
  //-----------------------------------
  // Class data members
  //-----------------------------------
  Method  method_  { GET };
  URI     uri_     {"/"};
  Version version_ {1U, 1U};
}; //< class Request_Line

  class Request_line_error : public std::runtime_error {
    using runtime_error::runtime_error;
  };

/**--v----------- Implementation Details -----------v--**/

template <typename Request>
inline Request_Line::Request_Line(Request&& request) {
  if (request.empty() or request.size() < 16 /*<-(16) minimum request length */) {
    return;
  }

  // Extract HTTP method
  std::string request_line = {request.substr(0, request.find("\r\n"))};

  // Should identify strings according to RFC 2616 sect.5.1
  // https://tools.ietf.org/html/rfc2616#section-5.1
  std::regex re_request_line {
    "\\s*(GET|POST|PUT|DELETE|OPTIONS|HEAD|TRACE|CONNECT) " // Method
      "(\\S+) " // URI
      "HTTP/(\\d+)\\.(\\d+)" // Version Major.Minor
      };

  std::smatch m;
  auto matched = std::regex_match(request_line,m, re_request_line);

  if (not matched)
    throw Request_line_error("Invalid request line: " + request_line);

  method_ = method::code(m[1]);
  uri_ = URI {m[2]};
  unsigned maj = static_cast<unsigned>(std::stoul(m[3]));
  unsigned min = static_cast<unsigned>(std::stoul(m[4]));
  version_ = Version{maj, min};

  // Trim the request for further processing
  request = request.substr(request.find("\r\n") + 2);
}

inline const Method& Request_Line::get_method() const noexcept {
  return method_;
}

inline void Request_Line::set_method(const Method& method) {
  method_ = method;
}

inline const URI& Request_Line::get_uri() const noexcept {
  return uri_;
}

inline void Request_Line::set_uri(const URI& uri) {
  uri_ = uri;
}

inline const Version& Request_Line::get_version() const noexcept {
  return version_;
}

inline void Request_Line::set_version(const Version& version) noexcept {
  version_ = version;
}

inline std::string Request_Line::to_string() const {
  return *this;
}

inline Request_Line::operator std::string () const {
  std::ostringstream req_line;
  //-----------------------------
  req_line << method_  << " "
           << uri_     << " "
           << version_ << "\r\n";
 //------------------------------
  return req_line.str();
}

inline std::ostream& operator << (std::ostream& output_device, const Request_Line& req_line) {
  return output_device << req_line.to_string();
}

/**--^----------- Implementation Details -----------^--**/

} //< namespace http

#endif //< HTTP_REQUEST_LINE_HPP
<|endoftext|>


<commit_before>#include "digitankswindow.h"

#include <sound/sound.h>
#include "glgui/glgui.h"
#include "digitanks/digitanksgame.h"
#include "instructor.h"
#include "hud.h"
#include "ui.h"
#include <game/digitanks/structures/cpu.h>
#include <game/digitanks/dt_camera.h>
#include <renderer/renderer.h>
#include <renderer/dissolver.h>
#include <tinker/keys.h>

void CDigitanksWindow::MouseMotion(int x, int y)
{
	glgui::CRootPanel::Get()->CursorMoved(x, y);

	if (DigitanksGame() && DigitanksGame()->GetGameType() == GAMETYPE_MENU)
		return;

	if (GameServer() && GameServer()->GetCamera())
		GameServer()->GetCamera()->MouseInput(x, y);

	if (IsMouseRightDown())
		m_iMouseMoved += (int)(fabs((float)x-m_iMouseLastX) + fabs((float)y-m_iMouseLastY));

	if (IsMouseLeftDown())
	{
		m_iMouseCurrentX = x;
		m_iMouseCurrentY = y;
	}

	m_iMouseLastX = x;
	m_iMouseLastY = y;
}

void CDigitanksWindow::MouseInput(int iButton, int iState)
{
	if (GameServer() && GameServer()->GetCamera())
	{
		// MouseButton enables camera rotation, so don't send the signal if the feature is disabled.
		if (!m_pInstructor->IsFeatureDisabled(DISABLE_ROTATE))
			GameServer()->GetCamera()->MouseButton(iButton, iState);
	}

	int mx, my;
	GetMousePosition(mx, my);
	if (iState == 1)
	{
		if (glgui::CRootPanel::Get()->MousePressed(iButton, mx, my))
		{
			m_bMouseDownInGUI = true;
			return;
		}
		else
			m_bMouseDownInGUI = false;
	}
	else
	{
		if (glgui::CRootPanel::Get()->MouseReleased(iButton, mx, my))
			return;

		if (m_bMouseDownInGUI)
		{
			m_bMouseDownInGUI = false;
			return;
		}
	}

	if (!DigitanksGame())
		return;

	if (DigitanksGame()->GetGameType() == GAMETYPE_MENU)
		return;

	Vector vecMousePosition;
	CBaseEntity* pClickedEntity = NULL;
	GetMouseGridPosition(vecMousePosition, &pClickedEntity);
	GetMouseGridPosition(vecMousePosition, NULL, CG_TERRAIN);

	if (DigitanksGame()->GetControlMode() != MODE_NONE && iButton == TINKER_KEY_MOUSE_LEFT && iState == 1)
	{
		// While aiming moving turning or building, either mouse button can be used and selections are disabled.

		if (DigitanksGame()->GetControlMode() == MODE_MOVE)
			DigitanksGame()->MoveTanks();
		else if (DigitanksGame()->GetControlMode() == MODE_TURN)
			DigitanksGame()->TurnTanks(vecMousePosition);
		else if (DigitanksGame()->GetControlMode() == MODE_AIM)
		{
			DigitanksGame()->FireTanks();
			GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_ATTACK);
		}
		else if (DigitanksGame()->GetControlMode() == MODE_BUILD)
		{
			if (DigitanksGame()->GetCurrentLocalDigitanksTeam())
			{
				CCPU* pCPU = DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetPrimaryCPU();
				if (pCPU && pCPU->IsPreviewBuildValid())
				{
					pCPU->BeginConstruction();
					DigitanksGame()->SetControlMode(MODE_NONE);
				}
			}
		}

		GetHUD()->SetupMenu();

		if (iState == 1)
			// Don't allow the release to take any action either.
			m_bMouseDownInGUI = true;

		return;
	}

	if (iButton == TINKER_KEY_MOUSE_RIGHT)
	{
		if (iState == 1)
			m_iMouseMoved = 0;
		else
		{
			if (m_iMouseMoved > 30)
				GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_TURNCAMERA);
		}
	}

	if (iButton == TINKER_KEY_MOUSE_LEFT)
	{
		if (iState == 1)
		{
			// Prevent UI interactions from affecting the camera target.
			// If the mouse was used no the UI, this will remain false.
			m_bBoxSelect = true;
			m_iMouseInitialX = m_iMouseCurrentX = mx;
			m_iMouseInitialY = m_iMouseCurrentY = my;
		}
	}

	if (iState == 0 && iButton == TINKER_KEY_MOUSE_LEFT)
	{
		if (m_bBoxSelect && IsMouseDragging())
		{
			if (!IsShiftDown() && DigitanksGame()->GetCurrentLocalDigitanksTeam())
				DigitanksGame()->GetCurrentLocalDigitanksTeam()->SetPrimarySelection(NULL);

			size_t iLowerX = (m_iMouseInitialX < m_iMouseCurrentX) ? m_iMouseInitialX : m_iMouseCurrentX;
			size_t iLowerY = (m_iMouseInitialY < m_iMouseCurrentY) ? m_iMouseInitialY : m_iMouseCurrentY;
			size_t iHigherX = (m_iMouseInitialX > m_iMouseCurrentX) ? m_iMouseInitialX : m_iMouseCurrentX;
			size_t iHigherY = (m_iMouseInitialY > m_iMouseCurrentY) ? m_iMouseInitialY : m_iMouseCurrentY;

			for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++)
			{
				CBaseEntity* pEntity = CBaseEntity::GetEntity(i);
				if (!pEntity)
					continue;

				CSelectable* pSelectable = dynamic_cast<CSelectable*>(pEntity);
				if (!pSelectable)
					continue;

				if (pSelectable->GetVisibility() == 0)
					continue;

				Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(pSelectable->GetOrigin());

				if (vecScreen.x < iLowerX || vecScreen.y < iLowerY || vecScreen.x > iHigherX || vecScreen.y > iHigherY)
					continue;

				if (DigitanksGame()->GetCurrentLocalDigitanksTeam())
					DigitanksGame()->GetCurrentLocalDigitanksTeam()->AddToSelection(pSelectable);
			}

			if (DigitanksGame()->GetCurrentLocalDigitanksTeam() && DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetNumSelected() == 3)
				GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_BOXSELECT);
		}
		else if (pClickedEntity && DigitanksGame()->GetCurrentLocalDigitanksTeam())
		{
			CSelectable* pSelectable = dynamic_cast<CSelectable*>(pClickedEntity);

			if (pSelectable)
			{
				if (IsShiftDown())
					DigitanksGame()->GetCurrentLocalDigitanksTeam()->AddToSelection(pSelectable);
				else
					DigitanksGame()->GetCurrentLocalDigitanksTeam()->SetPrimarySelection(pSelectable);
			}
			else if (!IsShiftDown())
				DigitanksGame()->GetCurrentLocalDigitanksTeam()->SetPrimarySelection(NULL);

			if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetNumSelected() == 3)
				GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_SHIFTSELECT);
		}

		m_bBoxSelect = false;
	}

	GetHUD()->SetupMenu();
}

void CDigitanksWindow::MouseWheel(int iState)
{
	if (DigitanksGame() && DigitanksGame()->GetGameType() == GAMETYPE_MENU)
		return;

	static int iOldState = 0;

	if (GameServer() && GameServer()->GetCamera())
	{
		if (iState > iOldState)
			DigitanksGame()->GetDigitanksCamera()->ZoomIn();
		else
			DigitanksGame()->GetDigitanksCamera()->ZoomOut();
	}

	iOldState = iState;
}

void CDigitanksWindow::KeyPress(int c)
{
	if (glgui::CRootPanel::Get()->KeyPressed(c, IsCtrlDown()))
		return;

	if (DigitanksGame() && DigitanksGame()->GetGameType() == GAMETYPE_MENU)
		return;

	if (c == TINKER_KEY_F4 && IsAltDown())
		exit(0);

	if (DigitanksGame() && (c == TINKER_KEY_ENTER || c == TINKER_KEY_KP_ENTER))
	{
		if (!m_pInstructor->IsFeatureDisabled(DISABLE_ENTER) && DigitanksGame()->GetCurrentLocalDigitanksTeam() == DigitanksGame()->GetCurrentTeam())
		{
			CSoundLibrary::PlaySound(NULL, L"sound/turn.wav");
			DigitanksGame()->EndTurn();
		}
	}

	if (c == TINKER_KEY_ESCAPE)
	{
		if (GetMenu()->IsVisible())
			GetMenu()->SetVisible(false);
		else if (DigitanksGame() && (DigitanksGame()->GetControlMode() == MODE_NONE || DigitanksGame()->GetPrimarySelection() == NULL))
			GetMenu()->SetVisible(true);
		else
			DigitanksGame()->SetControlMode(MODE_NONE);
	}

	if (GameServer() && GameServer()->GetCamera())
		GameServer()->GetCamera()->KeyDown(c);
}

void CDigitanksWindow::KeyRelease(int c)
{
	if (GameServer() && GameServer()->GetCamera())
		GameServer()->GetCamera()->KeyUp(c);
}

void CDigitanksWindow::CharPress(int c)
{
	if (c == '`')
	{
		ToggleConsole();
		return;
	}

	if (glgui::CRootPanel::Get()->CharPressed(c))
		return;

	if (!GetHUD())
		return;

	if (c == ' ')
		DigitanksGame()->WeaponSpecialCommand();

	if (c == 'h')
	{
		if (DigitanksGame()->GetCurrentLocalDigitanksTeam())
		{
			for (size_t i = 0; i < DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetNumMembers(); i++)
			{
				CBaseEntity* pMember = DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetMember(i);
				CCPU* pCPU = dynamic_cast<CCPU*>(pMember);
				if (pCPU)
				{
					DigitanksGame()->GetCurrentLocalDigitanksTeam()->SetPrimarySelection(pCPU);
					break;
				}
			}
		}
	}

	if (c == 'q')
		GetHUD()->ButtonCallback(0);

	if (c == 'w')
		GetHUD()->ButtonCallback(1);

	if (c == 'e')
		GetHUD()->ButtonCallback(2);

	if (c == 'r')
		GetHUD()->ButtonCallback(3);

	if (c == 't')
		GetHUD()->ButtonCallback(4);

	if (c == 'a')
		GetHUD()->ButtonCallback(5);

	if (c == 's')
		GetHUD()->ButtonCallback(6);

	if (c == 'd')
		GetHUD()->ButtonCallback(7);

	if (c == 'f')
		GetHUD()->ButtonCallback(8);

	if (c == 'g')
		GetHUD()->ButtonCallback(9);

	if (!DigitanksGame()->AllowCheats())
		return;

	// Cheats from here on out
	if (c == 'x')
		DigitanksGame()->SetRenderFogOfWar(!DigitanksGame()->ShouldRenderFogOfWar());

	if (c == 'c')
		DigitanksGame()->CompleteProductions();

	if (c == 'v')
	{
		if (DigitanksGame()->GetPrimarySelection())
			DigitanksGame()->GetPrimarySelection()->Delete();
	}

	if (c == 'b')
	{
		CDigitanksTeam* pTeam = DigitanksGame()->GetCurrentTeam();
		for (size_t x = 0; x < UPDATE_GRID_SIZE; x++)
		{
			for (size_t y = 0; y < UPDATE_GRID_SIZE; y++)
			{
				if (DigitanksGame()->GetUpdateGrid()->m_aUpdates[x][y].m_eUpdateClass == UPDATECLASS_EMPTY)
					continue;

				pTeam->DownloadUpdate(x, y, false);
				pTeam->DownloadComplete();
			}
		}
	}

	if (c == 'n')
		GetHUD()->SetVisible(!GetHUD()->IsVisible());

	if (c == 'm')
	{
		if (DigitanksGame()->GetPrimarySelection())
			DigitanksGame()->TankSpeak(DigitanksGame()->GetPrimarySelectionTank(), ":D!");
	}
}

void CDigitanksWindow::CharRelease(int c)
{
}

bool CDigitanksWindow::GetBoxSelection(size_t& iX, size_t& iY, size_t& iX2, size_t& iY2)
{
	if (m_bBoxSelect)
	{
		iX = (m_iMouseInitialX < m_iMouseCurrentX) ? m_iMouseInitialX : m_iMouseCurrentX;
		iY = (m_iMouseInitialY < m_iMouseCurrentY) ? m_iMouseInitialY : m_iMouseCurrentY;
		iX2 = (m_iMouseInitialX > m_iMouseCurrentX) ? m_iMouseInitialX : m_iMouseCurrentX;
		iY2 = (m_iMouseInitialY > m_iMouseCurrentY) ? m_iMouseInitialY : m_iMouseCurrentY;
		return true;
	}

	return false;
}

bool CDigitanksWindow::IsMouseDragging()
{
	size_t iDifference = abs((int)m_iMouseCurrentX - (int)m_iMouseInitialX) + abs((int)m_iMouseCurrentY - (int)m_iMouseInitialY);

	return iDifference > 30;
}
<commit_msg>Enable use of the right mouse button to do stuff. Hopefully it works.<commit_after>#include "digitankswindow.h"

#include <sound/sound.h>
#include "glgui/glgui.h"
#include "digitanks/digitanksgame.h"
#include "instructor.h"
#include "hud.h"
#include "ui.h"
#include <game/digitanks/structures/cpu.h>
#include <game/digitanks/dt_camera.h>
#include <renderer/renderer.h>
#include <renderer/dissolver.h>
#include <tinker/keys.h>

void CDigitanksWindow::MouseMotion(int x, int y)
{
	glgui::CRootPanel::Get()->CursorMoved(x, y);

	if (DigitanksGame() && DigitanksGame()->GetGameType() == GAMETYPE_MENU)
		return;

	if (GameServer() && GameServer()->GetCamera())
		GameServer()->GetCamera()->MouseInput(x, y);

	if (IsMouseRightDown())
		m_iMouseMoved += (int)(fabs((float)x-m_iMouseLastX) + fabs((float)y-m_iMouseLastY));

	if (IsMouseLeftDown())
	{
		m_iMouseCurrentX = x;
		m_iMouseCurrentY = y;
	}

	m_iMouseLastX = x;
	m_iMouseLastY = y;
}

void CDigitanksWindow::MouseInput(int iButton, int iState)
{
	if (GameServer() && GameServer()->GetCamera())
	{
		// MouseButton enables camera rotation, so don't send the signal if the feature is disabled.
		if (!m_pInstructor->IsFeatureDisabled(DISABLE_ROTATE))
			GameServer()->GetCamera()->MouseButton(iButton, iState);
	}

	int mx, my;
	GetMousePosition(mx, my);
	if (iState == 1)
	{
		if (glgui::CRootPanel::Get()->MousePressed(iButton, mx, my))
		{
			m_bMouseDownInGUI = true;
			return;
		}
		else
			m_bMouseDownInGUI = false;
	}
	else
	{
		if (glgui::CRootPanel::Get()->MouseReleased(iButton, mx, my))
			return;

		if (m_bMouseDownInGUI)
		{
			m_bMouseDownInGUI = false;
			return;
		}
	}

	if (!DigitanksGame())
		return;

	if (DigitanksGame()->GetGameType() == GAMETYPE_MENU)
		return;

	Vector vecMousePosition;
	CBaseEntity* pClickedEntity = NULL;
	GetMouseGridPosition(vecMousePosition, &pClickedEntity);
	GetMouseGridPosition(vecMousePosition, NULL, CG_TERRAIN);

	bool bMouseAction = false;
	if (iButton == TINKER_KEY_MOUSE_RIGHT && iState == 0 && m_iMouseMoved < 30)
		bMouseAction = true;
	if (iButton == TINKER_KEY_MOUSE_LEFT && iState == 1)
		bMouseAction = true;

	if (DigitanksGame()->GetControlMode() != MODE_NONE && bMouseAction)
	{
		// While aiming moving turning or building, either mouse button can be used and selections are disabled.

		if (DigitanksGame()->GetControlMode() == MODE_MOVE)
			DigitanksGame()->MoveTanks();
		else if (DigitanksGame()->GetControlMode() == MODE_TURN)
			DigitanksGame()->TurnTanks(vecMousePosition);
		else if (DigitanksGame()->GetControlMode() == MODE_AIM)
		{
			DigitanksGame()->FireTanks();
			GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_ATTACK);
		}
		else if (DigitanksGame()->GetControlMode() == MODE_BUILD)
		{
			if (DigitanksGame()->GetCurrentLocalDigitanksTeam())
			{
				CCPU* pCPU = DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetPrimaryCPU();
				if (pCPU && pCPU->IsPreviewBuildValid())
				{
					pCPU->BeginConstruction();
					DigitanksGame()->SetControlMode(MODE_NONE);
				}
			}
		}

		GetHUD()->SetupMenu();

		if (iState == 1)
			// Don't allow the release to take any action either.
			m_bMouseDownInGUI = true;

		return;
	}

	if (iButton == TINKER_KEY_MOUSE_RIGHT)
	{
		if (iState == 1)
			m_iMouseMoved = 0;
		else
		{
			if (m_iMouseMoved > 30)
				GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_TURNCAMERA);
		}
	}

	if (iButton == TINKER_KEY_MOUSE_LEFT)
	{
		if (iState == 1)
		{
			// Prevent UI interactions from affecting the camera target.
			// If the mouse was used no the UI, this will remain false.
			m_bBoxSelect = true;
			m_iMouseInitialX = m_iMouseCurrentX = mx;
			m_iMouseInitialY = m_iMouseCurrentY = my;
		}
	}

	if (iState == 0 && iButton == TINKER_KEY_MOUSE_LEFT)
	{
		if (m_bBoxSelect && IsMouseDragging())
		{
			if (!IsShiftDown() && DigitanksGame()->GetCurrentLocalDigitanksTeam())
				DigitanksGame()->GetCurrentLocalDigitanksTeam()->SetPrimarySelection(NULL);

			size_t iLowerX = (m_iMouseInitialX < m_iMouseCurrentX) ? m_iMouseInitialX : m_iMouseCurrentX;
			size_t iLowerY = (m_iMouseInitialY < m_iMouseCurrentY) ? m_iMouseInitialY : m_iMouseCurrentY;
			size_t iHigherX = (m_iMouseInitialX > m_iMouseCurrentX) ? m_iMouseInitialX : m_iMouseCurrentX;
			size_t iHigherY = (m_iMouseInitialY > m_iMouseCurrentY) ? m_iMouseInitialY : m_iMouseCurrentY;

			for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++)
			{
				CBaseEntity* pEntity = CBaseEntity::GetEntity(i);
				if (!pEntity)
					continue;

				CSelectable* pSelectable = dynamic_cast<CSelectable*>(pEntity);
				if (!pSelectable)
					continue;

				if (pSelectable->GetVisibility() == 0)
					continue;

				Vector vecScreen = GameServer()->GetRenderer()->ScreenPosition(pSelectable->GetOrigin());

				if (vecScreen.x < iLowerX || vecScreen.y < iLowerY || vecScreen.x > iHigherX || vecScreen.y > iHigherY)
					continue;

				if (DigitanksGame()->GetCurrentLocalDigitanksTeam())
					DigitanksGame()->GetCurrentLocalDigitanksTeam()->AddToSelection(pSelectable);
			}

			if (DigitanksGame()->GetCurrentLocalDigitanksTeam() && DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetNumSelected() == 3)
				GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_BOXSELECT);
		}
		else if (pClickedEntity && DigitanksGame()->GetCurrentLocalDigitanksTeam())
		{
			CSelectable* pSelectable = dynamic_cast<CSelectable*>(pClickedEntity);

			if (pSelectable)
			{
				if (IsShiftDown())
					DigitanksGame()->GetCurrentLocalDigitanksTeam()->AddToSelection(pSelectable);
				else
					DigitanksGame()->GetCurrentLocalDigitanksTeam()->SetPrimarySelection(pSelectable);
			}
			else if (!IsShiftDown())
				DigitanksGame()->GetCurrentLocalDigitanksTeam()->SetPrimarySelection(NULL);

			if (DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetNumSelected() == 3)
				GetInstructor()->FinishedTutorial(CInstructor::TUTORIAL_SHIFTSELECT);
		}

		m_bBoxSelect = false;
	}

	GetHUD()->SetupMenu();
}

void CDigitanksWindow::MouseWheel(int iState)
{
	if (DigitanksGame() && DigitanksGame()->GetGameType() == GAMETYPE_MENU)
		return;

	static int iOldState = 0;

	if (GameServer() && GameServer()->GetCamera())
	{
		if (iState > iOldState)
			DigitanksGame()->GetDigitanksCamera()->ZoomIn();
		else
			DigitanksGame()->GetDigitanksCamera()->ZoomOut();
	}

	iOldState = iState;
}

void CDigitanksWindow::KeyPress(int c)
{
	if (glgui::CRootPanel::Get()->KeyPressed(c, IsCtrlDown()))
		return;

	if (DigitanksGame() && DigitanksGame()->GetGameType() == GAMETYPE_MENU)
		return;

	if (c == TINKER_KEY_F4 && IsAltDown())
		exit(0);

	if (DigitanksGame() && (c == TINKER_KEY_ENTER || c == TINKER_KEY_KP_ENTER))
	{
		if (!m_pInstructor->IsFeatureDisabled(DISABLE_ENTER) && DigitanksGame()->GetCurrentLocalDigitanksTeam() == DigitanksGame()->GetCurrentTeam())
		{
			CSoundLibrary::PlaySound(NULL, L"sound/turn.wav");
			DigitanksGame()->EndTurn();
		}
	}

	if (c == TINKER_KEY_ESCAPE)
	{
		if (GetMenu()->IsVisible())
			GetMenu()->SetVisible(false);
		else if (DigitanksGame() && (DigitanksGame()->GetControlMode() == MODE_NONE || DigitanksGame()->GetPrimarySelection() == NULL))
			GetMenu()->SetVisible(true);
		else
			DigitanksGame()->SetControlMode(MODE_NONE);
	}

	if (GameServer() && GameServer()->GetCamera())
		GameServer()->GetCamera()->KeyDown(c);
}

void CDigitanksWindow::KeyRelease(int c)
{
	if (GameServer() && GameServer()->GetCamera())
		GameServer()->GetCamera()->KeyUp(c);
}

void CDigitanksWindow::CharPress(int c)
{
	if (c == '`')
	{
		ToggleConsole();
		return;
	}

	if (glgui::CRootPanel::Get()->CharPressed(c))
		return;

	if (!GetHUD())
		return;

	if (c == ' ')
		DigitanksGame()->WeaponSpecialCommand();

	if (c == 'h')
	{
		if (DigitanksGame()->GetCurrentLocalDigitanksTeam())
		{
			for (size_t i = 0; i < DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetNumMembers(); i++)
			{
				CBaseEntity* pMember = DigitanksGame()->GetCurrentLocalDigitanksTeam()->GetMember(i);
				CCPU* pCPU = dynamic_cast<CCPU*>(pMember);
				if (pCPU)
				{
					DigitanksGame()->GetCurrentLocalDigitanksTeam()->SetPrimarySelection(pCPU);
					break;
				}
			}
		}
	}

	if (c == 'q')
		GetHUD()->ButtonCallback(0);

	if (c == 'w')
		GetHUD()->ButtonCallback(1);

	if (c == 'e')
		GetHUD()->ButtonCallback(2);

	if (c == 'r')
		GetHUD()->ButtonCallback(3);

	if (c == 't')
		GetHUD()->ButtonCallback(4);

	if (c == 'a')
		GetHUD()->ButtonCallback(5);

	if (c == 's')
		GetHUD()->ButtonCallback(6);

	if (c == 'd')
		GetHUD()->ButtonCallback(7);

	if (c == 'f')
		GetHUD()->ButtonCallback(8);

	if (c == 'g')
		GetHUD()->ButtonCallback(9);

	if (!DigitanksGame()->AllowCheats())
		return;

	// Cheats from here on out
	if (c == 'x')
		DigitanksGame()->SetRenderFogOfWar(!DigitanksGame()->ShouldRenderFogOfWar());

	if (c == 'c')
		DigitanksGame()->CompleteProductions();

	if (c == 'v')
	{
		if (DigitanksGame()->GetPrimarySelection())
			DigitanksGame()->GetPrimarySelection()->Delete();
	}

	if (c == 'b')
	{
		CDigitanksTeam* pTeam = DigitanksGame()->GetCurrentTeam();
		for (size_t x = 0; x < UPDATE_GRID_SIZE; x++)
		{
			for (size_t y = 0; y < UPDATE_GRID_SIZE; y++)
			{
				if (DigitanksGame()->GetUpdateGrid()->m_aUpdates[x][y].m_eUpdateClass == UPDATECLASS_EMPTY)
					continue;

				pTeam->DownloadUpdate(x, y, false);
				pTeam->DownloadComplete();
			}
		}
	}

	if (c == 'n')
		GetHUD()->SetVisible(!GetHUD()->IsVisible());

	if (c == 'm')
	{
		if (DigitanksGame()->GetPrimarySelection())
			DigitanksGame()->TankSpeak(DigitanksGame()->GetPrimarySelectionTank(), ":D!");
	}
}

void CDigitanksWindow::CharRelease(int c)
{
}

bool CDigitanksWindow::GetBoxSelection(size_t& iX, size_t& iY, size_t& iX2, size_t& iY2)
{
	if (m_bBoxSelect)
	{
		iX = (m_iMouseInitialX < m_iMouseCurrentX) ? m_iMouseInitialX : m_iMouseCurrentX;
		iY = (m_iMouseInitialY < m_iMouseCurrentY) ? m_iMouseInitialY : m_iMouseCurrentY;
		iX2 = (m_iMouseInitialX > m_iMouseCurrentX) ? m_iMouseInitialX : m_iMouseCurrentX;
		iY2 = (m_iMouseInitialY > m_iMouseCurrentY) ? m_iMouseInitialY : m_iMouseCurrentY;
		return true;
	}

	return false;
}

bool CDigitanksWindow::IsMouseDragging()
{
	size_t iDifference = abs((int)m_iMouseCurrentX - (int)m_iMouseInitialX) + abs((int)m_iMouseCurrentY - (int)m_iMouseInitialY);

	return iDifference > 30;
}
<|endoftext|>